protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare a variable for the input
            GH_Model model = null;

            // Use the DA object to retrieve the data inside the first input parameter.
            // If the retieval fails (for example if there is no data) we need to abort.
            if (!DA.GetData(0, ref model)) { return; }

            List<Vector3d> displacementVectors = new List<Vector3d>();
            List<Point3d> displacedPoints = new List<Point3d>();
            List<GeometryBase> displacedElements = new List<GeometryBase>();

            for (int i = 0; i < model.Nodes.Count; i++) {
                Vector3d vector = model.GetNodeDisplacement(i);
                Point3d point = model.GetDisplacedPoint(i);
                displacementVectors.Add(vector);
                displacedPoints.Add(point);
            }

            foreach (GH_Element element in model.Elements) {

                displacedElements.Add(element.GetDeformedGeometry(model));

            }

            DA.SetDataList(0, displacementVectors);
            DA.SetDataList(1, displacedPoints);
            DA.SetDataList(2, displacedElements);
        }
Ejemplo n.º 2
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)
        {
            // 1. Declare placeholder variables
            var struts = new List<Curve>();
            double tol = 0.0;
            // 2. Attempt to retrieve input
            if (!DA.GetDataList(0, struts)) { return; }
            if (!DA.GetData(1, ref tol)) { return; }
            // 3. Validate input
            if (struts == null || struts.Count == 1) { return; }
            if (tol < 0) { return; }

            // 4. Call cleaning method
            var nodes = new Point3dList();
            var nodePairs = new List<IndexPair>();
            struts = FrameTools.CleanNetwork(struts, tol, out nodes, out nodePairs);

            // 5. Organize index lists
            var strutStart = new List<int>();
            var strutEnd = new List<int>();
            foreach (IndexPair nodePair in nodePairs)
            {
                strutStart.Add(nodePair.I);
                strutEnd.Add(nodePair.J);
            }

            // 6. Set output
            DA.SetDataList(0, struts);
            DA.SetDataList(1, nodes);
            DA.SetDataList(2, strutStart);
            DA.SetDataList(3, strutEnd);

        }
Ejemplo n.º 3
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
   int n = vehicle.Wheels.Length;
   da.SetData(nextOutputIndex++, vehicle.Orientation);
   List<Point3d> wheelPositions = new List<Point3d>(n);
   List<Vector3d> wheelVelocities = new List<Vector3d>(n);
   List<double> wheelAngles = new List<double>(n);
   List<double> wheelRadii = new List<double>(n);
   List<double> wheelSpeeds = new List<double>(n);
   foreach (IWheel wheel in vehicle.Wheels)
   {
     wheelPositions.Add(wheel.Position);
     Vector3d wheelVelocity = vehicle.Velocity;
     wheelVelocity.Unitize();
     wheelVelocity = Vector3d.Multiply(wheelVelocity, wheel.TangentialVelocity);
     wheelVelocities.Add(wheelVelocity);
     wheelAngles.Add(wheel.Angle);
     wheelRadii.Add(wheel.Radius);
     wheelSpeeds.Add(wheel.AngularVelocity);
   }
   da.SetDataList(nextOutputIndex++, wheelPositions);
   da.SetDataList(nextOutputIndex++, wheelVelocities);
   da.SetDataList(nextOutputIndex++, wheelAngles);
   da.SetDataList(nextOutputIndex++, wheelRadii);
   da.SetDataList(nextOutputIndex++, wheelSpeeds);
 }
Ejemplo n.º 4
0
 protected override void SolveInstance(IGH_DataAccess DA)
 {
     DHr dhr = new DHr();
     if (DA.GetData(0, ref dhr))
     {
         DA.SetData(0, dhr.hr);
         DA.SetDataList(1, dhr.keys);
         DA.SetDataList(2, dhr.values);
         DA.SetData(3, dhr.color);
         DA.SetData(4, dhr.pos);
     }
 }
Ejemplo n.º 5
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<Line> bars = new List<Line>();
            DA.GetDataList(0, bars);


            //Calculate
            Point3d[] nodes = extractNodes(bars);
            double[] nodalLengths = calcNodalLengths(bars, nodes);


            //Output
            DA.SetDataList(0, nodes);
            DA.SetDataList(1, nodalLengths);
        }
Ejemplo n.º 6
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var location = default(Plane);
            var text = default(string);
            var size = default(double);
            var bold = default(bool);
            var hAlign = default(int);
            var vAlign = default(int);

            if (!DA.GetData(0, ref location)) return;
            if (!DA.GetData(1, ref text)) return;
            if (!DA.GetData(2, ref size)) return;
            if (!DA.GetData(3, ref bold)) return;
            if (!DA.GetData(4, ref hAlign)) return;
            if (!DA.GetData(5, ref vAlign)) return;

            var typeWriter = bold ? Typewriter.Bold : Typewriter.Regular;

            var position = location.Origin;
            var unitX = location.XAxis * size;
            var unitZ = location.YAxis * size;

            var curves = typeWriter.Write(text, position, unitX, unitZ, hAlign, vAlign);

            DA.SetDataList(0, curves);

            //FontWriter.Save(@"C:\Users\Thomas\Desktop\Test.xml", new[] { Typewriter.Regular, Typewriter.Bold });
        }
Ejemplo n.º 7
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Program program = null;
            GH_String ip = null;

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

            var robotCellUR = program.Value.RobotSystem as RobotCellUR;
            if (DA.GetData(1, ref ip) && ip != null)
                robotCellUR.Remote.IP = ip.Value;

            bool connect = false, upload = false, play = false, pause = false;
            if (!DA.GetData("Connect", ref connect)) { return; }
            if (!DA.GetData("Upload", ref upload)) { return; }
            if (!DA.GetData("Play", ref play)) { return; }
            if (!DA.GetData("Pause", ref pause)) { return; }

            if (connect && !connected) { robotCellUR.Remote.Connect(); connected = true; }
            if (!connect && connected) { robotCellUR.Remote.Disconnect(); connected = false; }
            if (upload && connected) robotCellUR.Remote.UploadProgram(program.Value);
            if (play && connected) robotCellUR.Remote.Play();
            if (pause && connected) robotCellUR.Remote.Pause();

            DA.SetDataList(0, robotCellUR.Remote.Log);
        }
Ejemplo n.º 8
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)
        {
            PlanktonMesh P = null;
            if (!DA.GetData(0, ref P)) return;

            List<Point3d> Positions = new List<Point3d>();
            List<int> OutHEdge = new List<int>();

            foreach (PlanktonVertex v in P.Vertices)
            {
                Positions.Add(new Point3f(v.X, v.Y, v.Z));
                OutHEdge.Add(v.OutgoingHalfedge);
            }
           
            List<int> StartV = new List<int>();
            List<int> AdjF = new List<int>();
            List<int> Next = new List<int>();
            List<int> Prev = new List<int>();
            List<int> Pair = new List<int>();

            for (int i = 0; i < P.Halfedges.Count; i++)
            {
                StartV.Add(P.Halfedges[i].StartVertex);
                AdjF.Add(P.Halfedges[i].AdjacentFace);
                Next.Add(P.Halfedges[i].NextHalfedge);
                Prev.Add(P.Halfedges[i].PrevHalfedge);
                Pair.Add(P.Halfedges.GetPairHalfedge(i));
            }
     
            List<int> FaceEdge = new List<int>();
            for (int i = 0; i < P.Faces.Count; i++)
            {
                FaceEdge.Add(P.Faces[i].FirstHalfedge);
            }

            DA.SetDataList(0, Positions);
            DA.SetDataList(1, OutHEdge);

            DA.SetDataList(2, StartV);
            DA.SetDataList(3, AdjF);
            DA.SetDataList(4, Next);
            DA.SetDataList(5, Prev);
            DA.SetDataList(6, Pair);

            DA.SetDataList(7, FaceEdge);    

        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            ResultElement re = null;
            string name = null;
            if (!DA.GetData(0, ref re)) { return; }

            if (!DA.GetData(1, ref name))
            {
                name = re.N1.First().Key;
            }

            DA.SetDataList(0, re.pos);
            DA.SetDataList(1, re.u[name]);
            DA.SetDataList(2, re.v[name]);
            DA.SetDataList(3, re.w[name]);
            DA.SetDataList(4, re.fi[name]);
        }
Ejemplo n.º 10
0
 protected override void SolveInstance(IGH_DataAccess DA)
 {
     HashType value = new HashType();
     DA.GetData("Hash", ref value);
     List<object> valuelist = new List<object>();
     valuelist.Add(value.Key);
     DA.SetDataList(0, valuelist);
     IEnumerable list = value.HashValue as IEnumerable;
     if (list != null)
     {
         DA.SetDataList(1, list);
     }
     else
     {
         List<object> outlist = new List<object>();
         outlist.Add(value.HashValue);
         DA.SetDataList(1, outlist);
     }
 }
Ejemplo n.º 11
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            AWorld wrld = new AWorld(refwrld);

            int g = 0;
            if (!DA.GetData(1, ref g)) return;
            if (g > wrld.GenCount - 1) g = wrld.GenCount - 1;
            DA.SetDataList(0, wrld.gens[g]);
        }
Ejemplo n.º 12
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //container for errors/messages passed by controller, partition, etc.
            List<String> errorContainer = new List<String>();

            GH_PreviewUtil preview = new GH_PreviewUtil(true);

            //declare placeholder variables and assign initial empty mesh
            Mesh baseMesh = new Rhino.Geometry.Mesh();
            int errorMetricIdentifer = -1;
            int numPanels = -1;

            //Retrieve input data
            if (!DA.GetData(0, ref baseMesh)) { return; }
            if (!DA.GetData(1, ref errorMetricIdentifer)) { return; }
            if (!DA.GetData(2, ref numPanels)) { return; }

            if (baseMesh.DisjointMeshCount > 1)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Problem with mesh input - disjoint mesh");
            }
            else
            {
                //compute and unify normal
                baseMesh.Normals.ComputeNormals();
                baseMesh.UnifyNormals();

                //create wingedmesh from rhinomesh
                WingedMesh myMesh = new WingedMesh(errorContainer, baseMesh);

                PlanarMesher controller = new PlanarMesher(errorContainer, myMesh, baseMesh, numPanels, errorMetricIdentifer, preview);

                controller.createFirstCluster();

                for (int i = 0; i < 40; i++)
                {
                    controller.iterateCluster();
                    //controller.currentPartition.drawProxies(preview);
                }

                controller.createConnectivityMesh();

                //creating voronoi
                WingedMesh voronoiMesh = new WingedMesh(errorContainer, controller.currentPartition.proxyToMesh.convertWingedMeshToPolylines());

                //set all the output data
                DA.SetDataList(0, voronoiMesh.convertWingedMeshToPolylines());
            }

            foreach (var item in errorContainer)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, item);
            }
        }
Ejemplo n.º 13
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ITurtleMesh m = null;
            if (DA.GetData(0, ref m))
            {
                List<ITurtleMesh> l = new List<ITurtleMesh>();
                for (int i = 0; i < m.FaceCount; i++)
                {
                    l.Add(ITurtleMeshExtensions.ExportFaceAt(m, i));
                }

                DA.SetDataList(0, l);
            }
        }
Ejemplo n.º 14
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
   da.SetDataList(nextOutputIndex++, particle.Position3DHistory.ToList());
   da.SetData(nextOutputIndex++, particle.Velocity3D);
   da.SetData(nextOutputIndex++, particle.PreviousAcceleration3D);
   da.SetData(nextOutputIndex++, particle.Lifespan);
   //da.SetData(nextOutputIndex++, particle.Mass);
   //da.SetData(nextOutputIndex++, particle.BodySize);
   if (particle.Environment.GetType() == typeof (SurfaceEnvironmentType))
   {
     da.SetData(nextOutputIndex++, particle.Position);
     da.SetData(nextOutputIndex++, particle.Velocity);
     da.SetData(nextOutputIndex++, particle.PreviousAcceleration);
   }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //------------------INPUT--------------------//
            PlanktonMesh pMesh = new PlanktonMesh();
            DA.GetData(0, ref pMesh);

            bool projXY = false;
            DA.GetData(1, ref projXY);



            //------------------CALCULATE--------------------//
            PMeshExt pMeshE = new PMeshExt(pMesh);

            if (!pMeshE.isMeshTriangulated())
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The mesh has to be triangulated");
            }

            //Extract vertices from initial 3d pMesh
            Point3d[] verticesXYZ = pMeshE.convertVerticesToXYZ();

            //If projected then create new pMesh
            if (projXY)
            {
                pMeshE = pMeshE.projectMeshToXY();
            }

            Vector3d[] vertexAreas = pMeshE.calcVertexVoronoiAreas(projXY);



            //------------------OUTPUT--------------------//
            DA.SetDataList(0, verticesXYZ);
            DA.SetDataList(1, vertexAreas);
        }
Ejemplo n.º 16
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
            Vector3d snow = new Vector3d();
            DA.GetData(0, ref snow);

            List<Vector3d> vertexNormals = new List<Vector3d>();
            DA.GetDataList(1, vertexNormals);


            //Calculate
            List<Vector3d> nodalLoads = calcNodalSnowLoads(vertexNormals, snow);


            //Output
            DA.SetDataList(0, nodalLoads);
        }
Ejemplo n.º 17
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
            Vector3d wind = new Vector3d();
            DA.GetData(0, ref wind);

            List<Vector3d> vertexNormals = new List<Vector3d>();
            DA.GetDataList(1, vertexNormals);

            bool scale = true;
            DA.GetData(2, ref scale);


            //Calculate
            List<Vector3d> nodalLoads = calcNodalWindLoads(vertexNormals, wind, scale);


            //Output
            DA.SetDataList(0, nodalLoads);
        }
Ejemplo n.º 18
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<Vector3d> vertexNormals = new List<Vector3d>();
            DA.GetDataList(0, vertexNormals);

            double thickness = 0.0;
            DA.GetData(1, ref thickness);

            double rho = 0.0;
            DA.GetData(2, ref rho);


            //Calculate
            List<Vector3d> nodalLoads = calcNodalSelfweight(vertexNormals, thickness, rho);


            //Output
            DA.SetDataList(0, nodalLoads);
        }
Ejemplo n.º 19
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // --- Input

            var curves = new List<Curve>();
            var plane = default(Plane?);

            DA.GetDataList(0, curves);
            DA.GetData(1, ref plane);


            // --- Execute

            var result = BBPolyline.Boolean(ClipType.ctUnion, PolyFillType.pftNonZero, curves, new Curve[0], plane);


            // --- Output

            DA.SetDataList(0, result);
        }
Ejemplo n.º 20
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<Line> lines = new List<Line>();
            DA.GetDataList(0, lines);

            List<double> moments = new List<double>();
            DA.GetDataList(1, moments);

            List<Plane> planes = new List<Plane>();
            DA.GetDataList(2, planes);


            //Calculate
            List<Vector3d> shearVectors = calcShearVectors(lines, moments, planes);


            //Output
            DA.SetDataList(0, shearVectors);
        }
Ejemplo n.º 21
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<double> barLengths = new List<double>();
            DA.GetDataList(0, barLengths);

            double area = 0.0;
            DA.GetData(1, ref area);

            double rho = 0.0;
            DA.GetData(2, ref rho);


            //Calculate
            List<Vector3d> selfweight = calcNodalSelfweight(barLengths, area, rho);


            //Output
            DA.SetDataList(0, selfweight);
        }
Ejemplo n.º 22
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // --- Input

            var curvesA = new List<Curve>();
            var curvesB = new List<Curve>();
            var plane = default(Plane?);

            DA.GetDataList(0, curvesA);
            DA.GetDataList(1, curvesB);
            DA.GetData(2, ref plane);


            // --- Execute

            var result = BBPolyline.Boolean(ClipType.ctDifference, PolyFillType.pftNonZero, curvesA, curvesB, plane);
            

            // --- Output

            DA.SetDataList(0, result);
        }
Ejemplo n.º 23
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<Point3d> initialPositions = new List<Point3d>();
            DA.GetDataList(0, initialPositions);

            List<Point3d> finalPositions = new List<Point3d>();
            DA.GetDataList(1, finalPositions);


            //Calculate displacements
            List<Vector3d> displSum = new List<Vector3d>();
            List<double> displX = new List<double>();
            List<double> displY = new List<double>();
            List<double> displZ = new List<double>();

            for (int i = 0; i < initialPositions.Count; i++)
            {
                Vector3d displ = finalPositions[i] - initialPositions[i];
                displ *= 1000;

                displSum.Add(displ);
                displX.Add(displ.X);
                displY.Add(displ.Y);
                displZ.Add(displ.Z);
            }

            //Maximum values
            double xMax = calcMaximumAbsVal(displX);
            double yMax = calcMaximumAbsVal(displY);
            double zMax = calcMaximumAbsVal(displZ);

            //Output
            DA.SetDataList(0, displSum);
            DA.SetData(1, xMax);
            DA.SetData(2, yMax);
            DA.SetData(3, zMax);
        }
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)
        {
            da.GetDataList(0, _sheetsresults);
            _reportList = new List<string>();
            int t = 1;
            foreach (var res in _sheetsresults)
            {
                var aux = new List<string>
                {
                    "Sheet : " + t + "\n",
                    "Panel Size : " + res.SheetInfo.PanelSize.X + "x" + res.SheetInfo.PanelSize.Y + "\n",
                    "PanelArea : " + res.SheetInfo.PanelArea + "\n",
                    "Objects Num : " + res.SheetInfo.CountObjects + "\n",
                    "Objects Area : " + res.SheetInfo.TotalAreaObjects + "\n",
                    "Obtimization : " + res.SheetInfo.Optimitzation + "\n",
                    "\n"
                };
                _reportList.AddRange(aux);
                t++;
            }

            da.SetDataList(0, _reportList);
        }
Ejemplo n.º 25
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <GH_Integer> treeConnectivity = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Point>   treePoints       = new GH_Structure <GH_Point>();
            List <string>             bctxt            = new List <string>();
            List <string>             loadtxt          = new List <string>();
            List <string>             deftxt           = new List <string>();

            if (!DA.GetDataTree(0, out treeConnectivity))
            {
                return;
            }
            if (!DA.GetDataTree(1, out treePoints))
            {
                return;
            }
            if (!DA.GetDataList(2, bctxt))
            {
                return;
            }
            if (!DA.GetDataList(3, loadtxt))
            {
                return;
            }
            if (!DA.GetDataList(4, deftxt))
            {
                return;
            }


            // Temporary way of finding the size of stiffness matrix and B matrix
            int sizeOfM = FindSizeOfM(treeConnectivity);

            //List of global points with correct numbering
            Point3d[] globalPoints = CreatePointList(treeConnectivity, treePoints, sizeOfM);

            //Create K_tot
            var tuple = CreateGlobalStiffnessMatrix(treeConnectivity, treePoints, sizeOfM);

            double[,] K_tot = tuple.Item1;

            //B_all
            //List<List<Matrix<double>>> B_all = tuple.Item2;
            Matrix <double>[,] B_all = tuple.Item2;

            //Create boundary condition list AND predeformations
            var        tupleBC = CreateBCList(bctxt, globalPoints);
            List <int> bcNodes = tupleBC.Item1;

            var        tupleDef    = CreateBCList(deftxt, globalPoints);
            List <int> predefNodes = tupleDef.Item1;

            List <double> predef = tupleDef.Item2;

            //Apply boundary condition and predeformations
            K_tot = ApplyBC(K_tot, bcNodes);
            K_tot = ApplyBC(K_tot, predefNodes);

            //Needs to take the predefs into account
            Vector <double> R_def = Vector <double> .Build.Dense(sizeOfM);

            if (deftxt.Any())
            {
                R_def = ApplyPreDef(K_tot, predefNodes, predef, sizeOfM);
            }

            //Inverting K matrix
            //Matrix<double> K_tot_inverse = K_tot.Inverse();

            //double[] R_array = SetLoads(sizeOfM, loadtxt);
            double[] R_array = AssignLoadsAndBC(loadtxt, bcNodes, globalPoints);
            var      V       = Vector <double> .Build;
            var      R       = (V.DenseOfArray(R_array)).Subtract(R_def);

            double[] R_array_def = new double[sizeOfM];
            for (int j = 0; j < sizeOfM; j++)
            {
                R_array_def[j] = R[j];
            }


            //Caluculation of the displacement vector u
            //Vector<double> u = K_tot_inverse.Multiply(R);

            //Trying with cholesky
            Deformations  def = new Deformations(K_tot, R_array_def);
            List <double> u   = def.Cholesky_Banachiewicz();

            DataTree <double> defTree = new DataTree <double>();
            int n = 0;

            for (int i = 0; i < u.Count; i += 3)
            {
                List <double> u_node = new List <double>(3);
                u_node.Add(u[i]);
                u_node.Add(u[i + 1]);
                u_node.Add(u[i + 2]);

                defTree.AddRange(u_node, new GH_Path(new int[] { 0, n }));
                n++;
            }

            //Calculatin strains for each node and stresses based on strain.
            List <Matrix <double> > B_e         = new List <Matrix <double> >();
            List <GH_Integer>       c_e         = new List <GH_Integer>();
            DataTree <double>       strain_node = new DataTree <double>();
            Cmatrix         C        = new Cmatrix(E, nu);
            Matrix <double> C_matrix = C.CreateMatrix();



            //List<List<Vector<double>>> strain = new List<List<Vector<double>>>();
            Vector <double>[,] strain = CalcStrain(treeConnectivity, u, B_all);



            DataTree <double> strainTree = new DataTree <double>();
            DataTree <double> stressTree = new DataTree <double>();

            double[,] globalStrain = FindGlobalStrain(strain, treeConnectivity, sizeOfM);

            Vector <double>[] globalStress = CalcStress(globalStrain, C_matrix);

            for (int i = 0; i < globalStrain.GetLength(0); i++)
            {
                //strainTree.AddRange(globalStrain[i], new GH_Path(new int[] { 0, i }));
                stressTree.AddRange(globalStress[i], new GH_Path(new int[] { 0, i }));
                for (int j = 0; j < globalStrain.GetLength(1); j++)
                {
                    strainTree.Add(globalStrain[i, j], new GH_Path(new int[] { 0, i }));
                }
            }

            DA.SetDataTree(0, defTree);
            DA.SetDataTree(1, strainTree);
            DA.SetDataTree(2, stressTree);
            DA.SetDataList(3, globalPoints);


            /*
             * GH_Boolean => Boolean
             * GH_Integer => int
             * GH_Number => double
             * GH_Vector => Vector3d
             * GH_Matrix => Matrix
             * GH_Surface => Brep
             */
        }
Ejemplo n.º 26
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)
        {
            // Input variables
            List <RobotComponents.Actions.Action> actions = new List <RobotComponents.Actions.Action>();
            int    interpolations      = 0;
            double interpolationSlider = 0;
            bool   update = false;

            // Catch the input data
            if (!DA.GetData(0, ref _robot))
            {
                return;
            }
            if (!DA.GetDataList(1, actions))
            {
                return;
            }
            if (!DA.GetData(2, ref interpolations))
            {
                return;
            }
            if (!DA.GetData(3, ref interpolationSlider))
            {
                return;
            }
            if (!DA.GetData(4, ref update))
            {
                return;
            }

            // Update the path
            if (update == true | _calculated == false)
            {
                // Create forward kinematics for mesh display
                _forwardKinematics = new ForwardKinematics(_robot);

                // Create the path generator
                _pathGenerator = new PathGenerator(_robot);

                // Re-calculate the path
                _pathGenerator.Calculate(actions, interpolations);

                // Makes sure that there is always a calculated solution
                _calculated = true;
            }

            // Get the index number of the current target
            int index = (int)(((_pathGenerator.Planes.Count - 1) * interpolationSlider));

            // Calculate foward kinematics
            _forwardKinematics.HideMesh = !_previewMesh;
            _forwardKinematics.Calculate(_pathGenerator.RobotJointPositions[index], _pathGenerator.ExternalJointPositions[index]);

            // Show error messages
            if (_pathGenerator.ErrorText.Count != 0)
            {
                for (int i = 0; i < _pathGenerator.ErrorText.Count; i++)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, _pathGenerator.ErrorText[i]);
                    if (i == 30)
                    {
                        break;
                    }
                }
            }

            // Output Parameters
            int ind;

            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[0].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[0].NickName));
                DA.SetData(ind, _pathGenerator.Planes[index]);
            }
            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[1].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[1].NickName));
                DA.SetDataList(ind, _pathGenerator.Planes);
            }
            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[2].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[2].NickName));
                DA.SetData(ind, _pathGenerator.RobotJointPositions[index]);
            }
            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[3].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[3].NickName));
                DA.SetDataList(ind, _pathGenerator.RobotJointPositions);
            }
            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[4].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[4].NickName));
                DA.SetDataList(ind, _forwardKinematics.PosedExternalAxisPlanes);
            }
            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[5].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[5].NickName));
                DA.SetData(ind, _pathGenerator.ExternalJointPositions[index]);
            }
            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[6].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[6].NickName));
                DA.SetDataList(ind, _pathGenerator.ExternalJointPositions);
            }
            if (Params.Output.Any(x => x.NickName.Equality(outputParameters[7].NickName)))
            {
                ind = Params.Output.FindIndex(x => x.NickName.Equality(outputParameters[7].NickName));
                DA.SetDataList(ind, _pathGenerator.ErrorText);
            }
            DA.SetDataList(outputParameters[8].Name, _pathGenerator.Paths);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 計算部分
        /// </summary>
        /// <param name="DA">インプットパラメータからデータを取得し、出力用のデータを保持するオブジェクト</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            int              nFL = 0;
            double           FH = 0, Angle = 0, R = 0;
            IGH_GeometricGoo FL    = null;
            Brep             Floor = null;

            // 入力設定============================
            if (!DA.GetData(0, ref nFL))
            {
                return;
            }
            if (!DA.GetData(1, ref FH))
            {
                return;
            }
            if (!DA.GetData(2, ref Angle))
            {
                return;
            }
            if (!DA.GetData(3, ref R))
            {
                return;
            }
            if (!DA.GetData(4, ref FL))
            {
                return;
            }
            if (!DA.GetData(4, ref Floor))
            {
                return;
            }

            // 床の作成
            List <IGH_GeometricGoo> list = new List <IGH_GeometricGoo>(nFL);
            Vector3d DirectionVector     = new Vector3d(0, 0, FH);
            Point3d  Center = new Point3d(0, 0, 0);

            for (int i = 0; i < nFL; i++)
            {
                ITransform transform  = new Translation(DirectionVector * (double)i);
                ITransform transform2 = new Rotation(Center, DirectionVector, Angle * (double)i);
                if (FL != null)
                {
                    IGH_GeometricGoo FL2 = FL.DuplicateGeometry();
                    FL2 = FL2.Transform(transform.ToMatrix());
                    FL2 = FL2.Transform(transform2.ToMatrix());
                    list.Add(FL2);
                }
                else
                {
                    list.Add(null);
                }
            }

            // 柱の作成
            List <Brep> collist = new List <Brep>(nFL);

            Point3d[] CornerPoints = Floor.DuplicateVertices();
            // 内柱
            Point3d Point1in = new Point3d(CornerPoints[0].X / 2.0, CornerPoints[0].Y / 2.0, CornerPoints[0].Z / 2.0);
            Point3d Point2in = new Point3d(CornerPoints[1].X / 2.0, CornerPoints[1].Y / 2.0, CornerPoints[1].Z / 2.0);
            Point3d Point3in = new Point3d(CornerPoints[2].X / 2.0, CornerPoints[2].Y / 2.0, CornerPoints[2].Z / 2.0);
            Point3d Point4in = new Point3d(CornerPoints[3].X / 2.0, CornerPoints[3].Y / 2.0, CornerPoints[3].Z / 2.0);
            // 外柱
            Point3d Point1outS = new Point3d(CornerPoints[0].X, CornerPoints[0].Y, CornerPoints[0].Z);
            Point3d Point2outS = new Point3d(CornerPoints[1].X, CornerPoints[1].Y, CornerPoints[1].Z);
            Point3d Point3outS = new Point3d(CornerPoints[2].X, CornerPoints[2].Y, CornerPoints[2].Z);
            Point3d Point4outS = new Point3d(CornerPoints[3].X, CornerPoints[3].Y, CornerPoints[3].Z);
            Point3d Point1outE = Point1outS;
            Point3d Point2outE = Point2outS;
            Point3d Point3outE = Point3outS;
            Point3d Point4outE = Point4outS;

            double num1 = GH_Component.DocumentTolerance();
            double num2 = GH_Component.DocumentAngleTolerance();

            for (int i = 0; i < nFL - 1; i++)
            {
                if (FL != null)
                {
                    if (i != 0)
                    {
                        // 内柱
                        Point1in = new Point3d(Point1in.X, Point1in.Y, Point1in.Z + FH);
                        Point2in = new Point3d(Point2in.X, Point2in.Y, Point2in.Z + FH);
                        Point3in = new Point3d(Point3in.X, Point3in.Y, Point3in.Z + FH);
                        Point4in = new Point3d(Point4in.X, Point4in.Y, Point4in.Z + FH);
                        // 外柱
                        Point1outS = new Point3d(Point1outE.X, Point1outE.Y, Point1outE.Z);
                        Point2outS = new Point3d(Point2outE.X, Point2outE.Y, Point2outE.Z);
                        Point3outS = new Point3d(Point3outE.X, Point3outE.Y, Point3outE.Z);
                        Point4outS = new Point3d(Point4outE.X, Point4outE.Y, Point4outE.Z);
                    }

                    // 外柱 終点
                    Point1outE = new Point3d(
                        Point1outS.X * Math.Cos(Angle) - Point1outS.Y * Math.Sin(Angle),
                        Point1outS.X * Math.Sin(Angle) + Point1outS.Y * Math.Cos(Angle),
                        Point1outS.Z + FH);
                    Point2outE = new Point3d(
                        Point2outS.X * Math.Cos(Angle) - Point2outS.Y * Math.Sin(Angle),
                        Point2outS.X * Math.Sin(Angle) + Point2outS.Y * Math.Cos(Angle),
                        Point2outS.Z + FH);
                    Point3outE = new Point3d(
                        Point3outS.X * Math.Cos(Angle) - Point3outS.Y * Math.Sin(Angle),
                        Point3outS.X * Math.Sin(Angle) + Point3outS.Y * Math.Cos(Angle),
                        Point3outS.Z + FH);
                    Point4outE = new Point3d(
                        Point4outS.X * Math.Cos(Angle) - Point4outS.Y * Math.Sin(Angle),
                        Point4outS.X * Math.Sin(Angle) + Point4outS.Y * Math.Cos(Angle),
                        Point4outS.Z + FH);

                    LineCurve LineCurve1in = new LineCurve(new Line(Point1in, DirectionVector));
                    LineCurve LineCurve2in = new LineCurve(new Line(Point2in, DirectionVector));
                    LineCurve LineCurve3in = new LineCurve(new Line(Point3in, DirectionVector));
                    LineCurve LineCurve4in = new LineCurve(new Line(Point4in, DirectionVector));
                    //
                    LineCurve LineCurve1out = new LineCurve(new Line(Point1outS, Point1outE));
                    LineCurve LineCurve2out = new LineCurve(new Line(Point2outS, Point2outE));
                    LineCurve LineCurve3out = new LineCurve(new Line(Point3outS, Point3outE));
                    LineCurve LineCurve4out = new LineCurve(new Line(Point4outS, Point4outE));

                    Brep[] col1in = Brep.CreatePipe(LineCurve1in, R, true, 0, false, num1, num2);
                    Brep[] col2in = Brep.CreatePipe(LineCurve2in, R, true, 0, false, num1, num2);
                    Brep[] col3in = Brep.CreatePipe(LineCurve3in, R, true, 0, false, num1, num2);
                    Brep[] col4in = Brep.CreatePipe(LineCurve4in, R, true, 0, false, num1, num2);
                    //
                    Brep[] col1out = Brep.CreatePipe(LineCurve1out, R, true, 0, false, num1, num2);
                    Brep[] col2out = Brep.CreatePipe(LineCurve2out, R, true, 0, false, num1, num2);
                    Brep[] col3out = Brep.CreatePipe(LineCurve3out, R, true, 0, false, num1, num2);
                    Brep[] col4out = Brep.CreatePipe(LineCurve4out, R, true, 0, false, num1, num2);

                    collist.AddRange(col1in);
                    collist.AddRange(col2in);
                    collist.AddRange(col3in);
                    collist.AddRange(col4in);
                    collist.AddRange(col1out);
                    collist.AddRange(col2out);
                    collist.AddRange(col3out);
                    collist.AddRange(col4out);
                }
            }
            // 出力設定============================
            DA.SetDataList(0, list);
            DA.SetDataList(1, collist);
        }
Ejemplo n.º 28
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var geometry   = new List <IGH_GeometricGoo>();
            var domainType = 0;
            var cellSize   = 1.0;
            var z0         = false;
            var centerXY   = true;
            var xyScale    = 1.2;
            var xyOffset   = 10.0;
            var zScale     = 2.0;
            var square     = true;
            var plane      = new Plane();

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

            DA.GetData(1, ref domainType);

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

            if (cellSize <= 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Cell Size has to be larger that 0. Given Cell Size was: {cellSize}");
            }

            DA.GetData(3, ref z0);
            DA.GetData(4, ref centerXY);
            DA.GetData(5, ref square);
            DA.GetData(6, ref xyScale);
            DA.GetData(7, ref xyOffset);
            DA.GetData(8, ref zScale);
            DA.GetData(9, ref plane);

            // Create Bounding Box
            var bbs = geometry.Select(element => element.Boundingbox).ToList();

            var boundingBox = Domain.GetMultiBoundingBox(bbs, cellSize, z0, centerXY, xyScale, xyOffset, zScale, square);

            if (domainType == 1)
            {
                boundingBox = Domain.Create2DDomain(boundingBox, plane, cellSize);
            }

            // Construct Surface Dict

            var surfaces = GetSurfaces(geometry, cellSize);

            var refinementRegions = GetRefinementRegions(geometry, cellSize);

            var locationInMesh = Domain.GetLocationInMesh(new Box(boundingBox));
            var cellEstimation = Convert.ToInt32(Domain.EstimateCellCount(geometry, cellSize, xyScale, zScale));
            var outputs        = new Inputs
            {
                Mesh = new CFDMesh
                {
                    BaseMesh = new BaseMesh
                    {
                        Type        = "simpleBox",
                        CellSize    = cellSize,
                        BoundingBox = new Dictionary <string, object>
                        {
                            {
                                "min", new List <double>
                                {
                                    boundingBox.Min.X, boundingBox.Min.Y, boundingBox.Min.Z
                                }
                            },
                            {
                                "max", new List <double>
                                {
                                    boundingBox.Max.X, boundingBox.Max.Y, boundingBox.Max.Z
                                }
                            }
                        },
                        Parameters = new Dictionary <string, string>
                        {
                            { "square", Convert.ToString(square) },
                            { "z0", Convert.ToString(z0) }
                        }
                    },
                    SnappyHexMesh = new SnappyHexMesh
                    {
                        Surfaces  = surfaces,
                        Overrides = new SnappyHexMeshOverrides
                        {
                            CastellatedMeshControls = new CastellatedMeshControls
                            {
                                LocationInMesh = new List <double>
                                {
                                    locationInMesh.X, locationInMesh.Y, locationInMesh.Z
                                }
                            }
                        },
                        RefinementRegions = refinementRegions
                    },
                    CellEstimate = cellEstimation
                }
            };

            DA.SetData(0, outputs.ToJson());
            DA.SetData(1, GetInfoText(cellEstimation, cellSize, surfaces.Keys.Select(key => surfaces[key].Level.Min)));
            DA.SetData(2, boundingBox);
            DA.SetDataList(3, geometry);
        }
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)
        {
            var inputJson = "";
            var exclude   = "";
            var include   = "";
            var rerun     = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            DA.GetData(1, ref exclude);
            DA.GetData(2, ref include);
            DA.GetData(3, ref rerun);

            // Get Cache to see if we already did this
            var cacheKey     = inputJson + "exc" + exclude + "inc" + include;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || rerun == true)
            {
                var queueName = "FileList" + cacheKey;

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results = FileList.GetFileList(
                                inputJson,
                                exclude,
                                include
                                );
                            cachedValues = results;
                            StringCache.setCache(cacheKey, cachedValues);
                            StringCache.setCache(InstanceGuid.ToString(), "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            // Read from Cache
            if (cachedValues != null)
            {
                var outputs = cachedValues.Split(',');
                if (outputs.Length > 1)
                {
                    outputs = outputs.OrderBy(file => file).ToArray();
                }
                DA.SetDataList(0, outputs);
            }

            HandleErrors();
        }
Ejemplo n.º 30
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <double> linVals  = new List <double>();
            List <double> rotVals  = new List <double>();
            List <double> timeVals = new List <double>();
            List <string> names    = new List <string>();

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

            // Get the optional inputs, if present.
            if (rotOption.Checked)
            {
                if (!DA.GetDataList("Rotation", rotVals))
                {
                    return;
                }
            }
            if (timeOption.Checked)
            {
                if (!DA.GetDataList("Time", timeVals))
                {
                    return;
                }
            }
            if (nameOption.Checked)
            {
                if (!DA.GetDataList("Name", names))
                {
                    return;
                }
            }

            // Always try to check for default dictionary zones.
            bool snapDefault = true;

            List <Speed>  speeds       = new List <Speed>();
            List <string> declarations = new List <string>();

            // Default and current speed dictionaries.
            Dictionary <double, Speed> defaultSpeeds = Util.ABBSpeeds();
            Dictionary <double, Speed> presentSpeeds = new Dictionary <double, Speed>();

            if (timeOption.Checked)
            {
                for (int i = 0; i < timeVals.Count; i++)
                {
                    if (i < names.Count)
                    {
                        Speed speed = new Speed(100, 30, names[i], timeVals[i]);
                        speeds.Add(speed);
                    }
                    else
                    {
                        Speed speed = new Speed(100, 30, "time_" + timeVals[i].ToString(), timeVals[i]);
                        speeds.Add(speed);
                    }
                }
            }
            else
            {
                // Default rotation value.
                double rotVal = 30;

                for (int i = 0; i < linVals.Count; i++)
                {
                    Speed speed = new Speed(100, 60, "Speed100");

                    if (snapDefault && defaultSpeeds.ContainsKey(linVals[i]))
                    {
                        speed = defaultSpeeds[linVals[i]];
                    }
                    else
                    {
                        if (rotOption.Checked)
                        {
                            if (i < rotVals.Count)
                            {
                                rotVal = rotVals[i];
                            }
                            else
                            {
                                rotVal = rotVals[rotVals.Count - 1];
                            }
                        }

                        if (i < names.Count)
                        {
                            speed = new Speed(linVals[i], rotVal, names[i], 0);
                        }
                        else
                        {
                            string name = linVals[i].ToString().Replace('.', '_');
                            speed = new Speed(linVals[i], rotVal, "v" + name, 0);
                        }
                    }

                    // Check to see if the dictionary contains the current speed, if not, add it.
                    if (presentSpeeds.ContainsKey(linVals[i]))
                    {
                        speeds.Add(speed);
                    }
                    else
                    {
                        speeds.Add(speed);
                        presentSpeeds.Add(speed.TranslationSpeed, speed);
                    }
                }
            }

            List <Speed> speedList = presentSpeeds.Values.ToList();

            for (int i = 0; i < speedList.Count; i++)
            {
                if (!defaultSpeeds.ContainsKey(speedList[i].TranslationSpeed))
                {
                    Speed  sp  = speedList[i];
                    string dec = "VAR speeddata " + sp.Name + " := [ " + Math.Round(sp.TranslationSpeed, 2).ToString() + ", " + Math.Round(sp.RotationSpeed, 2).ToString() + ", 200, 30 ];";
                    declarations.Add(dec);
                }
            }

            DA.SetDataList(0, speeds);

            if (declarationCheck.Checked)
            {
                DA.SetDataList("Declaration", declarations);
            }
        }
Ejemplo n.º 31
0
 protected override void TrySolveInstance(IGH_DataAccess DA)
 {
     using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument).OfClass(typeof(Level)))
         DA.SetDataList("Levels", collector);
 }
Ejemplo n.º 32
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)
        {
            //retrive inputs
            string filePath = "";

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

            bool readFile = false;

            if (!DA.GetData(1, ref readFile))
            {
                return;
            }

            //JObject geoJsonData = null;
            JArray jsonObj = null;

            if (readFile)
            {
                //file = "filePath
                Harlow.ShapeFileReader harlowShpReader = new Harlow.ShapeFileReader(filePath);
                harlowShpReader.LoadFile();
                string shpJsonString = harlowShpReader.FeaturesAsJson();
                //string shpjsonString = harlowShpReader.FeatureAsJson()


                //System.IO.File.ReadAllText(filePath,)
                //geoJsonData = JObject.Parse(shpJsonString);
                jsonObj = JArray.Parse(shpJsonString);
                JObject geoJsonData = new JObject();
                geoJsonData.Add("features", jsonObj);

                //var json = Newtonsoft.Json.JsonConvert.SerializeObject(geoJsonData, Newtonsoft.Json.Formatting.Indented);
                //DA.SetData(0, json);


                //read features
                JArray features = (JArray)geoJsonData["features"];
                GH_Structure <GH_String> attributes      = new GH_Structure <GH_String>();
                GH_Structure <GH_Point>  featureGeometry = new GH_Structure <GH_Point>();
                int featureIndex = 0;
                foreach (JObject feature in features)
                {
                    GH_Path currentPath = new GH_Path(featureIndex);
                    foreach (var attr in (JObject)feature["properties"])
                    {
                        JToken    attributeToken  = attr.Value;
                        string    thisAttribute   = (string)attributeToken;
                        GH_String thisGhAttribute = new GH_String(thisAttribute);
                        attributes.Append(thisGhAttribute, currentPath);
                    }
                    int pathIndex = 0;


                    foreach (JArray pathsArray in (JArray)feature["coordinates"])
                    {
                        List <GH_Point> thisPathPoints = new List <GH_Point>();
                        foreach (var path in pathsArray)
                        {
                            Point3d  thisPoint   = new Point3d((double)path[0], (double)path[1], 0);
                            GH_Point thisGhPoint = new GH_Point(thisPoint);
                            thisPathPoints.Add(thisGhPoint);
                        }
                        GH_Path thisPath = new GH_Path(featureIndex, pathIndex);
                        featureGeometry.AppendRange(thisPathPoints, thisPath);
                        pathIndex++;
                    }

                    featureIndex++;
                }//end polyline
                DA.SetDataTree(1, attributes);
                DA.SetDataTree(2, featureGeometry);

                ///
                ///set attributes

                List <string> featureFields = new List <string>();
                JToken        fieldObjs     = geoJsonData["features"][0]["properties"];
                foreach (JProperty prop in fieldObjs)
                {
                    string thisField = (string)prop.Name;
                    featureFields.Add(thisField);
                }
                DA.SetDataList(0, featureFields);
            }//end if read file
        }
Ejemplo n.º 33
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <double> inWindVelocities = new List <double>();

            DA.GetDataList(0, inWindVelocities);

            List <double> inWindDirections = new List <double>();

            DA.GetDataList(1, inWindDirections);

            double inNoWindDirections = 0.0;


            DA.GetData(2, ref inNoWindDirections);

            int noWindDirections = (int)Math.Round(inNoWindDirections);

            bool debug = false;
            //DA.GetData(3, ref debug);

            double threshold = 1;

            DA.GetData(3, ref threshold);

            int noHours = inWindVelocities.Count;



            // each hour * speed . To find "most dominant" directions.
            List <double> allAccumulatedHourSpeeds = new List <double>(new double[noWindDirections]);



            // at 16 dirs, each angle is 22.5   this means +/-11.25° to each side.
            double angleTol = 360.0 / noWindDirections / 2.0;

            // list of doubles containing the picked directions
            List <double> outAllDirections = new List <double>();
            List <double> outSelDirections = new List <double>();

            //setting default list [  0, 45, 90, etc..]
            for (int i = 0; i < noWindDirections; i++)
            {
                outAllDirections.Add(360.0 * ((double)i / noWindDirections));
            }

            //if (debug) Rhino.RhinoApp.WriteLine($"{outAllDirections.Count}");

            // speeds per direction. will be sorted decreaasingly
            List <List <double> > outWindVelocitiesPerDirection = new List <List <double> >(noWindDirections);

            GH_Structure <GH_Number> outAllSpeedsPerDirection = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> outSelSpeedsPerDirection = new GH_Structure <GH_Number>();

            List <double> outAllRoundedDirections = new List <double>();

            //if (debug) Rhino.RhinoApp.WriteLine($"winddir 001");

            //if (debug)
            //{
            //    for (int i = 0; i < outAllDirections.Count; i++)
            //    {
            //        Rhino.RhinoApp.WriteLine($"- {outAllDirections[i]}");
            //    }
            //}


            // empty lists
            for (int i = 0; i < noWindDirections; i++)
            {
                outWindVelocitiesPerDirection.Add(new List <double>());
            }

            List <double> thresholds = Utilities.GetThresholds(outAllDirections);

            for (int h = 0; h < noHours; h++)
            {
                int thisWindDir = Utilities.GetClosestDirection(inWindDirections[h], thresholds);
                if (debug && h > 300 && h < 310)
                {
                    Rhino.RhinoApp.WriteLine($"thisWindDir =  {inWindDirections[h]} Rounded to  {outAllDirections[thisWindDir]}");
                }
                // distribute velocities per direction
                outWindVelocitiesPerDirection[thisWindDir].Add(inWindVelocities[h]);
                outAllRoundedDirections.Add(outAllDirections[thisWindDir]);
                allAccumulatedHourSpeeds[thisWindDir] += inWindVelocities[h];
            }

            //if (debug)
            //{
            //    Rhino.RhinoApp.WriteLine($"\nRaw data:");

            //    for (int i = 0; i < noWindDirections; i++)
            //    {
            //        Rhino.RhinoApp.WriteLine($"[{outAllDirections[i]}]  Hours * Average = {allAccumulatedHourSpeeds[i]:0.0},      ({allAccumulatedHourSpeeds[i]/ allAccumulatedHourSpeeds.Sum()*100.0:0.0}%)");

            //    }

            //    Rhino.RhinoApp.WriteLine($"\n");
            //}



            //if (debug)
            //{
            //    Rhino.RhinoApp.WriteLine($"\nMost relevant directions:");

            //    for (int i = 0; i < noWindDirections; i++)
            //    {
            //        if (allAccumulatedHourSpeeds[i] > allAccumulatedHourSpeeds.Sum()/noWindDirections)
            //            if (debug) Rhino.RhinoApp.WriteLine($"[{outAllDirections[i]}] Rounded dir: {outAllRoundedDirections[i]},    Hours * Average = {allAccumulatedHourSpeeds[i]:0.0},      ({allAccumulatedHourSpeeds[i] / allAccumulatedHourSpeeds.Sum() * 100.0:0.0}%)");

            //    }

            //    Rhino.RhinoApp.WriteLine($"\n");
            //}



            // Exporting unsorted data:
            if (debug)
            {
                Rhino.RhinoApp.WriteLine($"\n\nAll directions:");
            }
            List <GH_Number> ghVelocitiesThisDirection = new List <GH_Number>();

            for (int i = 0; i < noWindDirections; i++)
            {
                ghVelocitiesThisDirection = new List <GH_Number>();
                for (int j = 0; j < outWindVelocitiesPerDirection[i].Count; j++)
                {
                    ghVelocitiesThisDirection.Add(new GH_Number(outWindVelocitiesPerDirection[i][j]));
                }

                //outAllDirections.Add(inWindDirections[i]);
                outAllSpeedsPerDirection.AppendRange(ghVelocitiesThisDirection, new GH_Path(i));

                if (debug)
                {
                    Rhino.RhinoApp.WriteLine($"[{outAllDirections[i]}] Hours: {outWindVelocitiesPerDirection[i].Count},       Hours * Average = {allAccumulatedHourSpeeds[i]:0.0},      ({allAccumulatedHourSpeeds[i] / allAccumulatedHourSpeeds.Sum() * 100.0:0.0}%)");
                }
            }


            //exporting sorted data:
            int countOut = 0;

            if (debug)
            {
                Rhino.RhinoApp.WriteLine($"\n\nMost relevant directions:");
            }
            for (int i = 0; i < noWindDirections; i++)
            {
                ghVelocitiesThisDirection = new List <GH_Number>();
                if (allAccumulatedHourSpeeds[i] > allAccumulatedHourSpeeds.Sum() / noWindDirections / threshold)
                {
                    for (int j = 0; j < outWindVelocitiesPerDirection[i].Count; j++)
                    {
                        ghVelocitiesThisDirection.Add(new GH_Number(outWindVelocitiesPerDirection[i][j]));
                    }

                    outSelDirections.Add(outAllDirections[i]);
                    outSelSpeedsPerDirection.AppendRange(ghVelocitiesThisDirection, new GH_Path(countOut));

                    countOut++;

                    if (debug)
                    {
                        Rhino.RhinoApp.WriteLine($"[{outAllDirections[i]}] Hours: {outWindVelocitiesPerDirection[i].Count},       Hours * Average = {allAccumulatedHourSpeeds[i]:0.0},      ({allAccumulatedHourSpeeds[i] / allAccumulatedHourSpeeds.Sum() * 100.0:0.0}%)");
                    }
                }
            }



            //// MUCH FUSS OF JUST SORTING TWO LISTS TOGETHER LOL.
            //List <AccumulatedHourAndWindDirection> accHourWindDirPairs = new List<AccumulatedHourAndWindDirection>();
            //for (int i = 0; i < allAccumulatedHourSpeeds.Count; i++)
            //    accHourWindDirPairs.Add(new AccumulatedHourAndWindDirection(allAccumulatedHourSpeeds[i], outAllDirections[i], outWindVelocitiesPerDirection[i]));

            //accHourWindDirPairs.Sort((data1, data2) => data1.AccumulatedHours.CompareTo(data2.AccumulatedHours));

            //List<double> sortedDirections = new List<double>();
            //List<List<double>> outSortedWindVelocitiesPerDirection = new List<List<double>>();
            //List<double> sortedAccumulatedHourSpeeds = new List<double>();


            ////if (debug) Rhino.RhinoApp.WriteLine($"accPairs {accHourWindDirPairs.Count}");


            //for (int i = 0; i < accHourWindDirPairs.Count; i++)
            //{
            //    sortedAccumulatedHourSpeeds.Add(accHourWindDirPairs[i].AccumulatedHours);

            //    sortedDirections.Add(accHourWindDirPairs[i].WindDirection);

            //    outSortedWindVelocitiesPerDirection.Add(new List<double>(accHourWindDirPairs[i].Velocities));
            //}

            //allAccumulatedHourSpeeds.Reverse();
            //sortedDirections.Reverse();
            //outSortedWindVelocitiesPerDirection.Reverse();



            //List<GH_Number> ghVelocitiesThisDirection = new List<GH_Number>();

            //if (debug) Rhino.RhinoApp.WriteLine($"All {noWindDirections} directions:");

            //for (int i = 0; i < noWindDirections; i++)
            //{
            //    if (debug) Rhino.RhinoApp.WriteLine($"[{sortedDirections[i]}] --> {allAccumulatedHourSpeeds[i]} hourspeeds added... no of entries: {outSortedWindVelocitiesPerDirection[i].Count}");

            //}



            //    for (int i = 0; i < noWindDirections; i++)
            //{
            //    List<double> velocitiesThisDirection = new List<double>(outWindVelocitiesPerDirection[i]);



            //    if (allAccumulatedHourSpeeds[i] > allAccumulatedHourSpeeds.Sum() * 0.05)
            //    {
            //        if (debug) Rhino.RhinoApp.WriteLine($"[{sortedDirections[i]}] --> {allAccumulatedHourSpeeds[i]} hourspeeds added");

            //        for (int j = 0; j < velocitiesThisDirection.Count; j++)
            //            ghVelocitiesThisDirection.Add(new GH_Number(velocitiesThisDirection[j]));


            //        outSelDirections.Add(sortedDirections[i]);
            //        outSelSpeedsPerDirection.AppendRange(ghVelocitiesThisDirection, new GH_Path(outSelSpeedsPerDirection.PathCount));
            //    }

            //    outAllDirections.Add(inWindDirections[i]);
            //    outAllSpeedsPerDirection.AppendRange(ghVelocitiesThisDirection, new GH_Path(i));
            //}



            //for (int i = 0; i < sortedDirections.Count; i++)
            //{
            //    if (debug) Rhino.RhinoApp.WriteLine($"{sortedDirections[i]}");
            //}



            //// adding accumulated hour/speeds to each direction
            //for (int i = 0; i < noWindDirections; i++)
            //{

            //    //if (debug) Rhino.RhinoApp.WriteLine($"dimwinds 002a");

            //    List<double> velocitiesThisDirection = new List<double>(outWindVelocitiesPerDirection[i]);


            //    velocitiesThisDirection.Sort();
            //    velocitiesThisDirection.Reverse(); // largest first

            //    for (int j = 0; j < velocitiesThisDirection.Count; j++)
            //    {

            //        ghVelocitiesThisDirection.Add(new GH_Number(velocitiesThisDirection[j]));
            //        //if (debug) Rhino.RhinoApp.WriteLine($"dimwinds 002d{accumulatedHourSpeeds.Count} .. {velocitiesThisDirection.Count}");
            //        allAccumulatedHourSpeeds[i] += velocitiesThisDirection[j];
            //    }

            //    if (debug) Rhino.RhinoApp.WriteLine($"[dir {i}] velocitiescount {outWindVelocitiesPerDirection[i].Count} .. accspeeds :   {allAccumulatedHourSpeeds[i]:0.0}");
            //}



            //if(debug) Rhino.RhinoApp.WriteLine($"dimwinds 003");


            //// sorting the accumulated hour/speeds and adding to gh_outputs
            //for (int i = 0; i < noWindDirections; i++)
            //{
            //    //if (debug) Rhino.RhinoApp.WriteLine($"dimwinds 003a");
            //    if (allAccumulatedHourSpeeds[i] > allAccumulatedHourSpeeds.Sum() * 0.05)
            //    {
            //        outSelDirections.Add(inWindDirections[i]);
            //        outSelSpeedsPerDirection.AppendRange(ghVelocitiesThisDirection, new GH_Path(outSelSpeedsPerDirection.PathCount));

            //    }

            //    outAllDirections.Add(inWindDirections[i]);
            //    outAllSpeedsPerDirection.AppendRange(ghVelocitiesThisDirection, new GH_Path(i));
            //}

            //if (debug) Rhino.RhinoApp.WriteLine($"dimwinds 004");



            DA.SetDataList(0, outAllDirections);
            DA.SetDataTree(1, outAllSpeedsPerDirection);

            DA.SetDataList(2, outSelDirections);
            DA.SetDataTree(3, outSelSpeedsPerDirection);

            DA.SetDataList(4, outAllRoundedDirections);


            return;
        }
Ejemplo n.º 34
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<HashType> Output = new List<HashType>();
            foreach (IGH_Param Input in this.Params.Input)
            {
                object value = "";
                DA.GetData(Input.Name, ref value);
                Output.Add(new HashType(Input.NickName, value));
            }

            //Output.Add(

            DA.SetDataList(0, Output);
        }
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)
        {
            List <string>           props = new List <string>();
            List <GH_ObjectWrapper> vals  = new List <GH_ObjectWrapper>();
            List <string>           opts  = new List <string>();

            DA.GetDataList(0, props);
            DA.GetDataList(1, vals);
            DA.GetDataList(2, opts);

            DropDown dd = new DropDown()
            {
                ID = Guid.NewGuid().ToString(),
            };

            foreach (string opt in opts)
            {
                dd.Items.Add(opt);
            }

            for (int i = 0; i < props.Count; i++)
            {
                string n = props[i];
                object val;
                try { val = vals[i].Value; }
                catch (ArgumentOutOfRangeException)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "P, V should correspond each other");
                    return;
                }

                if (n.ToLower() == "textcolor" || n.ToLower() == "fontcolor")
                {
                    if (val is GH_Colour gclr)
                    {
                        dd.TextColor = Color.FromArgb(gclr.Value.ToArgb());
                    }
                    else if (val is GH_String gstr)
                    {
                        if (Color.TryParse(gstr.Value, out Color clr))
                        {
                            dd.TextColor = clr;
                        }
                    }
                    else if (val is GH_Point pt)
                    {
                        Color clr = Color.FromArgb((int)pt.Value.X, (int)pt.Value.Y, (int)pt.Value.Z);
                        dd.TextColor = clr;
                    }
                    else if (val is GH_Vector vec)
                    {
                        Color clr = Color.FromArgb((int)vec.Value.X, (int)vec.Value.Y, (int)vec.Value.Z);
                        dd.TextColor = clr;
                    }
                    else if (val is Color etoclr)
                    {
                        dd.TextColor = etoclr;
                    }
                    else
                    {
                        try { Util.SetProp(dd, "TextColor", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "showborder" || n.ToLower() == "border")
                {
                    if (val is GH_Boolean gbool)
                    {
                        dd.ShowBorder = gbool.Value;
                    }
                    else if (val is GH_Integer gint)
                    {
                        if (gint.Value == 0)
                        {
                            dd.ShowBorder = false;
                        }
                        else if (gint.Value == 1)
                        {
                            dd.ShowBorder = true;
                        }
                        else
                        {
                            dd.ShowBorder = false;
                        }
                    }
                    else if (val is GH_String gstr)
                    {
                        if (gstr.Value.ToLower() == "true")
                        {
                            dd.ShowBorder = true;
                        }
                        else if (gstr.Value.ToLower() == "false")
                        {
                            dd.ShowBorder = false;
                        }
                        else
                        {
                            dd.ShowBorder = false;
                        }
                    }
                    else
                    {
                        try { Util.SetProp(dd, "ShowBorder" +
                                           "", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "font" || n.ToLower() == "typeface")
                {
                    if (val is GH_String txt)
                    {
                        string fam = txt.Value;
                        try
                        {
                            Font efont = new Font(fam, (float)8.25);
                            dd.Font = efont;
                        }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                    else if (val is Font f)
                    {
                        dd.Font = f;
                    }
                    else
                    {
                        try { Util.SetProp(dd, "Font", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else
                {
                    try { Util.SetProp(dd, n, Util.GetGooVal(val)); }
                    catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                }
            }

            DA.SetData(1, new GH_ObjectWrapper(dd));

            PropertyInfo[] allprops  = dd.GetType().GetProperties();
            List <string>  printouts = new List <string>();

            foreach (PropertyInfo prop in allprops)
            {
                if (prop.CanWrite)
                {
                    printouts.Add(prop.Name + ": " + prop.PropertyType.ToString());
                }
            }
            DA.SetDataList(0, printouts);
        }
Ejemplo n.º 36
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.º 37
0
    protected override void SetOutputs(IGH_DataAccess da)
    {
      if (system == null)
      {
        system = new SystemType(agents, emitters, environment);
      }
      else
      {
        system = new SystemType(agents, emitters, environment, (SystemType) system);
      }

      // Finally assign the system to the output parameter.
      da.SetData(nextOutputIndex++, system);
      da.SetDataList(nextOutputIndex++, (List<IQuelea>)system.Quelea.SpatialObjects);
      da.SetData(nextOutputIndex++, new SpatialCollectionType(system.Quelea));
    }
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)
        {
            FFDSolver        ffdSolver;
            List <FFDSolver> ffdSolvers = new List <FFDSolver>();


            DA.GetDataList(0, ffdSolvers);

            if (ffdSolvers.Count == 0)
            {
                return;
            }
            ffdSolver = ffdSolvers[0];

            Domain        omega = ffdSolver.omega;
            FluidSolver   ffd   = ffdSolver.ffd;
            DataExtractor de    = new DataExtractor(ffdSolver.omega, ffdSolver.ffd);


            //double[,,] pstagResults = ffdSolver.pstag;



            //double[,,] p = ffdSolver.p;
            //List<double[,,]> veloutCen = ffdSolver.veloutCen;
            //List<double[,,]> veloutStag = ffdSolver.veloutStag;
            //double[,,] pstag = ffdSolver.pstag;
            //DataExtractor de = ffdSolver.de;
            //int[,,] obstacle_cells = ffdSolver.obstacle_cells;


            //DA.SetDataList(0, veloutCen);
            //DA.SetData(1, p);
            //DA.SetDataList(2, veloutStag);
            //DA.SetData(3, pstag);
            ////DA.SetData(3, pstagResults);
            //DA.SetData(4, de);
            //DA.SetData(5, obstacle_cells);
            //DA.SetData(6, ffdSolver);



            int Nx = ffdSolver.Nx;
            int Ny = ffdSolver.Ny;
            int Nz = ffdSolver.Nz;

            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // I could move all this away, an only output de data extractor
            double[,,] p  = new double[Nx, Ny, Nz];
            double[,,] vu = new double[Nx, Ny, Nz];
            double[,,] vv = new double[Nx, Ny, Nz];
            double[,,] vw = new double[Nx, Ny, Nz];

            double[,,] pstag  = new double[Nx + 1, Ny + 1, Nz + 1];
            double[,,] vustag = new double[Nx + 1, Ny + 1, Nz + 1];
            double[,,] vvstag = new double[Nx + 1, Ny + 1, Nz + 1];
            double[,,] vwstag = new double[Nx + 1, Ny + 1, Nz + 1];

            for (int i = 0; i < Nx; i++)
            {
                for (int j = 0; j < Ny; j++)
                {
                    for (int k = 0; k < Nz; k++)
                    {
                        if (omega.obstacle_cells[i + 1, j + 1, k + 1] != 1)
                        {
                            p[i, j, k] = de.get_pressure(i * omega.hx + 0.5 * omega.hx, j * omega.hy + 0.5 * omega.hy, k * omega.hz + 0.5 * omega.hz);
                            double[] vel = de.get_velocity(i * omega.hx + 0.5 * omega.hx, j * omega.hy + 0.5 * omega.hy, k * omega.hz + 0.5 * omega.hz);
                            vu[i, j, k] = vel[0];
                            vv[i, j, k] = vel[1];
                            vw[i, j, k] = vel[2];
                        }
                        else
                        {
                            p[i, j, k]  = 0;
                            vu[i, j, k] = 0;
                            vv[i, j, k] = 0;
                            vw[i, j, k] = 0;
                        }
                        pstag[i, j, k] = de.get_pressure(i * omega.hx, j * omega.hy, k * omega.hz);
                        double[] velcen = de.get_velocity(i * omega.hx, j * omega.hy, k * omega.hz);
                        vustag[i, j, k] = velcen[0];
                        vvstag[i, j, k] = velcen[1];
                        vwstag[i, j, k] = velcen[2];
                    }
                }
            }

            //last x slice
            for (int j = 0; j < Ny + 1; j++)
            {
                for (int k = 0; k < Nz + 1; k++)
                {
                    pstag[Nx, j, k] = de.get_pressure((Nx) * omega.hx, j * omega.hy, k * omega.hz);
                    double[] vcen = de.get_velocity((Nx) * omega.hx, j * omega.hy, k * omega.hz);
                    vustag[Nx, j, k] = vcen[0];
                    vvstag[Nx, j, k] = vcen[1];
                    vwstag[Nx, j, k] = vcen[2];
                }
            }

            //last y slice
            for (int i = 0; i < Nx + 1; i++)
            {
                for (int k = 0; k < Nz + 1; k++)
                {
                    pstag[i, Ny, k] = de.get_pressure(i * omega.hx, (Ny) * omega.hy, k * omega.hz);
                    double[] vcen = de.get_velocity(i * omega.hx, (Ny) * omega.hy, k * omega.hz);
                    vustag[i, Ny, k] = vcen[0];
                    vvstag[i, Ny, k] = vcen[1];
                    vwstag[i, Ny, k] = vcen[2];
                }
            }

            //last z slice
            for (int i = 0; i < Nx + 1; i++)
            {
                for (int j = 0; j < Ny + 1; j++)
                {
                    pstag[i, j, Nz] = de.get_pressure(i * omega.hx, j * omega.hy, (Nz) * omega.hz);
                    double[] vcen = de.get_velocity(i * omega.hx, j * omega.hy, (Nz) * omega.hz);
                    vustag[i, j, Nz] = vcen[0];
                    vvstag[i, j, Nz] = vcen[1];
                    vwstag[i, j, Nz] = vcen[2];
                }
            }

            List <double[, , ]> veloutCen = new List <double[, , ]> {
            };

            veloutCen.Add(vu);
            veloutCen.Add(vv);
            veloutCen.Add(vw);

            List <double[, , ]> veloutStag = new List <double[, , ]> {
            };

            veloutStag.Add(vustag);
            veloutStag.Add(vvstag);
            veloutStag.Add(vwstag);



            DA.SetDataList(0, veloutCen);
            DA.SetData(1, p);
            DA.SetDataList(2, veloutStag);
            DA.SetData(3, pstag);
            DA.SetData(4, de);

            DA.SetData(5, omega.obstacle_cells);



            GH_Structure <GH_Number> outNumbers = new GH_Structure <GH_Number>();

            for (int j = 0; j < veloutStag[0].GetLength(0); j++)
            {
                for (int k = 0; k < veloutStag[0].GetLength(1); k++)
                {
                    double velocity = Math.Sqrt(veloutStag[0][j, k, 1] * veloutStag[0][j, k, 1] + veloutStag[1][j, k, 1] * veloutStag[1][j, k, 1] + veloutStag[2][j, k, 1] * veloutStag[2][j, k, 1]);

                    outNumbers.Append(new GH_Number(velocity), new GH_Path(j, k));
                }
            }

            DA.SetDataTree(7, outNumbers);
        }
        /// <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        boundary  = null;
            List <Curve> rooms     = new List <Curve>();
            List <Line>  corridors = new List <Line>();
            double       cellSize  = 1;

            DA.GetData("Boundary", ref boundary);
            DA.GetDataList("Rooms", rooms);
            DA.GetData("CellSize", ref cellSize);

            int gridXCapacity = (int)((boundary.GetBoundingBox(false).Diagonal.X) / cellSize);
            int gridYCapacity = (int)((boundary.GetBoundingBox(false).Diagonal.Y) / cellSize);

            int[,] grid          = new int[gridXCapacity, gridYCapacity];
            int[,] corridorsGrid = new int[gridXCapacity, gridYCapacity];

            InitializeGrid(ref grid, boundary.GetBoundingBox(false).Corner(true, true, true), cellSize, rooms);

            List <int> numberGrid = new List <int>();

            for (int i = 0; i < grid.GetLength(0); i++)
            {
                for (int j = 0; j < grid.GetLength(1); j++)
                {
                    numberGrid.Add(grid[i, j]);
                }
            }


            // DO IT FOR HORIZONTALS
            for (int i = 0; i < corridorsGrid.GetLength(0); i++)
            {
                for (int j = 0; j < corridorsGrid.GetLength(1) - 1; j++)
                {
                    if (grid[i, j] != grid[i, j + 1])
                    {
                        corridorsGrid[i, j] = 1;
                    }
                    else
                    {
                        corridorsGrid[i, j] = 0;
                    }
                }
            }

            corridors.AddRange(GatherCorridorList(corridorsGrid, boundary, Direction.Horizontal));

            // DO IT FOR VERTICALS
            for (int i = 0; i < corridorsGrid.GetLength(0) - 1; i++)
            {
                for (int j = 0; j < corridorsGrid.GetLength(1); j++)
                {
                    if (grid[i, j] != grid[i + 1, j])
                    {
                        corridorsGrid[i, j] = 1;
                    }
                    else
                    {
                        corridorsGrid[i, j] = 0;
                    }
                }
            }

            corridors.AddRange(GatherCorridorList(corridorsGrid, boundary, Direction.Vertical));



            DA.SetDataList("Corridors", corridors);
            DA.SetData("XGridDim", gridXCapacity);
            DA.SetDataList("NumberGrid", numberGrid);
        }
Ejemplo n.º 40
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string streetLayerNames = "";
            string setbacks         = "";

            DA.GetData(0, ref streetLayerNames); // GET THE STRING : LAYER NAMES
            DA.GetData(1, ref setbacks);         // GET THE STRING : SETBACK DISTANCES

            InputProc inputproc = new InputProc(streetLayerNames, setbacks);

            List <string> STREET_LAYER_NAMES = inputproc.GetStreetNames();
            List <double> SETBACKS           = inputproc.GetSetbacks();

            // DA.SetDataList(0, STREET_LAYER_NAMES); // SET THE STRING : LAYER NAMES
            // DA.SetDataList(1, SETBACKS); // SET THE DOUBLE - SETBACKS

            inputproc.GetLayerGeom();
            List <LineCurve> STREETLINES = inputproc.GetLinesFromLayers();
            // DA.SetDataList(2, STREETLINES); // SET THE STREET LINE : CURVES

            List <ProcObj> PROCOBJLI    = inputproc.GetProcObjs();
            List <string>  PROCOBJLIStr = inputproc.GetProcObjLiString();
            // DA.SetDataList(3, PROCOBJLIStr); // SET THE PROC-OBJ-LI-STRING : STRING

            List <Curve> SITES = new List <Curve>();
            double       FSR   = 2.5;
            double       MAXHT = 10.0;
            double       MINHT = 0.0;

            DA.GetDataList(2, SITES);
            DA.GetData(3, ref FSR);
            DA.GetData(4, ref MAXHT);
            DA.GetData(5, ref MINHT);

            int NUMRAYS = 4; // DA.GetData(6, ref NUMRAYS);

            double MAGNITUDERAYS = 2.0;

            DA.GetData(6, ref MAGNITUDERAYS); // DA.GetData(7, ref MAGNITUDERAYS);

            ProcessIntx processintx = new ProcessIntx(
                PROCOBJLI,
                SITES,
                FSR, MINHT, MAXHT,
                NUMRAYS, MAGNITUDERAYS);

            processintx.GenRays();

            List <SiteObj> SITEOBJ = processintx.GetSiteObjList();
            List <Curve>   crvSite = new List <Curve>();
            List <Point3d> intxpts = new List <Point3d>();
            List <Line>    rays    = new List <Line>();

            rays = processintx.GetRays();
            List <Extrusion> solids = new List <Extrusion>();

            for (int i = 0; i < SITEOBJ.Count; i++)
            {
                intxpts.Add(SITEOBJ[i].GetIntxPt());
                crvSite.Add(SITEOBJ[i].GetSite());
                solids.Add(SITEOBJ[i].GetOffsetExtrusion());
            }

            // DA.SetDataList(4, rays);
            // DA.SetDataList(5, intxpts);
            // DA.SetDataList(6, crvSite);
            DA.SetDataList(0, solids);
        }
Ejemplo n.º 41
0
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            int index = -1;

            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            if (document == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Core.SAMObject sAMObject = null;
            index = Params.IndexOfInputParam("_analytical");
            if (index == -1 || !dataAccess.GetData(index, ref sAMObject))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            List <Panel> panels = null;

            if (sAMObject is Panel)
            {
                panels = new List <Panel>()
                {
                    (Panel)sAMObject
                };
            }
            else if (sAMObject is AdjacencyCluster)
            {
                panels = ((AdjacencyCluster)sAMObject).GetPanels();
            }
            else if (sAMObject is AnalyticalModel)
            {
                panels = ((AnalyticalModel)sAMObject).GetPanels();
            }

            if (panels == null || panels.Count == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            StartTransaction(document);

            List <ElementType> elementTypes = new List <ElementType>();

            for (int i = 0; i < panels.Count; i++)
            {
                Panel panel = panels[i];
                if (panel == null)
                {
                    continue;
                }

                Geometry.Spatial.Vector3D normal = panel.Normal;
                PanelType panelType = panel.PanelType;

                if (panelType == PanelType.Air || panelType == PanelType.Undefined)
                {
                    panels[i] = Create.Panel(panel);
                    ElementType elementType = Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false));
                    if (elementType != null && elementTypes.Find(x => x.Id == elementType.Id) == null)
                    {
                        elementTypes.Add(elementType);
                    }

                    continue;
                }

                PanelType panelType_Normal = Analytical.Revit.Query.PanelType(normal);
                if (panelType_Normal == PanelType.Undefined || panelType.PanelGroup() == panelType_Normal.PanelGroup())
                {
                    panels[i] = Create.Panel(panel);
                    ElementType elementType = Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false));
                    if (elementType != null && elementTypes.Find(x => x.Id == elementType.Id) == null)
                    {
                        elementTypes.Add(elementType);
                    }

                    continue;
                }

                if (panelType.PanelGroup() == PanelGroup.Floor || panelType.PanelGroup() == PanelGroup.Roof)
                {
                    double value = normal.Unit.DotProduct(Geometry.Spatial.Vector3D.WorldY);
                    if (Math.Abs(value) <= Core.Revit.Tolerance.Tilt)
                    {
                        panels[i] = Create.Panel(panel);
                        ElementType elementType = Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false));
                        if (elementType != null && elementTypes.Find(x => x.Id == elementType.Id) == null)
                        {
                            elementTypes.Add(elementType);
                        }

                        continue;
                    }
                }

                HostObjAttributes hostObjAttributes = Analytical.Revit.Modify.DuplicateByType(document, panelType_Normal, panel.Construction) as HostObjAttributes;
                if (hostObjAttributes == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, string.Format("Skipped - Could not duplicate construction for {0} panel (Guid: {1}).", panel.Name, panel.Guid));
                    continue;
                }

                panels[i] = Create.Panel(panel, panelType_Normal);

                if (elementTypes.Find(x => x.Id == hostObjAttributes.Id) == null)
                {
                    elementTypes.Add(hostObjAttributes);
                }
            }


            int index_Analytical = Params.IndexOfOutputParam("analytical");

            if (index_Analytical != -1)
            {
                if (sAMObject is Panel)
                {
                    dataAccess.SetData(index_Analytical, panels?.FirstOrDefault());
                }
                else if (sAMObject is AnalyticalModel)
                {
                    AnalyticalModel analyticalModel = new AnalyticalModel((AnalyticalModel)sAMObject);
                    panels.ForEach(x => analyticalModel.AddPanel(x));
                    dataAccess.SetData(index_Analytical, analyticalModel);
                }
                else if (sAMObject is AdjacencyCluster)
                {
                    AdjacencyCluster adjacencyCluster = new AdjacencyCluster((AdjacencyCluster)sAMObject);
                    panels.ForEach(x => adjacencyCluster.AddObject(x));
                    dataAccess.SetData(index_Analytical, adjacencyCluster);
                }
            }

            int index_ElementType = Params.IndexOfOutputParam("elementType");

            if (index_ElementType != -1)
            {
                dataAccess.SetDataList(index_ElementType, elementTypes);
            }
        }
Ejemplo n.º 42
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)
        {
            bool writeFile = false;

            //input variables
            List <string> inputs  = new List <string>();
            List <string> outputs = new List <string>();

            List <object> inJSON = new List <object>();
            //object inJSON = null;

            var imgParams = new ImgParam();

            //get data
            DA.GetData(0, ref Folder);
            DA.GetDataList(1, inputs);
            DA.GetDataList(2, outputs);
            DA.GetData(3, ref imgParams);
            DA.GetDataList(4, inJSON);
            DA.GetData(5, ref writeFile);

            //operations is ExpandoObject
            inJSON.RemoveAll(item => item == null);
            var JSON = new threeDParam();

            if (!inJSON.IsNullOrEmpty())
            {
                JSON = new threeDParam(inJSON);
            }


            Dictionary <string, string> inputCSVstrings  = ColibriBase.FormatDataToCSVstring(inputs, "in:");
            Dictionary <string, string> outputCSVstrings = ColibriBase.FormatDataToCSVstring(outputs, "out:");
            //Dictionary<string, string> imgParamsClean = ColibriBase.ConvertBactToDictionary(imgParams);

            string csvPath = Folder + @"\data.csv";
            //var rawData = inputs;
            //int inDataLength = rawData.Count;
            //rawData.AddRange(outputs);
            //int allDataLength = rawData.Count;

            //Parsing data to csv format
            string flyID      = inputCSVstrings["FlyID"];
            string keyReady   = inputCSVstrings["DataTitle"];
            string valueReady = inputCSVstrings["DataValue"];

            //add output data when it is not empty
            keyReady   = string.IsNullOrWhiteSpace(outputCSVstrings["DataTitle"]) ? keyReady : keyReady + "," + outputCSVstrings["DataTitle"];
            valueReady = string.IsNullOrWhiteSpace(outputCSVstrings["DataValue"]) ? valueReady : valueReady + "," + outputCSVstrings["DataValue"];

            string systemSafeFileName = flyID.Replace(" ", "");

            systemSafeFileName = Path.GetInvalidFileNameChars()
                                 .Aggregate(systemSafeFileName, (current, c) => current.Replace(c.ToString(), ""));

            //write only when toggle is connected
            if (this.Params.Input.Last().Sources.Any())
            {
                //first open check
                if (_isFirstTimeOpen)
                {
                    _isFirstTimeOpen = false;
                    setWriteFileToFalse();
                    return;
                }
                this._write = writeFile;
            }
            else
            {
                this._write = false;
            }

            //var ViewNames = new List<string>();


            //if we aren't told to write, clean out the list of already written items
            if (!_write)
            {
                DA.SetDataList(0, _printOutStrings);
                _alreadyWrittenLines = new List <string>();
                this.Message         = "[OVERRIDE MODE]\n" + OverrideTypes.ToString() + "\n------------------------------\n[RECORDING DISABLED]\n";
                return;
            }

            //if we are told to run and we haven't written this line yet, do so

            if (_write)
            {
                //Check folder if existed
                checkStudyFolder(Folder);

                //check csv file
                if (!File.Exists(csvPath))
                {
                    //clean out the list of already written items
                    _printOutStrings = new List <string>();
                    //add key lines

                    //check if there is one or more imges
                    if (imgParams.IsDefined)
                    {
                        int imgCounts = imgParams.ViewNames.Count;
                        imgCounts = imgCounts > 0 ? imgCounts : 1;

                        if (imgCounts > 1)
                        {
                            for (int i = 1; i <= imgCounts; i++)
                            {
                                keyReady += ",img_" + i;
                            }
                        }
                        else
                        {
                            keyReady += ",img";
                        }
                    }
                    else
                    {
                        keyReady += ",img";
                    }

                    if (JSON.IsDefined)
                    {
                        keyReady += ",threeD";
                    }

                    keyReady += Environment.NewLine;
                    File.WriteAllText(csvPath, keyReady);
                    _alreadyWrittenLines.Add("[Title] " + keyReady);
                }
                else
                {
                    //add data lins
                    if (!_alreadyWrittenLines.Contains("[FlyID] " + flyID))
                    {
                        string writeInData = valueReady;

                        //save img
                        string imgFileName = captureViews(imgParams, systemSafeFileName);
                        writeInData += "," + imgFileName;

                        //save json
                        if (JSON.IsDefined)
                        {
                            string jsonFileName = systemSafeFileName + ".json";
                            string jsonFilePath = Folder + @"\" + jsonFileName;
                            File.WriteAllText(jsonFilePath, JSON.JsonSting);
                            writeInData += "," + jsonFileName;
                        }

                        //save csv // add data at the end
                        //writeInData = string.Format("{0},{1},{2}\n", valueReady, imgFileName, jsonFileName);
                        writeInData += "\n";
                        File.AppendAllText(csvPath, writeInData);

                        //add this line to our list of already written lines
                        _alreadyWrittenLines.Add("[FlyID] " + flyID);
                    }
                }

                _printOutStrings = _alreadyWrittenLines;

                //updateMsg();
                this.Message = "[OVERRIDE MODE]\n" + OverrideTypes.ToString() + "\n------------------------------\n[RECORDING STARTED]\n";
                DA.SetDataList(0, _printOutStrings);
            }

            //set output
            //DA.SetData(0, writeInData);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string               beamSetName   = "";
            List <Curve>         beamSetCurves = new List <Curve>();
            List <sCrossSection> crossSections = new List <sCrossSection>();
            List <object>        lineLoadObjs  = new List <object>();

            if (!DA.GetData(0, ref beamSetName))
            {
                return;
            }
            if (!DA.GetDataList(1, beamSetCurves))
            {
                return;
            }
            if (!DA.GetDataList(2, crossSections))
            {
                return;
            }
            DA.GetDataList(3, lineLoadObjs);



            List <IFrameSet> sets = new List <IFrameSet>();

            string          modelUnit = Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem.ToString();
            sRhinoConverter rhcon     = new sRhinoConverter(modelUnit, "Meters");


            int minuteCount = 0;

            for (int i = 0; i < beamSetCurves.Count; ++i)
            {
                if (beamSetCurves[i].GetLength() > 0.005)
                {
                    Curve     rc     = rhcon.EnsureUnit(beamSetCurves[i]);
                    sCurve    setCrv = rhcon.TosCurve(rc);
                    IFrameSet bset   = new sFrameSet(setCrv);
                    bset.frameSetName = beamSetName;
                    bset.setId        = i;

                    if (crossSections.Count == 1)
                    {
                        bset.crossSection = crossSections[0] as sCrossSection;
                    }
                    else if (crossSections.Count == beamSetCurves.Count)
                    {
                        bset.crossSection = crossSections[i] as sCrossSection;
                    }

                    if (lineLoadObjs.Count > 0)
                    {
                        foreach (object lo in lineLoadObjs)
                        {
                            GH_ObjectWrapper wap = new GH_ObjectWrapper(lo);
                            sLineLoad        sl  = wap.Value as sLineLoad;
                            if (sl != null)
                            {
                                bset.UpdateLineLoad(sl);
                            }
                            sLineLoadGroup sg = wap.Value as sLineLoadGroup;
                            if (sg != null)
                            {
                                if (sg.loads.Count == beamSetCurves.Count)
                                {
                                    bset.UpdateLineLoad(sg.loads[i]);
                                }
                                else
                                {
                                    return;
                                }
                            }
                        }
                    }
                    sets.Add(bset);
                }
                else
                {
                    minuteCount++;
                }
            }

            if (minuteCount > 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, minuteCount + "Beams are too short");
            }
            DA.SetDataList(0, sets);
        }
Ejemplo n.º 44
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)
        {
            double            tolerance = 1d;
            Mesh              mesh      = null;
            IField3d <double> f         = null;
            double            iso       = 0d;

            if (!DA.GetData(0, ref mesh))
            {
                return;
            }
            if (!DA.GetData(1, ref f))
            {
                return;
            }
            if (!DA.GetData(2, ref tolerance))
            {
                return;
            }
            if (!DA.GetData(3, ref iso))
            {
                return;
            }

            var lines = new List <LineCurve>();

            Parallel.For(0, mesh.Faces.Count, i =>
            {
                Point3d p0 = mesh.Vertices[mesh.Faces[i].A];
                Point3d p1 = mesh.Vertices[mesh.Faces[i].B];
                Point3d p2 = mesh.Vertices[mesh.Faces[i].C];

                double t0 = f.ValueAt(mesh.Vertices[mesh.Faces[i].A]);
                double t1 = f.ValueAt(mesh.Vertices[mesh.Faces[i].B]);
                double t2 = f.ValueAt(mesh.Vertices[mesh.Faces[i].C]);

                int mask = 0;
                if (t0 >= iso)
                {
                    mask |= 1;
                }
                if (t1 >= iso)
                {
                    mask |= 2;
                }
                if (t2 >= iso)
                {
                    mask |= 4;
                }

                switch (mask)
                {
                case 1:
                    lines.Add(DrawLine(p0, p1, p2, Normalize(t0, t1, iso), Normalize(t0, t2, iso)));
                    break;

                case 2:
                    lines.Add(DrawLine(p1, p2, p0, Normalize(t1, t2, iso), Normalize(t1, t0, iso)));
                    break;

                case 3:
                    lines.Add(DrawLine(p2, p0, p1, Normalize(t2, t0, iso), Normalize(t2, t1, iso)));
                    break;

                case 4:
                    lines.Add(DrawLine(p2, p0, p1, Normalize(t2, t0, iso), Normalize(t2, t1, iso)));
                    break;

                case 5:
                    lines.Add(DrawLine(p1, p2, p0, Normalize(t1, t2, iso), Normalize(t1, t0, iso)));
                    break;

                case 6:
                    lines.Add(DrawLine(p0, p1, p2, Normalize(t0, t1, iso), Normalize(t0, t2, iso)));
                    break;
                }
            });

            DA.SetDataList(0, Curve.JoinCurves(lines, tolerance));
        }
Ejemplo n.º 45
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare a variable for the input String
            bool data = false;

            // Use the DA object to retrieve the data inside the first input parameter.
            // If the retieval fails (for example if there is no data) we need to abort.
            if (!DA.GetData(0, ref data))
            {
                return;
            }
            if (!DA.GetData(1, ref baseID))
            {
                return;
            }
            if (!DA.GetData(2, ref appKey))
            {
                return;
            }
            if (!DA.GetData(3, ref tablename))
            {
                return;
            }
            if (!DA.GetDataList(4, stringIDs))
            {
                return;
            }

            // If the retrieved data is Nothing, we need to abort.
            // We're also going to abort on a zero-length String.
            if (data == false)
            {
                stringIDs.Clear();
                return;
            }

            //
            var           looped  = LoopTasks();
            List <String> strings = new List <string>();
            int           d       = 0;

            //

            while (!outRecords.Any())
            {
                if (!stringIDs.Any())
                {
                    break;
                }
                d++;
                if (d == 100000000)
                {
                    break;
                }
            }

            // Use the DA object to assign a new String to the first output parameter.
            DA.SetData(0, errorMessage);
            DA.SetDataList(1, outRecords);
            outRecords.Clear();
        }
Ejemplo n.º 46
0
        protected override void GroundHogSolveInstance(IGH_DataAccess DA)
        {
            var CURVES  = new List <Curve>();
            var STARTS  = new List <Point3d>();
            var ENDS    = new List <Point3d>();
            var LENGTHS = new List <double>();

            // Access and extract data from the input parameters individually
            if (!DA.GetDataList(0, CURVES))
            {
                return;
            }
            if (!DA.GetDataList(1, STARTS))
            {
                return;
            }
            if (!DA.GetDataList(2, ENDS))
            {
                return;
            }
            DA.GetDataList(3, LENGTHS);

            // Input validation
            int negativeIndex = LENGTHS.FindIndex(_isNegative);

            if (negativeIndex != -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  string.Format("Distances cannot be negative. At least one negative value found at index {0}.", negativeIndex));
                return;
            }

            CURVES.RemoveAll(_removeNullAndInvalidDelegate);
            if (CURVES.Count < 1)
            {
                return;
            }

            STARTS.RemoveAll(_removeInvalidDelegate);
            ENDS.RemoveAll(_removeInvalidDelegate);
            if (STARTS.Count != ENDS.Count)
            {
                if (ENDS.Count == 1 && STARTS.Count > 1)
                {
                    // Assume multiple starts going to single end; populate ends to match
                    for (int i = 1; i < STARTS.Count; i++)
                    {
                        ENDS.Add(ENDS[0]);
                    }
                }
                else if (STARTS.Count == 1 && ENDS.Count > 1)
                {
                    // Assume single start going to multiple ends; populate starts to match
                    for (int i = 1; i < ENDS.Count; i++)
                    {
                        STARTS.Add(STARTS[0]);
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The quantity of start points does not match the quantity of end points");
                    return;
                }
            }

            if (LENGTHS.Count > 0 && LENGTHS.Count != CURVES.Count)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "If lengths are provided they must match the number of curves");
                return;
            }

            // Construct topology
            CurvesTopology top = new CurvesTopology(CURVES, GH_Component.DocumentTolerance());
            //CurvesTopologyPreview.Mark(top, Color.BurlyWood, Color.Bisque);
            PathMethod pathSearch;

            if (LENGTHS.Count == 0)
            {
                IList <double> distances = top.MeasureAllEdgeLengths();
                pathSearch = new AStar(top, distances);
            }
            else if (LENGTHS.Count == 1)
            {
                pathSearch = new Dijkstra(top, LENGTHS[0]);
            }
            else
            {
                IList <double> interfLengths = LENGTHS;

                if (interfLengths.Count < top.EdgeLength)
                {
                    interfLengths = new ListByPattern <double>(interfLengths, top.EdgeLength);
                }

                bool isAlwaysShorterOrEqual = true;
                for (int i = 0; i < top.EdgeLength; i++)
                {
                    if (top.LinearDistanceAt(i) > interfLengths[i])
                    {
                        isAlwaysShorterOrEqual = false;
                        break;
                    }
                }

                if (isAlwaysShorterOrEqual)
                {
                    pathSearch = new AStar(top, interfLengths);
                }
                else
                {
                    pathSearch = new Dijkstra(top, interfLengths);
                }
            }

            var resultCurves  = new List <Curve>();
            var resultLinks   = new GH_Structure <GH_Integer>();
            var resultDirs    = new GH_Structure <GH_Boolean>();
            var resultLengths = new List <double>();

            for (int i = 0; i < STARTS.Count; i++)
            {
                int fromIndex = top.GetClosestNode(STARTS[i]);
                int toIndex   = top.GetClosestNode(ENDS[i]);

                if (fromIndex == toIndex)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The start and end positions are equal; perhaps because they are not close enough to one of the curves in the network.");
                    resultCurves.Add(null);
                    continue;
                }

                var current = pathSearch.Cross(fromIndex, toIndex, out int[] nodes, out int[] edges, out bool[] dir, out double tot);

                if (current == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                      string.Format("No walk found for start point at position {0}. Are end points isolated?", i.ToString()));
                }
                else
                {
                    var pathLinks = DA.ParameterTargetPath(1).AppendElement(i);

                    resultLinks.AppendRange(GhWrapTypeArray <int, GH_Integer>(edges), pathLinks);
                    resultDirs.AppendRange(GhWrapTypeArray <bool, GH_Boolean>(dir), pathLinks);
                    resultLengths.Add(tot);
                }

                resultCurves.Add(current);
            }

            DA.SetDataList(0, resultCurves);
            DA.SetDataTree(1, resultLinks);
            DA.SetDataTree(2, resultDirs);
            DA.SetDataList(3, resultLengths);
        }
Ejemplo n.º 47
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (DA.Iteration == 0)
            {
                switch (this.areaMode)
                {
                case AreaMode.None:
                    this.Message = "Select Mode";
                    break;

                case AreaMode.Rooms:
                    this.Message = "Rooms";
                    break;

                case AreaMode.Areas:
                    this.Message = "Areas";
                    break;
                }
            }

            // Set up Utility object and start process
            Utility utility = new Utility(DA);

            utility.Print("Starting " + this.Message + ".");
            List <string> instructionData = new List <string>();

            // Get Inputs
            string folderPath = null, fileName = null;
            bool   write = false;

            if (!utility.GetInput(0, ref write))                     // Write command is required
            {
                utility.WriteOut();
                return;
            }
            if (!utility.GetInput(1, ref folderPath))                // Folder path is required
            {
                utility.WriteOut();
                return;
            }
            utility.GetInput(2, ref fileName, true, true, true);     // File name is optional
            if (fileName == null)
            {
                fileName = this.DEFAULT_FILE_NAME;
            }


            GH_Structure <GH_Point> points = null;               // Points in Data Tree required

            if (!utility.GetInput(3, out points))
            {
                return;
            }

            List <string>            parameterNames  = null;    // Parameter names list and values tree are optional but both must be provided if used.
            GH_Structure <GH_String> parameterValues = null;

            string[,] parameterArray = null;
            utility.GetParameterValueArray(4, 5, ref parameterNames, out parameterValues, out parameterArray);
            int iMaxCountParam = 0, jMaxCountParam = 0;

            if (parameterArray != null)
            {
                iMaxCountParam = parameterArray.GetLength(0);
                jMaxCountParam = parameterArray.GetLength(1);
                if (parameterNames.Count < jMaxCountParam)
                {
                    jMaxCountParam = parameterNames.Count;
                }
            }

            if (write)
            {
                try {
                    // Create RevitModelBuilderUtility object and link to CSV file
                    CsvWriter csvWriter = new CsvWriter();
                    utility.Print("CsvWriter Version: " + csvWriter.Version);
                    if (!utility.EstablishCsvLink(csvWriter, folderPath, fileName))
                    {
                        utility.Print("EstablishCsvLink() failed");
                        utility.WriteOut();
                        return;
                    }

                    // Loop for each room, get points, and place component; then set parameter values
                    for (int i = 0; i < points.Branches.Count; i++)
                    {
                        // Add the room
                        List <List <HbCurve> > curvesListListRevit      = new List <List <HbCurve> >();
                        List <Grasshopper.Kernel.Types.GH_Point> branch = points.Branches[i];
                        HbXYZ hbXYZ = new HbXYZ(branch[0].Value.X, branch[0].Value.Y, branch[0].Value.Z);

                        //switch on room or area
                        switch (this.areaMode)
                        {
                        case AreaMode.Rooms: {
                            csvWriter.AddRoom(hbXYZ);
                            instructionData.Add("Add Room: " + utility.formatPoint(hbXYZ));
                            break;
                        }

                        case AreaMode.Areas: {
                            csvWriter.AddArea(hbXYZ);
                            instructionData.Add("Add Room: " + utility.formatPoint(hbXYZ));
                            break;
                        }

                        default: {
                            break;
                        }
                        }

                        // Set parameters if needed. Assume user has matched the list lengths.  Error handling silently truncates if they don't match.
                        if (parameterArray != null)
                        {
                            for (int j = 0; j < parameterNames.Count; j++)
                            {
                                if (i < iMaxCountParam && j < jMaxCountParam)
                                {
                                    csvWriter.ModifyParameterSet(parameterNames[j], parameterArray[i, j]);
                                    instructionData.Add("Set Param: " + parameterNames[j] + ", " + parameterArray[i, j]);
                                }
                            }
                        }
                    }
                    csvWriter.WriteFile();
                    utility.Print("Rooms_Areas completed successfully.");
                }
                catch (Exception exception) {
                    utility.Print(exception.Message);

                    return;
                }
            }
            utility.WriteOut();
            DA.SetDataList(1, instructionData);
        }
Ejemplo n.º 48
0
    private int runCount;                              //Legacy field.

    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
        double ang = default(double);

        if (inputs[0] != null)
        {
            ang = (double)(inputs[0]);
        }

        double rad = default(double);

        if (inputs[1] != null)
        {
            rad = (double)(inputs[1]);
        }



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


        //4. Invoke RunScript
        RunScript(ang, rad, 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.º 49
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <double> node  = new List <double>();
            List <double> nodeX = new List <double>();
            List <double> nodeY = new List <double>();
            List <double> nodeZ = new List <double>();

            List <double> nodeNum     = new List <double>();
            List <double> stressesTen = new List <double>();
            List <double> stressesCom = new List <double>();
            List <double> nx          = new List <double>();
            List <double> ny          = new List <double>();

            List <Fiber> Fibers = new List <Fiber>();

            Surface Srf4Nodes = null;

            DA.GetDataList("X", nodeX);
            DA.GetDataList("Y", nodeY);
            DA.GetDataList("Z", nodeZ);
            DA.GetDataList("Node", node);           // small

            DA.GetDataList("Node Number", nodeNum); // big (duplicate)
            DA.GetDataList("Nodal Tension Stress", stressesTen);
            DA.GetDataList("Nodal Compression Stress", stressesCom);
            DA.GetDataList("Nodal Force Nx", nx);
            DA.GetDataList("Nodal Force Ny", ny);

            DA.GetDataList("Custom Fibers", Fibers);
            DA.GetData("Surface", ref Srf4Nodes);

            // SoFiNode: structure info assambly
            List <SoFiNode> SoFiNodesOnSrf = new List <SoFiNode>();

            for (int i = 0; i < nodeX.Count; i++)
            {
                SoFiNode inode = new SoFiNode(node[i], nodeX[i], nodeY[i], nodeZ[i]);
                double   u;
                double   v;
                Srf4Nodes.ClosestPoint(inode.Node, out u, out v);
                Point3d closestPt = Srf4Nodes.PointAt(u, v);

                if (closestPt.DistanceTo(inode.Node) < 0.01)  // on surface
                {
                    SoFiNodesOnSrf.Add(inode);
                }
            }
            // so far the sofiNodes have no structure info

            // ====================== structure info big list ===================================
            // node number, compression stress, tension stress, force in  local x, force in local y

            List <NodalStructureInfo> NodalStructureInfo = new List <NodalStructureInfo>();

            for (int i = 0; i < nodeNum.Count; i++)
            {
                NodalStructureInfo inodal = new NodalStructureInfo(nodeNum[i], stressesTen[i], stressesCom[i], nx[i], ny[i]);
                NodalStructureInfo.Add(inodal);
            }
            // ==================================================================================

            // abandom the nodes not on the srf
            // list.RemoveAll(item => !list2.Contains(item))
            List <double> nodeNumOnSrf = SoFiNodesOnSrf.Select(o => o.NodeNum).ToList();

            NodalStructureInfo.RemoveAll(o => !nodeNumOnSrf.Contains(o.NodeNum)); // remove structure info not on srf
            List <NodalStructureInfo> CondensedNodalStructureInfo = new List <RP1516.NodalStructureInfo>();

            for (int i = 0; i < SoFiNodesOnSrf.Count; i++)
            {
                double iNodeNumber = SoFiNodesOnSrf[i].NodeNum;
                List <NodalStructureInfo> iNodalinfo = NodalStructureInfo.Where(o => o.NodeNum == iNodeNumber).ToList();
                double iNodeCount = iNodalinfo.Count();

                // Com
                double iComStress = iNodalinfo
                                    .Select(o => o.StressCom).ToList().Sum()
                                    / iNodeCount;

                // Ten
                double iTenStress = iNodalinfo
                                    .Select(o => o.StressTen).ToList().Sum()
                                    / iNodeCount;

                // NX
                double iNX = iNodalinfo
                             .Select(o => o.Nx).ToList().Sum()
                             / iNodeCount;

                // NY
                double iNY = iNodalinfo
                             .Select(o => o.Ny).ToList().Sum()
                             / iNodeCount;

                NodalStructureInfo.Except(iNodalinfo);

                SoFiNodesOnSrf[i].StressCom = iComStress;
                SoFiNodesOnSrf[i].StressTen = iTenStress;
                SoFiNodesOnSrf[i].Nx        = iNX;
                SoFiNodesOnSrf[i].Ny        = iNY;
            }
            //List<NodalStructureInfo> CondensedNodalStructureInfo = Utils.CheckDuplicate(NodalStructureInfo);

            // SoFiNode.InfoRead(SoFiNodesOnSrf, CondensedNodalStructureInfo);

            // calculate structure significance
            Fibers.ForEach(o => o.StrutureValue(SoFiNodesOnSrf));

            List <Fiber> CriticleFibers = Fibers
                                          .OrderByDescending(o => o.StructureFactor)
                                          //.Take((int)(Fibers.Count * 0.2))
                                          .ToList();

            // Output
            DA.SetDataList("SoFiNodes", SoFiNodesOnSrf);
            DA.SetDataList("Node Positions", SoFiNodesOnSrf.Select(o => o.Node).ToList());
            DA.SetDataList("Node Number", SoFiNodesOnSrf.Select(o => o.NodeNum).ToList());
            DA.SetDataList("Info Number", CondensedNodalStructureInfo.Select(o => o.NodeNum).ToList());
            DA.SetDataList("Criticle Fibers", CriticleFibers.Select(o => o.FiberCrv).ToList());
            DA.SetDataList("Value", SoFiNodesOnSrf.Select(o => o.StressCom).ToList());
        }
Ejemplo n.º 50
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Autodesk.Revit.DB.Category category = null;
            DA.GetData("FamilyCategory", ref category);

            string familyName = null;

            DA.GetData("FamilyName", ref familyName);

            string name = null;

            DA.GetData("TypeName", ref name);

            var elementTypes = new List <ElementType>();

            using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument))
            {
                if (category != null)
                {
                    using (var familyCollector = new FilteredElementCollector(Revit.ActiveDBDocument))
                    {
                        var familiesSet = new HashSet <string>
                                          (
                            familyCollector.OfClass(typeof(Family)).
                            Cast <Family>().
                            Where((x) => x.FamilyCategory.Id == category.Id).
                            Select((x) => x.Name)
                                          );

                        foreach (var elementType in collector.WhereElementIsElementType().Cast <ElementType>())
                        {
                            if (elementType.Category?.Id != category.Id && !familiesSet.Contains(elementType.FamilyName))
                            {
                                continue;
                            }

                            if (familyName != null && elementType.FamilyName != familyName)
                            {
                                continue;
                            }

                            if (name != null && elementType.Name != name)
                            {
                                continue;
                            }

                            elementTypes.Add(elementType);
                        }
                    }
                }
                else
                {
                    foreach (var elementType in collector.WhereElementIsElementType().ToElements().OfType <ElementType>())
                    {
                        if (familyName != null && elementType.FamilyName != familyName)
                        {
                            continue;
                        }

                        if (name != null && elementType.Name != name)
                        {
                            continue;
                        }

                        elementTypes.Add(elementType);
                    }
                }
            }

            DA.SetDataList("ElementTypes", elementTypes);
        }
Ejemplo n.º 51
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var points = new List <Rhino.Geometry.Point3d>();

            if (!DA.GetDataList("Points", points))
            {
                return;
            }

            var tolerance = 0.0;

            if (!DA.GetData("Tolerance", ref tolerance))
            {
                return;
            }

            var boundingBox = true;

            if (!DA.GetData("BoundingBox", ref boundingBox))
            {
                return;
            }

            var strict = true;

            if (!DA.GetData("Strict", ref strict))
            {
                return;
            }

            var inverted = false;

            if (!DA.GetData("Inverted", ref inverted))
            {
                return;
            }

            var scaleFactor = 1.0 / Revit.ModelUnits;

            var targets = new List <Rhino.Geometry.Box>();

            Autodesk.Revit.DB.ElementFilter filter = null;

            if (boundingBox)
            {
                var pointsBBox = new Rhino.Geometry.BoundingBox(points);
                {
                    var box = new Rhino.Geometry.Box(pointsBBox);
                    box.Inflate(tolerance);
                    targets.Add(box);
                }

                pointsBBox = pointsBBox.Scale(scaleFactor);
                var outline = new Autodesk.Revit.DB.Outline(pointsBBox.Min.ToHost(), pointsBBox.Max.ToHost());

                if (strict)
                {
                    filter = new Autodesk.Revit.DB.BoundingBoxIsInsideFilter(outline, tolerance * scaleFactor, inverted);
                }
                else
                {
                    filter = new Autodesk.Revit.DB.BoundingBoxIntersectsFilter(outline, tolerance * scaleFactor, inverted);
                }
            }
            else
            {
                var filters = points.Select <Rhino.Geometry.Point3d, Autodesk.Revit.DB.ElementFilter>
                                  (x =>
                {
                    var pointsBBox = new Rhino.Geometry.BoundingBox(x, x);
                    {
                        var box = new Rhino.Geometry.Box(pointsBBox);
                        box.Inflate(tolerance);
                        targets.Add(box);
                    }

                    x           = x.Scale(scaleFactor);
                    var outline = new Autodesk.Revit.DB.Outline(x.ToHost(), x.ToHost());

                    if (strict)
                    {
                        return(new Autodesk.Revit.DB.BoundingBoxIsInsideFilter(outline, tolerance * scaleFactor, inverted));
                    }
                    else
                    {
                        return(new Autodesk.Revit.DB.BoundingBoxIntersectsFilter(outline, tolerance * scaleFactor, inverted));
                    }
                });

                filter = new Autodesk.Revit.DB.LogicalOrFilter(filters.ToList());
            }

            DA.SetDataList("Target", targets);
            DA.SetData("Filter", filter);
        }
Ejemplo n.º 52
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            bool         go        = false;
            WR_Structure structure = null;
            List <int>   modes     = new List <int>();

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();


            if (!DA.GetData(0, ref structure))
            {
                return;
            }
            if (!DA.GetDataList(1, modes))
            {
                return;
            }
            if (!DA.GetData(2, ref go))
            {
                return;
            }

            if (go)
            {
                _resElems = new List <ResultElement>();
                _log.Clear();
                watch.Restart();

                // Solve
                _solver = new WR_EigenSolver(structure);
                _solver.Solve();

                watch.Stop();

                _log.Add(String.Format("Solve system: {0}ms", watch.ElapsedMilliseconds));

                watch.Restart();


                if (_solver != null && structure != null)
                {
                    _eigVals = new List <double>();
                    foreach (int mode in modes)
                    {
                        _eigVals.Add(_solver.SetResultsToMode(mode));
                    }

                    watch.Stop();

                    _log.Add(String.Format("Analyse modes: {0}ms", watch.ElapsedMilliseconds));

                    watch.Restart();


                    // Extract results
                    List <WR_IElement> elems = structure.GetAllElements();
                    _resElems.Clear();

                    for (int i = 0; i < elems.Count; i++)
                    {
                        if (elems[i] is WR_Element3d)
                        {
                            WR_Element3d  el3d = (WR_Element3d)elems[i];
                            ResultElement re   = new ResultElement(el3d);
                            _resElems.Add(re);
                        }
                    }

                    watch.Stop();

                    _log.Add(String.Format("Extract results: {0}ms", watch.ElapsedMilliseconds));
                }
            }



            DA.SetDataList(0, _log);
            DA.SetDataList(1, _resElems);
            DA.SetDataList(2, _eigVals);
        }
Ejemplo n.º 53
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> crvs     = new List <Curve>();
            double       tol      = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;
            double       angelTol = Rhino.RhinoDoc.ActiveDoc.ModelAngleToleranceDegrees;
            int          option   = 0;

            if (!DA.GetDataList("Curves", crvs))
            {
                return;
            }
            DA.GetData("Tolerance", ref tol);
            if (!DA.GetData("Option", ref option))
            {
                return;
            }

            if (option == 0)
            {
                Curve[] crvsJ = Curve.JoinCurves(crvs, tol);
                DA.SetDataList("Curve", crvsJ);
            }
            else if (option == 1)
            {
                List <Curve> filletOutput     = new List <Curve>();
                List <Curve> filletOutputPara = new List <Curve>();
                Curve[]      filletSegment    = new Curve[0];
                double       crv1Parameter    = 0.0;
                double       crv2Parameter    = 1.0;
                for (int i = 0; i < crvs.Count; i++)
                {
                    if (i != crvs.Count - 1)
                    {
                        if (crvs[i] != null && crvs[i + 1] != null)
                        {
                            if (filletOutput.Count == 0 || filletSegment.Count() == 0)
                            {
                                filletSegment = Curve.CreateFilletCurves(
                                    crvs[i],
                                    crvs[i].PointAtNormalizedLength(crv1Parameter),
                                    crvs[i + 1],
                                    crvs[i + 1].PointAtNormalizedLength(crv2Parameter),
                                    0, false, true, false, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, angelTol);
                            }
                            else
                            {
                                filletSegment = Curve.CreateFilletCurves(
                                    filletOutput[filletOutput.Count - 1],
                                    filletOutput[filletOutput.Count - 1].PointAtNormalizedLength(crv1Parameter),
                                    crvs[i + 1],
                                    crvs[i + 1].PointAtNormalizedLength(crv2Parameter),
                                    0, false, true, false, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, angelTol);
                            }

                            if (filletSegment.Count() == 0)
                            {
                                int j = i + 1;
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No geometry produced between curve " + i.ToString() + " and curve " + j.ToString() + ".");
                            }
                            else
                            {
                                if (filletSegment[0].PointAtEnd.DistanceTo(crvs[i + 1].PointAtStart) > filletSegment[0].PointAtEnd.DistanceTo(crvs[i + 1].PointAtEnd))
                                {
                                    if (filletSegment[0].PointAtEnd.DistanceTo(crvs[i].PointAtStart) < filletSegment[0].PointAtEnd.DistanceTo(crvs[i].PointAtEnd))
                                    {
                                        crv1Parameter = 1.0;
                                        crv2Parameter = 0.0;
                                    }
                                    else
                                    {
                                        crv1Parameter = 0.0;
                                        crv2Parameter = 0.0;
                                    }
                                }
                                else
                                {
                                    if (filletSegment[0].PointAtEnd.DistanceTo(crvs[i].PointAtStart) < filletSegment[0].PointAtEnd.DistanceTo(crvs[i].PointAtEnd))
                                    {
                                        crv1Parameter = 1.0;
                                        crv2Parameter = 1.0;
                                    }
                                }

                                if (filletOutput.Count == 0 || filletSegment.Count() == 0)
                                {
                                    filletSegment = Curve.CreateFilletCurves(
                                        crvs[i],
                                        crvs[i].PointAtNormalizedLength(crv1Parameter),
                                        crvs[i + 1],
                                        crvs[i + 1].PointAtNormalizedLength(crv2Parameter),
                                        0, false, true, false, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, angelTol);
                                }
                                else
                                {
                                    filletSegment = Curve.CreateFilletCurves(
                                        filletOutput[filletOutput.Count - 1],
                                        filletOutput[filletOutput.Count - 1].PointAtNormalizedLength(crv1Parameter),
                                        crvs[i + 1],
                                        crvs[i + 1].PointAtNormalizedLength(crv2Parameter),
                                        0, false, true, false, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, angelTol);
                                }

                                Rhino.RhinoApp.WriteLine(crv1Parameter.ToString(), crv2Parameter.ToString());

                                filletOutput.Add(filletSegment[0]);
                                filletOutput.Add(filletSegment[1]);
                                filletOutputPara.Add(filletSegment[0]);
                                if (i == crvs.Count - 2)
                                {
                                    filletOutputPara.Add(filletSegment[1]);
                                }
                            }
                        }
                    }
                }

                Curve[] crvsJ = Curve.JoinCurves(filletOutputPara, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);
                DA.SetDataList("Curve", crvsJ);
            }
        }
Ejemplo n.º 54
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)
        {
            // get indata
            List <FemDesign.Results.BarDisplacement> iResult = new List <FemDesign.Results.BarDisplacement>();

            DA.GetDataList("Result", iResult);

            string iLoadCase = null;

            DA.GetData(1, ref iLoadCase);


            // Read Result from Abstract Method
            Dictionary <string, object> result;

            try
            {
                result = FemDesign.Results.BarDisplacement.DeconstructBarDisplacements(iResult, iLoadCase);
            }
            catch (ArgumentException ex)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message);
                return;
            }

            // Extract Results from the Dictionary
            var loadCases      = (List <string>)result["CaseIdentifier"];
            var elementId      = (List <string>)result["ElementId"];
            var positionResult = (List <double>)result["PositionResult"];
            var iTranslation   = (List <FemDesign.Geometry.FdVector3d>)result["Translation"];
            var iRotation      = (List <FemDesign.Geometry.FdVector3d>)result["Rotation"];


            var uniqueId = elementId.Distinct().ToList();


            // Convert Data in DataTree structure
            DataTree <object> elementIdTree      = new DataTree <object>();
            DataTree <object> positionResultTree = new DataTree <object>();
            DataTree <object> oTranslationTree   = new DataTree <object>();
            DataTree <object> oRotationTree      = new DataTree <object>();


            var ghPath = DA.Iteration;
            var i      = 0;

            foreach (var id in uniqueId)
            {
                // indexes where the uniqueId matches in the list
                elementIdTree.Add(id, new GH_Path(ghPath, i));

                var indexes = elementId.Select((value, index) => new { value, index })
                              .Where(a => string.Equals(a.value, id))
                              .Select(a => a.index);

                foreach (int index in indexes)
                {
                    positionResultTree.Add(positionResult.ElementAt(index), new GH_Path(ghPath, i));
                    oTranslationTree.Add(iTranslation.ElementAt(index).ToRhino(), new GH_Path(ghPath, i));
                    oRotationTree.Add(iRotation.ElementAt(index).ToRhino(), new GH_Path(ghPath, i));
                }
                i++;
            }

            // Set output
            DA.SetDataList(0, loadCases);
            DA.SetDataTree(1, elementIdTree);
            DA.SetDataTree(2, positionResultTree);
            DA.SetDataTree(3, oTranslationTree);
            DA.SetDataTree(4, oRotationTree);
        }
Ejemplo n.º 55
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Program program = null;
            var first = new List<GH_Integer>();
            var second = new List<GH_Integer>();
            GH_Mesh environment = null;
            int environmentPlane = -1;
            double linearStep = 100;
            double angularStep = PI / 4;

            if (!DA.GetData(0, ref program)) { return; }
            if (!DA.GetDataList(1, first)) { return; }
            if (!DA.GetDataList(2, second)) { return; }
            DA.GetData(3, ref environment);
            if (!DA.GetData(4, ref environmentPlane)) { return; }
            if (!DA.GetData(5, ref linearStep)) { return; }
            if (!DA.GetData(6, ref angularStep)) { return; }

            var collision = program.Value.CheckCollisions(first.Select(x => x.Value), second.Select(x => x.Value), environment?.Value, environmentPlane, linearStep, angularStep);

            DA.SetData(0, collision.HasCollision);
            if (collision.HasCollision) DA.SetData(1, collision.CollisionTarget.Index);
            if (collision.HasCollision) DA.SetDataList(2, collision.Meshes);
        }
Ejemplo n.º 56
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 <IGH_GeometricGoo> objs = new List <IGH_GeometricGoo>();

            DA.GetDataList(0, objs);

            string layerName = "Default";
            object material  = null;
            bool   clearL    = false;

            DA.GetData(1, ref layerName);
            DA.GetData(2, ref material);

            /*Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes();
             * att.LayerIndex = doc.Layers.Find(layerName, true);
             * att.MaterialIndex = doc.Materials.Find(matName, true);*/

            Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes();


            //Set material
            if (material != null)
            {
                string          matName       = "";
                DisplayMaterial mat           = new DisplayMaterial();
                Color           col           = new Color();
                int             isName        = -1;
                int             materialIndex = -1;
                try { matName = (material as GH_String).Value; isName = 1; }
                catch
                {
                    try
                    {
                        mat    = (material as GH_Material).Value;
                        isName = 0;
                    }
                    catch
                    {
                        try { col = (material as GH_Colour).Value; mat = new DisplayMaterial(col); isName = 0; }
                        catch { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Can't identify material object. Please supply render material name, GH material or color."); }
                    }
                }


                if (isName == 1)
                {
                    materialIndex      = doc.Materials.Find(matName, true);
                    att.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject;
                    if (materialIndex < 0)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Couldn't find material by name. If you're sure the material exists in the Rhino Material list, try adding it to one object manually. After that it should work.");
                    }
                    att.MaterialIndex = materialIndex;
                }

                else
                {
                    materialIndex = doc.Materials.Add();
                    if (materialIndex > -1)
                    {
                        Rhino.DocObjects.Material m = doc.Materials[materialIndex];
                        m.Name          = matName;
                        m.AmbientColor  = mat.Ambient;
                        m.DiffuseColor  = mat.Diffuse;
                        m.EmissionColor = mat.Emission;
                        //m.ReflectionColor = no equivalent
                        m.SpecularColor = mat.Specular;
                        m.Shine         = mat.Shine;
                        m.Transparency  = mat.Transparency;
                        //m.TransparentColor = no equivalent
                        m.CommitChanges();

                        att.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject;
                        att.MaterialIndex  = materialIndex;
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Couldn't add material. Try cleaning up your materials."); //This never happened to me.
                    }
                }
            }


            DA.GetData(3, ref att);
            DA.GetData(4, ref clearL);

            //Delete objects by GUID
            doc.Objects.Delete(ids, true);


            for (int i = 0; i < objs.Count; i++)
            {
                GeometryBase gb;
                Point3d      pt;
                Brep         b;
                if (ids.Count <= i)
                {
                    ids.Add(Guid.NewGuid());
                }

                att.ObjectId = ids[i];
                if (objs[i].CastTo <Point3d>(out pt))
                {
                    doc.Objects.AddPoint(pt, att);
                }
                else if (objs[i].CastTo <Brep>(out b))
                {
                    doc.Objects.AddBrep(b, att);
                }
                else if (objs[i].CastTo <GeometryBase>(out gb))
                {
                    doc.Objects.Add(gb, att);
                }

                else
                {
                    throw new Exception("Object nr. " + i + " is not bakeable:\n" + objs[i].ToString() + ".\nIf it's a box or a curve, try turning it into a Brep by wiring it through a Brep container component before feeding it to Instant Bake.");
                }
            }

            if (clearL)
            {
                foreach (Rhino.DocObjects.RhinoObject o in doc.Objects.FindByLayer(layerName))
                {
                    doc.Objects.Delete(o, true);
                }
            }

            if (counter >= 10)
            {
                Rhino.RhinoDoc.ActiveDoc.ClearUndoRecords(true);
                counter = 0;
            }


            DA.SetDataList(0, ids);
            counter++;
        }
Ejemplo n.º 57
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.º 58
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Toolpath> tpIn      = new List <Toolpath>();
            object          safety    = null;
            string          post_name = "";
            bool            post_all  = false;
            Plane           frame     = Plane.WorldXY;


            DA.GetData("Machine", ref post_name);
            this.Message = post_name;

            DA.GetDataList("Toolpaths", tpIn);
            DA.GetData("Safety", ref safety);
            DA.GetData("Frame", ref frame);
            DA.GetData("All codes", ref post_all);

            List <Toolpath> TP = tpIn.Select(x => x.Duplicate()).ToList();

            MachinePost post = null;

            switch (post_name)
            {
            case ("CMS"):
                post = new CMSPost();
                break;

            case ("Haas"):
                post = new HaasPost();
                break;

            case ("Shopbot"):
                post = new ShopbotPost();
                break;

            case ("Raptor"):
                post = new RaptorBCNPost();
                break;

            case ("CNC-STEP"):
                post = new CncStepPost();
                break;

            default:
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Machine {post_name} not found.");
                return;
            }


            // Program initialization
            var doc = OnPingDocument();

            if (doc != null)
            {
                post.Author = doc.Author.Name;
                post.Name   = doc.DisplayName;
            }
            else
            {
                post.Author = "Author";
                post.Name   = "Post";
            }

            post.StockModel = null;

            post.AlwaysWriteGCode = post_all;

            for (int i = 0; i < TP.Count; ++i)
            {
                var toolpath = TP[i];
                post.AddTool(toolpath.Tool);

                if (frame != Plane.WorldXY)
                {
                    toolpath.Transform(Transform.PlaneToPlane(Plane.WorldXY, frame));
                }

                post.AddPath(toolpath);
            }

            //cms.WorkOffset = new Point3d(0, 0, 0);

            // Post-process toolpaths

            var code = (post.Compute() as List <string>).Select(x => new GH_String(x));

            // ****** Fun stuff ends here. ******


            List <Point3d>  points  = new List <Point3d>();
            List <int>      types   = new List <int>();
            List <Vector3d> vectors = new List <Vector3d>();

            for (int i = 0; i < post.Paths.Count; ++i)
            {
                for (int j = 0; j < post.Paths[i].Paths.Count; ++j)
                {
                    for (int k = 0; k < post.Paths[i].Paths[j].Count; ++k)
                    {
                        points.Add(post.Paths[i].Paths[j][k].Plane.Origin);
                        vectors.Add(post.Paths[i].Paths[j][k].Plane.ZAxis);

                        if (post.Paths[i].Paths[j][k].IsRapid())
                        {
                            types.Add(0);
                        }
                        else if (post.Paths[i].Paths[j][k].IsFeed())
                        {
                            types.Add(1);
                        }
                        else if (post.Paths[i].Paths[j][k].IsPlunge())
                        {
                            types.Add(2);
                        }
                        else
                        {
                            types.Add(-1);
                        }
                    }
                }
            }

            Polyline    poly  = new Polyline(points);
            List <Line> lines = new List <Line>();

            for (int i = 1; i < poly.Count; ++i)
            {
                lines.Add(new Line(poly[i - 1], poly[i]));
            }

            types.RemoveAt(0);

            DA.SetDataList("Gcode", code);
            DA.SetDataList("Path", lines);
            DA.SetDataList("debug", post.Errors);

            if (post.Axes != null)
            {
                var axes = new List <string>();
                foreach (var values in post.Axes)
                {
                    axes.Add($"{values.X:0.000}, {values.Y:0.000}, {values.Z:0.000}, {values.B:0.000}, {values.C:0.000}");
                }
                DA.SetDataList("Axes", axes);
                DA.SetDataList("Speeds", post.Axes.Select(x => x.Speed));
            }
        }
Ejemplo n.º 59
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)
        {
            // 1. Retrieve and validate inputs
            var cell = new UnitCell();
            Surface s1 = null;
            Surface s2 = null;
            int nU = 0;
            int nV = 0;
            int nW = 0;
            bool morphed = false;

            if (!DA.GetData(0, ref cell)) { return; }
            if (!DA.GetData(1, ref s1)) { return; }
            if (!DA.GetData(2, ref s2)) { return; }
            if (!DA.GetData(3, ref nU)) { return; }
            if (!DA.GetData(4, ref nV)) { return; }
            if (!DA.GetData(5, ref nW)) { return; }
            if (!DA.GetData(6, ref morphed)) { return; }

            if (!cell.isValid) { return; }
            if (!s1.IsValid) { return; }
            if (!s2.IsValid) { return; }
            if (nU == 0) { return; }
            if (nV == 0) { return; }
            if (nW == 0) { return; }

            // 2. Initialize the lattice
            var lattice = new Lattice();
            // Will contain the morphed uv spaces (as surface-surface)
            var spaceTree = new DataTree<GeometryBase>(); 
            
            // 3. Package the number of cells in each direction into an array
            float[] N = new float[3] { nU, nV, nW };

            // 4. Normalize the UV-domain
            Interval unitDomain = new Interval(0,1);
            s1.SetDomain(0, unitDomain); // s1 u-direction
            s1.SetDomain(1, unitDomain); // s1 v-direction
            s2.SetDomain(0, unitDomain); // s2 u-direction
            s2.SetDomain(1, unitDomain); // s2 v-direction

            // 5. Prepare cell (this is a UnitCell object)
            cell = cell.Duplicate();
            cell.FormatTopology();

            // 6. Map nodes to design space
            //    Loop through the uvw cell grid
            for (int u = 0; u <= N[0]; u++)
            {
                for (int v = 0; v <= N[1]; v++)
                {
                    for (int w = 0; w <= N[2]; w++)
                    {
                        // Construct cell path in tree
                        GH_Path treePath = new GH_Path(u, v, w);
                        // Fetch the list of nodes to append to, or initialise it
                        var nodeList = lattice.Nodes.EnsurePath(treePath);      

                        // This loop maps each node in the cell onto the UV-surface maps
                        for (int i = 0; i < cell.Nodes.Count; i++)
                        {
                            double usub = cell.Nodes[i].X; // u-position within unit cell (local)
                            double vsub = cell.Nodes[i].Y; // v-position within unit cell (local)
                            double wsub = cell.Nodes[i].Z; // w-position within unit cell (local)
                            double[] uvw = { u + usub, v + vsub, w + wsub }; // uvw-position (global)

                            // Check if the node belongs to another cell (i.e. it's relative path points outside the current cell)
                            bool isOutsideCell = (cell.NodePaths[i][0] > 0 || cell.NodePaths[i][1] > 0 || cell.NodePaths[i][2] > 0);
                            // Check if current uvw-position is beyond the upper boundary
                            bool isOutsideSpace = (uvw[0] > N[0] || uvw[1] > N[1] || uvw[2] > N[2]);

                            if (isOutsideCell || isOutsideSpace)
                            {
                                nodeList.Add(null);
                            }
                            else
                            {
                                // Initialize for surface 1
                                Point3d pt1; Vector3d[] derivatives1;
                                // Initialize for surface 2
                                Point3d pt2; Vector3d[] derivatives2;

                                // Evaluate point on both surfaces
                                s1.Evaluate(uvw[0] / N[0], uvw[1] / N[1], 2, out pt1, out derivatives1);
                                s2.Evaluate(uvw[0] / N[0], uvw[1] / N[1], 2, out pt2, out derivatives2);

                                // Create vector joining the two points (this is our w-range)
                                Vector3d wVect = pt2 - pt1;

                                // Create the node, accounting for the position along the w-direction
                                var newNode = new LatticeNode(pt1 + wVect * uvw[2] / N[2]);
                                // Add node to tree
                                nodeList.Add(newNode);
                            }
                        }
                    }

                    // Define the uv space tree (used for morphing)
                    if (morphed && u < N[0] && v < N[1])
                    {
                        GH_Path spacePath = new GH_Path(u, v);
                        // Set trimming interval
                        var uInterval = new Interval((u) / N[0], (u + 1) / N[0]);
                        var vInterval = new Interval((v) / N[1], (v + 1) / N[1]);
                        // Create sub-surfaces
                        Surface ss1 = s1.Trim(uInterval, vInterval);
                        Surface ss2 = s2.Trim(uInterval, vInterval);
                        // Unitize domain
                        ss1.SetDomain(0, unitDomain); ss1.SetDomain(1, unitDomain);
                        ss2.SetDomain(0, unitDomain); ss2.SetDomain(1, unitDomain); 
                        // Save to the space tree
                        spaceTree.Add(ss1, spacePath);
                        spaceTree.Add(ss2, spacePath);
                    }
                    
                }
            }

            // 7. Map struts to the node tree
            if (morphed) lattice.MorphMapping(cell, spaceTree, N);
            else lattice.ConformMapping(cell, N);

            // 8. Set output
            DA.SetDataList(0, lattice.Struts);

        }
Ejemplo n.º 60
0
 protected override void SolveInstance(IGH_DataAccess DA)
 {
     DA.SetDataList(0, System.IO.Ports.SerialPort.GetPortNames());
 }