Ejemplo n.º 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);
        }
Ejemplo n.º 2
0
        protected override void SolveInstance(IGH_DataAccess dataAccess)
        {
            if (!dataAccess.GetDataTree(0, out GH_Structure <GH_Brep> breps))
            {
                return;
            }
            if (!dataAccess.GetDataTree(1, out GH_Structure <GH_String> materials))
            {
                return;
            }
            if (!dataAccess.GetDataTree(2, out GH_Structure <GH_Integer> stories))
            {
                return;
            }

            if (breps.Paths.Count != materials.Paths.Count || (breps.Paths.Count != stories.Paths.Count && !stories.IsEmpty))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Geometries, materials and stories must have the same number of items");
                return;
            }

            var filteredBreps = new GH_Structure <GH_Brep> [4];

            for (var i = 0; i < 4; i++)
            {
                filteredBreps[i] = new GH_Structure <GH_Brep>();
            }

            FilterValue(breps, stories, materials, filteredBreps);

            for (var i = 0; i < 4; i++)
            {
                dataAccess.SetDataTree(i, filteredBreps[i]);
            }
        }
Ejemplo n.º 3
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");
            }
        }
Ejemplo n.º 4
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)
        {
            Brep                srf          = null;
            ISolver2D           solver       = new ISolver2D();
            IField              field        = null;
            List <IConstraint>  constraints  = new List <IConstraint>();
            List <ITransfinite> transfinites = new List <ITransfinite>();

            DA.GetData(0, ref srf);
            DA.GetData(1, ref field);
            DA.GetDataList(2, constraints);
            DA.GetDataList(3, transfinites);
            DA.GetData(4, ref solver);

            if (srf.IsSolid || srf.Faces.Count > 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input geometry should be a trimmed/untrimmed surface.");
                return;
            }

            string logInfo;
            GH_Structure <IEntityInfo> entities;
            IMesh mesh = IKernel.IMeshingKernel.CreateShellMeshFromBrep(srf, solver, out logInfo, out entities, constraints, transfinites, field);

            DA.SetData(0, mesh);
            DA.SetDataTree(1, entities);
            DA.SetData(2, logInfo);
        }
Ejemplo n.º 5
0
    protected override void SetOutputs(IGH_DataAccess da)
    {
      outTree = new DataTree<Point3d>();
      GH_Path trunk = new GH_Path(0); // {0}
      GH_Path branch = new GH_Path(); // {}\
      GH_Path limb = new GH_Path();

      
      for (int i = 0; i < particles.Count; i++)
      {
        IQuelea particle = particles[i];
        branch = trunk.AppendElement(i);
        DataTree<Point3d> particlePositionHistoryTree = particle.Position3DHistory.ToTree();

        for (int j = 0; j < particlePositionHistoryTree.BranchCount; j++)
        {
          limb = branch.AppendElement(j);
          //for (int k = particlePositionHistoryTree.Branch(j).Count - 1; k >= 0; k--)
          //{
          //  outTree.Add(particlePositionHistoryTree.Branch(j)[k], limb);
          //}
          outTree.AddRange(particlePositionHistoryTree.Branch(j), limb);
          
        }
      }
      da.SetDataTree(nextOutputIndex++, outTree);
    }
Ejemplo n.º 6
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <GH_Brep> breps   = null;
            GH_Structure <GH_Brep> cutters = null;

            //Brep brep = null;
            //List<Brep> cutters = new List<Brep>();

            if (!DA.GetDataTree("Brep", out breps))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Invalid Brep input.");
                return;
            }
            if (!DA.GetDataTree("Cutters", out cutters))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Invalid cutter input.");
                return;
            }

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

            foreach (var path in breps.Paths)
            {
                resTree.EnsurePath(path);
            }

            List <string> errors = new List <string>();

            Parallel.For(0, breps.Paths.Count, index =>
            {
                GH_Path path = breps.Paths[index];
                if (cutters.PathExists(path) && breps[path].Count > 0)
                {
                    resTree[path].Add(new GH_Brep(breps[path][0].Value.Cut(
                                                      cutters[path].Select(x => x.Value))));
                }
                else if (cutters.PathCount == 1 && breps[path].Count > 0) // Handle a single list of cutters
                {
                    try
                    {
                        if (cutters[0].Count > 0 && breps[path][0] != null)
                        {
                            resTree[path].Add(new GH_Brep(breps[path][0].Value.Cut(
                                                              cutters[cutters.Paths[0]].Select(x => x.Value))));
                        }
                    }
                    catch (Exception ex)
                    {
                        errors.Add(ex.Message);
                    }
                }
                else
                {
                    resTree[path].AddRange(breps[path]);
                }
            });

            DA.SetDataTree(0, resTree);
            DA.SetDataList("Errors", errors);
        }
Ejemplo n.º 7
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Mesh m = new Mesh();

            DA.GetData(0, ref m);

            double d = 1;

            DA.GetData(1, ref d);

            Polyline[] polylinesOriginal = m.GetPolylines();
            Polyline[] polylines         = m.PlanarOffset(d);
            //Polyline[] polylines = m.PlanarBisectorOffset(d);

            DataTree <Polyline> dt = new DataTree <Polyline>();

            for (int i = 0; i < polylines.Length; i++)
            {
                dt.AddRange(new[] { polylinesOriginal[i], polylines[i] }, new Grasshopper.Kernel.Data.GH_Path(i));
            }

            this.PreparePreview(m, DA.Iteration, dt.AllData(), false);

            DA.SetDataTree(0, dt);
        }
Ejemplo n.º 8
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Mesh mesh  = new Mesh();
            Mesh mesh_ = new Mesh();

            DA.GetData(0, ref mesh);

            double scale = 1;

            DA.GetData(1, ref scale);

            //int t = 0;
            //DA.GetData(2, ref t);

            Polyline[][] pairplines = null;
            var          m          = mesh.ProjectPairsMesh(scale, ref pairplines);

            foreach (var mm in m)
            {
                mm.Clean();
                mesh_.Append(mm);
            }
            this.PreparePreview(mesh_, DA.Iteration);


            DA.SetDataList(0, m);
            DA.SetDataTree(1, GrasshopperUtil.JaggedArraysToTree(pairplines, 0));
        }
Ejemplo n.º 9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Grasshopper.Kernel.Types.GH_Line> lines = new List <Grasshopper.Kernel.Types.GH_Line>();

            if (!DA.GetDataList <Grasshopper.Kernel.Types.GH_Line>(0, lines))
            {
                return;
            }


            List <Line> RhinoLines = new List <Line>();

            foreach (GH_Line l in lines)
            {
                RhinoLines.Add(l.Value);
            }

            var GraphData = NGonsCore.Graphs.LineGraph.GetGraphData(RhinoLines);

            DA.SetDataList(0, GraphData.Item1);
            DA.SetDataList(1, GraphData.Item2);
            DA.SetDataList(2, GraphData.Item3);
            DA.SetDataList(3, GraphData.Item4);
            DA.SetDataList(4, GraphData.Item5);
            DA.SetDataTree(5, GraphData.Item6);
        }
Ejemplo n.º 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)
        {
            Curve               crv          = null;
            ISolver2D           solver       = new ISolver2D();
            List <IConstraint>  constraints  = new List <IConstraint>();
            List <ITransfinite> transfinites = new List <ITransfinite>();
            IField              field        = null;

            DA.GetData(0, ref crv);
            DA.GetData(1, ref field);
            DA.GetDataList(2, constraints);
            DA.GetDataList(3, transfinites);
            DA.GetData(4, ref solver);

            if (crv.IsClosed)
            {
                string logInfo;
                GH_Structure <IEntityInfo> entities;
                IMesh mesh = IKernel.IMeshingKernel.CreateShellMeshFromClosedCurve(crv, solver, out logInfo, out entities, constraints, transfinites, field);

                DA.SetData(0, mesh);
                DA.SetDataTree(1, entities);
                DA.SetData(2, logInfo);
            }
            else
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Curve should be closed.");
            }
        }
Ejemplo n.º 11
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)
        {
            counter++;
            DA.GetData(1, ref n);
            n = Math.Max(1, n);

            if (counter % n == 0)
            {
                Flex flex = null;


                DA.GetData(0, ref flex);

                if (flex != null)
                {
                    List <FlexParticle> part = flex.Scene.GetAllParticles();
                    List <int>          springsPairIndices = flex.Scene.GetSpringPairIndices();

                    lineTree = new GH_Structure <GH_Line>();

                    for (int i = 0; i < springsPairIndices.Count / 2; i++)
                    {
                        lineTree.Append(
                            new GH_Line(
                                new Line(
                                    new Point3d(part[springsPairIndices[2 * i]].PositionX, part[springsPairIndices[2 * i]].PositionY, part[springsPairIndices[2 * i]].PositionZ),
                                    new Point3d(part[springsPairIndices[2 * i + 1]].PositionX, part[springsPairIndices[2 * i + 1]].PositionY, part[springsPairIndices[2 * i + 1]].PositionZ))),
                            new GH_Path(part[springsPairIndices[2 * i]].GroupIndex));
                    }
                }
            }

            DA.SetDataTree(0, lineTree);
        }
Ejemplo n.º 12
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)
        {
            Brep                geom          = null;
            ISolver3D           solver        = new ISolver3D();
            List <IConstraint>  constraints   = new List <IConstraint>();
            List <ITransfinite> transfinites  = new List <ITransfinite>();
            List <int>          excludeSrfTag = new List <int>();
            IField              field         = null;

            DA.GetData(0, ref geom);
            DA.GetData(1, ref offset);
            DA.GetData(2, ref cut);
            DA.GetDataList(3, excludeSrfTag);
            DA.GetData(4, ref field);
            DA.GetDataList(5, constraints);
            DA.GetDataList(6, transfinites);
            DA.GetData(7, ref solver);

            if (geom.IsSolid)
            {
                string logInfo;
                GH_Structure <IEntityInfo> entities;
                IMesh mesh = IKernel.IMeshingKernel.CreateVolumeMeshFromThickSolid(geom, excludeSrfTag, offset, cut, solver, out logInfo, out entities, constraints, transfinites, field);

                DA.SetData(0, mesh);
                DA.SetDataTree(1, entities);
                DA.SetData(2, logInfo);
            }
            else
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Brep should be closed.");
            }
        }
Ejemplo n.º 13
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Mesh> mesh = new List <Mesh>();

            if (DA.GetDataList(0, mesh))
            {
                List <int>[] mc = MeshUtilSimple.MeshCollisions(mesh);
                DA.SetDataTree(0, GrasshopperUtil.ArrayOfListsToTree(mc));

                //Next check overlapping faces only if ngons exists

                List <Polyline[]>[] mcPlines = new List <Polyline[]> [mc.Length];

                for (int i = 0; i < mc.Length; i++)
                {
                    mcPlines[i] = new List <Polyline[]>();

                    for (int j = 0; j < mc[i].Count; j++)
                    {
                        //Do it with ngons
                        MeshUtil.GetOverlap(mesh[i], mesh[mc[i][j]], 0.1);
                    }
                }
            }//if
        }
Ejemplo n.º 14
0
        /// <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)
        {
            Boolean openEtabs = false;
            Boolean attaced   = false;
            string  filePath  = "";
            string  modelName = "";
            string  excelPath = "";

            double x = double.NaN;

            List <string>[] modalData;


            DA.GetData(0, ref openEtabs);
            DA.GetData(1, ref attaced);
            DA.GetData(2, ref filePath);
            DA.GetData(3, ref modelName);
            DA.GetData(4, ref excelPath);



            // set a as true to create an etabs model
            if (openEtabs == true)
            {
                // read data from excel
                Excel myExcel = new Excel(excelPath);
                modalData = myExcel.GetExcel();

                DataTree <string> GHmodalData = ToDataTree(modalData);
                x = Etabs.GetModel(attaced, "C:\\Program Files\\Computers and Structures\\ETABS 17\\ETABS.exe", filePath, modelName, GHmodalData);

                DA.SetDataTree(0, GHmodalData);
            }
        }
        /// <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)
        {
            //Take in inputs
            this.readSlidersList();

            var map = new GH_Structure <GH_Number>();

            if (!DA.GetDataTree(1, out map))
            {
                return;
            }
            this.DesignMap = StructureToListOfLists(map);

            if (!DA.GetData(2, ref Index))
            {
                return;
            }


            //Set Current slider list

            //Set Outputs
            var designVector = new List <double>();

            for (int i = 0; i < this.DesignMap[Index].Count; i++)
            {
                designVector.Add(this.DesignMap[Index][i]);
            }

            DA.SetDataTree(0, ListToTree <double>(designVector));
        }
Ejemplo n.º 16
0
Archivo: Edges.cs Proyecto: feklee/san
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var connectionType = new ConnectionType();

            DA.GetData(0, ref connectionType);
            var connection = connectionType.Value;

            var d = connection.graph;

            if (d == null)
            {
                return;
            }

            var edgeTree  = new DataTree <string>();
            var pathIndex = 0;

            foreach (var edge in d.edges)
            {
                var nodeIdsOfEdge = new List <string>();
                foreach (var nodeId in edge)
                {
                    nodeIdsOfEdge.Add(nodeId);
                }
                edgeTree.AddRange(nodeIdsOfEdge, new Grasshopper.Kernel.Data.GH_Path(pathIndex));
                pathIndex++;
            }
            DA.SetDataTree(0, edgeTree);
        }
Ejemplo n.º 17
0
        protected override void SolveInstance(IGH_DataAccess dataAccess)
        {
            var isBake = false;

            if (!dataAccess.GetData("Data", ref _stBridge))
            {
                return;
            }
            if (!dataAccess.GetData("Bake", ref isBake))
            {
                return;
            }

            CreateLine();
            if (isBake)
            {
                BakeLine();
            }

            dataAccess.SetDataList(0, _nodes);
            foreach ((GH_Structure <GH_Line> geometry, int i) in _lineList.Select((geo, index) => (geo, index + 1)))
            {
                dataAccess.SetDataTree(i, geometry);
            }
        }
Ejemplo n.º 18
0
        protected override void SetOutputs(IGH_DataAccess da)
        {
            AbstractEnvironmentType environment = new PolysurfaceEnvironmentType(brep, borderDir);

            da.SetData(nextOutputIndex++, environment);
            da.SetDataTree(nextOutputIndex++, BrepArray2DToDatatree(((PolysurfaceEnvironmentType)environment).BorderWallsArray));
        }
Ejemplo n.º 19
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Glulam> glulams = new List <Glulam>();

            if (!DA.GetDataList <Glulam>("Glulams", glulams))
            {
                return;
            }


            FindIntersections(glulams, out DataTree <int> indices, out DataTree <int> joint_types, out DataTree <double> parameters, 50.0, 0.1);

            DA.SetDataTree(0, indices);
            DA.SetDataTree(1, joint_types);
            DA.SetDataTree(2, parameters);
        }
Ejemplo n.º 20
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <IGH_GeometricGoo> iMeshTree = new GH_Structure <IGH_GeometricGoo>();

            DA.GetDataTree <IGH_GeometricGoo>(0, out iMeshTree);

            GH_Structure <IGH_GeometricGoo> oDualMeshTree      = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <IGH_GeometricGoo> oDualMeshCurveTree = new GH_Structure <IGH_GeometricGoo>();


            for (int i = 0; i < iMeshTree.PathCount; i++)
            {
                GH_Path path = iMeshTree.get_Path(i);

                for (int j = 0; j < iMeshTree.Branches[i].Count; j++)
                {
                    Mesh mesh;
                    if (!iMeshTree.Branches[i][j].CastTo <Mesh>(out mesh))
                    {
                        continue;
                    }
                    else
                    {
                        oDualMeshTree.Append(
                            GH_Convert.ToGeometricGoo(mesh.ToPlanktonMesh().Dual(0).ToRhinoMesh()),
                            path);
                    }
                }
            }

            DA.SetDataTree(0, oDualMeshTree);
        }
Ejemplo n.º 21
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var tree      = new GH_Structure <IGH_Goo>();
            var list      = new List <IGH_Goo>();
            var indexList = new List <int>();

            if (!DA.GetDataList(0, list))
            {
                return;
            }
            if (!DA.GetDataList(1, indexList))
            {
                return;
            }

            var prev = 0;
            var num  = 0;

            foreach (var i in indexList)
            {
                tree.AppendRange(list.GetRange(prev, i - prev), new GH_Path(num++));
                prev = i;
            }
            tree.AppendRange(list.GetRange(prev, list.Count - prev), new GH_Path(num));

            DA.SetDataTree(0, tree);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <sPointLoad> sups = new List <sPointLoad>();

            if (!DA.GetDataList(0, sups))
            {
                return;
            }

            DataTree <sPointLoad> supTree = new DataTree <sPointLoad>();
            var ngrouped = sups.GroupBy(n => n.loadPatternName);
            int ngroupID = 0;

            foreach (var nngroup in ngrouped)
            {
                GH_Path npth = new GH_Path(ngroupID);
                foreach (sPointLoad sn in nngroup)
                {
                    supTree.Add(sn, npth);
                }
                ngroupID++;
            }

            DA.SetDataTree(0, supTree);
        }
Ejemplo n.º 23
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Mesh mesh = new Mesh();

            DA.GetData(0, ref mesh);

            double angle = 10;
            double dist  = 0.2;
            double width = 0.1;

            DA.GetData(1, ref angle);
            DA.GetData(2, ref dist);
            DA.GetData(3, ref width);

            if (mesh.IsValid)
            {
                if (mesh.Ngons.Count == 0)
                {
                    mesh = MeshCreate.MeshFromPolylines(mesh.GetFacePolylines(), Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);
                }

                var dt = mesh.ReciprocalFrame(angle, dist, width);
                this.PreparePreview(mesh, DA.Iteration, dt.AllData(), false);
                DA.SetDataTree(0, dt);
            }
        }
Ejemplo n.º 24
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)
        {
            Plane plane    = Plane.WorldXY;
            Curve perimCrv = null;

            coreCrvs     = new List <Curve>();
            rectangles   = new List <Rectangle3d>();
            obstacleCrvs = new List <Curve>();
            DA.GetData(IN_autoColor, ref autoColor);

            DA.GetData(IN_plane, ref plane);
            DA.GetData(IN_perimCrv, ref perimCrv);
            DA.GetDataList(IN_voxelRects, rectangles);
            DA.GetDataList(IN_obstacleCrvs, obstacleCrvs);
            bool coreReceived = DA.GetDataList(IN_coreCrvs, coreCrvs);

            _plan = new SmartPlan(perimCrv, coreCrvs, rectangles, obstacleCrvs, plane);

            Rhino.RhinoDoc   doc    = Rhino.RhinoDoc.ActiveDoc;
            Rhino.UnitSystem system = doc.ModelUnitSystem;
            _plan.projectUnits = system.ToString() == "Meters" ? 0 : 1;

            _plan.ComputeCovid();

            compromisedMetric = _plan.GetCovidMetric();

            DA.SetDataList(OUT_hit, compromisedMetric);
            DA.SetDataTree(OUT_lines, _plan.covidLines);
        }
Ejemplo n.º 25
0
        private void AddToOutput(IGH_DataAccess DA, string name, DataTree <object> data)
        {
            var index = 0;
            var found = false;

            foreach (var param in Params.Output)
            {
                if (param.Name == name)
                {
                    found = true;
                    break;
                }

                index++;
            }

            if (!found)
            {
                var p = new Param_GenericObject
                {
                    Name     = name,
                    NickName = name,
                    Access   = GH_ParamAccess.tree
                };
                Params.RegisterOutputParam(p);
                Params.OnParametersChanged();
                ExpireSolution(true);
            }
            else
            {
                DA.SetDataTree(index, data);
            }
        }
Ejemplo n.º 26
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 A = new GH_Structure <GH_Number>(); int e = 0;

            for (int k = 0; k < n; k++)
            {
                if (!DA.GetDataTree(k, out GH_Structure <GH_Number> _T))
                {
                }
                else if (_T.Branches[0][0].Value != -9999)
                {
                    var T = _T.Branches;
                    var ni = T.Count; var nj = T[0].Count;
                    for (int i = 0; i < ni; i++)
                    {
                        var tlist = new List <GH_Number>();
                        for (int j = 0; j < nj; j++)
                        {
                            tlist.Add(new GH_Number(T[i][j].Value));
                        }
                        A.AppendRange(tlist, new GH_Path(e));
                        e += 1;
                    }
                }
            }
            DA.SetDataTree(0, A);
        }
Ejemplo n.º 27
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> objects = new GH_Structure <IGH_Goo>();

            if (!DA.GetDataTree(0, out objects))
            {
                return;
            }
            /////////////////////////////////////////////////////////////////////////////
            DataTree <object> newobj = new DataTree <object>();
            int        num           = objects.PathCount;
            List <int> index         = new List <int>();//////每个分支的长度

            for (int i = 0; i < num; i++)
            {
                index.Add(objects.Branches[i].Count);
            }
            index.Sort();                        /////排序长度,找出最大值
            int maxnum = index[index.Count - 1]; /////找出数据最长分支的长度

            for (int i = 0; i < maxnum; i++)
            {
                for (int j = 0; j < num; j++)
                {
                    List <object> obb  = new List <object>(objects.Branches[j]);
                    int           num2 = obb.Count;
                    if (num2 >= i + 1)/////////////////////如果分支的数据长度大于序号,则进入
                    {
                        newobj.Add(obb[i], new GH_Path(0, i));
                    }
                }
            }
            DA.SetDataTree(0, newobj);
        }
Ejemplo n.º 28
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)
        {
            bool condition = new bool();
            GH_Structure <IGH_Goo> data      = new GH_Structure <IGH_Goo>();
            AnteloopDoComponent    loopStart = new AnteloopDoComponent();

            if (!DA.GetData(0, ref condition))
            {
                return;
            }
            if (!DA.GetDataTree(1, out data))
            {
                return;
            }
            if (!DA.GetData(2, ref loopStart))
            {
                return;
            }


            if (condition)
            {
                loopStart.Params.Input[0].ClearData();
                loopStart.Params.Input[0].AddVolatileDataTree(data);

                // Dangerous
                loopStart.ExpireSolution(true);
            }
            else
            {
                DA.SetDataTree(0, data);
            }
        }
Ejemplo n.º 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)
        {
            List <string> bID = new List <string>();

            if (!DA.GetDataList(0, bID))
            {
                return;
            }

            DataTree <GeometryBase> gbs = new DataTree <GeometryBase>();

            for (int i = 0; i < bID.Count; i++)
            {
                InstanceDefinition def = RhinoDoc.ActiveDoc.InstanceDefinitions.Find(bID[i]);
                if (def == null)
                {
                    gbs.Add(null, new GH_Path(i));
                    continue;
                }
                RhinoObject[] objects = def.GetObjects();
                GeometryBase  gb;
                for (int j = 0; j < objects.Length; j++)
                {
                    gb = objects[j].DuplicateGeometry();
                    gbs.Add(gb, new GH_Path(i));
                }
            }

            DA.SetDataTree(0, gbs);
        }
Ejemplo n.º 30
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)
        {
            // First, we need to retrieve all data from the input parameters.
            // We'll start by declaring variables and assigning them starting values.
            Boolean reset                = true;
            bool    liveUpdate           = true;
            List <T.AgentSystem> systems = new List <T.AgentSystem>();

            // Then we need to access the input parameters individually.
            // When data cannot be extracted from a parameter, we should abort this method.
            if (!DA.GetData(0, ref reset))
            {
                return;
            }
            if (!DA.GetData(1, ref liveUpdate))
            {
                return;
            }
            if (!DA.GetDataList(2, systems))
            {
                return;
            }

            // We should now validate the data and warn the user if invalid data is supplied.

            // We're set to create the output now. To keep the size of the SolveInstance() method small,
            // The actual functionality will be in a different method:
            DataTree <AgentType> agents = run(reset, liveUpdate, systems);

            //List<Point3d> agents = new List<Point3d>();

            // Finally assign the spiral to the output parameter.
            DA.SetDataTree(0, agents);
        }
        /// <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)
        {
            // Define i/o parameters
            bool s = false;

            // Read inputs
            if (!DA.GetDataTree("Vectors", out GH_Structure <GH_Vector> vectorTree))
            {
                return;
            }
            if (!DA.GetData("Strict", ref s))
            {
                return;
            }

            // Exceptions
            if (vectorTree.GetType() != typeof(GH_Structure <GH_Vector>))
            {
                throw new Exception("Invalid vectorTree");
            }
            if (vectorTree.IsEmpty)
            {
                throw new Exception("Empty vectorTree");
            }
            if (vectorTree.PathCount < 1)
            {
                throw new Exception("This vectorTree is to small");
            }

            DA.SetDataTree(0, vectorTree.SplitVectors(s));
        }
Ejemplo n.º 32
0
        public override void SetData(IGH_DataAccess DA)
        {
            if (outputDict == null)
            {
                return;
            }
            foreach (var key in outputDict.Keys)
            {
                var indexOfOutputParam = Params.IndexOfOutputParam(key);
                if (indexOfOutputParam != -1)
                {
                    var ghStructure = outputDict[key];
                    DA.SetDataTree(indexOfOutputParam, ghStructure);
                }
            }

            // Report all conversion errors as warnings
            if (Converter != null)
            {
                foreach (var error in Converter.ConversionErrors)
                {
                    Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                             error.Message + ": " + error.InnerException?.Message);
                }
                Converter.ConversionErrors.Clear();
            }
            outputDict = null;
            (Parent as ExpandSpeckleObjectAsync).State = 0;
        }
Ejemplo n.º 33
0
        protected override void SetOutputs(IGH_DataAccess da)
        {
            outTree = new DataTree <Point3d>();
            GH_Path trunk  = new GH_Path(0); // {0}
            GH_Path branch = new GH_Path();  // {}\
            GH_Path limb   = new GH_Path();


            for (int i = 0; i < particles.Count; i++)
            {
                IQuelea particle = particles[i];
                branch = trunk.AppendElement(i);
                DataTree <Point3d> particlePositionHistoryTree = particle.Position3DHistory.ToTree();

                for (int j = 0; j < particlePositionHistoryTree.BranchCount; j++)
                {
                    limb = branch.AppendElement(j);
                    //for (int k = particlePositionHistoryTree.Branch(j).Count - 1; k >= 0; k--)
                    //{
                    //  outTree.Add(particlePositionHistoryTree.Branch(j)[k], limb);
                    //}
                    outTree.AddRange(particlePositionHistoryTree.Branch(j), limb);
                }
            }
            da.SetDataTree(nextOutputIndex++, outTree);
        }
Ejemplo n.º 34
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Mesh mesh = new Mesh();
            double contourBaseZ = 0;
            double contourInterval = 0;

            DA.GetData(0, ref mesh);
            DA.GetData(1, ref contourBaseZ);
            DA.GetData(2, ref contourInterval);

            if (mesh == null) return;

            List<double> contourZList = GetContourZList(mesh, contourBaseZ, contourInterval);
            DataTree<Curve> contourTree = GetContourTree(mesh, contourZList);
            List<Brep> brepList = GetBrepList(mesh, contourZList, contourTree);
            Brep terrainRegion = GetTerrainRegion(mesh);
            DataTree<Object> stepTree = GetStepTree(mesh, contourZList, contourTree, brepList);

            DA.SetDataTree(0, contourTree);
            DA.SetDataTree(1, stepTree);
        }
Ejemplo n.º 35
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)
    {
      // First, we need to retrieve all data from the input parameters.
      // We'll start by declaring variables and assigning them starting values.
      Boolean reset = true;
      bool liveUpdate = true;
      List<T.AgentSystem> systems = new List<T.AgentSystem>();

      // Then we need to access the input parameters individually. 
      // When data cannot be extracted from a parameter, we should abort this method.
      if (!DA.GetData(0, ref reset)) return;
      if (!DA.GetData(1, ref liveUpdate)) return;
      if (!DA.GetDataList(2, systems)) return;

      // We should now validate the data and warn the user if invalid data is supplied.

      // We're set to create the output now. To keep the size of the SolveInstance() method small, 
      // The actual functionality will be in a different method:
      DataTree<AgentType> agents = run(reset, liveUpdate, systems);
      //List<Point3d> agents = new List<Point3d>();

      // Finally assign the spiral to the output parameter.
      DA.SetDataTree(0, agents);
    }
Ejemplo n.º 36
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> hours = new List<DHr>();
            String key = "";
            if (DA.GetDataList(0, hours) && DA.GetData(1, ref key)) {
                if (hours.Count == 0) {
                    //TODO: we may want to return null values here instead.
                    return;
                }
                Interval ival_r = new Interval();
                float[] vals = new float[0];

                if (!(DA.GetData(2, ref ival_r))) DHr.get_domain(key, hours.ToArray(), ref vals, ref ival_r);
                else
                {
                    vals = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) vals[h] = hours[h].val(key);
                    /* FROM HEAD:
                    ival_r = new Interval(hours[0].val(key), hours[0].val(key));
                    vals = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) {
                        vals[h] = hours[h].val(key);
                        if (vals[h] < ival_r.T0) ival_r.T0 = vals[h];
                        if (vals[h] > ival_r.T1) ival_r.T1 = vals[h];
                    }
                     */
                }

                String period_string = "none";
                cycle_type = CType.Invalid;
                DA.GetData(3, ref period_string);

                if (period_string.Contains("year")) { this.cycle_type = CType.Year; }
                else if (period_string.Contains("day") || period_string.Contains("daily")) { this.cycle_type = CType.Day; }
                else if (period_string.Contains("none")) { this.cycle_type = CType.None; }
                if (cycle_type == CType.Invalid)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "I don't understand the time period you're looking for.\nPlease choose 'year', 'day', or 'none'.");
                    return;
                }

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(4, ref plane);

                Interval ival_gr = new Interval();
                Interval ival_ga = new Interval(Math.PI * 2, 0); // reversed interval to ensure clockwise direction
                DA.GetData(5, ref ival_gr);

                switch (this.cycle_type) {

                    case CType.None: {
                            List<Point3d> points = new List<Point3d>();
                            Rhino.Geometry.Mesh mesh = new Mesh();
                            for (int h = 0; h < hours.Count; h++) {
                                double radius = ival_gr.ParameterAt(ival_r.NormalizedParameterAt(vals[h]));
                                double theta = ival_ga.ParameterAt(h / (double)hours.Count);
                                Point3d gpt = PointByCylCoords(radius, theta); // a point in graph coordinates
                                hours[h].pos = gpt; // the hour records the point in graph coordinates

                                Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                                points.Add(wpt);  // adds this point in world coordinates

                                mesh.Vertices.Add(wpt);
                                mesh.VertexColors.Add(hours[h].color);
                                Point3d wbpt = PointByCylCoords(ival_gr.ParameterAt(-0.01), theta);
                                mesh.Vertices.Add(plane.PointAt(wbpt.X, wbpt.Y));
                                mesh.VertexColors.Add(hours[h].color);
                                if (h > 0) mesh.Faces.AddFace(h * 2, h * 2 + 1, h * 2 - 1);
                                if (h > 0) mesh.Faces.AddFace(h * 2 - 1, h * 2 - 2, h * 2);
                            }
                            mesh.Normals.ComputeNormals();
                            mesh.Compact();

                            DA.SetDataList(0, hours);
                            DA.SetDataList(1, points);
                            //DA.SetDataTree(2, regions);
                            DA.SetData(2, mesh);
                        }
                        break;

                    case CType.Day: {
                            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> points = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                            List<Mesh> meshes = new List<Mesh>();
                            Rhino.Geometry.Mesh mesh = new Mesh();
                            int hour_of_day = 0;
                            int cycle_count = 0;
                            for (int i = 0; i < hours.Count; i++) {
                                if (hours[i].hr % 24 != hour_of_day) {
                                    cycle_count++;
                                    hour_of_day = hours[i].hr % 24;
                                    mesh.Normals.ComputeNormals();
                                    mesh.Compact();
                                    meshes.Add(mesh);
                                    mesh = new Mesh();
                                }
                                double radius = ival_gr.ParameterAt(ival_r.NormalizedParameterAt(vals[i]));
                                double theta = ival_ga.ParameterAt(hour_of_day / 24.0);
                                Point3d gpt = PointByCylCoords(radius, theta); // a point in graph coordinates
                                hours[i].pos = gpt; // the hour records the point in graph coordinates

                                Point3d wpt = plane.PointAt(gpt.X, gpt.Y);

                                points.Append(new Grasshopper.Kernel.Types.GH_Point(wpt),new Grasshopper.Kernel.Data.GH_Path(cycle_count)); // adds this point in world coordinates
                                hourTreeOut.Append(hours[i], new Grasshopper.Kernel.Data.GH_Path(cycle_count));

                                mesh.Vertices.Add(wpt);
                                mesh.VertexColors.Add(hours[i].color);
                                Point3d wbpt = PointByCylCoords(ival_gr.ParameterAt(-0.01), theta);
                                mesh.Vertices.Add(plane.PointAt(wbpt.X, wbpt.Y));
                                mesh.VertexColors.Add(hours[i].color);
                                if (hour_of_day > 0) mesh.Faces.AddFace(hour_of_day * 2, hour_of_day * 2 + 1, hour_of_day * 2 - 1);
                                if (hour_of_day > 0) mesh.Faces.AddFace(hour_of_day * 2 - 1, hour_of_day * 2 - 2, hour_of_day * 2);

                                hour_of_day++;
                            }

                            DA.SetDataTree(0, hourTreeOut);
                            DA.SetDataTree(1, points);
                            //DA.SetDataTree(2, regions);
                            DA.SetDataList(2, meshes);
                        }
                        break;
                }

            }
        }
Ejemplo n.º 37
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> hours = new List<DHr>();
            String key_r = "";
            String key_a = "";
            if (DA.GetDataList(0, hours) && DA.GetData(1, ref key_r) && DA.GetData(2, ref key_a)) {

                Interval ival_r = new Interval();
                Interval ival_a = new Interval();
                float[] vals_r = new float[0];
                float[] vals_a = new float[0];

                if (!(DA.GetData(3, ref ival_r))) DHr.get_domain(key_r, hours.ToArray(), ref vals_r, ref ival_r);
                else {
                    ival_r = new Interval(hours[0].val(key_r), hours[0].val(key_r));

                    vals_r = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) {
                        vals_r[h] = hours[h].val(key_r);
                        if (vals_r[h] < ival_r.T0) ival_r.T0 = vals_r[h];
                        if (vals_r[h] > ival_r.T1) ival_r.T1 = vals_r[h];
                    }
                }

                DHr.get_domain(key_a, hours.ToArray(), ref vals_a, ref ival_a);
                DA.GetData(4, ref ival_a);

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(5, ref plane);

                Interval ival_gr = new Interval();
                Interval ival_ga = new Interval(0, Math.PI * 2);
                DA.GetData(6, ref ival_gr);

                Interval subdivs = new Interval();
                DA.GetData(7, ref subdivs);
                int subdivs_r = (int)Math.Floor(subdivs.T0);
                int subdivs_a = (int)Math.Floor(subdivs.T1);

                List<Point3d> points = new List<Point3d>();
                for (int h = 0; h < hours.Count; h++) {
                    double radius = ival_gr.ParameterAt(ival_r.NormalizedParameterAt(vals_r[h]));
                    double theta = ival_a.NormalizedParameterAt(vals_a[h]) * Math.PI * 2;
                    Point3d gpt = PointByCylCoords(radius, theta); // a point in graph coordinates
                    hours[h].pos = gpt; // the hour records the point in graph coordinates

                    Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                    points.Add(wpt);  // adds this point in world coordinates
                }

                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Curve> regions = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Curve>();

                int segments_in_whole_circle = 36;
                //double step_r = ival_r.Length / subdivs_r;
                //double step_a = Math.PI*2 / subdivs_a;

                for (int r = 0; r < subdivs_r; r++)
                    for (int a = 0; a < subdivs_a; a++) {
                        Interval rad = new Interval(ival_gr.ParameterAt(r / (float)subdivs_r), ival_gr.ParameterAt((r + 1) / (float)subdivs_r));
                        Interval ang = new Interval(ival_ga.ParameterAt(a / (float)subdivs_a), ival_ga.ParameterAt((a + 1) / (float)subdivs_a));

                        int cnt = (int)Math.Ceiling(segments_in_whole_circle * ang.Length / Math.PI * 2);
                        Polyline pcrv = new Polyline();
                        pcrv.AddRange(FakeArc(plane, rad.T0, ang.T0, ang.T1, cnt));
                        pcrv.AddRange(FakeArc(plane, rad.T1, ang.T1, ang.T0, cnt));
                        pcrv.Add(pcrv[0]);

                        Grasshopper.Kernel.Types.GH_Curve gh_curve = new Grasshopper.Kernel.Types.GH_Curve();
                        Grasshopper.Kernel.GH_Convert.ToGHCurve(pcrv, GH_Conversion.Both, ref gh_curve);
                        regions.Append(gh_curve, new Grasshopper.Kernel.Data.GH_Path(new int[] { r, a }));
                    }

                DA.SetDataList(0, hours);
                DA.SetDataList(1, points);
                DA.SetDataTree(2, regions);

            }
        }
Ejemplo n.º 38
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)
        {
            //---- Declareing ---------------------------------------------------------------------------

            List<Tri_Loop_Component> All_Components = new List<Tri_Loop_Component>();
            DA.GetDataList<Tri_Loop_Component>("Components", All_Components);

            DataTree<Curve> All_Curves = new DataTree<Curve>();

            //// =======================================================================================
            // Added by Gene
            DataTree<Curve> All_ExtendedCurves = new DataTree<Curve>();
            DataTree<Brep> All_SingleStripeBreps = new DataTree<Brep>();

            //// =======================================================================================

            DataTree<Point3d> All_CentrePointsL01 = new DataTree<Point3d>();
            DataTree<Point3d> All_CentrePointsL02 = new DataTree<Point3d>();
            DataTree<Curve> All_PlateCrv = new DataTree<Curve>();

            DataTree<Point3d> All_PentagonPts_L01 = new DataTree<Point3d>();
            DataTree<Point3d> All_PentagonPts_L02 = new DataTree<Point3d>();

            DataTree<int> All_StripeIds = new DataTree<int>();
            DataTree<Brep> All_StripeBreps = new DataTree<Brep>();
            DataTree<Curve> All_StripeIntersectCrvs = new DataTree<Curve>();
            DataTree<Plane> All_StripeIntersectPlane = new DataTree<Plane>();

            //---- End Declareing -----------------------------------------------------------------------
            //---- Functions ----------------------------------------------------------------------------

            int componentIdx = 0;

            foreach (Tri_Loop_Component component in All_Components)
            {
                GH_Path pth1 = new GH_Path(componentIdx);

                // run / generate Informations for Sofistik
                // create output information
                for (int p = 0; p < component.CentersL01.Count; p++)
                {
                    All_CentrePointsL01.Add(component.CentersL01[p], pth1);
                    All_CentrePointsL02.Add(component.CentersL02[p], pth1);
                }

                for (int c = 0; c < component.Curves.BranchCount; c++)
                {
                    All_Curves.Add(component.Curves.Branch(c)[0], pth1.AppendElement(c));
                    All_Curves.Add(component.Curves.Branch(c)[1], pth1.AppendElement(c));

                    //// =======================================================================================
                    // Added by Gene
                    All_ExtendedCurves.Add(component.ExtendedCurves.Branch(c)[0], pth1.AppendElement(c));
                    All_ExtendedCurves.Add(component.ExtendedCurves.Branch(c)[1], pth1.AppendElement(c));
                    //// =======================================================================================
                }

                for (int sid = 0; sid < component.StripeID.BranchCount; sid++)
                {
                    All_StripeIds.Add(component.StripeID.Branch(sid)[0], pth1.AppendElement(sid));
                    All_StripeIds.Add(component.StripeID.Branch(sid)[1], pth1.AppendElement(sid));
                    All_StripeIds.Add(component.StripeID.Branch(sid)[2], pth1.AppendElement(sid));
                }

                for (int p = 0; p < component.PlateCrv.BranchCount; p++)
                {
                    All_PlateCrv.Add(component.PlateCrv.Branch(p)[0], pth1.AppendElement(p));
                    All_PlateCrv.Add(component.PlateCrv.Branch(p)[1], pth1.AppendElement(p));
                }

                for (int pent = 0; pent < component.PlanarPentagonL01.BranchCount; pent++)
                {
                    All_PentagonPts_L01.Add(component.PlanarPentagonL01.Branch(pent)[0], pth1.AppendElement(pent));
                    All_PentagonPts_L01.Add(component.PlanarPentagonL01.Branch(pent)[1], pth1.AppendElement(pent));
                    All_PentagonPts_L01.Add(component.PlanarPentagonL01.Branch(pent)[2], pth1.AppendElement(pent));
                    All_PentagonPts_L01.Add(component.PlanarPentagonL01.Branch(pent)[3], pth1.AppendElement(pent));
                    All_PentagonPts_L01.Add(component.PlanarPentagonL01.Branch(pent)[4], pth1.AppendElement(pent));
                }

                for (int pent = 0; pent < component.PlanarPentagonL02.BranchCount; pent++)
                {
                    All_PentagonPts_L02.Add(component.PlanarPentagonL02.Branch(pent)[0], pth1.AppendElement(pent));
                    All_PentagonPts_L02.Add(component.PlanarPentagonL02.Branch(pent)[1], pth1.AppendElement(pent));
                    All_PentagonPts_L02.Add(component.PlanarPentagonL02.Branch(pent)[2], pth1.AppendElement(pent));
                    All_PentagonPts_L02.Add(component.PlanarPentagonL02.Branch(pent)[3], pth1.AppendElement(pent));
                    All_PentagonPts_L02.Add(component.PlanarPentagonL02.Branch(pent)[4], pth1.AppendElement(pent));
                }

                // Information from Stripe Class
                for (int s = 0; s < component.Stripes.Count; s++)
                {
                    for (int t = 0; t < component.Stripes[s].SurfaceAtLoop.Length; t++)
                    { All_StripeBreps.Add(component.Stripes[s].SurfaceAtLoop[t], pth1.AppendElement(s)); }

                    //for (int u = 0; u < component.Stripes[s].IntersectionCurve.Length; u++)
                    //{ All_StripeIntersectCrvs.Add(component.Stripes[s].IntersectionCurve[u], pth1.AppendElement(s));}

                    All_StripeIntersectPlane.Add(component.Stripes[s].IntersectionPlane, pth1.AppendElement(s));
                }

                // ======================================================================================================
                // Gene Added

                for (int s = 0; s < component.StripesSingle.Count; s++)
                {
                    All_SingleStripeBreps.Add(component.StripesSingle[s].loop, pth1.AppendElement(s));

                    //for (int u = 0; u < component.Stripes[s].IntersectionCurve.Length; u++)
                    //{ All_StripeIntersectCrvs.Add(component.Stripes[s].IntersectionCurve[u], pth1.AppendElement(s));}

                    //All_StripeIntersectPlane.Add(component.StripesSingle[s].IntersectionPlane, pth1.AppendElement(s));
                }

                // ======================================================================================================

                componentIdx++;
            }

            //---- End Functions ------------------------------------------------------------------------
            //---- Set Output ---------------------------------------------------------------------------

            DA.SetDataTree(0, All_CentrePointsL01);
            DA.SetDataTree(1, All_CentrePointsL02);
            DA.SetDataTree(2, All_Curves);
            DA.SetDataTree(3, All_PlateCrv);
            DA.SetDataTree(4, All_PentagonPts_L01);
            DA.SetDataTree(5, All_PentagonPts_L02);
            DA.SetDataTree(6, All_StripeIds);
            DA.SetDataTree(7, All_StripeBreps);
            DA.SetDataTree(8, All_StripeIntersectPlane);

            //// =======================================================================================
            // Added by Gene

            DA.SetDataTree(9, All_ExtendedCurves);
            DA.SetDataTree(10, All_SingleStripeBreps);
            //// =======================================================================================

            //---- End Set 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)
        {
            //----Declareing--------------------------------------------------------------------------

            // contains the 3 points of each face
            DataTree<Point3f> facePoints = new DataTree<Point3f>();
            // contains the coresponding topology points of each face
            DataTree<int> faceTopologyPoints = new DataTree<int>();
            // contains the face normals of each face
            List<Vector3f> faceNormals = new List<Vector3f>();

            // contains the 3 topology edges of each face
            DataTree<int> faceTopoEdgesIdx = new DataTree<int>();
            // contains the points of each topology edge
            DataTree<int> topologyEdgesTopPtsIdx = new DataTree<int>();

            // Contains the coordinates of each topology point
            List<Point3d> topologyPoints = new List<Point3d>();
            // Contains the index of neighbouring faces for each face
            DataTree<int> faceNeighbours = new DataTree<int>();
            // Contains Normals of topology vertices
            List<Vector3d> topologyNormals = new List<Vector3d>();

            // Contains the index of topology Edges for each Topology Point
            DataTree<int> TopPt_Connected_TopEdges = new DataTree<int>();

            //get Mesh from input
            Mesh M = new Mesh();
            DA.GetData<Mesh>("Mesh", ref M);

            //----End Declareing-----------------------------------------------------------------------

            //----Functions------------------------------------------------------------------------------

            // get List with sublist of 3 points per face
            for (int face_id = 0; face_id < M.Faces.Count; face_id++)
            {
                // set up the branch index
                GH_Path pth = new GH_Path(face_id);

                # region FacePoints

                //---- Face Points (Point3f)
                Point3f A, B, C, D;
                M.Faces.GetFaceVertices(face_id, out A, out B, out C, out D);

                facePoints.Add(A, pth);
                facePoints.Add(B, pth);
                facePoints.Add(C, pth);

                #endregion FacePoints

                #region FaceNormals
                //---- Face Normals (Vector3f)
                M.FaceNormals.ComputeFaceNormals();
                faceNormals.Add(M.FaceNormals[face_id]);
                #endregion FaceNormals

                #region faceTopologyPoints

                //---- Topology Points of the face (int)
                int TA = M.Faces.GetTopologicalVertices(face_id)[0];
                int TB = M.Faces.GetTopologicalVertices(face_id)[1];
                int TC = M.Faces.GetTopologicalVertices(face_id)[2];

                faceTopologyPoints.Add(TA, pth);
                faceTopologyPoints.Add(TB, pth);
                faceTopologyPoints.Add(TC, pth);

                #endregion faceTopologyPoints

                #region faceNeighbours

                //---- Neighbours of face (int)

                foreach (int i in M.TopologyEdges.GetEdgesForFace(face_id))
                {
                    if (M.TopologyEdges.GetConnectedFaces(i).Length > 1)
                    {
                        foreach (int j in M.TopologyEdges.GetConnectedFaces(i))
                        {
                            if (j != face_id)
                            { faceNeighbours.Add(j, pth); }
                        }
                    }
                    else
                    { faceNeighbours.Add(-1, pth); }
                }

                #endregion faceNeighbours

                #region Face Topology Edges

                //---- Topology Edges (int)

                foreach (int i in M.TopologyEdges.GetEdgesForFace(face_id))
                { faceTopoEdgesIdx.Add(i, pth); }

                #endregion Face Topology Edges

            }

            for (int i = 0; i < M.TopologyVertices.Count; i++)
            {
                #region topologyPoints
                //---- Topology Points (point3f)
                int[] vertIdx = M.TopologyVertices.MeshVertexIndices(i);
                topologyPoints.Add(M.Vertices[vertIdx[0]]);
                #endregion topologyPoints

                #region topologyNormals
                //---- Topology Normals
                M.FaceNormals.ComputeFaceNormals();
                Vector3d normal = new Vector3d(0, 0, 0);
                int count = 0;

                foreach (int face in M.TopologyVertices.ConnectedFaces(i))
                {
                    Vector3f temp = new Vector3f();
                    temp = M.FaceNormals[face];
                    Vector3d temp2 = new Vector3d(temp.X, temp.Y, temp.Z);
                    normal += temp2;
                    count++;
                }

                normal /= count;
                topologyNormals.Add(normal);
                #endregion topologyNormals

            }

            #region Topology Edges

            for (int i = 0; i < M.TopologyEdges.Count; i++)
            {
                topologyEdgesTopPtsIdx.Add(M.TopologyEdges.GetTopologyVertices(i).I, new GH_Path(i));
                topologyEdgesTopPtsIdx.Add(M.TopologyEdges.GetTopologyVertices(i).J, new GH_Path(i));
            }

            #endregion Topology Edges

            #region Topology Vertex connected Topology Edge

            for (int i = 0; i < topologyPoints.Count; i++)
            {
                // i = index of Topology Point
                GH_Path pth = new GH_Path(i);

                for (int j = 0; j < topologyEdgesTopPtsIdx.BranchCount; j++)
                {
                    // j = index of Topology Edge
                    foreach (int k in topologyEdgesTopPtsIdx.Branch(j))
                    {
                        if (k == i)
                        // add multiple Topology Edges to the branch index, which is representing the topology point index
                        { TopPt_Connected_TopEdges.Add(j, pth); }
                    }
                }
            }

            #endregion Topology Vertex connected Topology Edge

            //----End Functions--------------------------------------------------------------------------

            //----Set Output-----------------------------------------------------------------------------

            DA.SetDataTree(0, facePoints);
            DA.SetDataTree(1, faceTopologyPoints);
            DA.SetDataList(2, faceNormals);
            DA.SetDataTree(3, faceNeighbours);
            DA.SetDataList(4, topologyPoints);
            DA.SetDataList(5, topologyNormals);
            DA.SetDataTree(6, faceTopoEdgesIdx);
            DA.SetDataTree(7, topologyEdgesTopPtsIdx);
            DA.SetDataTree(8, TopPt_Connected_TopEdges);

            //----End Set Output-------------------------------------------------------------------------
        }
        /// <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)
        {
            ////////////////////////
            //  Retrieve crucial (fixed) input data, exit if non-existent
            ////////////////////////

            if (!DA.GetData(0, ref clusterUrlParam)) { return; }

            ////////////////////////
            // check if cluster was properly loaded, and if parameters are correct
            // and if not, do something about it!
            ////////////////////////

            if (loadedClusterUrlParam == null ||
                loadedClusterUrlParam != clusterUrlParam)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cluster not loaded properly - click on 'Reload Cluster' button!");
            //                MessageBox.Show("hey, don't we have a parameter mismatch?");
                //we've got a parameter mismatch
                // urge user to click on buttom to match paramcount to cluster param count
            /*                (this.m_attributes as Attributes_Custom).button.Palette = GH_Palette.Pink;
                (this.m_attributes as Attributes_Custom).ExpireLayout();
                (this.m_attributes as Attributes_Custom).PerformLayout();
                NEXT STEP - HIGHLIGHT BUTTON */

            }
            else
            {
                //successful! parameters match. so - let's run this thing:

                //get data from hairworm inputs, put into array
                for (int i = fixedParamNumInput; i < (fixedParamNumInput + clusterParamNumInput); i++)
                {
                    if (!DA.GetDataList(i, clusterInputLists[i - fixedParamNumInput])) { return; }
                    //if (!DA.GetData(i, ref clusterInput[i - fixedParamNumInput])) { return; }
            //                    debugText += "okay, input # " + i + " is: " + clusterInputs[i - fixedParamNumInput].ToString() + "\n";
            //					DA.SetData(0, debugText);
                }

                // get data from array, input into cluster
                for (int i = fixedParamNumInput; i < (fixedParamNumInput + clusterParamNumInput); i++)
                {
            //                    wormCluster.Params.Input[i - fixedParamNumInput].AddVolatileData(new GH_Path(0), 0, clusterInputs[i - fixedParamNumInput]);
                    wormCluster.Params.Input[i - fixedParamNumInput].AddVolatileDataList(new GH_Path(0), clusterInputLists[i - fixedParamNumInput]);

                }

                // RUN CLUSTER AND RECOMPUTE THIS
                wormCluster.ExpireSolution(true);

                // get computed data from cluster outputs, push into hairworm outputs
                for (int i = fixedParamNumOutput; i < (fixedParamNumOutput + clusterParamNumOutput); i++)
                {
                    // Create a copy of this data (the original data will be wiped)
                    DataTree<object> copy = new DataTree<object>();
                    copy.MergeStructure(wormCluster.Params.Output[i - fixedParamNumOutput].VolatileData, new Grasshopper.Kernel.Parameters.Hints.GH_NullHint());

                    // push into hairworm component outputs
                    DA.SetDataTree(i, copy);
                }

                DA.SetData(0, debugText);

            }

            DA.SetData(0, debugText);
        }
 protected override void SetOutputs(IGH_DataAccess da)
 {
     da.SetDataTree(0, prop);
 }
Ejemplo n.º 42
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)
        {
            //---- Declareing ---------------------------------------------------------------------------

            List<Tri_Loop_Component> All_Components = new List<Tri_Loop_Component>();
            DA.GetDataList<Tri_Loop_Component>("Components", All_Components);

            DataTree<Point3d> SofistikPoints = new DataTree<Point3d>();
            DataTree<int> SofistikIndexies = new DataTree<int>();

            DataTree<int> SofistikCrvPtIdx = new DataTree<int>();
            DataTree<Point3d> SofistikCrvPtCoo = new DataTree<Point3d>();

            DataTree<Brep> SofistikBreps = new DataTree<Brep>();
            DataTree<int> SofistikBrepsIdx = new DataTree<int>();

            DataTree<Curve> SofistikCurves = new DataTree<Curve>();

            //---- End Declareing -----------------------------------------------------------------------

            //---- Functions ----------------------------------------------------------------------------

            int componentIdx = 0;

            foreach (Tri_Loop_Component component in All_Components)
            {
                GH_Path pth1 = new GH_Path(componentIdx);

                // run / generate Informations for Sofistik
                component.SofistikInformation();
                component.SofistikCreateSurfaces();

                // Points
                for (int j = 0; j < component.SofistikPlatePoints.BranchCount; j++)
                {

                    foreach (Point3d p in component.SofistikPlatePoints.Branch(j))
                    { SofistikPoints.Add(p, pth1.AppendElement(j)); }

                    foreach (int idx in component.SofistikPlateIndexies.Branch(j))
                    { SofistikIndexies.Add(idx, pth1.AppendElement(j)); }
                }

                // CurvePoints
                for (int j = 0; j < component.SofistikCrvPtCoo.BranchCount; j++)
                {
                    GH_Path pth0 = component.SofistikCrvPtCoo.Path(j);

                    foreach (Point3d pt in component.SofistikCrvPtCoo.Branch(j))
                    {
                        //pth1.AppendElement(pth0[0]);
                        //pth1.AppendElement(pth0[1]);
                        //SofistikCrvPtCoo.Add(pt, pth1.AppendElement(pth0[0]));

                        // 2 level Tree
                        SofistikCrvPtCoo.Add(pt, pth1.AppendElement(pth0[0]));

                    }

                    foreach (int idx in component.SofistikCrvPtIdx.Branch(j))
                    {
                        //pth1.AppendElement(pth0[0]);
                        //pth1.AppendElement(pth0[1]);
                        //SofistikCrvPtIdx.Add(idx, pth1.AppendElement(pth0[0]));

                        // 2 level Tree
                        SofistikCrvPtIdx.Add(idx, pth1.AppendElement(pth0[0]));

                    }
                }

                // Curves
                for (int i = 0; i < component.SofistikCurves.BranchCount; i++)
                {
                    GH_Path pth0 = component.SofistikCurves.Path(i);

                    foreach (Curve c in component.SofistikCurves.Branch(i))
                    {
                        SofistikCurves.Add(c, pth1.AppendElement(pth0[0]));
                    }

                }

                // Surfaces
                for (int j = 0; j < component.SofistikSurfaces.BranchCount; j++)
                {

                    foreach (Brep[] p in component.SofistikSurfaces.Branch(j))
                    { SofistikBreps.Add(p[0], pth1.AppendElement(j)); }

                    foreach (int idx in component.SofistikSurfacesIdx.Branch(j))
                    { SofistikBrepsIdx.Add(idx, pth1.AppendElement(j)); }
                }

                componentIdx++;
            }

            //---- End Functions ------------------------------------------------------------------------
            //---- Set Output ---------------------------------------------------------------------------

            DA.SetDataTree(0, SofistikPoints);
            DA.SetDataTree(1, SofistikIndexies);

            DA.SetDataTree(2, SofistikCrvPtCoo);
            DA.SetDataTree(3, SofistikCrvPtIdx);

            DA.SetDataTree(4, SofistikBreps);
            DA.SetDataTree(5, SofistikBrepsIdx);

            DA.SetDataTree(6, SofistikCurves);

            //---- End Set Output -----------------------------------------------------------------------
        }
Ejemplo n.º 43
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> hours = new List<DHr>();
            List<String> keys = new List<string>();
            if (DA.GetDataList(0, hours) && DA.GetDataList(1, keys)) {
                if ((hours[0].is_surrogate) && ((hours.Count != 1) && (hours.Count != 12) && (hours.Count != 52) && (hours.Count != 365))) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This component can only plot unmasked surrogate hours for yearly, monthly, weekly, and daily statistics"); }

                Interval ival_y = new Interval();
                bool calc_ival_y = false;
                if (!(DA.GetData(2, ref ival_y))) {
                    ival_y.T0 = hours[0].val(keys[0]);
                    ival_y.T1 = hours[0].val(keys[0]);
                    calc_ival_y = true;
                }
                Dictionary<string, float[]> val_dict = new Dictionary<string, float[]>();
                List<Interval> val_ranges = new List<Interval>();
                foreach (string key in keys) {
                    Interval ival = new Interval();
                    float[] vals = new float[0];
                    DHr.get_domain(key, hours.ToArray(), ref vals, ref ival);
                    vals = new float[hours.Count];
                    for (int h = 0; h < hours.Count; h++) vals[h] = hours[h].val(key);
                    val_dict.Add(key, vals);
                    val_ranges.Add(ival);
                }

                bool force_start_at_zero = true;

                int stack_dir = StackDirection(val_ranges[0]);
                if (stack_dir==0) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The first key returned nothing but zero values.  I can't deal!");
                foreach (Interval ival in val_ranges) {
                    if (StackDirection(ival) != stack_dir) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "A stacked graph can only handle all negative or all positive numbers.");
                    if (calc_ival_y) {
                        if (stack_dir < 1) {
                            if (ival.T1 > ival_y.T0) ival_y.T0 = ival.T1;
                            if (ival.T0 < ival_y.T1) ival_y.T1 = ival.T0;
                        } else {
                            if (ival.T0 < ival_y.T0) ival_y.T0 = ival.T0;
                            if (ival.T1 > ival_y.T1) ival_y.T1 = ival.T1;
                        }
                    }
                }

                if (force_start_at_zero && calc_ival_y) ival_y.T0 = 0;

                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval> intervalTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval>();
                intervalTreeOut.Append(new Grasshopper.Kernel.Types.GH_Interval(ival_y),new Grasshopper.Kernel.Data.GH_Path(0));
                foreach (Interval ival in val_ranges) intervalTreeOut.Append(new Grasshopper.Kernel.Types.GH_Interval(ival), new Grasshopper.Kernel.Data.GH_Path(1));

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(3, ref plane);

                Grasshopper.Kernel.Types.UVInterval ival2d = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(4, ref ival2d)) {
                    ival2d.U0 = 0.0;
                    ival2d.U1 = 12.0;
                    ival2d.V0 = 0.0;
                    ival2d.V1 = 1.0;
                }

                double barWidth = 1.0;
                DA.GetData(5, ref barWidth);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> pointTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle> rectTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle>();
                List<Point3d> basepoints = new List<Point3d>();
                for (int h = 0; h < hours.Count; h++) {
                    Point3d gpt = GraphPoint(hours[h].hr, 0.0f, plane, ival_y, ival2d);
                    Point3d wpt = plane.PointAt(gpt.X, 0.0);
                    basepoints.Add(wpt);
                }

                for (int k = 0; k < keys.Count; k++) {
                    Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(k);
                    List<Point3d> points = new List<Point3d>();
                    List<Rectangle3d> rects = new List<Rectangle3d>();

                    for (int h = 0; h < hours.Count; h++) {
                        float val = val_dict[keys[k]][h];
                        for (int kk = 0; kk < k; kk++) val += val_dict[keys[kk]][h]; // add in all previous values
                        Point3d gpt = GraphPoint(hours[h].hr, val, plane, ival_y, ival2d); // returns a point in graph coordinates

                        hours[h].pos = gpt; // the hour records the point in graph coordinates
                        hourTreeOut.Append(new DHr(hours[h]), key_path);

                        Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                        points.Add(wpt); // adds this point in world coordinates

                        Interval ival_gx; // interval of horz space occupied by this hour in graphic units
                        Interval ival_gy = new Interval(ival2d.V0, gpt.Y); // interval of vertical space occupied by this hour in graphic units
                        if (!hours[h].is_surrogate) {
                            double delta_x2 = (Math.Abs(ival2d.U.Length) / 8760 / 2.0);
                            ival_gx = new Interval(gpt.X - delta_x2, gpt.X + delta_x2); // interval of horz space occupied by this hour in graphic units
                        } else {

                            // if we've been passed surrogate hours, the spacing between bars may not be consistant
                            // we assume we've been given an hour at the start of the range represented
                            double ival_gx_0 = gpt.X;
                            double ival_gx_1;
                            if (h < hours.Count - 1) {
                                Point3d pt_next = GraphPoint(hours[h + 1].hr, val_dict[keys[k]][h + 1], plane, ival_y, ival2d);
                                ival_gx_1 = gpt.X + (pt_next.X - gpt.X) * barWidth;
                            } else { ival_gx_1 = gpt.X + (ival2d.U1 - gpt.X) * barWidth; }
                            ival_gx = new Interval(ival_gx_0, ival_gx_1);
                            if (hours.Count == 1) ival_gx = ival2d.U;

                        }
                        Rectangle3d rect = new Rectangle3d(plane, ival_gx, ival_gy);
                        rects.Add(rect);
                    }

                    List<Grasshopper.Kernel.Types.GH_Point> gh_points = new List<Grasshopper.Kernel.Types.GH_Point>();
                    foreach (Point3d pt in points) gh_points.Add(new Grasshopper.Kernel.Types.GH_Point(pt));
                    pointTreeOut.AppendRange(gh_points, key_path);

                    List<Grasshopper.Kernel.Types.GH_Rectangle> gh_rects = new List<Grasshopper.Kernel.Types.GH_Rectangle>();
                    foreach (Rectangle3d rec in rects) gh_rects.Add(new Grasshopper.Kernel.Types.GH_Rectangle(rec));
                    rectTreeOut.AppendRange(gh_rects, key_path);

                }

                DA.SetDataTree(0, hourTreeOut);
                DA.SetDataTree(1, intervalTreeOut);
                DA.SetDataTree(2, pointTreeOut);
                DA.SetDataList(3, basepoints);
                DA.SetDataTree(4, rectTreeOut);

            }
        }
Ejemplo n.º 44
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            List<object> v_list = new List<object>();
            GH_ObjectWrapper gh_dict = new GH_ObjectWrapper();
            IDictionary<string, string> dict = new Dictionary<string,string>();
            string k = "";

            //GH_Dict test = GH_Dict.create("a", 1.0);

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();
            if (!DA.GetData(0, ref gph)) return;

            int nGen = 0;
            string pyString = "";
            if (!DA.GetData(1, ref pyString)) return;
            if (!DA.GetDataList(2, v_list)) return;
            if (!DA.GetData(3, ref nGen)) return;
            if (!DA.GetData(4, ref gh_dict)) return;
            if (!DA.GetData(5, ref k)) return;

            //dict = (IDictionary<string, string>)gh_dict.Value;

            //object d = gh_dict.Value;
            var t = Type.GetType("IronPython.Runtime.PythonDictionary,IronPython");
            IDictionary i_dict = Activator.CreateInstance(t) as IDictionary;
            //IronPython.Runtime.PythonDictionary d = gh_dict.Value;
            //string v = d.get(k);
            string v = "oops";

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            //object[] val_list = new object[gph.nodes.Count];
            //int v_i = 0;
            //for (int i = 0; i < gph.nodes.Count; i++)
            //{
            //    if (v_i == v_list.Count) v_i = 0;
            //    val_list[i] = v_list[v_i];
            //    v_i++;
            //}

            //AWorld wrld = new AWorld(gph, val_list);

            //_py = PythonScript.Create();
            //_py.Output = this.m_py_output.Write;
            //_compiled_py = _py.Compile(pyString);

            //// console out
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            //// Main evaluation cycle
            //// Should move code into the Antsworld Class
            //for (int g = 0; g < nGen; g++)
            //{
            //    // console out
            //    this.m_py_output.Reset();

            //    double[] new_vals = new double[wrld.NodeCount];
            //    for (int i = 0; i < wrld.NodeCount; i++)
            //    {
            //        int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

            //        // build list of neighboring values
            //        List<double> neighboring_vals = new List<double>();
            //        for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

            //        double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals);
            //        //double d = g + i + 0.0;

            //        new_vals[i] = d;
            //    }
            //    wrld.AddGen(new_vals);

            //    // console out
            //    Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
            //    List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
            //    foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
            //    consoleOut.AppendRange(gh_strs, key_path);

            //}

            DA.SetDataTree(0, consoleOut);
            //DA.SetData(1, wrld);
            DA.SetData(2, v);
        }
Ejemplo n.º 45
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> dhrs = new List<DHr>();
            string period_string = "";
            if ((DA.GetDataList(0, dhrs)) && (DA.GetData(1, ref period_string))) {
                if (period_string == "") { return; }
                period_string = period_string.ToLowerInvariant().Trim();
                this.cycle_type = CType.Invalid;
                if (period_string.Contains("year")) { this.cycle_type = CType.Yearly; } else if (period_string.Contains("monthly diurnal")) { this.cycle_type = CType.MonthlyDiurnal; } else if (period_string.Contains("month")) { this.cycle_type = CType.Monthly; } else if (period_string.Contains("day") || period_string.Contains("daily")) { this.cycle_type = CType.Daily; } else if (period_string.Contains("weekly diurnal")) { this.cycle_type = CType.WeeklyDiurnal; } else if (period_string.Contains("weekly")) { this.cycle_type = CType.Weekly; } else {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "I don't understand the time period you're looking for.\nPlease choose 'yearly', 'monthly', 'monthly diurnal', 'weekly', 'weekly diurnal', or 'daily'.");
                }

                string[] commonKeys = DHr.commonkeys(dhrs.ToArray());
                Dictionary<string, List<DHr>> stat_hours = new Dictionary<string, List<DHr>>();
                InitStatHours(ref stat_hours);

                HourMask mask = new HourMask();

                switch (this.cycle_type) {

                    case CType.MonthlyDiurnal:
                    case CType.WeeklyDiurnal:
                        Grasshopper.Kernel.Data.GH_Structure<DHr> meanTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> modeTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> highTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> uqTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> medianTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> lqTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> lowTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                        Grasshopper.Kernel.Data.GH_Structure<DHr> sumTree = new Grasshopper.Kernel.Data.GH_Structure<DHr>();

                        switch (this.cycle_type) {
                            case CType.MonthlyDiurnal:
                                for (int mth = 0; mth < 12; mth++) {
                                    InitStatHours(ref stat_hours);
                                    for (int hour = 0; hour < 24; hour++) {
                                        mask.maskByMonthAndHour(mth, hour);
                                        int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddMonths(mth).AddHours(hour)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                                        CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                                    }
                                    meanTree.AppendRange(stat_hours["meanHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    modeTree.AppendRange(stat_hours["modeHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    highTree.AppendRange(stat_hours["highHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    uqTree.AppendRange(stat_hours["uqHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    medianTree.AppendRange(stat_hours["medianHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    lqTree.AppendRange(stat_hours["lqHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    lowTree.AppendRange(stat_hours["lowHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                    sumTree.AppendRange(stat_hours["sumHrs"], new Grasshopper.Kernel.Data.GH_Path(mth));
                                }
                                break;
                            case CType.WeeklyDiurnal:
                                for (int wk = 0; wk < 52; wk++) {
                                    InitStatHours(ref stat_hours);
                                    for (int hour = 0; hour < 24; hour++) {
                                        mask.maskByWeekAndHour(wk, hour);
                                        int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddDays(wk * 7).AddHours(hour)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                                        CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                                    }
                                    meanTree.AppendRange(stat_hours["meanHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    modeTree.AppendRange(stat_hours["modeHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    highTree.AppendRange(stat_hours["highHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    uqTree.AppendRange(stat_hours["uqHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    medianTree.AppendRange(stat_hours["medianHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    lqTree.AppendRange(stat_hours["lqHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    lowTree.AppendRange(stat_hours["lowHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                    sumTree.AppendRange(stat_hours["sumHrs"], new Grasshopper.Kernel.Data.GH_Path(wk));
                                }
                                break;
                        }
                        DA.SetDataTree(0, meanTree);
                        DA.SetDataTree(1, modeTree);
                        DA.SetDataTree(2, highTree);
                        DA.SetDataTree(3, uqTree);
                        DA.SetDataTree(4, medianTree);
                        DA.SetDataTree(5, lqTree);
                        DA.SetDataTree(6, lowTree);
                        DA.SetDataTree(7, sumTree);
                        break;

                    case CType.Daily:
                        for (int day = 0; day < 365; day++) {
                            mask.maskByDayOfYear(day, day); // passing in same day twice masks to this single day
                            int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddDays(day).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                            CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                        }
                        SetOutputData(DA, stat_hours);
                        break;

                    case CType.Weekly:
                        for (int wk = 0; wk < 52; wk++) {
                            mask.maskByWeek(wk);
                            int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddDays(wk * 7).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                            CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                        }
                        SetOutputData(DA, stat_hours);
                        break;

                    case CType.Monthly:
                        for (int mth = 0; mth < 12; mth++) {
                            mask.maskByMonthOfYear(mth);
                            int hh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddMonths(mth).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                            CalculateStats(dhrs, commonKeys, stat_hours, mask, hh, true);
                        }
                        SetOutputData(DA, stat_hours);
                        break;

                    case CType.Yearly:
                        mask.fillMask(true); // all hours may pass
                        int hhh = Util.hourOfYearFromDatetime(Util.baseDatetime().AddMonths(6).AddDays(15).AddHours(0)) + 1; // had to add one, looks like Util function was designed for parsing non-zero-indexed hours
                        CalculateStats(dhrs, commonKeys, stat_hours, mask, hhh, true);
                        SetOutputData(DA, stat_hours);
                        break;
                    default:
                        this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Time period option not yet implimented.  Cannot produce statistics.");
                        break;
                }

            }
        }
        /// <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)
        {
            //---- Declareing -------------------------------------------------------------------------------

            GH_Structure<GH_Point> SofistikPts;
            DA.GetDataTree("SofistikPoints", out SofistikPts);

            List<Point3d> flatclean = new List<Point3d>();
            DA.GetDataList<Point3d>("Flatten Points", flatclean);

            DataTree<int> SofistikInt = new DataTree<int>();

            //---- End Declareing ---------------------------------------------------------------------------

            //---- Functions --------------------------------------------------------------------------------

            for (int i = 0; i < flatclean.Count; i++)
            {
                Point3d fpoint = flatclean[i];

                for (int j = 0; j < SofistikPts.Paths.Count; j++)
                {
                    GH_Path pth = SofistikPts.Paths[j];
                    for (int k = 0; k < SofistikPts[pth].Count; k++)
                    {
                        GH_Point ghp = SofistikPts[pth][k];

                        if ((Math.Abs(fpoint.X - ghp.Value.X) <= 0.01) &&
                                (Math.Abs(fpoint.Y - ghp.Value.Y) <= 0.01) &&
                                (Math.Abs(fpoint.Z - ghp.Value.Z) <= 0.01))
                        {
                            SofistikInt.Add(i, pth.AppendElement(k));
                        }
                    }

                }
            }

            //---- End Functions ----------------------------------------------------------------------------

            //---- Set Output -----------------------------------------------------------------------------

            DA.SetDataTree(0, SofistikInt);

            //---- End Set Output -----------------------------------------------------------------------------
        }
 protected override void SetOutputs(IGH_DataAccess da)
 {
   AbstractEnvironmentType environment = new PolysurfaceEnvironmentType(brep, borderDir);
   da.SetData(nextOutputIndex++, environment);
   da.SetDataTree(nextOutputIndex++, BrepArray2DToDatatree(((PolysurfaceEnvironmentType)environment).BorderWallsArray));
 }
Ejemplo n.º 48
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)
        {
            //-----------------------------------------------------------------INPUT----------------------------------------------------------------------------//

            List<IGoal> permanentGoals = new List<IGoal>();
            DA.GetDataList(0, permanentGoals);

            List<IGoal> loadGoals = new List<IGoal>();
            DA.GetDataList(1, loadGoals);

            double fStart = 1.0;
            DA.GetData(2, ref fStart);

            double fStep = 0.1;
            DA.GetData(3, ref fStep);

            double angle = 15.0;
            DA.GetData(4, ref angle);
            angle *= Math.PI / 180.0;

            double displ = 2.0;
            DA.GetData(5, ref displ);

            double threshold = 1e-15;
            DA.GetData(6, ref threshold);

            int equilibriumIter = 100;
            DA.GetData(7, ref equilibriumIter);

            bool opt = false;
            DA.GetData(8, ref opt);

            int maxIterations = 1000;


            //--------------------------------------------------------------CALCULATE----------------------------------------------------------------------------//

            //-------------------VALUES TO STORE----------------------------//
            //Position lists
            List<Point3d> initialPositions = new List<Point3d>();
            List<Point3d> previousPositions = new List<Point3d>();
            List<Point3d> currentPositions = new List<Point3d>();
            DataTree<Point3d> vertexPositions = new DataTree<Point3d>();

            //Goal output lists
            List<object> previousGOutput = new List<object>();
            List<object> currentGOutput = new List<object>();
            DataTree<object> outputGoals = new DataTree<object>();

            //Load factors and displacements
            List<double> loadfactors = new List<double>();
            List<double> displacementsRMS = new List<double>();


            //-------------------K2 PHYSICAL SYSTEM----------------------------//
            //Initialise Kangaroo solver
            var PS = new KangarooSolver.PhysicalSystem();
            var GoalList = new List<IGoal>();

            //Assign indexes to the particles in each Goal
            foreach (IGoal pG in permanentGoals)
            {
                PS.AssignPIndex(pG, 0.01);
                GoalList.Add(pG);
            }

            foreach (IGoal lG in loadGoals)
            {
                PS.AssignPIndex(lG, 0.01);
                GoalList.Add(lG);
            }

            //Store initial loads
            List<Vector3d> initialLoads = new List<Vector3d>();
            for (int i = 0; i < loadGoals.Count; i++)
            {
                initialLoads.Add(loadGoals[i].Move[0]);
            }


            //-------------------INITIALISE VALUE LISTS----------------------------//
            //Initial vertex positions
            Point3d[] initPos = PS.GetPositionArray();
            foreach (Point3d pt in initPos)
            {
                initialPositions.Add(pt);
                previousPositions.Add(pt);
                currentPositions.Add(pt);
            }

            //Initial goal output
            List<object> initGOutput = PS.GetOutput(GoalList);
            for (int i = 0; i < permanentGoals.Count; i++)
            {
                previousGOutput.Add(initGOutput[i]);
                currentGOutput.Add(initGOutput[i]);
            }


            //-------------------LOAD INCREMENT LOOP----------------------------//
            bool run = true;
            int iter = 0;

            double LF;
            double BLF = 0.0;
            double preRMS = 0.0;

            while (run && iter < maxIterations)
            {
                LF = fStart + (fStep * iter);
                loadfactors.Add(LF);

                //Scale load goals in each iteration
                for (int i = 0; i < loadGoals.Count; i++)
                {
                    int index = GoalList.Count - loadGoals.Count + i;
                    Vector3d scaledLoad = initialLoads[i] * LF;
                    GoalList[index] = new KangarooSolver.Goals.Unary(GoalList[index].PIndex[0], scaledLoad);
                }


                //Solve equilibrium for given load increment
                int counter = 0;
                do
                {
                    PS.Step(GoalList, true, threshold);
                    counter++;
                } while (PS.GetvSum() > threshold && counter < equilibriumIter);



                //Update value lists
                GH_Path path = new GH_Path(iter);

                //Get new equilibrium positions and update position lists
                Point3d[] newPositions = PS.GetPositionArray();

                for (int k = 0; k < initialPositions.Count; k++)
                {
                    previousPositions[k] = currentPositions[k];
                    currentPositions[k] = newPositions[k];

                    if (opt)
                    {
                        vertexPositions.Add(newPositions[k], path);
                    }
                }

                //Get new goal output and update goal output lists
                List<object> newGOutput = PS.GetOutput(GoalList);
                for (int m = 0; m < permanentGoals.Count; m++)
                {
                    previousGOutput[m] = currentGOutput[m];
                    currentGOutput[m] = newGOutput[m];

                    if (opt)
                    {
                        outputGoals.Add(newGOutput[m], path);
                    }
                }



                //Does buckling occur?
                List<Vector3d> nodalDisplacements = calcDisplacement(currentPositions, initialPositions);
                double curRMS = calcDisplacementsRMS(nodalDisplacements);
                displacementsRMS.Add(curRMS);

                bool buckled = isBuckled(curRMS, preRMS, iter, fStart, fStep, angle);
                bool deflected = isDeflectionTooBig(nodalDisplacements, displ);

                if (buckled || deflected)
                {
                    run = false;
                    BLF = LF - fStep;
                }

                //Update
                preRMS = curRMS;
                iter++;
            }


            //-----------------------FLAG BUCKLED STATE----------------------------//
            if (BLF >= 1.0)
            {
                this.Message = "Works!";
            }
            else
            {
                this.Message = "Buckles!";
            }


            //-----------------------WARNING----------------------------//
            //If the maximum number of iterations has been reached
            if (iter == maxIterations)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Buckling did not occur within " + maxIterations + " load increments. Adjust load-step");
            }


            //-----------------------UPDATE VALUE LISTS----------------------------//
            //If opt is false then add results from last two iterations
            if (!opt)
            {
                for (int i = 0; i < currentPositions.Count; i++)
                {
                    vertexPositions.Add(previousPositions[i], new GH_Path(0));
                    vertexPositions.Add(currentPositions[i], new GH_Path(1));
                }

                for (int j = 0; j < currentGOutput.Count; j++)
                {
                    outputGoals.Add(previousGOutput[j], new GH_Path(0));
                    outputGoals.Add(currentGOutput[j], new GH_Path(1));
                }

            }


            //---------------------------------------------------------------OUTPUT-------------------------------------------------------------------------------//

            DA.SetData(0, BLF);
            DA.SetDataList(1, loadfactors);
            DA.SetDataList(2, displacementsRMS);
            DA.SetDataTree(3, vertexPositions);
            DA.SetDataTree(4, outputGoals);
        }
Ejemplo n.º 49
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeIn = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
            String key = "";
            if (DA.GetDataTree(0, out hourTreeIn) && DA.GetData(1, ref key)) {

                Interval ival_y = new Interval();
                float[] garbage = new float[0];
                if (!(DA.GetData(2, ref ival_y))) DHr.get_domain(key, hourTreeIn.ToArray(), ref garbage, ref ival_y); // vals are no good here, we would need a tree of values

                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(3, ref plane);

                Grasshopper.Kernel.Types.UVInterval ival2d = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(4, ref ival2d)) {
                    ival2d.U0 = 0.0;
                    ival2d.U1 = 12.0;
                    ival2d.V0 = 0.0;
                    ival2d.V1 = 1.0;
                }

                double barWidth = 1.0;
                DA.GetData(5, ref barWidth);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> points = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle> rects = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle>();

                double ival2d_u_delta = ival2d.U.Length / hourTreeIn.Branches.Count;

                for (int b = 0; b < hourTreeIn.Branches.Count; b++) {
                    List<DHr> hours = hourTreeIn.Branches[b];
                    Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(b);
                    hourTreeOut.EnsurePath(path);
                    points.EnsurePath(path);
                    rects.EnsurePath(path);

                    Grasshopper.Kernel.Types.UVInterval ival2d_sub = new Grasshopper.Kernel.Types.UVInterval(new Interval(b * ival2d_u_delta, (b + 1) * ival2d_u_delta), ival2d.V);
                    double t0_sub = ival2d_sub.U.Mid - (ival2d_sub.U.Mid - ival2d_sub.U.T0) * barWidth;
                    double t1_sub = ival2d_sub.U.Mid + (ival2d_sub.U.T1 - ival2d_sub.U.Mid) * barWidth;
                    ival2d_sub.U = new Interval(t0_sub, t1_sub);

                    for (int h = 0; h < hours.Count; h++) {
                        Point3d gpt = GraphPoint(hours[h].hr % 24, hours[h].val(key), plane, ival_y, ival2d_sub); // returns a point in graph coordinates
                        hours[h].pos = gpt; // the hour records the point in graph coordinates
                        hourTreeOut.Append(hours[h], path);

                        Point3d wpt = plane.PointAt(gpt.X, gpt.Y);
                        points.Append(new Grasshopper.Kernel.Types.GH_Point(wpt), path);  // adds this point in world coordinates

                        double delta_x2 = (Math.Abs(ival2d_sub.U.Length) / 24.0 / 2.0);
                        Interval ival_gx = new Interval(gpt.X - delta_x2, gpt.X + delta_x2); // interval of horz space occupied by this hour in graphic units
                        Interval ival_gy = new Interval(ival2d_sub.V0, gpt.Y); // interval of vertical space occupied by this hour in graphic units

                        Rectangle3d rect = new Rectangle3d(plane, ival_gx, ival_gy);
                        rects.Append(new Grasshopper.Kernel.Types.GH_Rectangle(rect), path);

                    }
                }

                DA.SetDataTree(0, hourTreeOut);
                DA.SetDataTree(1, points);
                DA.SetDataTree(2, rects);

            }
        }
Ejemplo n.º 50
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeIn = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
            string key = "";
            int subdivs = 0;
            if ((DA.GetDataTree(0, out hourTreeIn)) && (DA.GetData(1, ref key)) && (DA.GetData(3, ref subdivs)))
            {
                Interval ival_overall = new Interval();
                if (!DA.GetData(2, ref ival_overall)) {
                    // go thru the given hours and find the max and min value for the given key
                    ival_overall.T0 = MDHr.INVALID_VAL;
                    ival_overall.T1 = MDHr.INVALID_VAL;
                    foreach (DHr dhr in hourTreeIn.AllData(true)) {
                        float val = dhr.val(key);
                        if ((ival_overall.T0 == MDHr.INVALID_VAL) || (val < ival_overall.T0)) ival_overall.T0 = val;
                        if ((ival_overall.T1 == MDHr.INVALID_VAL) || (val > ival_overall.T1)) ival_overall.T1 = val;
                    }
                }

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer> freqTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval> ivalTreeOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval>();

                List<Interval> ivalList = new List<Interval>();
                if (ival_overall.IsDecreasing) ival_overall.Swap();
                double delta = ival_overall.Length / subdivs;
                for (int n = 0; n < subdivs; n++) {  ivalList.Add(new Interval(ival_overall.T0 + n * delta, ival_overall.T0 + ((n + 1) * delta)));  }

                for (int b = 0; b < hourTreeIn.Branches.Count; b++)
                {
                    Grasshopper.Kernel.Data.GH_Structure<DHr> hourBranch = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                    for (int n = 0; n < subdivs; n++) { hourBranch.EnsurePath(n); }
                    List<int> freqOut = new List<int>();

                    List<DHr> hrsIn = hourTreeIn.Branches[b];
                    foreach (DHr dhr in hrsIn)
                    {
                        if (dhr.val(key) < ivalList[0].T0)
                        {
                            hourBranch.Append(dhr, new Grasshopper.Kernel.Data.GH_Path(0));
                            continue;
                        }
                        if (dhr.val(key) > ivalList[ivalList.Count - 1].T1)
                        {
                            hourBranch.Append(dhr, new Grasshopper.Kernel.Data.GH_Path(ivalList.Count - 1));
                            continue;
                        }
                        for (int n = 0; n < subdivs; n++)
                        {
                            if (ivalList[n].IncludesParameter(dhr.val(key)))
                            {
                                hourBranch.Append(dhr,new Grasshopper.Kernel.Data.GH_Path(n));
                                break;
                            }
                        }
                    }

                    for (int bb = 0; bb < hourBranch.Branches.Count; bb++)
                    {
                        Grasshopper.Kernel.Data.GH_Path branch_path = hourTreeIn.Paths[b].AppendElement(bb);
                        hourTreeOut.AppendRange(hourBranch.Branches[bb], branch_path);
                        Grasshopper.Kernel.Types.GH_Integer freq = new Grasshopper.Kernel.Types.GH_Integer(hourBranch.Branches[bb].Count);
                        freqTreeOut.Append(freq, branch_path);
                        Grasshopper.Kernel.Types.GH_Interval ival = new Grasshopper.Kernel.Types.GH_Interval(ivalList[bb]);
                        ivalTreeOut.Append(ival, branch_path);
                    }

                }

                hourTreeOut.Simplify(Grasshopper.Kernel.Data.GH_SimplificationMode.CollapseAllOverlaps);
                freqTreeOut.Simplify(Grasshopper.Kernel.Data.GH_SimplificationMode.CollapseAllOverlaps);
                ivalTreeOut.Simplify(Grasshopper.Kernel.Data.GH_SimplificationMode.CollapseAllOverlaps);

                DA.SetDataTree(0, freqTreeOut);
                DA.SetDataTree(1, ivalTreeOut);
                DA.SetDataTree(2, hourTreeOut);
            }
        }
Ejemplo n.º 51
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeIn = new Grasshopper.Kernel.Data.GH_Structure<DHr>();

            if (DA.GetDataTree(0, out hourTreeIn)) {
                Plane plane = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1));
                DA.GetData(1, ref plane);

                Grasshopper.Kernel.Types.UVInterval ival2d = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(2, ref ival2d)) {
                    ival2d.U0 = 0.0;
                    ival2d.U1 = 1.0;
                    ival2d.V0 = 0.0;
                    ival2d.V1 = 2.0;
                }
                if (ival2d.U.IsDecreasing) ival2d.U.Swap();
                if (ival2d.V.IsDecreasing) ival2d.V.Swap();

                double barWidthScale = 1.0;
                DA.GetData(3, ref barWidthScale);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hourTreeOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point> points = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Point>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle> srects = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Rectangle>();
                List<Rectangle3d> rects = new List<Rectangle3d>();
                List<Mesh> meshes = new List<Mesh>();

                int i = 0;//keeps track of which branch we're on... note, this assumes we've been passed a list of lists and nothing 'deeper'
                int maxHourCount = hourTreeIn.Branches[0].Count;
                foreach (List<DHr> hourList in hourTreeIn.Branches) if (hourList.Count > maxHourCount) maxHourCount = hourList.Count;
                Rectangle3d brect = new Rectangle3d(plane, new Interval(0, ival2d.U1), new Interval(0, ival2d.V.ParameterAt((double)hourTreeIn.DataCount / maxHourCount)));
                DA.SetData(5, brect);

                double dx = ival2d.U.Length / hourTreeIn.Branches.Count * barWidthScale;
                double dy = ival2d.V.Length / maxHourCount;
                foreach (List<DHr> hourList in hourTreeIn.Branches) {
                    Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(i);
                    hourTreeOut.EnsurePath(path);
                    points.EnsurePath(path);
                    srects.EnsurePath(path);

                    double x = ival2d.U.ParameterAt((i + 0.5) / hourTreeIn.Branches.Count);
                    for (int j = 0; j < hourList.Count; j++) {
                        DHr dhour = hourList[j];

                        double y = ival2d.V.ParameterAt((j + 0.5) / maxHourCount);
                        Point3d pt = plane.PointAt(x, y);
                        dhour.pos = new Point3d(x, y, 0);
                        points.Append(new Grasshopper.Kernel.Types.GH_Point(pt), path);
                        hourTreeOut.Append(dhour, path);

                        Plane pln = new Plane(plane);
                        pln.Origin = plane.PointAt(x - dx / 2, y - dy / 2);
                        Rectangle3d rct = new Rectangle3d(pln, dx, dy);
                        srects.Append(new Grasshopper.Kernel.Types.GH_Rectangle(rct), path);
                    }

                    // make meshes & big rectangles
                    if (hourList.Count > 0) {
                        Mesh mesh = new Mesh();
                        // add bottom pts
                        mesh.Vertices.Add(plane.PointAt(x - dx / 2, 0));
                        mesh.VertexColors.Add(hourList[0].color);
                        mesh.Vertices.Add(plane.PointAt(x + dx / 2, 0));
                        mesh.VertexColors.Add(hourList[0].color);

                        for (int j = 0; j < hourList.Count; j++) {
                            double y = ival2d.V.ParameterAt((j + 0.5) / maxHourCount);
                            mesh.Vertices.Add(plane.PointAt(x - dx / 2, y));
                            mesh.VertexColors.Add(hourList[j].color);
                            mesh.Vertices.Add(plane.PointAt(x + dx / 2, y));
                            mesh.VertexColors.Add(hourList[j].color);
                        }

                        // add top pts
                        double yy = ival2d.V.ParameterAt((float)hourList.Count / maxHourCount);
                        mesh.Vertices.Add(plane.PointAt(x - dx / 2, yy));
                        mesh.VertexColors.Add(hourList[hourList.Count - 1].color);
                        mesh.Vertices.Add(plane.PointAt(x + dx / 2, yy));
                        mesh.VertexColors.Add(hourList[hourList.Count - 1].color);

                        for (int n = 2; n < mesh.Vertices.Count; n = n + 2) mesh.Faces.AddFace(n - 2, n - 1, n + 1, n);
                        meshes.Add(mesh);

                        Plane pln = new Plane(plane);
                        pln.Origin = plane.PointAt(x - dx / 2, 0);
                        Rectangle3d rct = new Rectangle3d(pln, dx, yy);
                        rects.Add(rct);
                    }

                    i++;
                }

                DA.SetDataTree(0, hourTreeOut);
                DA.SetDataTree(1, points);
                DA.SetDataList(2, srects);
                DA.SetDataList(3, rects);
                DA.SetDataList(4, meshes);

            }
        }
Ejemplo n.º 52
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> dhrs = new List<DHr>();
            string key_u = "";
            string key_v = "";
            Interval subdivs = new Interval();
            if ((DA.GetDataList(0, dhrs)) && (DA.GetData(1, ref key_u)) && (DA.GetData(2, ref key_v)) && (DA.GetData(4, ref subdivs)))
            {
                int subdivs_u = (int) Math.Floor(subdivs.T0);
                int subdivs_v = (int) Math.Floor(subdivs.T1);

                Grasshopper.Kernel.Types.UVInterval ival_overall = new Grasshopper.Kernel.Types.UVInterval();
                if (!DA.GetData(3, ref ival_overall)) {
                    // go thru the given hours and find the max and min value for the given key
                    Interval ival_temp_u = new Interval(MDHr.INVALID_VAL, MDHr.INVALID_VAL);
                    Interval ival_temp_v = new Interval(MDHr.INVALID_VAL, MDHr.INVALID_VAL);
                    foreach (DHr dhr in dhrs) {
                        float val_u = dhr.val(key_u);
                        float val_v = dhr.val(key_v);
                        if ((ival_temp_u.T0 == MDHr.INVALID_VAL) || (val_u < ival_temp_u.T0)) ival_temp_u.T0 = val_u;
                        if ((ival_temp_u.T1 == MDHr.INVALID_VAL) || (val_u > ival_temp_u.T1)) ival_temp_u.T1 = val_u;
                        if ((ival_temp_v.T0 == MDHr.INVALID_VAL) || (val_v < ival_temp_v.T0)) ival_temp_v.T0 = val_v;
                        if ((ival_temp_v.T1 == MDHr.INVALID_VAL) || (val_v > ival_temp_v.T1)) ival_temp_v.T1 = val_v;
                    }
                }

                bool cull_outliers = false;
                DA.GetData(5, ref cull_outliers);

                Grasshopper.Kernel.Data.GH_Structure<DHr> hrsOut = new Grasshopper.Kernel.Data.GH_Structure<DHr>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer> freqOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Integer>();
                Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval2D> ivalsOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_Interval2D>();

                if (ival_overall.U.IsDecreasing) ival_overall.U.Swap();
                if (ival_overall.V.IsDecreasing) ival_overall.V.Swap();
                double delta_u = ival_overall.U.Length / subdivs_u;
                double delta_v = ival_overall.V.Length / subdivs_v;
                for (int u = 0; u < subdivs_u; u++) {
                    for (int v = 0; v < subdivs_v; v++) {
                        Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(new int[] { u, v });
                        ivalsOut.EnsurePath(path);
                        hrsOut.EnsurePath(path);

                        Interval sub_u = new Interval(ival_overall.U.T0 + u * delta_u, ival_overall.U.T0 + ((u + 1) * delta_u));
                        Interval sub_v = new Interval(ival_overall.V.T0 + v * delta_v, ival_overall.V.T0 + ((v + 1) * delta_v));
                        Grasshopper.Kernel.Types.UVInterval sub_uv = new Grasshopper.Kernel.Types.UVInterval(sub_u, sub_v);
                        Grasshopper.Kernel.Types.GH_Interval2D i2d = new Grasshopper.Kernel.Types.GH_Interval2D();
                        i2d.Value = sub_uv;
                        ivalsOut.Append(i2d, path);
                    }
                }

                foreach (DHr dhr in dhrs) {
                    int[] address = new int[] { -1 , -1};
                    for (int u = 0; u < subdivs_u; u++)
                    {
                        Grasshopper.Kernel.Data.GH_Path path_u = new Grasshopper.Kernel.Data.GH_Path(new int[] { u, 0 });
                        Interval sub_u = ivalsOut.get_DataItem(path_u, 0).Value.U;
                        double val = dhr.val(key_u);
                        if ((sub_u.IncludesParameter(val)) || ((!cull_outliers) && (u == 0) && (val <= sub_u.Min)) || ((!cull_outliers) && (u == subdivs_u - 1) && (val >= sub_u.Max)))
                        {
                            address[0] = u;
                            break;
                        }
                    }

                    for (int v = 0; v < subdivs_v; v++)
                    {
                        Grasshopper.Kernel.Data.GH_Path path_v = new Grasshopper.Kernel.Data.GH_Path(new int[] { 0, v });
                        Interval sub_v = ivalsOut.get_DataItem(path_v, 0).Value.V;
                        double val = dhr.val(key_v);
                        if ((sub_v.IncludesParameter(val)) || ((!cull_outliers) && (v == 0) && (val <= sub_v.Min)) || ((!cull_outliers) && (v == subdivs_v - 1) && (val >= sub_v.Max)))
                        {
                            address[1] = v;
                            break;
                        }
                    }
                    if ((address[0] < 0) || (address[1] < 0))
                    {
                        if (!cull_outliers) this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Crud. Could not place an outlier into any intervals.  What gives?!");
                    }
                    else
                    {
                        Grasshopper.Kernel.Data.GH_Path path = new Grasshopper.Kernel.Data.GH_Path(address);
                        hrsOut.Append(dhr, path);
                    }
                }

                foreach (Grasshopper.Kernel.Data.GH_Path path in hrsOut.Paths)
                {
                    int n = hrsOut.get_Branch(path).Count;
                    freqOut.Append(new Grasshopper.Kernel.Types.GH_Integer(n), path);
                }

                DA.SetDataTree(0, freqOut);
                DA.SetDataTree(1, ivalsOut);
                DA.SetDataTree(2, hrsOut);
            }
        }
Ejemplo n.º 53
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // 1. Declare placeholder
            string source = null;
            string query = null;
            string indexPath = null;

            DataTree<string> queryResultTree = new DataTree<string>();

            // 2. Abort on invalid inputs.
            if (!DA.GetData(0, ref source)) { return; }
            if (source == null) { return; }
            if (source.Length == 0) { return; }
            if (!DA.GetData(1, ref query)) { return; }
            if (query == null) { return; }
            if (query.Length == 0) { return; }
            if (!DA.GetData(2, ref indexPath)) { return; }
            if (query == null) { return; }
            if (query.Length == 0) { return; }

            gh_watcher = new GH_FileWatcher(indexPath, true, gh_watcher_Changed);

            // 3. Connect to source & fetch data

            MySqlConnection connection = new MySqlConnection(source);

            try
            {
                connection.Open();
            }
            catch (Exception ex)
            {
                output.Add("Connection Failed.\n" + ex.ToString());
            }

            try
            {
                MySqlCommand command = connection.CreateCommand();
                command.CommandText = query;

                MySqlDataReader reader = command.ExecuteReader();

                int i = 0;
                while (reader.Read())
                {
                    for (int j = 0; j < reader.FieldCount; j++)
                    {
                        queryResultTree.Add(reader.GetString(j), new GH_Path(i));
                    }
                    i++;
                }
            }
            catch (Exception ex)
            {
                output.Add("Fetching failed.\n" + ex.ToString());
            }

            connection.Close();

            // 4. Output
            DA.SetDataTree(0, queryResultTree);
            DA.SetDataList(1, output);
        }
Ejemplo n.º 54
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);
        }
Ejemplo n.º 55
0
        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
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // getting input
            DA.GetData<SpringMesh>("Spring Mesh", ref iSpringMesh);
            DA.GetDataList<Curve>("PolyLine", iPolyLine);
            DA.GetDataList<int>("PolyLine ID", iPolyLineID);
            DA.GetDataList<double>("Thickness", iThickness);
            DA.GetDataList<bool>("Vertex status", iVertexStatus);
            DA.GetData<bool>("Allow PolySrf", ref iPolySrf);
            DA.GetData<double>("TangentScale Min", ref iTangentScaleMin);
            DA.GetData<double>("TangentScale Max", ref iTangentScaleMax);
            DA.GetDataList<Point3d>("Attractors", iAttractors);
            DA.GetDataList<bool>("Vertex Panel2", iVertexPanel2);
            DA.GetData<double>("PlanarOffset Min", ref iPlanarOffsetScaleMin);
            DA.GetData<double>("PlanarOffset Max", ref iPlanarOffsetScaleMax);
            DA.GetData<double>("Curve Pointiness Min", ref CurvePointinessMin);
            DA.GetData<double>("Curve Pointiness Max", ref CurvePointinessMax);

            DA.GetData<double>("Opening Width Min", ref iOpeningWidthMin);
            DA.GetData<double>("Opening Width Max", ref iOpeningWidthMax);
            DA.GetDataTree<GH_Number>("Manual Adjustments", out ManualValueTree);
            DA.GetData<int>("Curve Degree", ref curveDegree);
            DA.GetData<double>("Ground Level", ref iGroundPos);

            DA.GetData<bool>("Super Normalization", ref iSuperNormalization);
            //------------------------------------------------------------

            // get all Vertex indexies that are manual adjusted
            for (int i = 0; i < ManualValueTree.Branches.Count; i++)
            { ManualAdjustedVertexIndexies.Add(ManualValueTree.Paths[i].Indices[0]); }

            storePlatesTPI();

            calculateVerticesValues();
            calculateVertexNormals();
            calculateVertexCps();
            //calculateVerticesValues();

            triLoop();

            half_dualLoop();

            oDebugList = vertexNormals;

            //------------------------------------------------------------

            // setting output
            DA.SetData("Info", oInfo);
            DA.SetDataList("General List", oDebugList);
            DA.SetDataTree(2, oTriLoop);
            DA.SetDataTree(3, oTriLoopID);
            DA.SetDataTree(4, oTriLoopCurves);
            DA.SetDataTree(5, oDualLoop1);
            DA.SetDataTree(6, oDualLoop2);
            DA.SetDataTree(7, oDualLoop1ID);
            DA.SetDataTree(8, oDualLoop2ID);
            DA.SetDataTree(9, oDualLoop1Curves);
            DA.SetDataTree(10, oDualLoop2Curves);
            DA.SetDataTree(11, oClosedPanel);
            DA.SetDataTree(12, oTriLoopPlanCrv);
            DA.SetDataTree(13, oTriLoopEffectorHoles);

            // -----------------------------------------------------------
        }
Ejemplo n.º 57
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            List<double> v_list = new List<double>();
            //GH_Dict test = GH_Dict.create("a", 1.0);

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();
            if (!DA.GetData(0, ref gph)) return;

            int nGen = 0;
            string pyString = "";
            if (!DA.GetData(1, ref pyString)) return;
            if (!DA.GetDataList(2, v_list)) return;
            if (!DA.GetData(3, ref nGen)) return;

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            double[] val_list = new double[gph.nodes.Count];
            int v_i = 0;
            for (int i = 0; i < gph.nodes.Count; i++)
            {
                if (v_i == v_list.Count) v_i = 0;
                val_list[i] = v_list[v_i];
                v_i++;
            }

            AWorld wrld = new AWorld(gph, val_list);

            _py = PythonScript.Create();
            _py.Output = this.m_py_output.Write;
            _compiled_py = _py.Compile(pyString);

            // console out
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            // Main evaluation cycle
            // Should move code into the Antsworld Class
            for (int g = 0; g < nGen; g++)
            {
                // console out
                this.m_py_output.Reset();

                double[] new_vals = new double[wrld.NodeCount];
                for (int i = 0; i < wrld.NodeCount; i++)
                {
                    int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

                    // build list of neighboring values
                    List<double> neighboring_vals = new List<double>();
                    for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

                    double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals);
                    //double d = g + i + 0.0;

                    new_vals[i] = d;
                }
                wrld.AddGen(new_vals);

                // console out
                Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
                List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
                foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
                consoleOut.AppendRange(gh_strs, key_path);

            }

            DA.SetDataTree(0, consoleOut);
            DA.SetData(1, wrld);
        }
Ejemplo n.º 58
0
    private List<string> __out = new List<string>(); //Do not modify this list directly.

    #endregion Fields

    #region Methods

    public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List<object> inputs, IGH_DataAccess DA)
    {
        //Prepare for a new run...
        //1. Reset lists
        this.__out.Clear();
        this.__err.Clear();

        this.Component = owner;
        this.Iteration = iteration;
        this.GrasshopperDocument = owner.OnPingDocument();
        this.RhinoDocument = rhinoDocument as Rhino.RhinoDoc;

        this.owner = this.Component;
        this.runCount = this.Iteration;
        this. doc = this.RhinoDocument;

        //2. Assign input parameters
        Mesh Profile = default(Mesh);
        if (inputs[0] != null)
        {
          Profile = (Mesh)(inputs[0]);
        }

        List<Mesh> x = null;
        if (inputs[1] != null)
        {
          x = GH_DirtyCaster.CastToList<Mesh>(inputs[1]);
        }
        bool y = default(bool);
        if (inputs[2] != null)
        {
          y = (bool)(inputs[2]);
        }

        //3. Declare output parameters
          object A = null;

        //4. Invoke RunScript
        RunScript(Profile, x, y, ref A);

        try
        {
          //5. Assign output parameters to component...
            if (A != null)
          {
        if (GH_Format.TreatAsCollection(A))
        {
          IEnumerable __enum_A = (IEnumerable)(A);
          DA.SetDataList(1, __enum_A);
        }
        else
        {
          if (A is Grasshopper.Kernel.Data.IGH_DataTree)
          {
            //merge tree
            DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(A));
          }
          else
          {
            //assign direct
            DA.SetData(1, A);
          }
        }
          }
          else
          {
        DA.SetData(1, null);
          }

        }
        catch (Exception ex)
        {
          this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
          //Add errors and messages...
          if (owner.Params.Output.Count > 0)
          {
        if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
        {
          List<string> __errors_plus_messages = new List<string>();
          if (this.__err != null) { __errors_plus_messages.AddRange(this.__err); }
          if (this.__out != null) { __errors_plus_messages.AddRange(this.__out); }
          if (__errors_plus_messages.Count > 0)
            DA.SetDataList(0, __errors_plus_messages);
        }
          }
        }
    }
Ejemplo n.º 59
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
        }
Ejemplo n.º 60
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; }
        }