Beispiel #1
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Program program = null;
            DA.GetData(0, ref program);

            var path = DA.ParameterTargetPath(0);
            var cellTargets = program.Value.Targets;
            var groupCount = cellTargets[0].ProgramTargets.Count;

            var planes = new GH_Structure<GH_Plane>();
            var joints = new GH_Structure<GH_Number>();
            var configuration = new GH_Structure<GH_String>();
            var deltaTime = new GH_Structure<GH_Number>();

            for (int i = 0; i < groupCount; i++)
            {
                var tempPath = path.AppendElement(i);
                for (int j = 0; j < cellTargets.Count; j++)
                {
                    planes.AppendRange(cellTargets[j].ProgramTargets[i].Kinematics.Planes.Select(x => new GH_Plane(x)), tempPath.AppendElement(j));
                    joints.AppendRange(cellTargets[j].ProgramTargets[i].Kinematics.Joints.Select(x => new GH_Number(x)), tempPath.AppendElement(j));
                    configuration.Append(new GH_String(cellTargets[j].ProgramTargets[i].Kinematics.Configuration.ToString()), tempPath);
                    deltaTime.Append(new GH_Number(cellTargets[j].DeltaTime), tempPath);
                }
            }

            DA.SetDataTree(0, planes);
            DA.SetDataTree(1, joints);
            DA.SetDataTree(2, configuration);
            DA.SetDataTree(3, deltaTime);
        }
Beispiel #2
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string name = null; 
            GH_RobotSystem robotSystem = null;
            var initCommandsGH = new List<GH_Command>();
            var targetsA = new List<GH_Target>();
            var targetsB = new List<GH_Target>();
            var multiFileIndices = new List<int>();
            double stepSize = 1;

            if (!DA.GetData(0, ref name)) { return; }
            if (!DA.GetData(1, ref robotSystem)) { return; }
            if (!DA.GetDataList(2, targetsA)) { return; }
            DA.GetDataList(3, targetsB);
            DA.GetDataList(4, initCommandsGH);
            DA.GetDataList(5, multiFileIndices);
            if (!DA.GetData(6, ref stepSize)) { return; }

            var initCommands = initCommandsGH.Count > 0 ? new Robots.Commands.Group(initCommandsGH.Select(x => x.Value)) : null;

            var targets = new List<IEnumerable<Target>>();
            targets.Add(targetsA.Select(x => x.Value));
            if (targetsB.Count > 0) targets.Add(targetsB.Select(x => x.Value));

            var program = new Program(name, robotSystem.Value, targets, initCommands, multiFileIndices, stepSize);

            DA.SetData(0, new GH_Program(program));


            if (program.Code != null)
            {
                var path = DA.ParameterTargetPath(2);
                var structure = new GH_Structure<GH_String>();

                for (int i = 0; i < program.Code.Count; i++)
                {
                    var tempPath = path.AppendElement(i);
                    for (int j = 0; j < program.Code[i].Count; j++)
                    {
                        structure.AppendRange(program.Code[i][j].Select(x => new GH_String(x)), tempPath.AppendElement(j));
                    }
                }

                DA.SetDataTree(1, structure);
            }

            DA.SetData(2, program.Duration);

            if (program.Warnings.Count > 0)
            {
                DA.SetDataList(3, program.Warnings);
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Warnings in program");
            }

            if (program.Errors.Count > 0)
            {
                DA.SetDataList(4, program.Errors);
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Errors in program");
            }
        }
Beispiel #3
0
        public GH_Structure <GH_Number> DataTree()
        {
            GH_Structure <GH_Number>  dataTree = new GH_Structure <GH_Number>();
            GH_Structure <GH_Integer> indices  = new GH_Structure <GH_Integer>();

            for (int i = 0; i < trainedVectors.GetLength(0); i++)
            {
                GH_Path p = new GH_Path(Utils.ReverseArray(this.adressBook[i]));
                indices.Append(new GH_Integer(i), p);
            }
            indices.Flatten();
            dataTree = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> valueTree = Utils.MultidimensionalArrayToGHTree(trainedVectors);

            for (int i = 0; i < indices.DataCount; i++)
            {
                dataTree.AppendRange(valueTree.Branches[indices.Branches[0][i].Value], new GH_Path(this.adressBook[i]));
            }
            return(dataTree);
        }
Beispiel #4
0
        protected override bool Prompt_ManageCollection(GH_Structure <T> values)
        {
            foreach (var item in values.AllData(true))
            {
                if (item.IsValid)
                {
                    continue;
                }

                if (item is Types.IGH_ElementId elementId)
                {
                    if (elementId.IsReferencedElement)
                    {
                        elementId.LoadElement();
                    }
                }
            }

            return(base.Prompt_ManageCollection(values));
        }
Beispiel #5
0
        public static List <object> DataTreeToNestedLists(GH_Structure <IGH_Goo> dataInput, ISpeckleConverter converter, Action OnConversionProgress = null)
        {
            var output = new List <object>();

            for (var i = 0; i < dataInput.Branches.Count; i++)
            {
                var path   = dataInput.Paths[i].Indices.ToList();
                var leaves = new List <object>();

                foreach (var goo in dataInput.Branches[i])
                {
                    OnConversionProgress?.Invoke();
                    leaves.Add(TryConvertItemToSpeckle(goo, converter));
                }

                RecurseTreeToList(output, path, 0, leaves);
            }

            return(output);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //input
            GH_Structure <GH_Plane> planes = new GH_Structure <GH_Plane>();
            double t1 = 0;
            double t2 = 0;

            if (!DA.GetDataTree(0, out planes))
            {
                return;
            }
            if (!DA.GetData(1, ref t1))
            {
                return;
            }
            if (!DA.GetData(2, ref t2))
            {
                return;
            }

            int trimLengthBase = (int)t1;
            int trimLengthTop  = (int)t2;

            //find nodes
            List <List <List <GH_Plane> > > nodesList = ExtractNodes(planes, trimLengthTop);

            //trim nodes
            List <List <List <GH_Plane> > > trimmedNodesList = TrimNodes(nodesList, trimLengthBase, trimLengthTop);

            //find stems
            GH_Structure <GH_Plane> stems = ExtractStems(planes, trimLengthBase, trimLengthTop);

            //convert to datatree
            GH_Structure <GH_Plane> untrimmedNodesTree = ConvertListToTree(nodesList);
            GH_Structure <GH_Plane> trimmedNodesTree   = ConvertListToTree(trimmedNodesList);

            //output
            DA.SetDataTree(0, untrimmedNodesTree);
            DA.SetDataTree(1, trimmedNodesTree);
            DA.SetDataTree(2, stems);
        }
Beispiel #7
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.GetDataTree("R", out GH_Structure <GH_Number> _R); var R = _R.Branches;
            var x = new List <double>(); DA.GetDataList("x", x); var y = new List <double>(); DA.GetDataList("y", y);
            var xlabel = new List <string>(); DA.GetDataList("xlabel", xlabel); var ylabel = new List <string>(); DA.GetDataList("ylabel", ylabel);
            var xl = new List <string>(); DA.GetDataList("xlabel for check", xl); var yl = new List <string>(); DA.GetDataList("ylabel for check", yl);

            DA.GetDataTree("reac_f", out GH_Structure <GH_Number> _reac_f); var reac_f = _reac_f.Branches;
            var eps = 0.1; DA.GetData("eps", ref eps);
            var QX = new GH_Structure <GH_Number>(); var QY = new GH_Structure <GH_Number>();

            for (int i = 0; i < xl.Count; i++)
            {
                int ind = xlabel.IndexOf(xl[i]);
                var qy  = new List <GH_Number>();
                for (int j = 0; j < reac_f.Count; j++)
                {
                    int k = (int)reac_f[j][0 + 7].Value;
                    if (Math.Abs(x[ind] - R[k][0].Value) < 5e-3 && Math.Abs(reac_f[j][2 + 7].Value) > eps)
                    {
                        qy.Add(new GH_Number(Math.Abs(reac_f[j][2 + 7].Value)));
                    }
                }
                QY.AppendRange(qy, new GH_Path(i));
            }
            for (int i = 0; i < yl.Count; i++)
            {
                int ind = ylabel.IndexOf(yl[i]);
                var qx  = new List <GH_Number>();
                for (int j = 0; j < reac_f.Count; j++)
                {
                    int k = (int)reac_f[j][0].Value;
                    if (Math.Abs(y[ind] - R[k][1].Value) < 5e-3 && Math.Abs(reac_f[j][1].Value) > eps)
                    {
                        qx.Add(new GH_Number(Math.Abs(reac_f[j][1].Value)));
                    }
                }
                QX.AppendRange(qx, new GH_Path(i));
            }
            DA.SetDataTree(0, QX); DA.SetDataTree(1, QY);
        }
        public GH_Structure <GH_Brep> Slab(IEnumerable <StbSlab> slabs)
        {
            var brepList = new GH_Structure <GH_Brep>();

            if (slabs == null)
            {
                return(brepList);
            }

            foreach ((StbSlab slab, int i) in slabs.Select((slab, index) => (slab, index)))
            {
                StbSlabOffset[] offsets   = slab.StbSlabOffsetList;
                var             curveList = new PolylineCurve[2];
                double          depth     = BrepMaker.Slab.GetDepth(_sections, slab);
                string[]        nodeIds   = slab.StbNodeIdOrder.Split(' ');
                var             topPts    = new List <Point3d>();
                foreach (string nodeId in nodeIds)
                {
                    var offsetVec = new Vector3d();
                    if (offsets != null)
                    {
                        foreach (StbSlabOffset offset in offsets)
                        {
                            if (nodeId == offset.id_node)
                            {
                                offsetVec = new Vector3d(offset.offset_X, offset.offset_Y, offset.offset_Z);
                            }
                        }
                    }

                    StbNode node = _nodes.First(n => n.id == nodeId);
                    topPts.Add(new Point3d(node.X, node.Y, node.Z) + offsetVec);
                }

                topPts.Add(topPts[0]);
                curveList[0] = new PolylineCurve(topPts);
                brepList.Append(CreateSlabBrep(depth, curveList, topPts), new GH_Path(0, i));
            }

            return(brepList);
        }
        public static GH_Structure <GH_String> MakeReportForRequests(
            Dictionary <OSMTag, int> foundItemsForResult)
        {
            var output = new GH_Structure <GH_String>();
            var tInfo  = CultureInfo.CurrentCulture.TextInfo;

            var requestMetaDataItems = foundItemsForResult.Keys.ToList();

            for (int i = 0; i < requestMetaDataItems.Count; i++)
            {
                var     metaData      = requestMetaDataItems[i];
                GH_Path path          = new GH_Path(i);
                var     count         = foundItemsForResult[metaData];
                var     colorForItem  = GetPerceptualColorForTreeItem(requestMetaDataItems.Count, i);
                var     metaDataTitle = tInfo.ToTitleCase(metaData.Name);

                output.Append(new GH_String(metaDataTitle), path);
                output.Append(new GH_String(metaData.ToString()), path);
                output.Append(new GH_String($"{count} found"), path);
                output.Append(new GH_String(colorForItem.ToString()));
                if (metaData.Key != null)
                {
                    var titleName = tInfo.ToTitleCase(metaData.Key.Name);
                    output.Append(new GH_String(titleName), path);
                    var layerName = titleName + "::" + metaDataTitle;
                    output.Append(new GH_String(layerName), path); // Layer path helper
                }
                else
                {
                    output.Append(new GH_String("(No Parent Feature)"), path);
                    output.Append(new GH_String(metaDataTitle + "::"), path); // Layer path helper
                }

                if (!string.IsNullOrEmpty(metaData.Description))
                {
                    output.Append(new GH_String($"Defined as: {metaData.Description}"), path);
                }
            }

            return(output);
        }
Beispiel #10
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <IGH_Goo> treeIn = new GH_Structure <IGH_Goo>();

            DA.GetDataTree <IGH_Goo>(0, out treeIn);

            int pruneDepth = 0;

            DA.GetData <int>(1, ref pruneDepth);

            GH_Structure <IGH_Goo> treeOut = new GH_Structure <IGH_Goo>();

            ///Create list of path strings
            var pathStrings = treeIn.Paths.Select(x => x.ToString());
            ///Find the deepest path in the tree
            var maxDepthPath = pathStrings.Aggregate((max, cur) => max.Split(';').Length > cur.Split(';').Length ? max : cur);
            ///Get number of branches for deepest path
            var maxDepthInt = maxDepthPath.Split(';').Length;

            foreach (var path in treeIn.Paths)
            {
                ///Determine number of branches to prune if any
                GH_Path.SplitPathLikeString(path.ToString(), out string[] path_segments, out string index_segment);
                var numBranchesToRemove = path_segments.Length - (maxDepthInt - pruneDepth);

                var newPath = path;

                if (numBranchesToRemove > 0 && maxDepthInt - pruneDepth > 0)
                {
                    ///Remove pruned branches from path string
                    path_segments = path_segments.Take(path_segments.Count() - numBranchesToRemove).ToArray();
                    int[] path_args = path_segments.Select(int.Parse).ToArray();

                    newPath = new GH_Path(path_args);
                }

                treeOut.AppendRange(treeIn[path], newPath);
            }

            DA.SetDataTree(0, treeOut);
        }
Beispiel #11
0
        protected override void SolveInstance(IGH_DataAccess access)
        {
// ===============================================================================================
// Read input parameters
// ===============================================================================================
            var tree = new GH_Structure <IGH_Goo>();

            //get values from grasshopper
            access.GetDataTree(0, out tree);
// ===============================================================================================
// Applying Values to Class
// ===============================================================================================
            var partitioned = new GH_Structure <IGH_Goo>();

            if (tree != null && !tree.IsEmpty)
            {
                for (int p = 0; p < tree.PathCount; p++)
                {
                    var path  = tree.Paths[p];
                    var list  = tree.Branches[p];
                    int index = 0;
                    int count = 0;

                    for (int i = 0; i < list.Count; i++)
                    {
                        partitioned.Append(list[i], path.AppendElement(index));

                        count++;
                        if (count >= 8)
                        {
                            count = 0;
                            index++;
                        }
                    }
                }
            }
// ===============================================================================================
// Exporting Data to Grasshopper
// ===============================================================================================
            access.SetDataTree(0, partitioned);
        }
Beispiel #12
0
        /// <summary>
        /// Match the number of values of two given data structure, modifing the one with less elements. GH_Breps => GH_Numbers
        /// </summary>
        /// <param name="inGhBreps"></param>
        /// <param name="inGhNums"></param>
        /// <param name="outGhNums"></param>
        /// <returns></returns>
        public static GH_Structure <GH_Number> NumbersDSFromBreps(GH_Structure <GH_Brep> inGhBreps, GH_Structure <GH_Number> inGhNums, GH_Structure <GH_Number> outGhNums)
        {
            bool brepTopoEqualNumsTopo = inGhNums.TopologyDescription.Equals(inGhBreps.TopologyDescription);

            if (brepTopoEqualNumsTopo)
            {
                outGhNums = inGhNums.Duplicate();
            }
            else
            {
                foreach (GH_Path ghPath in inGhBreps.Paths)
                {
                    for (int i = 0; i < inGhBreps.get_Branch(ghPath).Count; i++)
                    {
                        outGhNums.Insert(inGhNums.get_LastItem(true), ghPath, i);
                    }
                }
            }

            return(outGhNums);
        }
Beispiel #13
0
        protected override void CollectVolatileData_FromSources()
        {
            base.CollectVolatileData_FromSources();
            collectedData.Clear();
            collectedData = m_data.Duplicate();
            List <GH_ValueListItem> ghValueListItemList = new List <GH_ValueListItem>((IEnumerable <GH_ValueListItem>)m_userItems);

            m_userItems.Clear();
            List <IGH_Goo> ghGooList = new List <IGH_Goo>((IEnumerable <IGH_Goo>)collectedData);

            for (int index = 0; index < ghGooList.Count; ++index)
            {
                IGH_Goo gooIn = ghGooList[index];
                m_userItems.Add(new GH_ValueListItem(gooIn.ToString(), "\"" + gooIn.ToString() + "\"", gooIn));
                if (index < ghValueListItemList.Count)
                {
                    m_userItems[index].Selected = ghValueListItemList[index].Selected;
                }
            }
            CollectVolatileData_Custom();
        }
        //GET FROM MESH CLASS
        public int FindSizeOfM(GH_Structure <GH_Integer> treeConnectivity)
        {
            int max = 0;

            for (int i = 0; i < treeConnectivity.PathCount; i++)
            {
                List <GH_Integer> cNodes = (List <GH_Integer>)treeConnectivity.get_Branch(i);

                for (int j = 0; j < cNodes.Count; j++)
                {
                    if (cNodes[j].Value > max)
                    {
                        max = cNodes[j].Value;
                    }
                }
            }

            int sizeOfM = 3 * (max + 1);

            return(sizeOfM);
        }
Beispiel #15
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <GH_Integer> Tt;

            if (!DA.GetDataTree(0, out Tt))
            {
                return;
            }

            GH_Structure <GH_Integer> Tinv = new GH_Structure <GH_Integer>();

            for (int i = 0; i < Tt.Branches.Count; i++)
            {
                for (int j = 0; j < Tt.Branches[i].Count; j++)
                {
                    Tinv.Append(new GH_Integer(Tt.Paths[i].Indices[0]), new GH_Path(Tt.Branches[i][j].Value));
                }
            }

            DA.SetDataTree(0, Tinv);
        }
        private static GH_Structure <IGH_Goo> GetSubTree(GH_Structure <IGH_Goo> valueTree, GH_Path searchPath)
        {
            var subTree = new GH_Structure <IGH_Goo>();
            var gen     = 0;

            foreach (var path in valueTree.Paths)
            {
                var branch = valueTree.get_Branch(path) as IEnumerable <IGH_Goo>;
                if (path.IsAncestor(searchPath, ref gen))
                {
                    subTree.AppendRange(branch, path);
                }
                else if (path.IsCoincident(searchPath))
                {
                    subTree.AppendRange(branch, path);
                    break;
                }
            }
            subTree.Simplify(GH_SimplificationMode.CollapseLeadingOverlaps);
            return(subTree);
        }
Beispiel #17
0
        /// <summary>
        /// Match the number of values of two given data structure, modifing the one with less elements. GH_Curve => GH_Plane
        /// </summary>
        /// <param name="refGhCurves"></param>
        /// <param name="inputPlanes"></param>
        /// <param name="outputPlanes"></param>
        /// <returns></returns>
        public static GH_Structure <GH_Plane> PlanesDSFromCurves(GH_Structure <GH_Curve> refGhCurves, GH_Structure <GH_Plane> inputPlanes, GH_Structure <GH_Plane> outputPlanes)
        {
            bool planesTopoEqualCurvesTopo = refGhCurves.TopologyDescription.Equals(inputPlanes.TopologyDescription);

            if (planesTopoEqualCurvesTopo)
            {
                outputPlanes = inputPlanes.Duplicate();
            }
            else
            {
                foreach (GH_Path ghPath in refGhCurves.Paths)
                {
                    for (int i = 0; i < refGhCurves.get_Branch(ghPath).Count; i++)
                    {
                        outputPlanes.Insert(inputPlanes.get_LastItem(true), ghPath, i);
                    }
                }
            }

            return(outputPlanes);
        }
Beispiel #18
0
        /// <summary>
        /// Match the number of values of two given data structure, modifing the one with less elements. GH_Breps => GH_Boolean
        /// </summary>
        /// <param name="inGhBreps"></param>
        /// <param name="inGhBool"></param>
        /// <param name="outGhBool"></param>
        /// <returns></returns>
        public static GH_Structure <GH_Boolean> BoolDSFromBreps(GH_Structure <GH_Brep> inGhBreps, GH_Structure <GH_Boolean> inGhBool, GH_Structure <GH_Boolean> outGhBool)
        {
            bool brepTopologyEqualBoolTopology = inGhBool.TopologyDescription.Equals(inGhBreps.TopologyDescription);

            if (brepTopologyEqualBoolTopology)
            {
                outGhBool = inGhBool.Duplicate();
            }
            else
            {
                foreach (GH_Path ghPath in inGhBreps.Paths)
                {
                    for (int i = 0; i < inGhBreps.get_Branch(ghPath).Count; i++)
                    {
                        outGhBool.Insert(inGhBool.get_LastItem(true), ghPath, i);
                    }
                }
            }

            return(outGhBool);
        }
Beispiel #19
0
        internal static IEnumerable <GH_String> GetSlabRcSection(object slabFigure, string strength)
        {
            var ghSecString = new GH_Structure <GH_String>();

            switch (slabFigure)
            {
            case StbSecSlab_RC_Straight figure:
                ghSecString.Append(new GH_String("t=" + figure.depth + "(" + strength + ")"));
                break;

            case StbSecSlab_RC_Taper figure:
                ghSecString.Append(new GH_String("t=" + figure.pos + ":" + figure.depth + "(" + strength + ")"));
                break;

            case StbSecSlab_RC_Haunch figure:
                ghSecString.Append(new GH_String("t=" + figure.pos + ":" + figure.depth + "(" + strength + ")"));
                break;
            }

            return(ghSecString);
        }
Beispiel #20
0
        internal static IEnumerable <GH_String> GetBraceSSection(object steelFigure)
        {
            var ghSecStrings = new GH_Structure <GH_String>();

            switch (steelFigure)
            {
            case StbSecSteelBrace_S_Same figure:
                ghSecStrings.Append(new GH_String(figure.shape + "(" + figure.strength_main + ")"));
                break;

            case StbSecSteelBrace_S_NotSame figure:
                ghSecStrings.Append(new GH_String(figure.pos + ":" + figure.shape + "(" + figure.strength_main + ")"));
                break;

            case StbSecSteelBrace_S_ThreeTypes figure:
                ghSecStrings.Append(new GH_String(figure.pos + ":" + figure.shape + "(" + figure.strength_main + ")"));
                break;
            }

            return(ghSecStrings);
        }
Beispiel #21
0
        /// <summary>
        /// 将二维树转化为列表
        /// </summary>
        /// <param name="tree"></param>
        /// <returns></returns>
        public static List <List <Plane> > TreeToList2(GH_Structure <GH_Plane> tree)
        {
            IList <GH_Path>        paths       = tree.Paths;
            List <List <Plane> >   list        = new List <List <Plane> >();
            IEnumerable <GH_Plane> this_branch = new List <GH_Plane>();

            for (int i = 0; i < paths.Count; i++)
            {
                list.Add(new List <Plane>());
                this_branch = tree.get_Branch(paths[i]).Cast <GH_Plane>();
                List <GH_Plane> this_list = this_branch.ToList();
                for (int j = 0; j < this_list.Count(); j++)
                {
                    GH_Plane raw_item = this_list[j];
                    Plane    item     = new Plane();
                    raw_item.CastTo(out item);
                    list[i].Add(item);
                }
            }
            return(list);
        }
        public GH_Structure <GH_Brep> Brace(IEnumerable <StbBrace> braces)
        {
            var brepList = new GH_Structure <GH_Brep>();

            if (braces == null)
            {
                return(brepList);
            }

            foreach ((StbBrace brace, int i) in braces.Select((brace, index) => (brace, index)))
            {
                StbBraceKind_structure kind = brace.kind_structure;

                StbNode[] endNodes =
                {
                    _nodes.First(node => node.id == brace.id_node_start),
                    _nodes.First(node => node.id == brace.id_node_end)
                };
                Point3d[] offset =
                {
                    new Point3d(brace.offset_start_X, brace.offset_start_Y, brace.offset_start_Z),
                    new Point3d(brace.offset_end_X,   brace.offset_end_Y,   brace.offset_end_Z)
                };
                Point3d[] sectionPoints =
                {
                    new Point3d(endNodes[0].X, endNodes[0].Y, endNodes[0].Z) + offset[0],
                    Point3d.Origin,
                    Point3d.Origin,
                    new Point3d(endNodes[1].X, endNodes[1].Y, endNodes[1].Z) + offset[1]
                };
                Vector3d memberAxis = sectionPoints[3] - sectionPoints[0];
                sectionPoints[1] = sectionPoints[0] + memberAxis / memberAxis.Length * brace.joint_start;
                sectionPoints[2] = sectionPoints[3] - memberAxis / memberAxis.Length * brace.joint_end;

                var brepMaker = new BrepMaker.Brace(_sections, _tolerance);
                brepList.Append(new GH_Brep(brepMaker.CreateBraceBrep(brace.id_section, brace.rotate, kind, sectionPoints, memberAxis)), new GH_Path(0, i));
            }

            return(brepList);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Line> bldGrid = new List <Line>();
            double      xcell   = 0;
            double      ycell   = 0;
            double      zcell   = 0;


            if (!DA.GetData(0, ref xcell))
            {
                return;
            }
            if (!DA.GetData(1, ref ycell))
            {
                return;
            }
            if (!DA.GetData(2, ref zcell))
            {
                return;
            }
            if (!DA.GetDataList(3, bldGrid))
            {
                return;
            }

            Parameters     parameters = new Parameters(xcell, ycell, zcell);
            PartController pControl   = new PartController(bldGrid, parameters);

            GH_Structure <GH_Mesh> caveSlices = new GH_Structure <GH_Mesh>();
            GH_Structure <GH_Brep> bboxes     = new GH_Structure <GH_Brep>();

            getSlices(pControl, ref bboxes, ref caveSlices);

            DA.SetDataTree(0, caveSlices);
            DA.SetDataTree(1, bboxes);

            Documenter documenter3d = new Documenter();

            documenter3d.WritePart3d(pControl, parameters, @"C:\Users\Admin\Documents\projects\PassageProjects\DD\Output\part.3dm");
        }
        public GH_Structure <GH_Brep> Post(IEnumerable <StbPost> posts)
        {
            var brepList = new GH_Structure <GH_Brep>();

            if (posts == null)
            {
                return(brepList);
            }

            foreach ((StbPost post, int i) in posts.Select((post, index) => (post, index)))
            {
                StbColumnKind_structure kind = post.kind_structure;

                StbNode[] endNodes =
                {
                    _nodes.First(node => node.id == post.id_node_bottom),
                    _nodes.First(node => node.id == post.id_node_top)
                };
                Point3d[] offset =
                {
                    new Point3d(post.offset_bottom_X, post.offset_bottom_Y, post.offset_bottom_Z),
                    new Point3d(post.offset_top_X,    post.offset_top_Y,    post.offset_top_Z)
                };
                Point3d[] sectionPoints =
                {
                    new Point3d(endNodes[0].X, endNodes[0].Y, endNodes[0].Z) + offset[0],
                    new Point3d(),
                    new Point3d(),
                    new Point3d(endNodes[1].X, endNodes[1].Y, endNodes[1].Z) + offset[1]
                };
                Vector3d memberAxis = sectionPoints[3] - sectionPoints[0];
                sectionPoints[1] = sectionPoints[0] + memberAxis / memberAxis.Length * post.joint_bottom;
                sectionPoints[2] = sectionPoints[3] - memberAxis / memberAxis.Length * post.joint_top;

                var brepMaker = new BrepMaker.Column(_sections, _tolerance);
                brepList.Append(new GH_Brep(brepMaker.CreateColumnBrep(post.id_section, post.rotate, kind, sectionPoints, memberAxis)), new GH_Path(0, i));
            }

            return(brepList);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <IGH_Goo> issue_tree = new GH_Structure <IGH_Goo>();
            string attributeName = "";

            DA.GetDataTree("Issues", out issue_tree);
            DA.GetData("Attribute", ref attributeName);

            StringBuilder output = new StringBuilder();
            int           total  = 0;

            for (int b = 0; b < issue_tree.Branches.Count; b++)
            {
                var summary = new StringCounter();
                foreach (var gh_issue in issue_tree[b])
                {
                    Issue issue = ((GH_ObjectWrapper)gh_issue).Value as Issue;
                    if (issue == null)
                    {
                        continue;
                    }

                    total += 1;
                    var value = issue.GetPropertyValue(attributeName);
                    summary.Increment(value);
                }
                output.Append(string.Format("[Path {0}]\r\n", b));
                var keys = new List <string>();
                keys.AddRange(summary.Keys);
                keys.Sort();
                foreach (var key in keys)
                {
                    output.Append(key).Append(": ").Append(summary[key].ToString()).Append("\n");
                }
                output.Append("\r\n\r\n");
            }

            DA.SetData(0, total);
            DA.SetData(1, output.ToString());
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Input variables
            GH_Structure <IGH_Goo> data;
            string name = String.Empty;

            // Catch the input data
            if (!DA.GetData(0, ref name))
            {
                return;
            }
            if (!DA.GetDataTree(1, out data))
            {
                return;
            }

            // Output variable
            GH_Structure <GH_String> names = HelperMethods.DataTreeNaming(name, data);

            // Output
            DA.SetDataTree(0, names);
        }
Beispiel #27
0
        public static GH_Structure <GH_String> MakeTreeForItemTags(RequestHandler result)
        {
            var output = new GH_Structure <GH_String>();

            for (int i = 0; i < result.RequestedMetaData.Requests.Count; i++)
            {
                new GH_Path(i);
                var metaData = result.RequestedMetaData.Requests[i];
                var results  = result.FoundData[metaData];
                for (int j = 0; j < results.Count; j++)
                {
                    var subPath = new GH_Path(i, j);
                    foreach (var tag in results[j].Tags)
                    {
                        var tagReadout = new GH_String(tag.Key + "=" + tag.Value);
                        output.Append(tagReadout, subPath);
                    }
                }
            }

            return(output);
        }
Beispiel #28
0
        public static List <Point3d> GHTreeToPointList(GH_Structure <GH_Point> pointTree)
        {
            int listLengthes = pointTree.Branches[0].Count;

            for (int i = 0; i < pointTree.Branches.Count; i++)
            {
                if (listLengthes != pointTree.Branches[i].Count)
                {
                    return(new List <Point3d>());
                }
            }
            List <Point3d> points = new List <Point3d>();

            for (int i = 0; i < pointTree.Branches.Count; i++)
            {
                for (int j = 0; j < pointTree.Branches[i].Count; j++)
                {
                    points.Add(pointTree[i][j].Value);
                }
            }
            return(points);
        }
Beispiel #29
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var shell = new List <Surface>();
            var xyz = new List <Point3d>(); GH_Structure <GH_Number> r = new GH_Structure <GH_Number>(); GH_Structure <GH_Number> ijkl = new GH_Structure <GH_Number>();
            int N = 6; int M = 32; double X = 1.5; double Y = 8.0; double angle = 120.0; var cp = new List <double>(); double te = 0.090; int me = 0; List <double> thickness = new List <double>(); List <int> mat = new List <int>();

            DA.GetData("number of points on width direction", ref N); DA.GetData("number of points on length direction", ref M); DA.GetData("thickness", ref te); DA.GetData("material number", ref me);
            DA.GetData("width of 1 unit", ref X); DA.GetData("length of 1 unit", ref Y); DA.GetData("fold angle", ref angle); DA.GetDataList("center point of the bottom", cp);
            var dx = X / ((double)N - 1.0); var dy = Y / ((double)M - 1.0); var theta = (180.0 - angle) / 2.0 / 180.0 * Math.PI;

            for (int j = 0; j < M; j++)
            {
                for (int i = 0; i < N * 2 - 1; i++)
                {
                    var l = dx * i;
                    var x = l * Math.Cos(theta); var z = l * Math.Sin(theta); var y = dy * j;
                    if (i >= N)
                    {
                        z = X * Math.Sin(theta) - (l - X) * Math.Sin(theta);
                    }
                    xyz.Add(new Point3d(x - X * Math.Cos(theta) + cp[0], y - Y / 2.0 + cp[1], z + cp[2]));
                    var rlist = new List <GH_Number>(); rlist.Add(new GH_Number(x - X * Math.Cos(theta) + cp[0])); rlist.Add(new GH_Number(y - Y / 2.0 + cp[1])); rlist.Add(new GH_Number(z + cp[2]));
                    r.AppendRange(rlist, new GH_Path(i + j * (N * 2 - 1)));
                    thickness.Add(te); mat.Add(me);
                }
            }
            DA.SetDataList("nodes", xyz);
            for (int j = 0; j < M - 1; j++)
            {
                for (int i = 0; i < N * 2 - 2; i++)
                {
                    int n1 = i + (N * 2 - 1) * j; int n2 = n1 + 1; int n3 = i + (N * 2 - 1) * (j + 1) + 1; int n4 = n3 - 1;
                    shell.Add(NurbsSurface.CreateFromCorners(xyz[n1], xyz[n2], xyz[n3], xyz[n4]));
                }
            }
            DA.SetDataList("shells", shell);
            DA.SetDataList("material number", mat);
            DA.SetDataList("thickness", thickness);
        }
Beispiel #30
0
        /// <summary>
        /// Path[0] = joint; Path[1] = member
        /// </summary>
        /// <param name="inputPlanes"></param>
        /// <returns></returns>
        private GH_Structure <GH_Curve> BuildStructureAsCurves()
        {
            GH_Structure <GH_Curve> curves = new GH_Structure <GH_Curve>();

            for (int i = 0; i < Utility.GetMainBranchCount(inputPlanes.Paths); i++)
            {
                int subBranchCount = Utility.GetSecondaryBranchCount(inputPlanes.Paths, i);
                for (int j = 0; j < subBranchCount; j++)
                {
                    GH_Path        path = new GH_Path(i, j);
                    List <Point3d> cp   = new List <Point3d>();
                    foreach (GH_Plane plane in inputPlanes.get_Branch(path))
                    {
                        cp.Add(plane.Value.Origin);
                    }
                    GH_Curve cv = new GH_Curve();
                    cv.CastFrom(Curve.CreateInterpolatedCurve(cp, 3));
                    curves.Append(cv, path);
                }
            }
            return(curves);
        }
        /// <summary>
        /// Returns true if all values are similar under a certain epsilon threshold.
        /// </summary>
        /// <param name="A"></param>
        /// <param name="B"></param>
        /// <param name="epsilon"></param>
        /// <returns></returns>
        internal static bool EqualNumData(GH_Structure <GH_Number> A, GH_Structure <GH_Number> B, double epsilon)
        {
            var    bA = A.Branches;
            var    bB = B.Branches;
            double a, b;

            for (int i = bA.Count - 1; i >= 0; i--)
            {
                for (int j = bA[i].Count - 1; j >= 0; j--)
                {
                    a = bA[i][j].Value;
                    b = bB[i][j].Value;
                    if (Math.Abs(b - a) >= epsilon ||
                        double.IsNaN(a) != double.IsNaN(b))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Beispiel #32
0
        //
        // Duplicate a structure.
        //
        internal GH_Structure <IGH_Goo> duplicateStructure(IGH_Structure source)
        {
            GH_Structure <IGH_Goo> copy = new GH_Structure <IGH_Goo>();

            foreach (GH_Path p in source.Paths)
            {
                List <IGH_Goo> l = new List <IGH_Goo>();
                foreach (IGH_Goo item in source.get_Branch(p))
                {
                    if (item == null)
                    {
                        l.Add(null);
                    }
                    else
                    {
                        l.Add(item.Duplicate());
                    }
                }
                copy.AppendRange(l, p);
            }
            return(copy);
        }
Beispiel #33
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            #region INPUTS
            // import silkwormSettings file
            List<string> silkwormSettings = new List<string>();
            if (!DA.GetDataList(0, silkwormSettings)) return;

            List<GH_ObjectWrapper> things = new List<GH_ObjectWrapper>();
            if (!DA.GetDataList(1, things)) return;

            // import Silkworm Movement
            #endregion

            SilkwormUtility sUtil = new SilkwormUtility();
            Dictionary<string, string> Settings = sUtil.convertSettings(silkwormSettings);

            #region Optional Variables
            int shell = -999;
            if (!DA.GetData(4, ref shell)) { }
            double layerheight = -999;
            if (!DA.GetData(3, ref layerheight)) { }
            //bool detect = false;
            //if (!DA.GetData(5, ref detect)) { }
            List<Plane> sliceplanes = new List<Plane>();
            if (!DA.GetDataList(2, sliceplanes)) { }

            if (shell == -999)
            {
                shell = int.Parse(Settings["perimeters"]);
            }
            if (layerheight == -999)
            {
                layerheight = double.Parse(Settings["layer_height"]);
            }
            if (sliceplanes.Count<1)
            {
                sliceplanes.Add(Plane.WorldXY);
            }

            #endregion

            List<Brep> Breps = new List<Brep>();

            List<Mesh> Meshes = new List<Mesh>();

            SilkwormSkein skein = new SilkwormSkein();

            #region Sort Types
            foreach (GH_ObjectWrapper obj in things)
            {
                if (obj.Value is GH_Brep)
                {
                    Brep brep = null;
                    GH_Convert.ToBrep(obj.Value, ref brep, GH_Conversion.Both);

                    Breps.Add(brep);
                    continue;

                }

                if (obj.Value is GH_Mesh)
                {
                    Mesh mesh = null;
                    GH_Convert.ToMesh(obj.Value, ref mesh, GH_Conversion.Both);
                    Meshes.Add(mesh);

                    continue;
                }
            }
            #endregion

            if (Breps.Count>0)
            {

                skein = new SilkwormSkein(Settings, Breps, sliceplanes, shell, layerheight);
                skein.BrepSlice(false);

            }

            if (Meshes.Count > 0)
            {

                //TODO
            }

            //Reflect Errors and Warnings

                foreach (string message in skein.ErrorMessages)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, message);

                }
                foreach (string message in skein.WarningMessages)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);

                }

            List<Curve>[] openregions = skein.openRegions;

            List<Brep>[] rRegions = skein.Regions;
            List<Brep>[] rPerimeterR = skein.regionPerimeter;
            List<Brep>[]  rInfillR = skein.regionInfill;

            GH_Structure<GH_Brep> Regions = new GH_Structure<GH_Brep>();

            GH_Structure<GH_Curve> openRegions = new GH_Structure<GH_Curve>();

            #region Add Regions to GH_Structure

            if (rRegions.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < rRegions.Length; i++)
                {

                    if (rRegions[i] != null)
                        {
                    for (int j = 0; j < rRegions[i].Count; j++)
                    {

                            GH_Brep gShapes = new GH_Brep(rRegions[i][j]);
                            Regions.Insert(gShapes, new GH_Path(i, 0), j);
                        }

                    }
                }
            }
            if (rPerimeterR.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < rPerimeterR.Length; i++)
                {
            if (rPerimeterR[i] != null)
                        {
                    for (int j = 0; j < rPerimeterR[i].Count; j++)
                    {

                            GH_Brep gShapes = new GH_Brep(rPerimeterR[i][j]);
                            Regions.Insert(gShapes, new GH_Path(i, 1), j);
                        }

                    }
                }
            }
            if (rInfillR.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < rInfillR.Length; i++)
                {
            if (rInfillR[i] != null)
                        {
                    for (int j = 0; j < rInfillR[i].Count; j++)
                    {

                            GH_Brep gShapes = new GH_Brep(rInfillR[i][j]);
                            Regions.Insert(gShapes, new GH_Path(i, 2), j);
                        }

                    }
                }
            }

            if (openregions.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < openregions.Length; i++)
                {
            if (openregions[i] != null)
                        {
                    for (int j = 0; j < openregions[i].Count; j++)
                    {

                            GH_Curve gShapes = new GH_Curve(openregions[i][j]);
                            openRegions.Insert(gShapes, new GH_Path(i), j);
                        }

                    }
                }
            }
            //TODO
            //Add Overhang and Bridges

            #endregion

            #region Add Open Regions to GH_Structure
            if (openregions.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < openregions.Length; i++)
                {

                    for (int j = 0; j < openregions[i].Count; j++)
                    {

                        if (openregions[i][j] != null)
                        {

                            SilkwormSegment segment = new SilkwormSegment(openregions[i][j]);
                            Curve curve = segment.Pline.ToNurbsCurve();
                            GH_Curve gShapes = new GH_Curve(curve);
                            openRegions.Insert(gShapes, new GH_Path(i), j);
                        }

                    }
                }
            }
            #endregion

            #region OUTPUT

            if (!DA.SetDataTree(0, Regions)) { return; }
            if (!DA.SetDataTree(1, openRegions)) { return; }

            #endregion
        }
 public PositionHistoryAsGhStructure(int size)
 {
   this.structure = new GH_Structure<IGH_Goo>();
   this.size = size;
   this.nextPathIndex = 0;
 }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure<IGH_Goo> Input = new GH_Structure<IGH_Goo>();
            DA.GetDataTree("Input", out Input);

            GH_Structure<HashType> Output = new GH_Structure<HashType>();
            bool bEnumerate = false;
            DA.GetData("Enumerate", ref bEnumerate);
            // iterate through all the sources by the Params.input value (and thus bypass the DA object, is this ugly?)

            foreach (IGH_Param Param in this.Params.Input[0].Sources)
            {

                foreach (GH_Path path in Input.Paths)
                {
                    String nickname = Param.NickName;
                    if (nickname.Length == 0)
                    {
                        this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Nickname of the connected component is empty");
                        nickname = "Anonymous";
                    }
                    List<object> DataList = new List<object>();
                    IEnumerable Data = Param.VolatileData.get_Branch(path);
                    if (Data != null)
                    {
                        foreach (object item in Data)
                        {
                            if (item != null)
                            {
                                DataList.Add(item);
                            }
                            else
                            {
                                DataList.Add("");
                            }
                        }
                    }
                    //
                    // Add the data to the list. If result is a tree or something similar: this means the results will be flattened.

                    if (Data == null || DataList.Count == 0)
                    {

                    }
                    else if (DataList.Count == 1)
                    {
                        // If the component has a single output: name it singular
                        Output.Append(new HashType(nickname, DataList[0]), path);
                    }
                    else if (DataList.Count > 1)
                    {
                        // .. otherwise: add a
                        int j = 0;
                        if (bEnumerate)
                        {
                            foreach (object item in DataList)
                            {
                                Output.Append(new HashType(String.Format("{0}_{1}", nickname, j), item), path);
                                j++;
                            }
                        }
                        else
                        {
                            Output.Append(new HashType(nickname, DataList), path);
                        }
                    }
                }
            }
            DA.SetDataTree(0, Output);
        }
Beispiel #36
0
        protected override void SafeSolveInstance(IGH_DataAccess DA)
        {
            this.InitalizePrivateData();
            GH_Structure<Grasshopper.Kernel.Types.IGH_Goo> geom_tree = new GH_Structure<Grasshopper.Kernel.Types.IGH_Goo>();
            GH_Structure<Decodes_Attributes> attr_tree = new GH_Structure<Decodes_Attributes>();
            if ((DA.GetDataTree<Grasshopper.Kernel.Types.IGH_Goo>(0, out geom_tree)) && (DA.GetDataTree<Decodes_Attributes>(1, out attr_tree)))
            {
                if (geom_tree.PathCount != attr_tree.Branches.Count) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "geometry and property inputs do not have the same number of branches.  check your inputs."); return; }

                for (int b = 0; b < geom_tree.Branches.Count; b++)
                {
                    List<Grasshopper.Kernel.Types.IGH_Goo> geom_given = geom_tree.Branches[b];
                    List<Decodes_Attributes> attr_given = attr_tree.Branches[b];

                    if (geom_given.Count != attr_given.Count) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "geometry and property inputs are not lists of the same length.  check your inputs."); return; }

                    for (int i = 0; i < geom_given.Count; i++)
                    {
                        if (!(geom_given[i] is Grasshopper.Kernel.Types.IGH_GeometricGoo)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Did you give me something that isn't geometry?"); continue; }
                        try
                        {
                            m_obj.Add((Grasshopper.Kernel.Types.IGH_GeometricGoo)geom_given[i]);
                            if (!(attr_given[i] is Decodes_Attributes)) m_att.Add(new Decodes_Attributes());
                            else
                            {
                                m_att.Add(attr_given[i]);
                                if (!required_layers.Contains(attr_given[i].layer)) required_layers.Add(attr_given[i].layer);
                            }
                            m_branch_index.Add(b);
                        }
                        catch (Exception e)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Did you give me something that looks like geometry, but isn't?\n" + e.Message);
                        }

                    }
                }
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //declare input variables to load into

            AuthToken authToken = new AuthToken();
            string sheetName = "";
            string worksheet = "";
            bool rowsColumns = false;

            GH_Structure<GH_String> addresses = new GH_Structure<GH_String>();
            GH_Structure<GH_String> data = new GH_Structure<GH_String>();
            bool write = false;

            //declare output variables
            GH_Structure<GH_String> addressesOut = new GH_Structure<GH_String>();

            //get data from inputs
            if (!DA.GetData<AuthToken>("Token", ref authToken))
            {
                return; //exit if no token given
            }
            if (!authToken.IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The provided authentication token appears to be invalid. Try re-running the Google Authenticator component.");
                return; //exit if token invalid
            }

            if (!DA.GetData<string>("Name", ref sheetName))
            {
                return; //exit if no name given
            }
            DA.GetData<string>("Worksheet", ref worksheet);

            DA.GetData<bool>("Organize by Rows or Columns", ref rowsColumns);
            DA.GetDataTree<GH_String>("Address", out addresses);
            DA.GetDataTree<GH_String>("Data", out data);
            DA.GetData<bool>("Write", ref write);

            if (!write) return; //exit if write is not true

            //check each specified address for validity
            foreach (GH_String address in addresses.AllData(true))
            {
                if (!GDriveUtil.isValidAddress(address.ToString()))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error,"Not all addresses are specified in a valid format.");
                    return;
                }
            }

            //setup auth and factory
            //set up oAuth parameters
            OAuth2Parameters parameters = GDriveUtil.GetParameters(authToken);
            SpreadsheetsService service = GDriveUtil.GetSpreadsheetsService(parameters);

            //find spreadsheet by name
            SpreadsheetEntry spreadsheet = GDriveUtil.findSpreadsheetByName(sheetName, service);
            if (spreadsheet == null) //if the spreadsheet is not found
            {
                if (createNewSpreadsheets) //if the user has elected to create new spreadsheets
                {
                   List<string> worksheets = new List<string>();
                   if (!String.IsNullOrEmpty(worksheet))
                   {
                       worksheets.Add(worksheet); //create a 1-item list with the worksheet name
                   }
                    spreadsheet = CreateSpreadsheet.createNewSpreadsheet(this, authToken, sheetName, worksheets, false); //create the spreadsheet
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified spreadsheet not found.");
                    return;
                }
            }
            //find worksheet by name
            WorksheetEntry worksheetEntry = GDriveUtil.findWorksheetByName(worksheet, spreadsheet);
            if (worksheetEntry == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified worksheet not found.");
                return;
            }

            uint maxRow = 0;
            uint maxCol = 0;
            // set up dictionary<Cell address, cell input>
            // associate each input value with a corresponding address
            Dictionary<string, string> writeMap = constructWriteMap(addresses, data, rowsColumns, ref maxRow, ref maxCol, ref addressesOut);

                //expand worksheet if necessary
                if (worksheetEntry.Rows < maxRow)
                {

                        worksheetEntry.Rows = maxRow;
                        worksheetEntry.Etag = "*"; //required for compatibility with "new" google sheets (see:  http://stackoverflow.com/questions/22719170/updating-cell-in-google-spreadsheets-returns-error-missing-resource-version-id)
                        worksheetEntry.Update();

                }

                if (worksheetEntry.Cols < maxCol)
                {

                        worksheetEntry.Cols = maxCol;
                        worksheetEntry.Etag = "*"; //required for compatibility with "new" google sheets (see:  http://stackoverflow.com/questions/22719170/updating-cell-in-google-spreadsheets-returns-error-missing-resource-version-id)
                        worksheetEntry.Update();

                }

                //set bounds of cell query
                CellQuery cellQuery = new CellQuery(worksheetEntry.CellFeedLink);
                cellQuery.MinimumColumn = 0;
                cellQuery.MinimumRow = 0;
                cellQuery.MaximumColumn = maxCol;
                cellQuery.MaximumRow = maxRow;
                cellQuery.ReturnEmpty = ReturnEmptyCells.yes;

                //retrieve cellfeed
                CellFeed cellFeed = service.Query(cellQuery);

                //convert cell entries to dictionary
               Dictionary<string,AtomEntry> cellDict = cellFeed.Entries.ToDictionary(k => k.Title.Text);

                CellFeed batchRequest = new CellFeed(cellQuery.Uri, service);

                //set up batchrequest
                foreach (KeyValuePair<string, string> entry in writeMap)
                {
                    AtomEntry atomEntry;
                    cellDict.TryGetValue(entry.Key, out atomEntry);
                    CellEntry batchEntry = atomEntry as CellEntry;
                    batchEntry.InputValue = entry.Value;
                    batchEntry.Etag = "*"; //required for compatibility with "new" google sheets (see:  http://stackoverflow.com/questions/22719170/updating-cell-in-google-spreadsheets-returns-error-missing-resource-version-id)
                    batchEntry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.update);

                    batchRequest.Entries.Add(batchEntry);
                }
                CellFeed batchResponse = (CellFeed)service.Batch(batchRequest, new Uri(cellFeed.Batch));

                // Check the results
                bool isSuccess = true;
                foreach (CellEntry entry in batchResponse.Entries)
                {
                    string batchId = entry.BatchData.Id;
                    if (entry.BatchData.Status.Code != 200)
                    {
                        isSuccess = false;
                        GDataBatchStatus status = entry.BatchData.Status;
                    }
                }

                if (!isSuccess)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Update operations failed");
                }

            //output addresses
            DA.SetDataTree(0, addressesOut); //write addressesOut to first output parameter
        }
Beispiel #38
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //declare input variables to load into

            AuthToken authToken = new AuthToken();
            string sheetName = "";
            string worksheet = "";
            bool includeBlankCells = false;
            bool rangeSpecified = false;
            SpreadsheetRange range = new SpreadsheetRange();
            bool rowsColumns = false;
            bool formulasValues = false;

            //declare output variables
            List<string> metaData = new List<string>();
            GH_Structure<GH_String> values = new GH_Structure<GH_String>();
            GH_Structure<GH_String> addresses = new GH_Structure<GH_String>();

            //get data from inputs
            if (!DA.GetData<AuthToken>("Token", ref authToken))
            {
                return; //exit if no token
            }
            if (!authToken.IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The provided authentication token appears to be invalid. Try re-running the Google Authenticator component.");
                return; //exit if invalid token
            }

            if (!DA.GetData<string>("Name", ref sheetName))
            {
                return; //exit if no name provided
            }
            DA.GetData<string>("Worksheet", ref worksheet);
            DA.GetData<bool>("Include Blank Cells?", ref includeBlankCells);
            if (DA.GetData<SpreadsheetRange>("Spreadsheet Range", ref range))
            {
                rangeSpecified = true;
            }
            DA.GetData<bool>("Organize by Rows or Columns", ref rowsColumns);
            DA.GetData<bool>("Read Formulas or Values", ref formulasValues);

            //set up oAuth parameters
            OAuth2Parameters parameters = GDriveUtil.GetParameters(authToken);
            //establish spreadsheetservice
            SpreadsheetsService service = GDriveUtil.GetSpreadsheetsService(parameters);
            //get spreadsheet by name
            SpreadsheetEntry spreadsheet = GDriveUtil.findSpreadsheetByName(sheetName, service);

            if (spreadsheet == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified Spreadsheet not found.");
                return;
            }

            //gather spreadsheet metadata
            metaData.Add("Spreadsheet Name: " + spreadsheet.Title.Text);
            metaData.Add("Last Updated: " + spreadsheet.Updated.ToString());
            metaData.Add("Worksheets: " + worksheetList(spreadsheet.Worksheets));

            //find the specified worksheet, or first one if none specified
            WorksheetEntry worksheetEntry = null;
            worksheetEntry = GDriveUtil.findWorksheetByName(worksheet, spreadsheet);

            if (worksheetEntry == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified worksheet not found.");
                return;
            }

            // Fetch the cell feed of the worksheet.
            CellQuery cellQuery = new CellQuery(worksheetEntry.CellFeedLink);
            if (rangeSpecified)
            {
                if (range.TestValid())
                {
                    cellQuery.MinimumColumn = range.startColumn();
                    cellQuery.MinimumRow = range.startRow();
                    cellQuery.MaximumColumn = range.endColumn();
                    cellQuery.MaximumRow = range.endRow();
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid Range Specified");
                    return;
                }
            }

            //passes null values if user wants the blank cells represented, otherwise they are omitted from output.
            if (includeBlankCells)
            {
                cellQuery.ReturnEmpty = ReturnEmptyCells.yes;
            }
            //set up cell feed
            CellFeed cellFeed = service.Query(cellQuery);

            foreach (CellEntry cell in cellFeed.Entries) //for all the cells in the feed
            {

                GH_Path path = new GH_Path(DA.Iteration); //set up data path for data tree
                uint e = (rowsColumns) ? cell.Row : cell.Column; //decide whether to structure data path by row or column
                path = path.AppendElement((int)e);

                string v = (formulasValues) ? cell.InputValue : cell.Value; //decide whether to get the cell formula or the cell value as output
                values.Append(new GH_String(v), path); //save the value of the cell

                addresses.Append(new GH_String(cell.Title.Text), path); // save the address of the cell
            }

            //set output data
            DA.SetDataTree(0, values);
            DA.SetDataTree(1, addresses);
            DA.SetDataList("Sheet Info", metaData);
        }
        //this method associates addresses with every piece of data. Responds intelligently to different cases of user input
        private Dictionary<string, string> constructWriteMap(GH_Structure<GH_String> addresses, GH_Structure<GH_String> data, bool rowColumn, ref uint maxRow, ref uint maxCol, ref GH_Structure<GH_String> addressesOut)
        {
            Dictionary<string, string> writeMap = new Dictionary<string, string>();
            bool incrementBranches = false;
            bool incrementItems = false;

            //case 1: 1 address for entire tree
            //increment branches + increment items = true
            //case 2: 1 address per list
            //increment branches = false + increment items = true;
            //case 3: 1 address per item
            //increment branches + increment items = false

            bool validDataMatch = false;

            if (addresses.DataCount == 1) // case 1
            {
                incrementBranches = true;
                incrementItems = true;
                validDataMatch = true;
            }
            else if(addresses.Branches.Count==data.Branches.Count)
            {
                if (oneItemPerBranch(addresses))//one item in each address branch, case 2
                {
                    incrementItems = true;
                    validDataMatch = true;
                }
                else if(sameBranchLengths(data,addresses)){
                    //otherwise leave both to false in case 3
                    validDataMatch = true;
                }

            }

            if (!validDataMatch)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Either provide one address per data item, one address per list, or one address for the whole tree. \n In the latter two cases, sequential addresses are calculated automatically.");
                return writeMap; //return empty write map - nothing happens
            }

            for (int i_branch = 0; i_branch < data.Branches.Count; i_branch++)
            {
                List<GH_String> dataBranch = data.Branches[i_branch];
                List<GH_String> addressBranch = addresses.Branches[Math.Min(i_branch, addresses.Branches.Count - 1)];
                for (int i = 0; i < dataBranch.Count; i++)
                {
                    string dataItem = dataBranch[i].ToString();
                    string addressItem = addressBranch[Math.Min(i, addressBranch.Count - 1)].ToString();

                    int colOffset = 0;
                    int rowOffset = 0;
                    if (rowColumn) // if true, data is structured in rows - otherwise in columns
                    {
                      colOffset = (incrementItems) ? i : 0;
                        rowOffset = (incrementBranches) ? i_branch : 0;
                    }
                    else
                    {
                        colOffset = (incrementBranches) ? i_branch : 0;
                        rowOffset = (incrementItems) ? i : 0;
                    }

                    long colAddress = GDriveUtil.colFromAddress(addressItem) + colOffset;
                    long rowAddress = GDriveUtil.rowFromAddress(addressItem) + rowOffset;

                    if (colAddress > maxCol) maxCol = (uint)colAddress;
                    if (rowAddress > maxRow) maxRow = (uint)rowAddress;

                    addressItem = GDriveUtil.addressFromCells(colAddress, rowAddress);
                    //list of cell addresses that corresponds to input data order
                    addressesOut.Append(new GH_String(addressItem),data.Paths[i_branch]);
                    //dictionary of addresses + data to write - prep for batch write operation.
                    try
                    {
                        writeMap.Add(addressItem, dataItem); //will throw an error if you try to write to the same cell twice - key is already in dictionary.

                    }
                    catch
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "You are trying to write into the same cell twice. Some data is being lost");
                    }
                }

            }

            return writeMap;
        }
Beispiel #40
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            #region INPUTS

               List<Curve> things = new List<Curve>();
            if (!DA.GetDataList(0, things)) return;

            #region Optional Inputs
            int mainSegmentCount = 0;
            if (!DA.GetData(1, ref mainSegmentCount)) { }
            int subSegmentCount = 0;
            if (!DA.GetData(2, ref subSegmentCount)) { }
            double maxAngleRadians = 0.05;
            if (!DA.GetData(3, ref maxAngleRadians)) { }
            double maxChordLengthRatio = 0.1;
            if (!DA.GetData(4, ref maxChordLengthRatio)) { }

            double maxAspectRatio = 0;
            if (!DA.GetData(5, ref maxAspectRatio)) { }
            double tolerance = 0;
            if (!DA.GetData(6, ref tolerance)) { }
            double minEdgeLength = 0.1;
            if (!DA.GetData(7, ref minEdgeLength)) { }
            double maxEdgeLength = 0;
            if (!DA.GetData(8, ref maxEdgeLength)) { }
            bool keepStartPoint = true;
            if (!DA.GetData(9, ref keepStartPoint)) { }
            #endregion

            #endregion

            List<Curve>[] lines = new List<Curve>[things.Count];
            List<PolylineCurve> polylines = new List<PolylineCurve>();
            GH_Structure<GH_Curve> Lines = new GH_Structure<GH_Curve>();

            for (int i = 0; i < things.Count; i++)
            {
                SilkwormSegment segment = new SilkwormSegment(things[i], mainSegmentCount, subSegmentCount, maxAngleRadians, maxChordLengthRatio, maxAspectRatio, tolerance, minEdgeLength, maxEdgeLength, keepStartPoint);
                lines[i] = new List<Curve>();
                lines[i].AddRange(segment.Segments);
                PolylineCurve pline = new PolylineCurve(segment.Pline);
                polylines.Add(pline);
            }

            //        if (lines.GetUpperBound(0) > 1)
            //        {
            //            for (int i = 0; i < lines.Length; i++)
            //            {

            //                if (lines[i] != null)
            //                {
            //                    for (int j = 0; j < lines[i].Count; j++)
            //                    {

            //                        GH_Curve glines = new GH_Curve(lines[i][j]);
            //                        Lines.Insert(glines, new GH_Path(i), j);
            //                    }

            //                }
            //            }
            //        }
            //if (!DA.SetDataTree(0, Lines)) { return; }
            if (!DA.SetDataList(0, polylines)) { return; }
        }
Beispiel #41
0
        private List<RevitObject> AssignOrientation(List<RevitObject> currentList, GH_Structure<GH_Vector> orientations)
        {
            List<RevitObject> current = currentList;
            List<RevitObject> tempObj = new List<RevitObject>();
            for (int i = 0; i < orientations.Branches.Count; i++)
            {
                RevitObject ro = current[i];
                try
                {
                    Vector3d v = orientations[i][0].Value;

                    LyrebirdPoint p = new LyrebirdPoint {X = v.X, Y = v.Y, Z = v.Z};
                    ro.Orientation = p;
                    tempObj.Add(ro);
                }
                catch (Exception exception)
                {
                  Debug.WriteLine(exception.Message);
                }
            }
            return tempObj;
        }
Beispiel #42
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool runCommand = false;
            GH_Structure<GH_Point> origPoints = new GH_Structure<GH_Point>();
            GH_Structure<GH_Point> adaptPoints = new GH_Structure<GH_Point>();
            GH_Structure<GH_Curve> curves = new GH_Structure<GH_Curve>();
            GH_Structure<GH_Vector> orientations = new GH_Structure<GH_Vector>();
            GH_Structure<GH_Vector> faceOrientations = new GH_Structure<GH_Vector>();
            DA.GetData(0, ref runCommand);
            DA.GetDataTree(1, out origPoints);
            DA.GetDataTree(2, out adaptPoints);
            DA.GetDataTree(3, out curves);
            DA.GetDataTree(4, out orientations);
            DA.GetDataTree(5, out faceOrientations);

            // Make sure the family and type is set before running the command.
            if (runCommand && (familyName == null || familyName == "Not Selected"))
            {
                message = "Please select a family/type by double-clicking on the component before running the command.";
            }
            else if (runCommand)
            {
                // Get the scale
                GHInfo ghi = new GHInfo();
                GHScale scale = ghi.GetScale(Rhino.RhinoDoc.ActiveDoc);

                // Send to Revit
                LyrebirdChannel channel = new LyrebirdChannel(appVersion);
                channel.Create();

                if (channel != null)
                {
                    string documentName = channel.DocumentName();
                    if (documentName != null)
                    {
                        // Create RevitObjects
                        List<RevitObject> obj = new List<RevitObject>();

                        #region OriginPoint Based
                        if (origPoints != null && origPoints.Branches.Count > 0)
                        {
                            List<RevitObject> tempObjs = new List<RevitObject>();
                            // make sure the branches match the datacount
                            if (origPoints.Branches.Count == origPoints.DataCount)
                            {
                                for (int i = 0; i < origPoints.Branches.Count; i++)
                                {
                                    GH_Point ghpt = origPoints[i][0];
                                    LyrebirdPoint point = new LyrebirdPoint
                                    {
                                        X = ghpt.Value.X,
                                        Y = ghpt.Value.Y,
                                        Z = ghpt.Value.Z
                                    };

                                    RevitObject ro = new RevitObject
                                    {
                                        Origin = point,
                                        FamilyName = familyName,
                                        TypeName = typeName,
                                        Category = category,
                                        CategoryId = categoryId,
                                        GHPath = origPoints.Paths[i].ToString(),
                                        GHScaleFactor = scale.ScaleFactor,
                                        GHScaleName = scale.ScaleName
                                    };

                                    tempObjs.Add(ro);
                                }
                                obj = tempObjs;
                            }
                            else
                            {
                                // Inform the user they need to graft their inputs.  Only one point per branch
                                System.Windows.Forms.MessageBox.Show("Warning:\n\nEach Branch represents an object, " +
                                    "so origin point based elements should be grafted so that each point is on it's own branch.");
                            }
                        }
                        #endregion

                        #region AdaptiveComponents
                        else if (adaptPoints != null && adaptPoints.Branches.Count > 0)
                        {
                            // generate adaptive components
                            List<RevitObject> tempObjs = new List<RevitObject>();
                            for (int i = 0; i < adaptPoints.Branches.Count; i++)
                            {
                                RevitObject ro = new RevitObject();
                                List<LyrebirdPoint> points = new List<LyrebirdPoint>();
                                for (int j = 0; j < adaptPoints.Branches[i].Count; j++)
                                {
                                    LyrebirdPoint point = new LyrebirdPoint(adaptPoints.Branches[i][j].Value.X, adaptPoints.Branches[i][j].Value.Y, adaptPoints.Branches[i][j].Value.Z);
                                    points.Add(point);
                                }
                                ro.AdaptivePoints = points;
                                ro.FamilyName = familyName;
                                ro.TypeName = typeName;
                                ro.Origin = null;
                                ro.Category = category;
                                ro.CategoryId = categoryId;
                                ro.GHPath = adaptPoints.Paths[i].ToString();
                                ro.GHScaleFactor = scale.ScaleFactor;
                                ro.GHScaleName = scale.ScaleName;
                                tempObjs.Add(ro);
                            }
                            obj = tempObjs;

                        }
                        #endregion

                        #region Curve Based
                        else if (curves != null && curves.Branches.Count > 0)
                        {
                            // Get curves for curve based components

                            // Determine if we're profile or line based
                            if (curves.Branches.Count == curves.DataCount)
                            {
                                // Determine if the curve is a closed planar curve
                                Curve tempCrv = curves.Branches[0][0].Value;
                                if (tempCrv.IsPlanar(0.00000001) && tempCrv.IsClosed)
                                {
                                    // Closed planar curve
                                    List<RevitObject> tempObjs = new List<RevitObject>();
                                    for (int i = 0; i < curves.Branches.Count; i++)
                                    {
                                        Curve crv = curves[i][0].Value;
                                        List<Curve> rCurves = new List<Curve>();
                                        bool getCrvs = CurveSegments(rCurves, crv, true);
                                        if (rCurves.Count > 0)
                                        {
                                            RevitObject ro = new RevitObject();
                                            List<LyrebirdCurve> lbCurves = new List<LyrebirdCurve>();
                                            for (int j = 0; j < rCurves.Count; j++)
                                            {
                                                LyrebirdCurve lbc;
                                                lbc = GetLBCurve(rCurves[j]);
                                                lbCurves.Add(lbc);
                                            }
                                            ro.Curves = lbCurves;
                                            ro.FamilyName = familyName;
                                            ro.Category = category;
                                            ro.CategoryId = categoryId;
                                            ro.TypeName = typeName;
                                            ro.Origin = null;
                                            ro.GHPath = curves.Paths[i].ToString();
                                            ro.GHScaleFactor = scale.ScaleFactor;
                                            ro.GHScaleName = scale.ScaleName;
                                            tempObjs.Add(ro);
                                        }
                                    }
                                    obj = tempObjs;

                                }
                                else if (!tempCrv.IsClosed)
                                {
                                    // Line based.  Can only be arc or linear curves
                                    List<RevitObject> tempObjs = new List<RevitObject>();
                                    for (int i = 0; i < curves.Branches.Count; i++)
                                    {

                                        Curve ghc = curves.Branches[i][0].Value;
                                        // Test that there is only one curve segment
                                        PolyCurve polycurve = ghc as PolyCurve;
                                        if (polycurve != null)
                                        {
                                            Curve[] segments = polycurve.Explode();
                                            if (segments.Count() != 1)
                                            {
                                                break;
                                            }
                                        }
                                        if (ghc != null)
                                        {
                                            //List<LyrebirdPoint> points = new List<LyrebirdPoint>();
                                            LyrebirdCurve lbc = GetLBCurve(ghc);
                                            List<LyrebirdCurve> lbcurves = new List<LyrebirdCurve> { lbc };

                                            RevitObject ro = new RevitObject
                                            {
                                                Curves = lbcurves,
                                                FamilyName = familyName,
                                                Category = category,
                                                CategoryId = categoryId,
                                                TypeName = typeName,
                                                Origin = null,
                                                GHPath = curves.Paths[i].ToString(),
                                                GHScaleFactor = scale.ScaleFactor,
                                                GHScaleName = scale.ScaleName
                                            };

                                            tempObjs.Add(ro);
                                        }
                                    }
                                    obj = tempObjs;
                                }
                            }
                            else
                            {
                                // Make sure all of the curves in each branch are closed
                                bool allClosed = true;
                                DataTree<CurveCheck> crvTree = new DataTree<CurveCheck>();
                                for (int i = 0; i < curves.Branches.Count; i++)
                                {
                                    List<GH_Curve> ghCrvs = curves.Branches[i];
                                    List<CurveCheck> checkedcurves = new List<CurveCheck>();
                                    GH_Path path = new GH_Path(i);
                                    for (int j = 0; j < ghCrvs.Count; j++)
                                    {
                                        Curve c = ghCrvs[j].Value;
                                        if (c.IsClosed)
                                        {
                                            AreaMassProperties amp = AreaMassProperties.Compute(c);
                                            if (amp != null)
                                            {
                                                double area = amp.Area;
                                                CurveCheck cc = new CurveCheck(c, area);
                                                checkedcurves.Add(cc);
                                            }
                                        }
                                        else
                                        {
                                            allClosed = false;
                                        }
                                    }
                                    if (allClosed)
                                    {
                                        // Sort the curves by area
                                        checkedcurves.Sort((x, y) => x.Area.CompareTo(y.Area));
                                        checkedcurves.Reverse();
                                        foreach (CurveCheck cc in checkedcurves)
                                        {
                                            crvTree.Add(cc, path);
                                        }
                                    }
                                }

                                if (allClosed)
                                {
                                    // Determine if the smaller profiles are within the larger
                                    bool allInterior = true;
                                    List<RevitObject> tempObjs = new List<RevitObject>();
                                    for (int i = 0; i < crvTree.Branches.Count; i++)
                                    {
                                        try
                                        {
                                            List<int> crvSegmentIds = new List<int>();
                                            List<LyrebirdCurve> lbCurves = new List<LyrebirdCurve>();
                                            List<CurveCheck> checkedCrvs = crvTree.Branches[i];
                                            Curve outerProfile = checkedCrvs[0].Curve;
                                            double outerArea = checkedCrvs[0].Area;
                                            List<Curve> planarCurves = new List<Curve>();
                                            planarCurves.Add(outerProfile);
                                            double innerArea = 0.0;
                                            for (int j = 1; j < checkedCrvs.Count; j++)
                                            {
                                                planarCurves.Add(checkedCrvs[j].Curve);
                                                innerArea += checkedCrvs[j].Area;
                                            }
                                            // Try to create a planar surface
                                            IEnumerable<Curve> surfCurves = planarCurves;
                                            Brep[] b = Brep.CreatePlanarBreps(surfCurves);
                                            if (b.Count() == 1)
                                            {
                                                // Test the areas
                                                double brepArea = b[0].GetArea();
                                                double calcArea = outerArea - innerArea;
                                                double diff = (brepArea - calcArea) / calcArea;

                                                if (diff < 0.1)
                                                {
                                                    // The profiles probably are all interior
                                                    foreach (CurveCheck cc in checkedCrvs)
                                                    {
                                                        Curve c = cc.Curve;
                                                        List<Curve> rCurves = new List<Curve>();
                                                        bool getCrvs = CurveSegments(rCurves, c, true);

                                                        if (rCurves.Count > 0)
                                                        {
                                                            int crvSeg = rCurves.Count;
                                                            crvSegmentIds.Add(crvSeg);
                                                            foreach (Curve rc in rCurves)
                                                            {
                                                                LyrebirdCurve lbc;
                                                                lbc = GetLBCurve(rc);
                                                                lbCurves.Add(lbc);
                                                            }
                                                        }
                                                    }
                                                    RevitObject ro = new RevitObject();
                                                    ro.Curves = lbCurves;
                                                    ro.FamilyName = familyName;
                                                    ro.Category = category;
                                                    ro.CategoryId = categoryId;
                                                    ro.TypeName = typeName;
                                                    ro.Origin = null;
                                                    ro.GHPath = crvTree.Paths[i].ToString();
                                                    ro.GHScaleFactor = scale.ScaleFactor;
                                                    ro.GHScaleName = scale.ScaleName;
                                                    ro.CurveIds = crvSegmentIds;
                                                    tempObjs.Add(ro);
                                                }
                                            }
                                            else
                                            {
                                                allInterior = false;
                                                message = "Warning:\n\nEach Branch represents an object, " +
                                                "so curve based elements should be grafted so that each curve is on it's own branch, or all curves on a branch should " +
                                                "be interior to the largest, outer boundary.";
                                            }
                                        }
                                        catch
                                        {
                                            allInterior = false;
                                            // Inform the user they need to graft their inputs.  Only one curve per branch
                                            message = "Warning:\n\nEach Branch represents an object, " +
                                                "so curve based elements should be grafted so that each curve is on it's own branch, or all curves on a branch should " +
                                                "be interior to the largest, outer boundary.";
                                        }
                                    }
                                    if (tempObjs.Count > 0)
                                    {
                                        obj = tempObjs;
                                    }
                                }
                            }
                        }
                        #endregion

                        // Orientation
                        if (orientations != null && orientations.Branches.Count > 0)
                        {
                            List<RevitObject> tempList = AssignOrientation(obj, orientations);
                            obj = tempList;
                        }

                        // face orientation
                        if (faceOrientations != null && faceOrientations.Branches.Count > 0)
                        {
                            List<RevitObject> tempList = AssignFaceOrientation(obj, faceOrientations);
                            obj = tempList;
                        }

                        // Parameters...
                        if (Params.Input.Count > 6)
                        {
                            List<RevitObject> currentObjs = obj;
                            List<RevitObject> tempObjs = new List<RevitObject>();
                            for (int r = 0; r < currentObjs.Count; r++)
                            {
                                RevitObject ro = currentObjs[r];
                                List<RevitParameter> revitParams = new List<RevitParameter>();
                                for (int i = 6; i < Params.Input.Count; i++)
                                {

                                    RevitParameter rp = new RevitParameter();
                                    IGH_Param param = Params.Input[i];
                                    string paramInfo = param.Description;
                                    string[] pi = paramInfo.Split(new[] { "\n", ":" }, StringSplitOptions.None);
                                    string paramName = null;
                                    try
                                    {
                                        paramName = pi[1].Substring(1);
                                        string paramStorageType = pi[5].Substring(1);
                                        rp.ParameterName = paramName;
                                        rp.StorageType = paramStorageType;
                                    }
                                    catch (Exception ex)
                                    {
                                        Debug.WriteLine(ex.Message);
                                    }
                                    if (paramName != null)
                                    {
                                        GH_Structure<IGH_Goo> data = null;
                                        try
                                        {
                                            DA.GetDataTree(i, out data);
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                        if (data != null)
                                        {
                                            string value = data[r][0].ToString();
                                            rp.Value = value;
                                            revitParams.Add(rp);
                                        }
                                    }

                                }
                                ro.Parameters = revitParams;
                                tempObjs.Add(ro);
                            }
                            obj = tempObjs;
                        }

                        // Send the data to Revit to create and/or modify family instances.
                        if (obj != null && obj.Count > 0)
                        {
                            try
                            {
                                string docName = channel.DocumentName();
                                if (docName == null || docName == string.Empty)
                                {
                                    message = "Could not contact the lyrebird server.  Make sure it's running and try again.";
                                }
                                else
                                {
                                    string nn = NickName;
                                    if (nn == null || nn.Length == 0)
                                    {
                                        nn = "LBOut";
                                    }
                                    channel.CreateOrModify(obj, InstanceGuid, NickName);
                                    message = obj.Count.ToString() + " objects sent to the lyrebird server.";
                                }
                            }
                            catch
                            {
                                message = "Could not contact the lyrebird server.  Make sure it's running and try again.";
                            }
                        }
                        channel.Dispose();
                        try
                        {
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        message = "Error\n" + "The Lyrebird Service could not be found.  Ensure Revit is running, the Lyrebird server plugin is installed, and the server is active.";
                    }
                }
            }
            else
            {
                message = null;
            }

            // Check if the revit information is set
            if (familyName != null || (familyName != "Not Selected" && typeName != "Not Selected"))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Family: " + familyName);
                sb.AppendLine("Type: " + typeName);
                sb.AppendLine("Category: " + category);
                for (int i = 0; i < inputParameters.Count; i++)
                {
                    RevitParameter rp = inputParameters[i];
                    string type = "Instance";
                    if (rp.IsType)
                    {
                        type = "Type";
                    }
                    sb.AppendLine(string.Format("Parameter{0}: {1}  /  {2}  /  {3}", (i + 1).ToString(CultureInfo.InvariantCulture), rp.ParameterName, rp.StorageType, type));
                }
                objMessage = sb.ToString();
            }
            else
            {
                objMessage = "No data type set.  Double-click to set data type";
            }

            DA.SetData(0, objMessage);
            DA.SetData(1, message);
        }
Beispiel #43
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            #region INPUTS
            // import silkwormSettings file
            List<string> silkwormSettings = new List<string>();
            if (!DA.GetDataList(0, silkwormSettings)) return;

            List<Brep> things = new List<Brep>();
            if (!DA.GetDataList(1, things)) return;
            // import Silkworm Movement

            SilkwormUtility sUtil = new SilkwormUtility();
            Dictionary<string, string> Settings = sUtil.convertSettings(silkwormSettings);
            SilkwormCalculator calc = new SilkwormCalculator(Settings);

            #region Optional Inputs

            int infType = 0;
            if (!DA.GetData(2, ref infType)) { }

            List<double> spacing = new List<double>();
            if (!DA.GetDataList(3, spacing)) { }

            List<double> infDens = new List<double>();
            if (!DA.GetDataList(4, infDens)) { }
            List<double> infRot = new List<double>();
            if (!DA.GetDataList(5, infRot)) { }

            #endregion

            if (spacing.Count<1)
            {
                spacing.Add(0.66);
                //TODO Calculator

            }
            if (infDens.Count < 1)
            {
                infDens.Add(double.Parse(Settings["fill_density"]));

            }
            if (infRot.Count < 1)
            {
                infRot.Add(double.Parse(Settings["fill_angle"]));

            }
            #endregion

            SilkwormSkein skein = new SilkwormSkein(Settings, things);

            //Switch depending on which infill type is selected by input
            if (infType == 0)
            {
                //Match length of data
                if (spacing.Count != things.Count)
                {
                    List<double> newspacing = new List<double>();
                    for (int e = 0; e < things.Count; e++)
                    {
                        newspacing.Add(spacing[0]);
                    }
                    spacing = newspacing;
                }

                skein.Skinner(spacing);
            }
            if (infType == 1)
            {
                //Match length of data
                if (infDens.Count != things.Count)
                {
                    List<double> newinfDens = new List<double>();
                    for (int e = 0; e < things.Count; e++)
                    {
                        newinfDens.Add(infDens[0]);
                    }
                    spacing = newinfDens;
                }
                if (infRot.Count != things.Count)
                {
                    List<double> newinfRot = new List<double>();
                    for (int e = 0; e < things.Count; e++)
                    {
                        newinfRot.Add(infRot[0]);
                    }
                    spacing = newinfRot;
                }

                skein.Filler(infDens, infRot);
            }

            //Reflect Errors and Warnings

            foreach (string message in skein.ErrorMessages)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, message);

            }
            foreach (string message in skein.WarningMessages)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);

            }

            //Output Holders
            List<Curve>[] plPerimeter = skein.curvePerimeter;
            List<Curve>[] plInfill = skein.curveInfill;

            GH_Structure<GH_Curve> InfillRegion = new GH_Structure<GH_Curve>();

            //Create GH_Structure
            #region Create Structure from Curves

            if (plPerimeter.Length > 0)
            {
                for (int i = 0; i < plPerimeter.Length; i++)
                {
                  if (plPerimeter[i] != null)
                        {
                    for (int j = 0; j < plPerimeter[i].Count; j++)
                    {

                            Curve aShape = plPerimeter[i][j].ToNurbsCurve();

                            GH_Curve gShapes = new GH_Curve(aShape);
                            InfillRegion.Insert(gShapes, new GH_Path(i, 0), j);
                            //}
                        }
                    }
                }
            }
            if (plInfill.Length > 0)
            {
                for (int i = 0; i < plInfill.Length; i++)
                {
            if (plInfill[i] != null)
                        {
                    for (int j = 0; j < plInfill[i].Count; j++)
                    {

                            Curve aShape = plInfill[i][j].ToNurbsCurve();

                            GH_Curve gShapes = new GH_Curve(aShape);
                            InfillRegion.Insert(gShapes, new GH_Path(i, 1), j);
                        }
                    }
                }
            }

            #endregion

            //Output
            if (!DA.SetDataTree(0, InfillRegion)) { return; }
        }