示例#1
0
    protected override bool GetInputs(IGH_DataAccess da)
    {
      agents = new List<IQuelea>();
      emitters = new List<AbstractEmitterType>();
      environment = new WorldEnvironmentType();
      // Then we need to access the input parameters individually. 
      // When data cannot be extracted from a parameter, we should abort this
      // method.
      if (!da.GetDataList(nextInputIndex++, agents)) return false;
      if (!da.GetDataList(nextInputIndex++, emitters)) return false;
      da.GetData(nextInputIndex++, ref environment);

      // We should now validate the data and warn the user if invalid data is 
      // supplied.
      if (agents.Count <= 0)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, RS.agentsCountErrorMessage);
        return false;
      }
      if (emitters.Count <= 0)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, RS.emittersCountErrorMessage);
        return false;
      }
      return true;
    }
        /// <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>();
            if(!DA.GetDataList(0, bars)) { return; }

            List<Point3d> nodes = new List<Point3d>();
            if(!DA.GetDataList(1, nodes)) { return; }

            List<double> displacements = new List<double>();
            if(!DA.GetDataList(2, displacements)) { return; }

            List<Color> gradientColours = new List<Color>();
            if(!DA.GetDataList(3, gradientColours)) { return; }


            //Calculate
            lines = new List<Line>();
            for(int i=0; i<bars.Count; i++)
            {
                lines.Add(bars[i]);
            }

            List<double> barDispl = calcBarDisplacements(bars, nodes, displacements);
            colours = mapDisplToColour(barDispl, gradientColours);

        }
示例#3
0
文件: Program.cs 项目: visose/Robots
        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");
            }
        }
示例#4
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_RobotSystem robotSystem = null;
            var targets = new List<GH_Target>();
            var prevJointsText = new List<GH_String>();
            bool drawMeshes = false;

            if (!DA.GetData(0, ref robotSystem)) { return; }
            if (!DA.GetDataList(1, targets)) { return; }
            DA.GetDataList(2, prevJointsText);
            if (!DA.GetData(3, ref drawMeshes)) { return; }

            List<double[]> prevJoints = null;

            if (prevJointsText.Count > 0)
            {
                prevJoints = new List<double[]>();

                foreach (var text in prevJointsText)
                {
                    if (text != null)
                    {
                        string[] jointsText = text.Value.Split(',');
                        var prevJoint = new double[jointsText.Length];

                        for (int i = 0; i < jointsText.Length; i++)
                            if (!GH_Convert.ToDouble_Secondary(jointsText[i], ref prevJoint[i])) throw new Exception(" Previous joints not formatted correctly.");

                        prevJoints.Add(prevJoint);
                    }
                }
            }

            var kinematics = robotSystem.Value.Kinematics(targets.Select(x => x.Value), prevJoints, drawMeshes);

            var errors = kinematics.SelectMany(x => x.Errors);
            if (errors.Count() > 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Errors in solution");
            }

            var strings = kinematics.SelectMany(x => x.Joints).Select(x => new GH_Number(x).ToString());
            var joints = string.Join(",", strings);

            var planes = kinematics.SelectMany(x => x.Planes);
            if (drawMeshes)
            {
                var meshes = kinematics.SelectMany(x => x.Meshes);
                DA.SetDataList(0, meshes.Select(x => new GH_Mesh(x)));
            }

            DA.SetData(1, joints);
            DA.SetDataList(2, planes.Select(x => new GH_Plane(x)));
            DA.SetDataList(3, errors);
        }
 protected override bool GetInputs(IGH_DataAccess da)
 {
     obs = new List<Brep>();
     cont = new List<Brep>();
     if (!da.GetData(0, ref u_count)) return false;
     if (!da.GetData(1, ref v_count)) return false;
     if (!da.GetData(2, ref srf)) return false;
     da.GetDataList(3, cont);
     da.GetDataList(4, obs);
     return true;
 }
 /// <summary>
 /// Gets the unique ID for this component. Do not change this ID after release.
 /// </summary>
 protected override bool GetInputs(IGH_DataAccess da)
 {
     breps = new List<Brep>();
     obs = new List<Brep>();
     if (!da.GetData(nextInputIndex++, ref x_count)) return false;
     if (!da.GetData(nextInputIndex++, ref y_count)) return false;
     if (!da.GetData(nextInputIndex++, ref z_count)) return false;
     if (!da.GetDataList(nextInputIndex++, breps)) return false;
     da.GetDataList(4, obs);
     return true;
 }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<GH_Element> elements = new List<GH_Element>();
            List<GH_Support> supports = new List<GH_Support>();

            List<GH_Load> loads = new List<GH_Load>();

            int modelType = 0;

            if (!DA.GetDataList<GH_Element>(0, elements))
            {
                return;
            }

            if (!DA.GetDataList<GH_Support>(1, supports))
            {
                return;
            }

            if (!DA.GetDataList<GH_Load>(2, loads))
            {
                return;
            }

            if (!DA.GetData(3, ref modelType))
            {
                return;
            }

            //Clear current structure... Perhaps change this for a more parametric approach, or opening existing files
            GH_Model model = null;

            switch (modelType)
            {
                case 0:
                    model = new GH_Model(ModelType.Truss2D);
                    break;
                case 1:
                    model = new GH_Model(ModelType.Full3D);
                    break;
                default:
                    throw new Exception("Model type does not exist or not yet implemented");
            }

            model.Elements = elements;
            model.Loads = loads;
            model.Supports = supports;

            model.AssembleSharpModel();

            DA.SetData(0, model);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool reset = false;
            DA.GetData(6, ref reset);
            if (reset)
                Particle.Zones.Clear(); //= new List<Particle>();

            List<Point3d> origin = new List<Point3d>();
            DA.GetDataList<Point3d>(1, origin);
            foreach (Point3d pt in origin) //FIXME: remove duplicates for each component calling
                Particle.Create(pt);

            double D = 25;
            DA.GetData<double>(2, ref D);
            Particle.step_size = D;

            double dk = 1.2;
            DA.GetData<double>(4, ref dk);
            Particle.eatable_distance = D * dk;

            double di = 4;
            DA.GetData<double>(3, ref di);
            Particle.infuence_distance = D * di;

            int loop = 1;
            DA.GetData<int>(5, ref loop);

            List<Point3d> food = new List<Point3d>();
            bool haveFood = (DA.GetDataList<Point3d>(0, food));

            if (haveFood)
            {
                while (loop > 0)
                {
                    for (int i = food.Count() - 1; i >= 0; i--)
                    {
                        // if food is eatable
                        if (Particle.IsEatable(food[i]))
                        {
                            food.RemoveAt(i); // eat it
                            //Print("food at index " + i + " was removed");
                        }
                    }
                    Particle.Move();
                    loop--;
                }
            }

            DA.SetDataList(0, Particle.Connections());
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
#if DEBUG
            Rhino.RhinoApp.WriteLine("Assessment " + this.Name + " is solving");
#endif
            
            // check dependencies
            if (this.m_Assessment == null) { return; }

            // check if the controller is online
            SOGrasshopperController con = SOGrasshopperController.GetInstance(OnPingDocument());

            List<SODesigner_GHData> designersList = new List<SODesigner_GHData>();
            DA.GetDataList<SODesigner_GHData>(0, designersList);
            this.m_Assessment.ClearDesigners();
            foreach (SODesigner_GHData data in designersList)
            {
                this.m_Assessment.AddDesigner(data.Value);
            }

            List<SOAnalysis_GHData> analysisList = new List<SOAnalysis_GHData>();
            DA.GetDataList<SOAnalysis_GHData>(1, analysisList);
            this.m_Assessment.ClearAnalysis();
            foreach (SOAnalysis_GHData data in analysisList)
            {
                this.m_Assessment.AddAnalysis(data.Value);
            }

            List<SOAssessment_GHData> assessmentsList = new List<SOAssessment_GHData>();
            DA.GetDataList<SOAssessment_GHData>(2, assessmentsList);
            this.m_Assessment.ClearAssessments();
            foreach (SOAssessment_GHData data in assessmentsList)
            {
                this.m_Assessment.AddAssessment(data.Value);
            }

            // run the assessment
            try
            {
                this.m_Assessment.RunAssessment();
            }
            catch (Exception)
            {
                return;
            }

            SOAssessment_GHData assessment = new SOAssessment_GHData(this.m_Assessment);
            DA.SetData(0, assessment);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            SpringMesh iSpringMesh = new SpringMesh();
            List<Circle> iCircles = new List<Circle>();
            double iBendingStiffness = double.NaN;
            double iStiffness = double.NaN;
            List<double> iPlanarRegionBendingStiffness = new List<double>();
            List<double> iPlanarRegionStiffness = new List<double>();

            DA.GetData<SpringMesh>(0, ref iSpringMesh);
            DA.GetDataList<Circle>(1, iCircles);
            DA.GetData<double>(2, ref iBendingStiffness);
            DA.GetData<double>(3, ref iStiffness);
            DA.GetDataList<double>(4, iPlanarRegionBendingStiffness);
            DA.GetDataList<double>(5, iPlanarRegionStiffness);

            SpringMesh oSpringMesh = new SpringMesh(iSpringMesh);

            foreach (Edge edge in iSpringMesh.Edges)
            {
                edge.RestLength = Utils.Distance(oSpringMesh.Vertices[edge.FirstVertexIndex].Position, oSpringMesh.Vertices[edge.SecondVertexIndex].Position);
                edge.Stiffness = iStiffness;
                if (edge.SecondTriangleIndex >= 0)
                {
                    edge.RestAngle = Utils.AngleBetweenTwoTriangles(
                        iSpringMesh.Vertices[edge.FirstVertexIndex].Position,
                        iSpringMesh.Vertices[edge.SecondVertexIndex].Position,
                        iSpringMesh.Vertices[edge.FirstAdjacentVertexIndex].Position,
                        iSpringMesh.Vertices[edge.SecondAdjacentVertexIndex].Position
                        );
                }
                edge.BendingStiffness = iBendingStiffness;
            }

            for (int i = 0; i < oSpringMesh.Vertices.Count; i++)
                for (int j = 0; j < iCircles.Count; j++ )
                    if (Utils.Distance(iCircles[j].Center, oSpringMesh.Vertices[i].Position) <= iCircles[j].Radius)
                    {
                        foreach (Edge edge in oSpringMesh.Edges)
                            if (edge.FirstVertexIndex == i || edge.SecondVertexIndex == i)
                            {
                                edge.Stiffness = iPlanarRegionStiffness[j];
                                edge.RestAngle = Math.PI;
                                edge.BendingStiffness = iPlanarRegionBendingStiffness[j];
                            }
                        break;
                    }
            DA.SetData(0, oSpringMesh);
        }
示例#11
0
文件: Machine.cs 项目: visose/Robots
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string name = null;
            GH_Plane tcp = null;
            double weight = 0;
            GH_Mesh mesh = null;
            GH_Point centroid = null;
            List<GH_Plane> planes = new List<GH_Plane>();

            if (!DA.GetData(0, ref name)) { return; }
            if (!DA.GetData(1, ref tcp)) { return; }
            DA.GetDataList(2, planes);
            if (!DA.GetData(3, ref weight)) { return; }
            DA.GetData(4, ref centroid);
            DA.GetData(5, ref mesh);

            var tool = new Tool(tcp.Value, name, weight, centroid?.Value, mesh?.Value);

            if (planes.Count > 0)
            {
                if (planes.Count != 4)
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, " Calibration input must be 4 planes");
                else
                    tool.FourPointCalibration(planes[0].Value, planes[1].Value, planes[2].Value, planes[3].Value);
            }

            DA.SetData(0, new GH_Tool(tool));
            DA.SetData(1, tool.Tcp);
        }
示例#12
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> dhrs = new List<DHr>();
            string key = "";
            if ((DA.GetDataList(0, dhrs)) && (DA.GetData(1, ref key))) {
                float maxval = dhrs[0].val(key);
                float minval = dhrs[0].val(key);
                int max_day = 0;
                int min_day = 0;
                for (int n = 1; n < dhrs.Count; n++) {
                    float val = dhrs[n].val(key);
                    if (val > maxval) {
                        maxval = val;
                        max_day = dhrs[n].day_of_year;
                    }
                    if (val < minval) {
                        minval = val;
                        min_day = dhrs[n].day_of_year;
                    }
                }
                HourMask max_mask = new HourMask();
                max_mask.maskByDayOfYear(max_day, max_day);
                HourMask min_mask = new HourMask();
                min_mask.maskByDayOfYear(min_day, min_day);

                List<DHr> maxHrs = new List<DHr>();
                foreach (DHr hr in dhrs) if (max_mask.eval(hr)) maxHrs.Add(hr);
                List<DHr> minHrs = new List<DHr>();
                foreach (DHr hr in dhrs) if (min_mask.eval(hr)) minHrs.Add(hr);

                DA.SetDataList(0, maxHrs);
                DA.SetDataList(1, minHrs);
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            WR_Structure structure = null;
            bool go = false;
            List<int> modes = new List<int>();
            double sFac = 0;

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

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

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

                // Solve
                WR_ModeShapeOptimizer optimizer = new WR_ModeShapeOptimizer(structure);

                watch.Stop();

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

                watch.Restart();

                //Run
                optimizer.Run(modes, sFac);

                watch.Stop();

                _log.Add(String.Format("Run mode shape optimization: {0}ms", watch.ElapsedMilliseconds));

                watch.Restart();

                // Extract results
                List<WR_IElement> elems = structure.GetAllElements();
                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);
        }
        /// <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 parameters = new List<RhinoNestKernel.Nesting.RhinoNestObject>();

            //Declaration.
            var Object = new List<Guid>();
            var orientation = new OrientationGoo();
            var criterion = new CriterionGoo();
            var copies = 0;
            var priority = 0;
            //clear value and get the objects.
            if (!da.GetDataList(0, Object)) return;
            da.GetData(1, ref copies);
            da.GetData(2, ref priority);
            da.GetData(3, ref orientation);
            da.GetData(4, ref criterion);

            var organizer = new RhinoNestKernel.Curves.OrganizeObjects(Object);
            var res = organizer.Sort();

            foreach (var rhinoNestObject in organizer.Result)
            {
                rhinoNestObject.Parameters.Priority = priority;
                rhinoNestObject.Parameters.Copies = copies;
                rhinoNestObject.Parameters.Criterion = criterion.Value.Constraint;
                rhinoNestObject.Parameters.Orientation = orientation.Value.Constraint;
                parameters.Add(rhinoNestObject);
            }
            //Put the list to Output.
            da.SetDataList(0, parameters);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string name = String.Empty;
            bool gravityOn = false;
            Vector3d gravField = Vector3d.Unset;
            List<PointLoadCarrier> ptLds = new List<PointLoadCarrier>();

            if (!DA.GetData(0, ref name)) { return; }
            if (!DA.GetData(1, ref gravityOn)) { return; }
            if (!DA.GetData(2, ref gravField)) { return; }

            if(!DA.GetDataList(3, ptLds))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "No pointloads provided");
            }

            WR_LoadCombination loadComb;

            if(gravityOn)
            {
                loadComb = new WR_LoadCombination(name, new WR_Vector(gravField.X, gravField.Y, gravField.Z));
            }
            else
            {
                loadComb = new WR_LoadCombination(name, gravityOn);
            }

            foreach (PointLoadCarrier plc in ptLds)
            {
                loadComb.AddPointLoad(plc.CIForce, plc.CIMoment, plc.CIPos);
            }

            DA.SetData(0, loadComb);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
#if DEBUG
            Rhino.RhinoApp.WriteLine("Designer " + this.Name + " is solving");
#endif
            
            // check if the controller is online
            SOGrasshopperController con = SOGrasshopperController.GetInstance(OnPingDocument());

            List<SODesigner_GHData> designerList = new List<SODesigner_GHData>();
            DA.GetDataList<SODesigner_GHData>(0, designerList);
            this.m_Designer.ClearDesigners();
            foreach (SODesigner_GHData data in designerList)
            {
                this.m_Designer.AddDesigner(data.Value);
            }
            
            if (this.m_Designer == null) { return; }
            try
            {
                this.m_Designer.RunDesigner();
            }
            catch (Exception)
            {
                return;
            }

            // return the designer data
            SODesigner_GHData data1 = new SODesigner_GHData(this.m_Designer);
            DA.SetData(0, data1);
#if DEBUG
            Rhino.RhinoApp.WriteLine("> Controller state: " + SOController.Instance.State.ToString());
#endif
        }
示例#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)
        {
            // 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);

        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare a variable for the input

            List<Point3d> positions = new List<Point3d>();
            bool UX = false;
            bool UY = false;
            bool UZ = false;
            bool RX = false;
            bool RY = false;
            bool RZ = 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.GetDataList<Point3d>(0, positions)) { return; }
            if (!DA.GetData(1, ref UX )) { return; }
            if (!DA.GetData(2, ref UY)) { return; }
            if (!DA.GetData(3, ref UZ)) { return; }
            if (!DA.GetData(4, ref RX)) { return; }
            if (!DA.GetData(5, ref RY)) { return; }
            if (!DA.GetData(6, ref RZ)) { return; }

            //Create node constrain
            GH_NodeSupport nodeSupport = new GH_NodeSupport(positions, UX, UY, UZ, RX, RY, RZ);

            //Return
            DA.SetData(0, nodeSupport);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var curves = new List<Curve>();
            var lines = new List<Line>();

            if (DA.GetDataList(0, curves) && DA.GetDataList(1, lines))
            {
                curves.RemoveAll(_removeNullAndInvalidDelegate);
                lines.RemoveAll(_removeInvalidDelegate);

                if (curves.Count < 1)
                    return;

                CurvesTopology top = new CurvesTopology(curves, GH_Component.DocumentTolerance());

                var distances = top.MeasureAllEdgeLengths();

                List<Curve> result = new List<Curve>();

                for (int i = 0; i < lines.Count; i++)
                {
                    var line = lines[i];

                    int fromIndex = top.GetClosestNode(line.From);
                    int toIndex = top.GetClosestNode(line.To);

                    if (fromIndex == toIndex)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The start and end positions are equal");
                        result.Add(null);
                        continue;
                    }

                    var pathSearch = new AStar(top, distances);
                    var current = pathSearch.Cross(fromIndex, toIndex);

                    if (current == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                            string.Format("No walk found for line at position {0}. Are end points isolated?", i.ToString()));
                    }
                    result.Add(current);
                }

                DA.SetDataList(0, result);
            }
        }
示例#20
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)
        {
            PlanktonMesh P = new PlanktonMesh();
            List<Point3d> Points = new List<Point3d>();
            if ((!DA.GetData<PlanktonMesh>(0, ref P)) || (!DA.GetDataList(1, Points))) return;
            PlanktonMesh pMesh = P.ReplaceVertices(Points);           
            DA.SetData(0, pMesh);
        }
示例#21
0
 protected override bool GetInputs(IGH_DataAccess da)
 {
     if(! da.GetData(0, ref env)) return false;
     if (!da.GetData(1, ref emit)) return false;
     if (!da.GetData(2, ref food)) return false;
     da.GetDataList(3, setList);
     if (!da.GetData(4, ref rst)) return false;
     return true;
 }
示例#22
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. Retrieve and validate input
            var mesh = new List<Mesh>();
            if (!DA.GetDataList(0, mesh)) { return; }
            if (mesh == null || mesh.Count == 0) { return; }

            m_mesh = mesh; // for preview (see DrawViewPortMeshes method below)
        }
        /// <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> pts = new List<Point3d>();
            if (!DA.GetDataList(0, pts)) { return; }

            List<Vector3d> loads = new List<Vector3d>();
            if (!DA.GetDataList(1, loads)) { return; }

            c = Color.DarkCyan;
            DA.GetData(2, ref c);

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


            //Calculate
            lines = createLoadLines(pts, loads, scale);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<ResultElement> res = new List<ResultElement>();
            double sFac = double.NaN;
            string name = null;

            if (!DA.GetDataList(0, res)) { return; }
            if (!DA.GetData(1, ref sFac)) { return; }
            if(!DA.GetData(2, ref name))
            {
                if(res.Count>0)
                {
                    name = res[0].N1.First().Key;
                }
            }

            _dispCrvs.Clear();

            Point3d stPos, enPos;
            Vector3d norm, tan, yDir;

            List<Point3d> allPts = new List<Point3d>();

            foreach (ResultElement re in res)
            {
                stPos = re.sPos;
                enPos = re.ePos;
                norm = re.elNormal;

                norm.Unitize();

                tan = enPos - stPos;
                tan.Unitize();

                yDir = Vector3d.CrossProduct(norm, tan);
                yDir.Unitize();

                List<Point3d> curvePts = new List<Point3d>();

                int nbEval = re.pos.Count;

                for (int i = 0; i < nbEval; i++)
                {
                    Point3d curvePt = stPos + tan * (re.pos[i]+re.u[name][i]* sFac) +norm*re.w[name][i]* sFac + yDir*re.v[name][i]* sFac;
                    curvePts.Add(curvePt);
                    allPts.Add(curvePt);
                }

                _dispCrvs.Add(Rhino.Geometry.Curve.CreateInterpolatedCurve(curvePts, 3));
            }

            _bb = new BoundingBox(allPts);

            DA.SetDataList(0, _dispCrvs);
        }
示例#25
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);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            List<WR_Node3d> nodes = new List<WR_Node3d>();
            List<WR_IElemRcp> beams = new List<WR_IElemRcp>();

            if (!DA.GetDataList(0, nodes)) { return; }
            if (!DA.GetDataList(1, beams)) { return; }

            // Create structure wrapper
            WR_Structure structure = new WR_Structure();

            // Add restraint nodes
            foreach (WR_Node3d n in nodes)
                structure.AddNode(n);

            // Add elements
            foreach (WR_Elem3dRcp e in beams)
                structure.AddElementRcp(e);

            DA.SetData(0, structure);
        }
示例#27
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.ctIntersection, PolyFillType.pftNonZero, curvesA, curvesB, plane);
            

            // --- Output

            DA.SetDataList(0, result);
        }
        /// <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);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///// INPUTS /////
            Point3d pt = Point3d.Unset;
            List<bool> rels = new List<bool>();
            Plane pl = Plane.Unset;

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

            if (!DA.GetDataList<bool>(1, rels))
            {
                //Set as unrestrained if no release information is provided
                for (int i = 0; i < 6; i++)
                {
                    rels.Add(false);
                }
            }

            if (rels.Count != 6)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Number of bools in input should be 6");
                return;
            }

            if (!DA.GetData(2, ref pl))
            {
                // If no plane submitted, use global XY plane
                pl = new Rhino.Geometry.Plane(new Rhino.Geometry.Point3d(0,0,0),
                    new Rhino.Geometry.Vector3d(1,0,0), new Rhino.Geometry.Vector3d(0,1,0));
            }

            ///// SOLVE /////

            double factor = Utilities.GetScalingFactorFromRhino();

            WR_XYZ wrXYZ = new WR_XYZ(pt.X * factor, pt.Y * factor, pt.Z * factor);
            WR_Vector wrX = GetUnitizedWR_Vector(pl.XAxis);
            WR_Vector wrY = GetUnitizedWR_Vector(pl.YAxis);
            WR_Vector wrZ = GetUnitizedWR_Vector(pl.ZAxis);

            WR_Plane wrPl = new WR_Plane(wrX, wrY, wrZ, wrXYZ);
            WR_Restraint rest = new WR_Restraint(wrPl, rels[0], rels[1], rels[2], rels[3], rels[4], rels[5]);

            WR_INode node = new WR_Node3d(pt.X * factor, pt.Y * factor, pt.Z * factor, rest);

            ///// OUTPUTS /////
            DA.SetData(0, node);
        }
示例#30
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var list = new List<ITurtleMesh>();
            if (DA.GetDataList(0, list))
            {
                var nm = new TurtleMesh();

                for (int i = 0; i < list.Count; i++)
                {
                    if(list[i] != null)
                        nm.AppendOther(list[i]);
                }

                DA.SetData(0, nm);
            }
        }
示例#31
0
        /// <summary>
        /// Solves the instance.
        /// </summary>
        /// <param name="DA">Da.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Properties
            Mesh          mesh           = null;
            List <Curve>  perpGeodesics  = new List <Curve>();
            List <double> perpParameters = new List <double>();
            int           maxIter        = 0;
            bool          bothDir        = false;
            int           startIndex     = 0;

            mesh           = null;
            perpGeodesics  = new List <Curve>();
            perpParameters = new List <double>();
            double threshold = 0.0;

            // Set the input data
            if (!DA.GetData(0, ref mesh))
            {
                return;
            }
            if (!DA.GetDataList(1, perpGeodesics))
            {
                return;
            }
            if (!DA.GetDataList(2, perpParameters))
            {
                return;
            }
            if (!DA.GetData(3, ref maxIter))
            {
                return;
            }
            if (!DA.GetData(4, ref bothDir))
            {
                return;
            }
            if (!DA.GetData(5, ref startIndex))
            {
                return;
            }
            if (!DA.GetData(6, ref threshold))
            {
                return;
            }

            // Data validation
            if (maxIter == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "MaxIter cannot be 0");
            }
            if (!mesh.IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Mesh is invalid");
            }
            if (perpGeodesics.Count < 2)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "There must be at least 2 perpendicular geodesics");
            }
            if (perpParameters.Count != perpGeodesics.Count)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Curves and Params list must have the same number of items");
            }

            // Generate Initial values and variable Bounds for the optimization problem.
            // Only using first variable for now, the extra variable is just to make it work.
            double[] startData = { 0.010, 0 };
            double[] xl        = new double[] { -0.13, -1 };
            double[] xu        = new double[] { 0.13, 1 };


            BestFitPieceWiseGeodesic bestFitG = new BestFitPieceWiseGeodesic(mesh, perpGeodesics, perpParameters, maxIter, bothDir, startIndex, threshold, Vector3d.Unset);

            var optimizer = new Bobyqa(2, bestFitG.ComputeError, xl, xu);
            var result    = optimizer.FindMinimum(startData);

            if (bestFitG.bestFitInterval.Length == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "No best interval found?!");
                return;
            }

            // Sub curves methods go here
            List <Curve> pieceWiseList = new List <Curve>();

            pieceWiseList = bestFitG.GenerateSubCurves(startData, xl, xu, 0);


            DA.SetDataList(0, pieceWiseList);
            DA.SetDataList(1, result.X);
        }
        protected override void GroundHogSolveInstance(IGH_DataAccess DA)
        {
            // Create holder variables for input parameters
            var   PATH_ORIGINS = new List <Point3d>();
            var   STEP_SIZES   = new List <double>();
            int   STEP_COUNT   = 0;
            int?  SEED         = null;
            var   DIRECTIONS   = new List <double>();
            Curve BOUNDARY     = null;

            // Access and extract data from the input parameters individually
            if (!DA.GetDataList(0, PATH_ORIGINS))
            {
                return;
            }
            if (!DA.GetDataList(1, STEP_SIZES))
            {
                return;
            }
            DA.GetData(2, ref STEP_COUNT);
            DA.GetData(3, ref SEED);
            DA.GetDataList(4, DIRECTIONS);
            DA.GetData(5, ref BOUNDARY);

            // Input validation
            if (DIRECTIONS.Count == 0)
            {
                for (int degree = 0; degree < 360; degree++)
                {
                    DIRECTIONS.Add(degree);
                }
            }
            if (STEP_SIZES.Count == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "At least one step size must be provided.");
                return;
            }
            int negativeIndex = STEP_SIZES.FindIndex(IsZero);

            if (negativeIndex != -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  string.Format("Distances cannot be zero. At least one zero-value found at index {0}.", negativeIndex));
                return;
            }
            if (STEP_COUNT == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The amount of steps must be greater than 0.");
                return;
            }
            if (BOUNDARY != null)
            {
                if (BOUNDARY.IsClosed == false)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The boundary curve must be closed.");
                    return;
                }
                if (BOUNDARY.IsPlanar() == false)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The boundary curve must be planar.");
                    return;
                }
                for (int i = 0; i < PATH_ORIGINS.Count; i++)
                {
                    if (BOUNDARY.Contains(PATH_ORIGINS[i]) == PointContainment.Outside)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "If using a boundary curve all points must start within in.");
                        return;
                    }
                }
            }

            // Convert directions to radians
            for (int i = 0; i < DIRECTIONS.Count; i++)
            {
                DIRECTIONS[i] = Math.PI * DIRECTIONS[i] / 180.0;
            }

            // Create random generate just once
            Random rnd = new Random();

            if (SEED.HasValue)
            {
                rnd = new Random(SEED.Value); // Use SEED if it has been provided
            }
            // Calculate walks
            var outputPaths = new List <Curve>();

            for (int i = 0; i < PATH_ORIGINS.Count; i++)
            {
                outputPaths.Add(DispatchRandomPaths(PATH_ORIGINS[i], DIRECTIONS, STEP_SIZES,
                                                    STEP_COUNT, BOUNDARY, rnd));
            }

            // Assign variables to output parameters
            DA.SetDataList(0, outputPaths);
        }
        /// <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)
        {
            // Warning that this component is OBSOLETE
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This component is OBSOLETE and will be removed in the future.");

            // Input variables
            string      name       = "default_tool";
            List <Mesh> meshes     = new List <Mesh>();
            double      toolTransX = 0.0;
            double      toolTransY = 0.0;
            double      toolTransZ = 0.0;
            double      toolRotX   = 0.0;
            double      toolRotY   = 0.0;
            double      toolRotZ   = 0.0;

            // Catch the input data
            if (!DA.GetData(0, ref name))
            {
                return;
            }
            if (!DA.GetDataList(1, meshes))
            {
                meshes = new List <Mesh>()
                {
                    new Mesh()
                };
            }
            if (!DA.GetData(2, ref toolTransX))
            {
                return;
            }
            if (!DA.GetData(3, ref toolTransY))
            {
                return;
            }
            if (!DA.GetData(4, ref toolTransZ))
            {
                return;
            }
            if (!DA.GetData(5, ref toolRotX))
            {
                return;
            }
            if (!DA.GetData(6, ref toolRotY))
            {
                return;
            }
            if (!DA.GetData(7, ref toolRotZ))
            {
                return;
            }

            // Create the robot tool
            _robotTool = new RobotTool(name, meshes, toolTransX, toolTransY, toolTransZ, toolRotX, toolRotY, toolRotZ);

            // Outputs
            DA.SetData(0, _robotTool);
            DA.SetData(1, _robotTool.ToRAPIDDeclaration());

            #region Object manager
            // Gets ObjectManager of this document
            _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument());

            // Clears toolNames
            _objectManager.ToolNames.Remove(_toolName);
            _toolName = String.Empty;

            // Removes lastName from toolNameList
            if (_objectManager.ToolNames.Contains(_lastName))
            {
                _objectManager.ToolNames.Remove(_lastName);
            }

            // Adds Component to ToolsByGuid Dictionary
            if (!_objectManager.OldToolsEulerByGuid.ContainsKey(this.InstanceGuid))
            {
                _objectManager.OldToolsEulerByGuid.Add(this.InstanceGuid, this);
            }

            // Checks if tool name is already in use and counts duplicates
            #region Check name in object manager
            if (_objectManager.ToolNames.Contains(_robotTool.Name))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Tool Name already in use.");
                _nameUnique = false;
                _lastName   = "";
            }
            else
            {
                // Adds Robot Tool Name to list
                _toolName = _robotTool.Name;
                _objectManager.ToolNames.Add(_robotTool.Name);

                // Run SolveInstance on other Tools with no unique Name to check if their name is now available
                _objectManager.UpdateRobotTools();

                _lastName   = _robotTool.Name;
                _nameUnique = true;
            }

            // Checks if variable name exceeds max character limit for RAPID Code
            if (HelperMethods.VariableExeedsCharacterLimit32(name))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Robot Tool Name exceeds character limit of 32 characters.");
            }

            // Checks if variable name starts with a number
            if (HelperMethods.VariableStartsWithNumber(name))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Robot Tool Name starts with a number which is not allowed in RAPID Code.");
            }
            #endregion

            // Recognizes if Component is Deleted and removes it from Object Managers tool and name list
            GH_Document doc = this.OnPingDocument();
            if (doc != null)
            {
                doc.ObjectsDeleted += DocumentObjectsDeleted;
            }
            #endregion
        }
示例#34
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Fiber> AllPossibleFibers = new List <Fiber>();

            DA.GetDataList("All Fibers", AllPossibleFibers);  // big list

            string SortingFactor = null;

            DA.GetData <string>("Sorting Key", ref SortingFactor); // sorting rule

            double sagThreshold = 0.1;

            DA.GetData <double>("Sag Threshold", ref sagThreshold); // sag threshold

            double NegativeFiberDensity = 1.0;

            DA.GetData <double>("Sag Fiber Density", ref NegativeFiberDensity); // density

            double curlyThreshold = 0.5;

            DA.GetData <double>("Curliness Threshold", ref curlyThreshold); // curliness threshold

            // -------------------------------reduce negative---------------------------------
            List <Fiber> SkippedFibers   = new List <Fiber>();
            List <Fiber> RemainingFibers = new List <Fiber>();

            // - / +
            List <Fiber> NegativeFibers = AllPossibleFibers.Where(o => o.Type == "Negative").ToList(); // all negative fibers
            List <Fiber> PositiveFibers = AllPossibleFibers.Except(NegativeFibers).ToList();           //all positive fibers

            // narrow down -
            SkippedFibers.AddRange(NegativeFibers.Where(o => o.PinB.Index < 9 || o.PinB.Index > 17));
            NegativeFibers.RemoveAll(o => o.PinB.Index < 9 || o.PinB.Index > 17);

            // curliness
            // NC
            List <Fiber> NegaCurly = NegativeFibers
                                     .OrderByDescending(o => o.Curliness)
                                     .Take((int)(NegativeFibers.Count * curlyThreshold))
                                     .ToList();

            // NS
            List <Fiber> NegaStraight = NegativeFibers
                                        .Except(NegaCurly)
                                        .ToList();

            // PC
            List <Fiber> PosiCurly = PositiveFibers
                                     .OrderByDescending(o => o.Curliness)
                                     .Take((int)(PositiveFibers.Count * curlyThreshold))
                                     .ToList();

            // PS
            List <Fiber> PosiStraight = PositiveFibers.Except(PosiCurly).ToList();

            // reduce density
            if (NegativeFiberDensity == 0) // density 0
            {
                SkippedFibers.AddRange(NegaCurly);
                RemainingFibers = AllPossibleFibers.Except(SkippedFibers).ToList();
            }

            if (NegativeFiberDensity > 0 && NegativeFiberDensity < 1) // density 0 ~ 1
            {
                NegaCurly.OrderBy(o => o.PinA.Position.Z).ToList();

                // ============================================================================
                int skipCount = (int)Math.Floor(1 / NegativeFiberDensity);
                for (int i = 0; i < (int)((double)NegaCurly.Count / (double)skipCount); i++)
                {
                    for (int j = 0; j < skipCount - 1; j++) //remove
                    {
                        SkippedFibers.Add(NegaCurly[skipCount * i + j]);
                        NegaCurly.Remove(NegaCurly[skipCount * i + j]);
                    }
                    // remain
                }
                // ============================================================================

                RemainingFibers = AllPossibleFibers.Except(SkippedFibers).ToList();
            }

            // nega curly reduced

            List <Fiber> RemainingNegativeFibers = NegaCurly.Concat(NegaStraight).ToList(); // remaining nega
            // -------------------------------------------- Sorting --------------------------------------------

            // output parameters
            List <Fiber>  SortedFibers     = new List <Fiber>();
            List <Curve>  SortedFiberCrvs  = new List <Curve>();
            List <double> SortingKeyValues = new List <double>();
            List <string> FiberTypes       = new List <string>();


            #region : Relative height

            /*
             * if (SortingFactor == "Relative Height")
             * {
             *  // find out realtive hight betweenn all fibers
             *  for (int i = 0; i < AllPossibleFibers.Count - 1; i++)
             *  {
             *      for (int j = i + 1; j < AllPossibleFibers.Count; j++)
             *      {
             *          AllPossibleFibers[i].DetermineRelativeHeight(AllPossibleFibers[j]);
             *      }
             *  }
             *
             *  // sort
             *  SortedFibers.Add(AllPossibleFibers[0]);
             *  for (int i = 1; i < AllPossibleFibers.Count; i++)
             *  {
             *      for (int j = 0; j < SortedFibers.Count; j++) // sorted fibers from high to low
             *      {
             *          int index = -1;
             *          //AllPossibleFibers
             *          //AllPossibleFibers[i].IsHigher
             *      }
             *  }
             * }
             */

            #endregion // not finished
            #region : Length difference

            /*
             * if (SortingFactor == "Length difference")
             * {
             *  AllPossibleFibers.ForEach(o => o.CalculateLengthDifference());
             *  SortedFibers = AllPossibleFibers.OrderBy(o => o.LengthDifference).ToList();
             *  SortedFiberCrvs = SortedFibers.Select(o => o.FiberCrv).ToList();
             *  SortingKeyValues = SortedFibers.Select(o => o.LengthDifference).ToList();
             * }
             */

            #endregion
            #region : Pin position
            if (SortingFactor == "Pin position")
            {
                // calculate the sorting key value
                AllPossibleFibers.ForEach(o => o.CalculatePinPotential());
                // sorting
                SortedFibers = AllPossibleFibers.OrderByDescending(o => o.PinPotential).ToList();

                for (int i = 0; i < SortedFibers.Count; i++) // change fiber sorting ID
                {
                    SortedFibers[i].FiberSortingIndex = i;
                }

                SortedFiberCrvs  = SortedFibers.Select(o => o.FiberCrv).ToList();
                SortingKeyValues = SortedFibers.Select(o => o.PinPotential).ToList();
            }
            #endregion
            #region : Potential

            /*
             * if (SortingFactor == "Potential")
             * {
             *  AllPossibleFibers.ForEach(o => o.CalculatePotential());
             *  SortedFibers = AllPossibleFibers.OrderByDescending(o => o.Potential).ToList();
             *  SortedFiberCrvs = SortedFibers.Select(o => o.FiberCrv).ToList();
             *  SortingKeyValues = SortedFibers.Select(o => o.Potential).ToList();
             * }
             */
            #endregion
            #region : Fiber type

            /*
             * if (SortingFactor == "Fiber type")
             * {
             *  AllPossibleFibers.ForEach(o => o.FindTuringPtOnCrv());
             *  AllPossibleFibers.ForEach(o => o.CalculateLengthDifference());
             *
             *  List<Fiber> ChainFibers = new List<Fiber>();
             *  List<Fiber> DoublyFibers = new List<Fiber>();
             *  List<Fiber> ArchFibers = new List<Fiber>();
             *  foreach (Fiber ifiber in AllPossibleFibers)
             *  {
             *      if (ifiber.Type == "Chain")
             *          ChainFibers.Add(ifiber);
             *      if (ifiber.Type == "Arch")
             *          ArchFibers.Add(ifiber);
             *      if (ifiber.Type == "Doubly")
             *          DoublyFibers.Add(ifiber);
             *  }
             *
             *  List<Fiber> SortedChainFibers = new List<Fiber>();
             *  List<Fiber> SortedDoublyFibers = new List<Fiber>();
             *  List<Fiber> SortedArchFibers = new List<Fiber>();
             *  SortedChainFibers = ChainFibers.OrderBy(o => o.LengthDifference).ToList();
             *  SortedDoublyFibers = DoublyFibers.OrderBy(o => o.LengthDifference).ToList();
             *  SortedArchFibers = ArchFibers.OrderBy(o => o.LengthDifference).ToList();
             *
             *  SortedFibers = SortedChainFibers.Concat(SortedDoublyFibers).Concat(SortedArchFibers).ToList();
             *  SortedFiberCrvs = SortedFibers.Select(o => o.FiberCrv).ToList();
             *  SortingKeyValues = SortedFibers.Select(o => o.LengthDifference).ToList();
             *
             *  FiberTypes = SortedFibers.Select(o => o.Type).ToList();
             * }
             */
            #endregion
            #region : +-Curvature
            if (SortingFactor == "+-Curvature") // determine chain and nonchain, sorted by verticle distances.
            {
                // compute SagThreshold
                double maxDistanceMax = NegativeFibers.Select(o => o.Curliness).Max();
                double minDistanceMin = NegativeFibers.Select(o => o.Curliness).Min();
                double SagThreshold   = minDistanceMin + (maxDistanceMax - minDistanceMin) * sagThreshold;

                List <Fiber> ChainFibers        = new List <Fiber>();
                List <Fiber> NonChainfibers     = new List <Fiber>();
                List <Fiber> SortedChains       = new List <Fiber>();
                List <Fiber> SortedNonChains    = new List <Fiber>();
                List <Line>  FiberStraightLines = new List <Line>();

                AllPossibleFibers.ForEach(o => o.DetermineChain());

                foreach (Fiber ifiber in AllPossibleFibers) // grouping chains and nonchains
                {
                    if (ifiber.Type == "Chain")
                    {
                        ChainFibers.Add(ifiber);
                    }
                    else
                    {
                        NonChainfibers.Add(ifiber);
                    }
                }

                SortedChains = ChainFibers.OrderByDescending(o => o.MaximumDistance).ToList(); // sorting chains: max -> min

                if (sagThreshold > 0)
                {
                    SortedChains.Select(o => o.MaximumDistance > SagThreshold);
                    //List<Fiber> SkippedFibers = new List<Fiber>();
                }

                SortedChains.RemoveAll(o => o.MaximumDistance > SagThreshold);                    // remove top-top fibers, threshold default = 0.1m

                SortedNonChains = NonChainfibers.OrderByDescending(o => o.PinPotential).ToList(); // sorting nonchains: min -> max

                SortedFibers = SortedChains.Concat(SortedNonChains).ToList();                     // merging into a big fiber list

                for (int i = 0; i < SortedFibers.Count; i++)                                      // change fiber sorting ID
                {
                    SortedFibers[i].FiberSortingIndex = i;
                }

                SortedFiberCrvs    = SortedFibers.Select(o => o.FiberCrv).ToList();
                SortingKeyValues   = SortedFibers.Select(o => (double)o.FiberSortingIndex).ToList();
                FiberStraightLines = SortedFibers.Select(o => o.StraightLine).ToList();
                FiberTypes         = SortedFibers.Select(o => o.Type).ToList();
            }
            #endregion

            #region : Curliness
            if (SortingFactor == "Curliness")
            {
                double curlyMax   = 0.0;
                double curlyMin   = 0.0;
                double curlyValue = 0.0;
                curlyMax   = RemainingFibers.Select(o => o.Curliness).Max();
                curlyMin   = RemainingFibers.Select(o => o.Curliness).Min();
                curlyValue = curlyMin + (curlyMax - curlyMin) * curlyThreshold;

                NegaCurly.OrderBy(o => o.Curliness).ToList();              // curly -> stragiht
                NegaStraight.OrderBy(o => o.Curliness).ToList();           // curly -> stragiht
                PosiStraight.OrderByDescending(o => o.Curliness).ToList(); // stragiht -> curly
                PosiCurly.OrderByDescending(o => o.Curliness).ToList();    // straight ->curly

                SortedFibers = NegaCurly
                               .Concat(NegaStraight)
                               .Concat(PosiStraight)
                               .Concat(PosiCurly)
                               .ToList();



                for (int i = 0; i < SortedFibers.Count; i++) // change fiber sorting ID
                {
                    SortedFibers[i].FiberSortingIndex = i;
                }

                SortedFiberCrvs  = SortedFibers.Select(o => o.FiberCrv).ToList();
                SortingKeyValues = SortedFibers.Select(o => o.MaximumDistance).ToList();
            }
            #endregion

            // ===================================================================
            DA.SetDataList("Sorted Custom Fibers", SortedFibers);
            DA.SetDataList("Sorted Fiber Curves", SortedFiberCrvs);
            DA.SetDataList("Sorting Key Values", SortingKeyValues);

            DA.SetDataList("N", NegativeFibers.Select(o => o.FiberCrv).ToList());
            DA.SetDataList("P", PositiveFibers.Select(o => o.FiberCrv).ToList());
            DA.SetDataList("NC", NegaCurly.Select(o => o.FiberCrv).ToList());
            DA.SetDataList("PC", PosiCurly.Select(o => o.FiberCrv).ToList());
            DA.SetDataList("NS", NegaStraight.Select(o => o.FiberCrv).ToList());
            DA.SetDataList("PS", PosiStraight.Select(o => o.FiberCrv).ToList());

            DA.SetDataList("Skipped", SkippedFibers.Select(o => o.FiberCrv).ToList());
            //DA.SetDataList("Info", info);

            //DA.GetDataList<SoFiNode>("Structure Input", SoFiNodes);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///define i/o parameters
            PointCloud        Rhino_Cloud   = new PointCloud();
            List <double>     Rhino_indices = new List <double>();
            List <PointCloud> Sub_Clouds    = new List <PointCloud>();
            List <GH_Cloud>   GH_subclouds  = new List <GH_Cloud>();

            /// read inputs
            if (!DA.GetData("Point_Cloud", ref Rhino_Cloud))
            {
                return;
            }
            if (!DA.GetDataList <double>("Indices", Rhino_indices))
            {
                return;
            }

            /// define internal parameters
            int cluster_count = (int)Rhino_indices.Max();

            ///1. maak lijsten van idexen per value van Rhino-indices
            ///2. Retrieve het punt van iedere index
            ///3. Add punt aan nieuwe cloud
            ///7. output

            var Rhino_xyz = Rhino_Cloud.GetPoints();
            var Rhino_n   = Rhino_Cloud.GetNormals();
            var Rhino_c   = Rhino_Cloud.GetColors();

            for (int i = 0; i < cluster_count; i++)
            {
                PointCloud Rhino_subcloud = new PointCloud();

                ///1.
                var C_indexlist = Enumerable.Range(0, Rhino_indices.Count).Where(flap => Rhino_indices[flap] == i + 1).ToList();
                ///2.


                if (Rhino_Cloud.ContainsNormals == true && Rhino_Cloud.ContainsColors == true)
                {
                    for (int j = 0; j < C_indexlist.Count; j++)
                    {
                        ///3.
                        Rhino_subcloud.Add(Rhino_xyz[C_indexlist[j]], Rhino_n[C_indexlist[j]], Rhino_c[C_indexlist[j]]);
                    }
                }
                if (Rhino_Cloud.ContainsNormals == true && Rhino_Cloud.ContainsColors == false)
                {
                    for (int j = 0; j < C_indexlist.Count; j++)
                    {
                        ///3.
                        Rhino_subcloud.Add(Rhino_xyz[C_indexlist[j]], Rhino_n[C_indexlist[j]]);
                    }
                }
                if (Rhino_Cloud.ContainsNormals == false && Rhino_Cloud.ContainsColors == true)
                {
                    for (int j = 0; j < C_indexlist.Count; j++)
                    {
                        ///3.
                        Rhino_subcloud.Add(Rhino_xyz[C_indexlist[j]], Rhino_c[C_indexlist[j]]);
                    }
                }


                ///7.
                GH_Cloud GH_subcloud = new GH_Cloud(Rhino_subcloud);
                GH_subclouds.Add(GH_subcloud);
            }

            ///output
            DA.SetDataList(0, GH_subclouds);
        }
示例#36
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)
        {
            List <Mesh>  meshes      = new List <Mesh>();
            List <Curve> bldGrid     = new List <Curve>();
            List <Brep>  slabs       = new List <Brep>();
            List <Brep>  roof        = new List <Brep>();
            double       xcell       = 0;
            double       ycell       = 0;
            double       zcell       = 0;
            double       memberT     = 0;
            int          numBays     = 0;
            int          startBay    = 0;
            bool         exploreMode = true;
            List <Brep>  walls       = new List <Brep>();
            Plane        refPlane    = new Plane();

            if (!DA.GetDataList(0, meshes))
            {
                return;
            }
            if (!DA.GetData(1, ref xcell))
            {
                return;
            }
            if (!DA.GetData(2, ref ycell))
            {
                return;
            }
            if (!DA.GetData(3, ref zcell))
            {
                return;
            }
            if (!DA.GetData(4, ref memberT))
            {
                return;
            }
            if (!DA.GetData(5, ref numBays))
            {
                return;
            }
            if (!DA.GetData(6, ref startBay))
            {
                return;
            }
            if (!DA.GetData(7, ref exploreMode))
            {
                return;
            }
            DA.GetData(8, ref refPlane);
            if (!DA.GetDataList(9, bldGrid))
            {
                return;
            }
            if (!DA.GetDataList(10, slabs))
            {
                return;
            }
            if (!DA.GetDataList(11, walls))
            {
                return;
            }
            if (!DA.GetDataList(12, roof))
            {
                return;
            }

            VoxelParameters parameters = new VoxelParameters(startBay, xcell, ycell, zcell, memberT, exploreMode, startBay, slabs, walls, roof);
            MeshVoxeliser   mvox       = new MeshVoxeliser(meshes, numBays, refPlane, parameters);
            VoxelDocumenter vDoc       = new VoxelDocumenter();

            vDoc.writeSection3d(mvox, bldGrid);
            vDoc.moduleSchedule(mvox);
            vDoc.map3dToWorldXY(mvox);
            DataTree <StructuralCell> perimeterCells       = new DataTree <StructuralCell>();
            DataTree <StructuralCell> skinCells            = new DataTree <StructuralCell>();
            DataTree <StructuralCell> verticalSupportCells = new DataTree <StructuralCell>();
            DataTree <StructuralCell> undefinedCells       = new DataTree <StructuralCell>();
            GH_Structure <GH_Mesh>    caveSlices           = new GH_Structure <GH_Mesh>();
            GH_Structure <GH_Mesh>    sectionBoxes         = new GH_Structure <GH_Mesh>();
            GH_Structure <GH_Curve>   grid  = new GH_Structure <GH_Curve>();
            GH_Structure <GH_Curve>   links = new GH_Structure <GH_Curve>();

            getSlices(mvox, ref caveSlices, ref sectionBoxes, ref grid, ref links);
            getModules(mvox, ref perimeterCells, ref skinCells, ref verticalSupportCells, ref undefinedCells);


            DA.SetDataTree(0, skinCells);
            DA.SetDataTree(1, perimeterCells);
            DA.SetDataTree(2, verticalSupportCells);
            DA.SetDataTree(3, caveSlices);
            DA.SetDataTree(4, sectionBoxes);
            DA.SetDataTree(5, grid);
            DA.SetDataTree(6, links);
            DA.SetDataTree(7, undefinedCells);
        }
示例#37
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 <Mesh>     meshes       = new List <Mesh>();
            List <Vector3d> vels         = new List <Vector3d>();
            List <double>   masses       = new List <double>();
            List <double>   stiffnesses  = new List <double>();
            List <int>      groupIndices = new List <int>();

            DA.GetDataList(0, meshes);
            DA.GetDataList(1, vels);
            DA.GetDataList(2, masses);
            DA.GetDataList(3, stiffnesses);
            DA.GetDataList(4, groupIndices);

            List <RigidBody> rigids = new List <RigidBody>();

            for (int i = 0; i < meshes.Count; i++)
            {
                Mesh mesh = new Mesh();
                //make new super shallow copy, as user referenced meshes are crazy heavy smh
                mesh.Vertices.AddVertices(meshes[i].Vertices);
                mesh.Faces.AddFaces(meshes[i].Faces);

                mesh.UnifyNormals();
                mesh.Normals.ComputeNormals();
                mesh.Normals.UnitizeNormals();

                List <float> vertices  = new List <float>();
                List <float> normals   = new List <float>();
                List <float> invMasses = new List <float>();

                for (int j = 0; j < mesh.Vertices.Count; j++)
                {
                    vertices.Add(mesh.Vertices[j].X);
                    vertices.Add(mesh.Vertices[j].Y);
                    vertices.Add(mesh.Vertices[j].Z);

                    normals.Add(mesh.Normals[j].X);
                    normals.Add(mesh.Normals[j].Y);
                    normals.Add(mesh.Normals[j].Z);

                    double mass = 1.0;
                    if (masses.Count == 1)
                    {
                        mass = masses[0];
                    }
                    else if (masses.Count > i)
                    {
                        mass = masses[i];
                    }
                    invMasses.Add((float)(1.0 / Math.Max(mass, 0.00000000001)));
                }

                float[] velocity = new float[3] {
                    0.0f, 0.0f, 0.0f
                };
                if (vels.Count == 1)
                {
                    velocity = new float[3] {
                        (float)vels[0].X, (float)vels[0].Y, (float)vels[0].Z
                    }
                }
                ;

                else if (vels.Count > i)
                {
                    velocity = new float[3] {
                        (float)vels[i].X, (float)vels[i].Y, (float)vels[i].Z
                    }
                }
                ;

                float stiffness = 1.0f;
                if (stiffnesses.Count == 1)
                {
                    stiffness = (float)stiffnesses[0];
                }
                else if (stiffnesses.Count > i)
                {
                    stiffness = (float)stiffnesses[i];
                }

                int groupIndex = i;
                if (groupIndices.Count == 1)
                {
                    groupIndex += groupIndices[0];
                }
                else if (groupIndices.Count > i)
                {
                    groupIndex = groupIndices[i];
                }

                RigidBody rb = new RigidBody(vertices.ToArray(), velocity, normals.ToArray(), invMasses.ToArray(), stiffness, groupIndex);

                rb.Mesh = mesh;

                rigids.Add(rb);
            }

            DA.SetDataList(0, rigids);
        }
示例#38
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // get input
            List <FemDesign.GenericClasses.ILoadElement> objs = new List <FemDesign.GenericClasses.ILoadElement>();

            if (!DA.GetDataList(0, objs))
            {
                return;
            }
            if (objs == null)
            {
                return;
            }

            var r0 = new List <FemDesign.Loads.PointLoad>();
            var r1 = new List <FemDesign.Loads.LineLoad>();
            var r2 = new List <FemDesign.Loads.LineStressLoad>();
            var r3 = new List <FemDesign.Loads.LineTemperatureLoad>();
            var r4 = new List <FemDesign.Loads.SurfaceLoad>();
            var r5 = new List <FemDesign.Loads.SurfaceTemperatureLoad>();
            var r6 = new List <FemDesign.Loads.PressureLoad>();
            var r7 = new List <FemDesign.Loads.Footfall>();

            foreach (FemDesign.GenericClasses.ILoadElement load in objs)
            {
                if (load.GetType() == typeof(Loads.PointLoad))
                {
                    r0.Add((Loads.PointLoad)load);
                }

                else if (load.GetType() == typeof(Loads.LineLoad))
                {
                    r1.Add((Loads.LineLoad)load);
                }

                else if (load.GetType() == typeof(Loads.LineStressLoad))
                {
                    r2.Add((Loads.LineStressLoad)load);
                }

                else if (load.GetType() == typeof(Loads.LineTemperatureLoad))
                {
                    r3.Add((Loads.LineTemperatureLoad)load);
                }

                else if (load.GetType() == typeof(Loads.SurfaceLoad))
                {
                    r4.Add((Loads.SurfaceLoad)load);
                }

                else if (load.GetType() == typeof(Loads.SurfaceTemperatureLoad))
                {
                    r5.Add((Loads.SurfaceTemperatureLoad)load);
                }

                else if (load.GetType() == typeof(Loads.PressureLoad))
                {
                    r6.Add((Loads.PressureLoad)load);
                }
                else if (load.GetType() == typeof(Loads.Footfall))
                {
                    r7.Add((Loads.Footfall)load);
                }
                else
                {
                    throw new System.ArgumentException("Type not supported. SortLoads failed.");
                }
            }

            // return
            DA.SetDataList(0, r0);
            DA.SetDataList(1, r1);
            DA.SetDataList(2, r2);
            DA.SetDataList(3, r3);
            DA.SetDataList(4, r4);
            DA.SetDataList(5, r5);
            DA.SetDataList(6, r6);
            DA.SetDataList(7, r7);
        }
示例#39
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 <GH_ObjectWrapper> ctrls = new List <GH_ObjectWrapper>();

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

            StackLayout stack = new StackLayout()
            {
                Size = new Size(60, 40),
            };

            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() == "spacing")
                {
                    if (val is GH_Integer ghi)
                    {
                        stack.Spacing = ghi.Value;
                    }
                    else if (val is GH_String ghstr)
                    {
                        if (int.TryParse(ghstr.Value, out int v))
                        {
                            stack.Spacing = v;
                        }
                    }
                    else
                    {
                        try { Util.SetProp(stack, "Spacing", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "orientation")
                {
                    if (val is GH_String ghstr)
                    {
                        switch (ghstr.Value.ToLower())
                        {
                        case "horizontal":
                            stack.Orientation = Orientation.Horizontal;
                            break;

                        case "vertical":
                            stack.Orientation = Orientation.Vertical;
                            break;

                        case "h":
                            stack.Orientation = Orientation.Horizontal;
                            break;

                        case "v":
                            stack.Orientation = Orientation.Vertical;
                            break;

                        default:
                            break;
                        }
                    }
                    else if (val is GH_Integer ghi)
                    {
                        if (ghi.Value == 0)
                        {
                            stack.Orientation = Orientation.Horizontal;
                        }
                        else if (ghi.Value == 1)
                        {
                            stack.Orientation = Orientation.Vertical;
                        }
                    }
                    else if (val is Orientation or)
                    {
                        stack.Orientation = or;
                    }
                    else
                    {
                        try { Util.SetProp(stack, "Orientation", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "padding")
                {
                    if (val is GH_Integer ghi)
                    {
                        stack.Padding = new Padding(ghi.Value);
                    }
                    else if (val is GH_Number ghn)
                    {
                        stack.Padding = new Padding((int)ghn.Value);
                    }
                    else if (val is GH_String ghstr)
                    {
                        string s = ghstr.Value;
                        if (!s.Contains(","))
                        {
                            try { Util.SetProp(stack, "Padding", Util.GetGooVal(val)); }
                            catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                        }
                        else
                        {
                            string[] nums = s.Split(',');
                            if (nums.Length == 2)
                            {
                                bool a = int.TryParse(nums[0], out int na);
                                bool b = int.TryParse(nums[1], out int nb);
                                if (a && b)
                                {
                                    stack.Padding = new Padding(na, nb);
                                }
                            }
                            else if (nums.Length == 4)
                            {
                                bool a = int.TryParse(nums[0], out int na);
                                bool b = int.TryParse(nums[1], out int nb);
                                bool c = int.TryParse(nums[2], out int nc);
                                bool d = int.TryParse(nums[3], out int nd);
                                if (a && b && c && d)
                                {
                                    stack.Padding = new Padding(na, nb, nc, nd);
                                }
                            }
                            else
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, " couldn't parse padding integers");
                            }
                        }
                    }
                    else if (val is Padding pad)
                    {
                        stack.Padding = pad;
                    }
                    else if (val is GH_Rectangle grec)
                    {
                        int x = (int)grec.Value.X.Length;
                        int y = (int)grec.Value.Y.Length;
                        stack.Padding = new Padding(x, y);
                    }
                    else if (val is GH_ComplexNumber gcomp)
                    {
                        int x = (int)gcomp.Value.Real;
                        int y = (int)gcomp.Value.Imaginary;
                        stack.Padding = new Padding(x, y);
                    }
                    else
                    {
                        try { Util.SetProp(stack, "Padding", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "size")
                {
                    if (val is GH_Point pt)
                    {
                        Size size = new Size((int)pt.Value.X, (int)pt.Value.Y);
                        stack.Size = size;
                    }
                    else if (val is GH_Vector vec)
                    {
                        Size size = new Size((int)vec.Value.X, (int)vec.Value.Y);
                        stack.Size = size;
                    }
                    else if (val is GH_String sstr)
                    {
                        string[] xy = sstr.Value.Split(',');
                        bool     xp = int.TryParse(xy[0], out int x);
                        bool     yp = int.TryParse(xy[1], out int y);
                        if (xp && yp)
                        {
                            stack.Size = new Size(x, y);
                        }
                    }
                    else if (val is GH_Rectangle grec)
                    {
                        int x = (int)grec.Value.X.Length;
                        int y = (int)grec.Value.Y.Length;
                        stack.Size = new Size(x, y);
                    }
                    else if (val is GH_ComplexNumber gcomp)
                    {
                        int x = (int)gcomp.Value.Real;
                        int y = (int)gcomp.Value.Imaginary;
                        stack.Size = new Size(x, y);
                    }
                    else
                    {
                        try { Util.SetProp(stack, "Size", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else
                {
                    try { Util.SetProp(stack, n, Util.GetGooVal(val)); }
                    catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                }
            }

            foreach (GH_ObjectWrapper wrapped in ctrls)
            {
                if (wrapped.Value is Control ctrl)
                {
                    stack.Items.Add(ctrl);
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, " one or more object cannot be added\n are they non-Synapse components?");
                }
            }

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

            PropertyInfo[] allprops  = stack.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);
        }
示例#40
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <object> instructions = new List <object>();

            if (UpdateIO())
            {
                return;
            }

            switch (currentState)
            {
            case Opperation.Acceleration:
                double accVal = 35; if (!DA.GetData(0, ref accVal))
                {
                    return;
                }
                double decVal = 60; if (!DA.GetData(1, ref decVal))
                {
                    return;
                }
                instructions.Add(new Axis.Types.Command($"AccSet {accVal.ToString()}, {decVal.ToString()};", Kernal.Manufacturer.ABB));
                break;

            case Opperation.CallProcedure:
                string strName = null; if (!DA.GetData(0, ref strName))
                {
                    return;
                }
                bool          args = true;
                List <string> arg  = new List <string>(); if (!DA.GetDataList(1, arg))
                {
                    args = false;
                }

                if (args)
                {
                    foreach (string a in arg)
                    {
                        instructions.Add(new Axis.Types.Command($"{strName}({a});", Kernal.Manufacturer.ABB));
                    }
                }
                else
                {
                    instructions.Add(new Axis.Types.Command($"{strName};", Kernal.Manufacturer.ABB));
                }
                break;

            case Opperation.Comment:
                string strComm = null;
                if (!DA.GetData(0, ref strComm))
                {
                    return;
                }

                instructions.Add(new Axis.Types.Command($"! {strComm}", Kernal.Manufacturer.ABB));
                break;

            case Opperation.DefineProcedure:
                string procName = null; if (!DA.GetData(0, ref procName))
                {
                    return;
                }
                string        procVariable = null; DA.GetData(1, ref procVariable);
                List <string> strCommands  = new List <string>(); if (!DA.GetDataList(2, strCommands))
                {
                    return;
                }

                // Open procedure and build up list of commands.
                //strProc.Add("!");
                //strProc.Add("PROC" + " " + procName + "(" + procVariable + ")\n");

                //strProc.AddRange(strCommands);

                // Close procedure.
                //strProc.Add("ENDPROC");
                //strProc.Add("!");

                List <Axis.Kernal.Instruction> instr = strCommands.Select(ins => new Axis.Types.Command(ins, Kernal.Manufacturer.ABB) as Kernal.Instruction).ToList();

                /*
                 * @todo Add procVariable once implemented
                 * @body Pass the procVariable to the procedure once this implements the support therefore
                 */
                instructions.Add(new Types.Module.Procedure(code: instr, progName: procName));
                break;

            case Opperation.SetDO:
                string name   = "DO10_1";
                int    status = 0;
                bool   sync   = false;

                if (!DA.GetData(0, ref name))
                {
                    return;
                }
                if (!DA.GetData(1, ref status))
                {
                    return;
                }
                DA.GetData(2, ref sync);

                if (sync)
                {
                    instructions.Add(new Axis.Types.Command($"SetDO \\Sync, {name}, {status.ToString()};", Kernal.Manufacturer.ABB));
                }
                else
                {
                    instructions.Add(new Axis.Types.Command($"SetDO {name}, {status.ToString()};", Kernal.Manufacturer.ABB));
                }
                break;

            case Opperation.SetVelocity:
                double velPct = 100; if (!DA.GetData(0, ref velPct))
                {
                    return;
                }
                double maxSpeed = 900; if (!DA.GetData(1, ref maxSpeed))
                {
                    return;
                }

                instructions.Add(new Axis.Types.Command($"VelSet {velPct.ToString()}, {maxSpeed.ToString()};", Kernal.Manufacturer.ABB));
                break;

                //case Opperation.SoftMove:
                //    // string cssPlane = inPlane
                //    // string cssAct = "CSSAct ";
                //    break;
            }
            DA.SetDataList(0, instructions);
        }
示例#41
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)
        {
            // First, we need to retrieve all data from the input parameters.
            // We'll start by declaring variables and assigning them starting values.

            //Plane plane = Plane.WorldXY;
            //double radius0 = 0.0;
            //double radius1 = 0.0;
            //int turns = 0;

            List <Curve> Primary      = new List <Curve>();
            List <Curve> IntPrimary   = new List <Curve>();
            List <Curve> Secondary    = new List <Curve>();
            List <Curve> IntSecondary = new List <Curve>();

            // Then we need to access the input parameters individually.
            // When data cannot be extracted from a parameter, we should abort this method.
            if (!DA.GetDataList(0, Primary))
            {
                return;
            }
            //if (!DA.GetDataList(1, IntPrimary)) return;
            if (!DA.GetDataList(2, Secondary))
            {
                return;
            }
            //if (!DA.GetDataList(3, IntSecondary)) return;

            // We should now validate the data and warn the user if invalid data is supplied.
            if (Primary == null || Secondary == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input Primary and Secondary Curves");
                return;
            }

            // We're set to create the spiral now. To keep the size of the SolveInstance() method small,
            // The actual functionality will be in a different method:
            //Curve spiral = CreateSpiral(plane, radius0, radius1, turns);

            List <List <Double> > distPrimInt = new List <List <Double> >();
            List <List <Double> > distSecInt  = new List <List <Double> >();

            List <Vector3d> primVecs = new List <Vector3d>(Grid.GridUnitVectors(Primary));
            List <Vector3d> secVecs  = new List <Vector3d>(Grid.GridUnitVectors(Secondary));

            DataTree <Point3d> gridPoints = new DataTree <Point3d>(TreeUtilities.ListToTree(Intersection.CurveCurve(Primary, Secondary, out distPrimInt, out distSecInt)));

            DataTree <Double> distPrimIntTree = new DataTree <Double>(TreeUtilities.ListToTree(distPrimInt));
            DataTree <Double> distSecIntTree  = new DataTree <Double>(TreeUtilities.ListToTree(distSecInt));

            string Information = "To be implemented";

            // Finally assign the spiral to the output parameter.

            DA.SetData(0, Information);
            DA.SetDataTree(1, gridPoints);
            DA.SetDataTree(2, gridPoints);
            DA.SetDataList(3, primVecs);
            DA.SetDataList(4, secVecs);
            DA.SetDataTree(5, distPrimIntTree);
            DA.SetDataTree(6, distSecIntTree);
        }
示例#42
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare placeholder variables and assign initial invalid data.
            List <Line>   inputLines           = new List <Line>();
            List <string> names                = new List <string>();
            bool          firstConnectionIsFTF = false;
            Dictionary <string, HM.Triple> webNormalsDictionary = null;
            Dictionary <string, int>       prioritiesDictionary = null;
            Dictionary <string, int>       extensionDictionary  = null;
            double tolerance = 0.001;

            // Retrieve input data.
            if (!DA.GetDataList(0, inputLines))
            {
                return;
            }
            if (!DA.GetDataList(1, names))
            {
                names = null;
            }
            if (!DA.GetData(2, ref firstConnectionIsFTF))
            {
                firstConnectionIsFTF = false;
            }
            if (!DA.GetData(3, ref webNormalsDictionary))
            {
                webNormalsDictionary = null;
            }
            if (!DA.GetData(4, ref prioritiesDictionary))
            {
                prioritiesDictionary = null;
            }
            if (!DA.GetData(5, ref extensionDictionary))
            {
                extensionDictionary = null;
            }
            if (!DA.GetData(6, ref tolerance))
            {
                tolerance = 0.001;
            }

            if (names == null)
            {
                names = new List <string>();
                for (int j = 0; j < inputLines.Count; j++)
                {
                    names.Add(j.ToString());
                }
            }

            if (names.Count < inputLines.Count)
            {
                throw new Exception("You must provide a name for every member.");
            }

            // Convert GH lines to HM lines
            var HMLines = new List <HM.Line>();
            var i       = 0;

            foreach (Line l in inputLines)
            {
                HMLines.Add(HMGHUtil.GHLineToHMLine(l));
            }

            // Create Structure
            var structure = HM.hStructure.StructureFromLines(
                HMLines,
                names,
                webNormalsDict: webNormalsDictionary,
                priorityDict: prioritiesDictionary,
                extensionDict: extensionDictionary,
                firstConnectionIsFTF: firstConnectionIsFTF,
                intersectionTolerance: tolerance,
                planarityTolerance: tolerance);

            DA.SetDataList(0, structure.Members);
            DA.SetDataList(1, structure._solveOrder);
            DA.SetDataList(2, structure._solvedBy);
        }
示例#43
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            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);

            RadioButtonList rblist = new RadioButtonList()
            {
                ID          = Guid.NewGuid().ToString(),
                Spacing     = new Size(5, 5),
                Orientation = Orientation.Vertical,
            };

            foreach (string opt in opts)
            {
                rblist.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() == "orientation")
                {
                    if (val is GH_String ghstr)
                    {
                        switch (ghstr.Value.ToLower())
                        {
                        case "horizontal":
                            rblist.Orientation = Orientation.Horizontal;
                            break;

                        case "vertical":
                            rblist.Orientation = Orientation.Vertical;
                            break;

                        case "h":
                            rblist.Orientation = Orientation.Horizontal;
                            break;

                        case "v":
                            rblist.Orientation = Orientation.Vertical;
                            break;

                        default:
                            break;
                        }
                    }
                    else if (val is GH_Integer ghi)
                    {
                        if (ghi.Value == 0)
                        {
                            rblist.Orientation = Orientation.Horizontal;
                        }
                        else if (ghi.Value == 1)
                        {
                            rblist.Orientation = Orientation.Vertical;
                        }
                        else
                        {
                            rblist.Orientation = Orientation.Vertical;
                        }
                    }
                    else if (val is GH_Boolean gbool)
                    {
                        if (gbool.Value)
                        {
                            rblist.Orientation = Orientation.Vertical;
                        }
                        else
                        {
                            rblist.Orientation = Orientation.Horizontal;
                        }
                    }
                    else if (val is Orientation or)
                    {
                        rblist.Orientation = or;
                    }
                    else
                    {
                        try { Util.SetProp(rblist, "Orientation", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "spacing")
                {
                    if (val is GH_Integer ghi)
                    {
                        rblist.Spacing = new Size(ghi.Value, ghi.Value);
                    }
                    else if (val is GH_String ghstr)
                    {
                        if (ghstr.Value.Contains(","))
                        {
                            string[] xy = ghstr.Value.Split(',');
                            try
                            {
                                int x = int.Parse(xy[0]);
                                int y = int.Parse(xy[1]);
                                rblist.Spacing = new Size(x, y);
                            }
                            catch (Exception ex)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, ex.Message);
                            }
                        }
                        else if (int.TryParse(ghstr.Value, out int v))
                        {
                            rblist.Spacing = new Size(v, v);
                        }
                    }
                    else if (val is GH_ComplexNumber gcomp)
                    {
                        int x = (int)gcomp.Value.Real;
                        int y = (int)gcomp.Value.Imaginary;
                        rblist.Spacing = new Size(x, y);
                    }
                    else if (val is GH_Rectangle grec)
                    {
                        int x = (int)grec.Value.X.Length;
                        int y = (int)grec.Value.Y.Length;
                        rblist.Spacing = new Size(x, y);
                    }
                    else
                    {
                        try { Util.SetProp(rblist, "Spacing", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "textcolor" || n.ToLower() == "fontcolor")
                {
                    if (val is GH_Colour gclr)
                    {
                        rblist.TextColor = Color.FromArgb(gclr.Value.ToArgb());
                    }
                    else if (val is GH_String gstr)
                    {
                        if (Color.TryParse(gstr.Value, out Color clr))
                        {
                            rblist.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);
                        rblist.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);
                        rblist.TextColor = clr;
                    }
                    else if (val is Color etoclr)
                    {
                        rblist.TextColor = etoclr;
                    }
                    else
                    {
                        try { Util.SetProp(rblist, "TextColor", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else
                {
                    try { Util.SetProp(rblist, n, Util.GetGooVal(val)); }
                    catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                }
            }

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

            PropertyInfo[] allprops  = rblist.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);
        }
        /// <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, EvaluationUnit unit)
        {
            // Input counter
            modelDataCount1 = modelDataCount + modelDataCount2;

            // RFEM variables
            var        modelName = "";
            IModel     model     = null;
            IModelData data      = null;
            ILoads     loads     = null;

            // Assign GH Input
            bool getnodes      = false;
            bool getlines      = false;
            bool getmembers    = false;
            bool getsurfaces   = false;
            bool getopenings   = false;
            bool getsupportsP  = false;
            bool getsupportsL  = false;
            bool getLineHinges = false;
            bool getCroSecs    = false;
            bool getMaterials  = false;
            bool getNodalLoads = false;
            bool run           = false;
            var  ghFilters     = new List <GH_RFFilter>();
            var  inFilters     = new List <RFFilter>();

            DA.GetData(0, ref getnodes);
            DA.GetData(1, ref getlines);
            DA.GetData(2, ref getmembers);
            DA.GetData(3, ref getsurfaces);
            DA.GetData(4, ref getopenings);
            DA.GetData(5, ref getsupportsP);
            DA.GetData(6, ref getsupportsL);
            DA.GetData(7, ref getLineHinges);
            DA.GetData(8, ref getCroSecs);
            DA.GetData(9, ref getMaterials);
            DA.GetData(10, ref run);
            DA.GetData(11, ref getNodalLoads);
            if (DA.GetDataList(modelDataCount1, ghFilters))
            {
                inFilters = ghFilters.Select(x => x.Value).ToList();
            }

            // Do stuff
            if (run)
            {
                if (!DA.GetData(modelDataCount1 + 1, ref modelName))
                {
                    Component_GetData.ConnectRFEM(ref model, ref data);
                }
                else
                {
                    Component_GetData.ConnectRFEM(modelName, ref model, ref data);
                }
                Component_GetData.ClearOutput(ref rfNodes, ref rfLines, ref rfMembers, ref rfSurfaces, ref rfOpenings,
                                              ref rfSupportsP, ref rfSupportsL, ref rfLineHinges, ref rfCroSecs, ref rfMaterials, ref rfNodalLoads);

                try
                {
                    if (getnodes)
                    {
                        var filNodes = Component_GetData.FilterNodes(data, inFilters);
                        rfNodes = Component_GetData.GetRFNodes(filNodes, data);
                    }
                    if (getlines)
                    {
                        var filLines = Component_GetData.FilterLines(data, inFilters);
                        rfLines = Component_GetData.GetRFLines(filLines, data);
                    }
                    if (getmembers)
                    {
                        var filMembers = Component_GetData.FilterMembers(data, inFilters);
                        rfMembers = Component_GetData.GetRFMembers(filMembers, data);
                    }
                    if (getsurfaces)
                    {
                        var filSrfcs = Component_GetData.FilterSurfaces(data, inFilters);
                        rfSurfaces = Component_GetData.GetRFSurfaces(filSrfcs, data);
                    }
                    if (getopenings)
                    {
                        var filOpenings = Component_GetData.FilterOpenings(data, inFilters);
                        rfOpenings = Component_GetData.GetRFOpenings(filOpenings, data);
                    }
                    if (getsupportsP)
                    {
                        var filSupportsP = Component_GetData.FilterSupsP(data, inFilters);
                        rfSupportsP = Component_GetData.GetRFSupportsP(filSupportsP, data);
                    }
                    if (getsupportsL)
                    {
                        var filSupportsL = Component_GetData.FilterSupsL(data, inFilters);
                        rfSupportsL = Component_GetData.GetRFSupportsL(filSupportsL, data);
                    }
                    if (getLineHinges)
                    {
                        var filLineHinges = Component_GetData.FilterLH(data, inFilters);
                        rfLineHinges = Component_GetData.GetRFLineHinges(filLineHinges, data);
                    }
                    if (getCroSecs)
                    {
                        var filCroSecs = Component_GetData.FilterCroSecs(data, inFilters);
                        rfCroSecs = Component_GetData.GetRFCroSecs(filCroSecs, data);
                    }
                    if (getMaterials)
                    {
                        var filMaterials = Component_GetData.FilterMaterials(data, inFilters);
                        rfMaterials = Component_GetData.GetRFMaterials(filMaterials, data);
                    }
                    //Get Loads?
                    if (getNodalLoads)
                    {
                        Component_GetData.GetLoadsFromRFEM(model, ref loads);
                    }
                    if (getNodalLoads)
                    {
                        var filNodalLoads = Component_GetData.FilterNodalLoads(data, loads, inFilters);
                        rfNodalLoads = Component_GetData.GetRFNodalLoads(filNodalLoads, data);
                    }
                }
                catch (Exception ex)
                {
                    Component_GetData.ClearOutput(ref rfNodes, ref rfLines, ref rfMembers, ref rfSurfaces, ref rfOpenings,
                                                  ref rfSupportsP, ref rfSupportsL, ref rfLineHinges, ref rfCroSecs, ref rfMaterials, ref rfNodalLoads);
                    throw ex;
                }
                Component_GetData.DisconnectRFEM(ref model, ref data);
            }

            // Assign GH Output
            DA.SetDataList(0, rfNodes);
            DA.SetDataList(1, rfLines);
            DA.SetDataList(2, rfMembers);
            DA.SetDataList(3, rfSurfaces);
            DA.SetDataList(4, rfOpenings);
            DA.SetDataList(5, rfSupportsP);
            DA.SetDataList(6, rfSupportsL);
            DA.SetDataList(7, rfLineHinges);
            DA.SetDataList(8, rfCroSecs);
            DA.SetDataList(9, rfMaterials);
            DA.SetDataList(10, rfNodalLoads);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Objects = new List <object>();
            DA.GetDataList(0, Objects);

            List <Dictionary <string, object> > DictList = new List <Dictionary <string, object> >();

            foreach (var obj in Objects)
            {
                object FO = obj.GetType().GetProperty("Value").GetValue(obj, null);

                DictList.Add(FO.ToDictionary());
            }

            bool first = true;

            Global = new Dictionary <string, List <object> >();

            foreach (var dict in DictList)
            {
                foreach (var key in dict.Keys)
                {
                    if (first)
                    {
                        Global.Add(key, new List <object>());
                        Global[key].Add(dict[key]);
                    }
                    else if (!Global.Keys.Contains(key))
                    {
                        this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Object dictionaries do not match.");
                        return;
                    }
                    else
                    {
                        Global[key].Add(dict[key]);
                    }
                }
                first = false;
            }

            if (Global.Keys.Count == 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Empty dictionary.");
                return;
            }

            if (Params.Output.Count != Global.Keys.Count)
            {
                Rhino.RhinoApp.MainApplicationWindow.Invoke(setInputsAndExpireComponent);
            }
            else
            {
                int k = 0;
                foreach (var key in Global.Keys)
                {
                    Params.Output[k].Name = Params.Output[k].NickName = key;
                    if (Global[key] is IEnumerable)
                    {
                        DataTree <object> myTree = new DataTree <object>();
                        ToDataTree(Global[key], ref myTree, new List <int> {
                            0
                        });
                        var x = myTree;
                        DA.SetDataTree(k++, myTree);
                    }
                    else
                    {
                        DA.SetDataList(k++, Global[key]);
                    }
                }
            }
        }
示例#46
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 <Point3d> points  = new List <Point3d>();
            Point3d        point   = new Point3d();
            bool           reverse = false;

            if (!DA.GetDataList(0, points))
            {
                return;
            }
            if (!DA.GetData(1, ref point))
            {
                return;
            }
            if (!DA.GetData(2, ref reverse))
            {
                return;
            }
            List <Point3d> x = points;
            bool           y = reverse;
            //////////////////////////////////////////////////////
            Point3d c = ViperClass.center(x);

            if (point != Point3d.Unset)////如果指定点则以指定点为中心
            {
                c = point;
            }
            Plane pl;

            Plane.FitPlaneToPoints(x, out pl);
            pl.Origin = c;
            double dist = 0;///以所有点离中心点距离的平均值为半径

            for (int i = 0; i < x.Count; i++)
            {
                dist += c.DistanceTo(x[i]);
            }
            Circle cir = new Circle(pl, dist / x.Count);
            ///////////////////////////////////////////////////
            List <double> ts  = new List <double>();
            List <double> ts2 = new List <double>();

            for (int i = 0; i < x.Count; i++)
            {
                double t;
                cir.ClosestParameter(x[i], out t);
                ts.Add(t);
                ts2.Add(t);
            }
            ts.Sort();
            if (reverse)
            {
                ts.Reverse();
            }
            List <int> index = new List <int>();///找出对应的索引值

            for (int i = 0; i < x.Count; i++)
            {
                for (int j = 0; j < x.Count; j++)
                {
                    if (ts[i] == ts2[j])
                    {
                        index.Add(j);
                        ts2[j] = double.PositiveInfinity;
                        break;
                    }
                }
            }
            List <Point3d> ptnew = new List <Point3d>();

            for (int i = 0; i < x.Count; i++)
            {
                ptnew.Add(x[index[i]]);
            }
            DA.SetDataList(0, ptnew);
            DA.SetDataList(1, index);
        }
示例#47
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 iGeometry = new List <Brep>();

            DA.GetDataList(0, iGeometry);

            string nuSgsInsert = "";

            for (int i = 6; i < iGeometry.Count; i++)
            {
                nuSgsInsert += "   " + iGeometry[i].GetUserString("Name") + "\n" +
                               "    {\n" +
                               "        type           nutUSpaldingWallFunction;\n" +
                               "        value          $internalField;\n" +
                               "    }\n" +
                               "\n";
            }

            string shellString =
                "/*--------------------------------*- C++ -*----------------------------------*\\\n" +
                "| =========                 |                                                 |\n" +
                "| \\\\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox           |\n" +
                "|  \\\\    /   O peration     | Version:  2.2.0                                 |\n" +
                "|   \\\\  /    A nd           | Web:      www.OpenFOAM.org                      |\n" +
                "|    \\\\/     M anipulation  |                                                 |\n" +
                "\\*---------------------------------------------------------------------------*/\n" +
                "FoamFile\n" +
                "{{\n" +
                "     version     2.0;\n" +
                "     format      ascii;\n" +
                "     class       volScalarField;\n" +
                "     location       \"0\";\n" +
                "     object      nut;\n" +
                "}}\n" +
                "// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n\r" +
                "\n" +

                "dimensions     [0 2 -1 0 0 0 0];\n\r" +

                "internalField  uniform 1e-05;\n\r" +

                "boundaryField\n" +
                "{{\n\r" +

                "    INLET\n" +
                "    {{\n" +
                "           type            zeroGradient;\n" +
                "    }}\n\r" +

                "    OUTLET\n" +
                "    {{\n" +
                "           type            zeroGradient;\n" +
                "    }}\n\r" +

                "    LEFTSIDE\n" +
                "    {{\n" +
                "           type            symmetry;\n" +
                "    }}\n\r" +

                "    RIGHTSIDE\n" +
                "    {{\n" +
                "           type            symmetry;\n" +
                "    }}\n\r" +

                "    BOTTOM\n" +
                "    {{\n" +
                "           type            zeroGradient;\n" +
                "           value            $internalField;\n" +
                "    }}\n\r" +

                "    TOP\n" +
                "    {{\n" +
                "           type            symmetry;\n" +
                "    }}\n\r" +

                "{0}\n" +
                "}}";

            string nuSgs = string.Format(shellString, nuSgsInsert);

            var oNuSgs = new TextFile(nuSgs, "nuSgs");

            DA.SetData(0, oNuSgs);
        }
示例#48
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <string>           props = new List <string>();
            List <GH_ObjectWrapper> vals  = new List <GH_ObjectWrapper>();

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

            NumericStepper numsteps = new NumericStepper()
            {
                ID = Guid.NewGuid().ToString(),
            };

            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() == "minvalue" || n.ToLower() == "minimum")
                {
                    if (val is GH_String gstr)
                    {
                        if (double.TryParse(gstr.Value, out double sli))
                        {
                            numsteps.MinValue = sli;
                        }
                    }
                    else if (val is GH_Integer gint)
                    {
                        numsteps.MinValue = gint.Value;
                    }
                    else if (val is GH_Number gnum)
                    {
                        numsteps.MinValue = gnum.Value;
                    }
                    else if (val is GH_Boolean gbool)
                    {
                        if (gbool.Value)
                        {
                            numsteps.MinValue = 1;
                        }
                        else
                        {
                            numsteps.MinValue = 0;
                        }
                    }
                    else
                    {
                        try { Util.SetProp(numsteps, "MinValue", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "maxvalue" || n.ToLower() == "maximum")
                {
                    if (val is GH_String gstr)
                    {
                        if (double.TryParse(gstr.Value, out double sli))
                        {
                            numsteps.MaxValue = sli;
                        }
                    }
                    else if (val is GH_Integer gint)
                    {
                        numsteps.MaxValue = gint.Value;
                    }
                    else if (val is GH_Number gnum)
                    {
                        numsteps.MaxValue = gnum.Value;
                    }
                    else if (val is GH_Boolean gbool)
                    {
                        if (gbool.Value)
                        {
                            numsteps.MaxValue = 1;
                        }
                        else
                        {
                            numsteps.MaxValue = 0;
                        }
                    }
                    else
                    {
                        try { Util.SetProp(numsteps, "MaxValue", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else if (n.ToLower() == "increment" || n.ToLower() == "step")
                {
                    if (val is GH_Number gnum)
                    {
                        numsteps.Increment = gnum.Value;
                    }
                    else if (val is GH_Integer gint)
                    {
                        numsteps.Increment = gint.Value;
                    }
                    else if (val is GH_String gstr)
                    {
                        if (double.TryParse(gstr.Value, out double num))
                        {
                            numsteps.Increment = num;
                        }
                        else if (int.TryParse(gstr.Value, out int ii))
                        {
                            numsteps.Increment = ii;
                        }
                    }
                    else
                    {
                        try { Util.SetProp(numsteps, "Increment", Util.GetGooVal(val)); }
                        catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                    }
                }
                else
                {
                    try { Util.SetProp(numsteps, n, Util.GetGooVal(val)); }
                    catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); }
                }
            }

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

            PropertyInfo[] allprops  = numsteps.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);
        }
示例#49
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)
        {
            MaterialProperties mp    = null;
            List <Curve>       crvAg = new List <Curve>();
            List <Curve>       crvAs = new List <Curve>();
            int M = 0;

            if (!DA.GetData(0, ref mp))
            {
                return;
            }
            if (!DA.GetDataList(1, crvAg))
            {
                return;
            }
            if (!DA.GetDataList(2, crvAs))
            {
                return;
            }
            if (!DA.GetData(3, ref M))
            {
                return;
            }

            if (M <= 2)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input m must be an integer greater than 2");
                return;
            }

            //Copy to each analysis plugin - extracts material properties from MP input
            double fc = mp.fC; double Ec = mp.EC; double ec = mp.eC; double rhoc = mp.rhoC; double EEc = mp.EEC;
            double fy = mp.fY; double Es = mp.ES; double es = mp.eS; double rhos = mp.rhoS; double EEs = mp.EES;

            //Code limits for design
            double cdMax  = ec / (ec + es);
            double rhoMax = (0.36 * fc / (0.87 * fy)) * cdMax;
            double rhoMin = 0.25 * Math.Sqrt(fc) / fy;

            //Creates planar Breps from input curves
            Brep[] brepsAg = Brep.CreatePlanarBreps(crvAg, DocumentTolerance());
            Brep[] brepsAs = Brep.CreatePlanarBreps(crvAs, DocumentTolerance());

            List <Curve>  bwCrvs    = new List <Curve>();
            List <double> sectRho   = new List <double>();
            List <double> maxErrors = new List <double>();
            List <double> minErrors = new List <double>();

            List <double> rhoMaxs = new List <double>();
            List <double> rhoMins = new List <double>();

            ////REMOVE WHEN DONE TESTING COMPONENT
            //maxErrors.Add(rhoMax);
            //minErrors.Add(rhoMin);

            for (int i = 0; i < crvAg.Count; i++)
            {
                Brep brepAg = brepsAg[i];
                Brep brepAs = brepsAs[i];

                Surface srfAg = brepAg.Surfaces[0];

                Double uMidDom = (srfAg.Domain(0)[1] + srfAg.Domain(0)[0]) / 2;
                Double vMidDom = (srfAg.Domain(1)[1] + srfAg.Domain(1)[0]) / 2;

                //Correction of U and V curve extraction
                Curve   U0 = srfAg.IsoCurve(0, vMidDom);
                Curve[] UIntCrv; Point3d[] UIntPt;
                Rhino.Geometry.Intersect.Intersection.CurveBrep(U0, brepAg, DocumentTolerance(), out UIntCrv, out UIntPt);
                Curve U = UIntCrv[0];

                Curve   V0 = srfAg.IsoCurve(1, uMidDom);
                Curve[] VIntCrv; Point3d[] VIntPt;
                Rhino.Geometry.Intersect.Intersection.CurveBrep(V0, brepAg, DocumentTolerance(), out VIntCrv, out VIntPt);
                Curve V = VIntCrv[0];

                Point3d endPtV = V.PointAtEnd; Point3d startPtV = V.PointAtStart;
                if (endPtV.Z > startPtV.Z)
                {
                    V.Reverse();
                }

                Double[] vDivision = V.DivideByCount(M, false);
                Plane[]  vPlane    = V.GetPerpendicularFrames(vDivision);

                Curve[]  vContours = new Curve[vPlane.Length];
                double[] vConLen   = new double[vPlane.Length];
                for (int j = 0; j < vPlane.Length; j++)
                {
                    Curve[] vContour = Brep.CreateContourCurves(brepAg, vPlane[j]);
                    if (vContour.Length > 0)
                    {
                        vContours[j] = vContour[0];
                        vConLen[j]   = vContour[0].GetLength();
                    }
                }
                Curve bCrv = vContours[0];
                Array.Sort(vConLen, vContours);
                Curve bwCrv = null;
                //if (vContours[0] == null) { bwCrv = U; }
                //else { bwCrv = vContours[0]; }
                bwCrv = vContours[0];
                if (bwCrv == null)
                {
                    bwCrv = U;
                }

                bwCrvs.Add(bwCrv);

                double areaAs = AreaMassProperties.Compute(crvAs[i]).Area;
                double bw, d, bwd = 0;

                bw = bwCrv.GetLength(); d = U.GetLength(); bwd = bw * d;
                double rho = areaAs / bwd;

                if (double.IsPositiveInfinity(rho) || double.IsNegativeInfinity(rho))
                {
                    //AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Reinforcement ratio is invalid.");
                    //return;

                    rho = 0;
                }

                sectRho.Add(rho);

                double maxError = 100 * ((rhoMax - rho) / rhoMax);
                maxErrors.Add(maxError);

                double minError = 100 * (rho - rhoMin) / rhoMin;
                minErrors.Add(minError);

                rhoMaxs.Add(rhoMax);
                rhoMins.Add(rhoMin);
            }

            DA.SetDataList(0, sectRho);
            //DA.SetDataList(1, maxErrors);
            //DA.SetDataList(2, minErrors);
            DA.SetDataList(1, bwCrvs);
            DA.SetDataList(2, rhoMaxs);
            DA.SetDataList(3, rhoMins);
        }
示例#50
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve        perimeter = null;
            List <Curve> coreCrvs  = new List <Curve>();
            List <Curve> interiorPartitions;
            Plane        plane = Plane.Unset;

            try
            {
                if (InPreSolve)
                {
                    rectangles         = new List <Rectangle3d>();
                    interiorPartitions = new List <Curve>();

                    // DA.GetData(IN_reset, ref iReset);
                    DA.GetData(IN_AutoColor, ref autoColor);
                    DA.GetData(IN_plane, ref plane);
                    DA.GetData(IN_perimCurve, ref perimeter);
                    bool coreReceived = DA.GetDataList(IN_coreCurves, coreCrvs);
                    DA.GetDataList(IN_rects, rectangles);
                    DA.GetDataList(IN_partitions, interiorPartitions);

                    if (coreReceived)
                    {
                        _plan = new SmartPlan(perimeter, coreCrvs, rectangles, interiorPartitions, plane);
                    }
                    else
                    {
                        _plan = new SmartPlan(perimeter, rectangles, interiorPartitions, plane);
                    }


                    Task <SolveResults> task = Task.Run(() => ComputeIso(_plan), CancelToken);
                    TaskList.Add(task);
                    return;
                }

                if (!GetSolveResults(DA, out SolveResults result))
                {
                    rectangles         = new List <Rectangle3d>();
                    interiorPartitions = new List <Curve>();

                    DA.GetData(IN_AutoColor, ref autoColor);
                    DA.GetData(IN_plane, ref plane);
                    DA.GetData(IN_perimCurve, ref perimeter);
                    bool coreReceived = DA.GetData(IN_coreCurves, ref coreCrvs);
                    DA.GetDataList(IN_rects, rectangles);
                    DA.GetDataList(IN_partitions, interiorPartitions);

                    if (coreReceived)
                    {
                        _plan = new SmartPlan(perimeter, coreCrvs, rectangles, interiorPartitions, plane);
                    }
                    else
                    {
                        _plan = new SmartPlan(perimeter, rectangles, interiorPartitions, plane);
                    }

                    result = ComputeIso(_plan);
                    _plan  = result.Value;
                }

                if (result != null)
                {
                    iso = _plan.getIsovist();
                    DA.SetDataList(OUT_isovistMetric, iso);
                    DA.SetDataList(OUT_isovistPolys, _plan.isoPolylines);
                }
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.ToString());
            }

            // Params.ParameterChanged -= ObjectEventHandler;
            // Params.ParameterChanged += ObjectEventHandler;
        }
示例#51
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 <Line> lines = new List <Line>(); List <Surface> shells = new List <Surface>(); List <Line> slines = new List <Line>(); List <Line> dlines = new List <Line>();

            if (!DA.GetDataList("lines", lines))
            {
            }
            ;
            if (!DA.GetDataList("shells", shells))
            {
            }
            ;
            if (!DA.GetDataList("springs", slines))
            {
            }
            ;
            if (!DA.GetDataList("dampers", dlines))
            {
            }
            ;
            List <double> mat   = new List <double>(); DA.GetDataList("Material No. List", mat);
            List <double> sec   = new List <double>(); DA.GetDataList("Section No. List", sec);
            List <double> angle = new List <double>(); DA.GetDataList("Element Angle List", angle);
            List <double> mat2  = new List <double>(); DA.GetDataList("Material No. List(shell)", mat2);
            List <double> t     = new List <double>(); DA.GetDataList("thickness List", t);

            DA.GetDataTree("E", out GH_Structure <GH_Number> _E); var     E = _E.Branches;
            DA.GetDataTree("KCa", out GH_Structure <GH_Number> _KCa); var KCa = _KCa.Branches;
            var            r = new GH_Structure <GH_Number>(); var ij = new GH_Structure <GH_Number>(); var ijkl = new GH_Structure <GH_Number>(); var spring = new GH_Structure <GH_Number>(); var damper = new GH_Structure <GH_Number>();
            List <Point3d> xyz = new List <Point3d>();

            for (int e = 0; e < lines.Count; e++)
            {
                var r1 = lines[e].From; var r2 = lines[e].To;
                if (xyz.Exists(num => (num - r1).Length < 5e-3) == false)
                {
                    xyz.Add(r1);
                }
                if (xyz.Exists(num => (num - r2).Length < 5e-3) == false)
                {
                    xyz.Add(r2);
                }
            }
            for (int e = 0; e < shells.Count; e++)
            {
                var     shell = shells[e].ToNurbsSurface();
                var     p = shell.Points;
                Point3d r1; p.GetPoint(0, 0, out r1); Point3d r2; p.GetPoint(1, 0, out r2); Point3d r3; p.GetPoint(1, 1, out r3); Point3d r4; p.GetPoint(0, 1, out r4);
                if (xyz.Exists(num => (num - r1).Length < 5e-3) == false)
                {
                    xyz.Add(r1);
                }
                if (xyz.Exists(num => (num - r2).Length < 5e-3) == false)
                {
                    xyz.Add(r2);
                }
                if (xyz.Exists(num => (num - r3).Length < 5e-3) == false)
                {
                    xyz.Add(r3);
                }
                if (xyz.Exists(num => (num - r4).Length < 5e-3) == false)
                {
                    xyz.Add(r4);
                }
            }
            for (int e = 0; e < slines.Count; e++)
            {
                var r1 = slines[e].From; var r2 = slines[e].To;
                if (xyz.Exists(num => (num - r1).Length < 5e-3) == false)
                {
                    xyz.Add(r1);
                }
                if (xyz.Exists(num => (num - r2).Length < 5e-3) == false)
                {
                    xyz.Add(r2);
                }
            }
            for (int e = 0; e < dlines.Count; e++)
            {
                var r1 = dlines[e].From; var r2 = dlines[e].To;
                if (xyz.Exists(num => (num - r1).Length < 5e-3) == false)
                {
                    xyz.Add(r1);
                }
                if (xyz.Exists(num => (num - r2).Length < 5e-3) == false)
                {
                    xyz.Add(r2);
                }
            }
            for (int i = 0; i < xyz.Count; i++)
            {
                List <GH_Number> rlist = new List <GH_Number>();
                rlist.Add(new GH_Number(xyz[i].X)); rlist.Add(new GH_Number(xyz[i].Y)); rlist.Add(new GH_Number(xyz[i].Z));
                r.AppendRange(rlist, new GH_Path(i));
            }
            for (int e = 0; e < lines.Count; e++)
            {
                var r1 = lines[e].From; var r2 = lines[e].To; int i = 0; int j = 0;
                for (i = 0; i < xyz.Count; i++)
                {
                    if ((xyz[i] - r1).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                for (j = 0; j < xyz.Count; j++)
                {
                    if ((xyz[j] - r2).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                List <GH_Number> ijlist = new List <GH_Number>();
                ijlist.Add(new GH_Number(i)); ijlist.Add(new GH_Number(j));
                if (mat[0] == -9999)
                {
                    ijlist.Add(new GH_Number(0));
                }
                else
                {
                    ijlist.Add(new GH_Number(mat[e]));
                }
                if (sec[0] == -9999)
                {
                    ijlist.Add(new GH_Number(0));
                }
                else
                {
                    ijlist.Add(new GH_Number(sec[e]));
                }
                if (angle[0] == -9999)
                {
                    ijlist.Add(new GH_Number(0));
                }
                else
                {
                    ijlist.Add(new GH_Number(angle[e]));
                }
                ij.AppendRange(ijlist, new GH_Path(e));
            }
            for (int e = 0; e < shells.Count; e++)
            {
                int     i = 0; int j = 0; int k = 0; int l = -1;
                var     shell = shells[e].ToNurbsSurface();
                var     p = shell.Points;
                Point3d r1; p.GetPoint(0, 0, out r1); Point3d r2; p.GetPoint(1, 0, out r2);
                Point3d r3; p.GetPoint(1, 1, out r3); Point3d r4; p.GetPoint(0, 1, out r4);
                for (i = 0; i < xyz.Count; i++)
                {
                    if ((xyz[i] - r1).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                for (j = 0; j < xyz.Count; j++)
                {
                    if ((xyz[j] - r2).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                if (shells[e].IsSingular(0) == false && shells[e].IsSingular(1) == false && shells[e].IsSingular(2) == false && shells[e].IsSingular(3) == false)
                {
                    for (k = 0; k < xyz.Count; k++)
                    {
                        if ((xyz[k] - r3).Length <= 5e-3)
                        {
                            break;
                        }
                        ;
                    }
                    for (l = 0; l < xyz.Count; l++)
                    {
                        if ((xyz[l] - r4).Length <= 5e-3)
                        {
                            break;
                        }
                        ;
                    }
                }
                else
                {
                    for (int k1 = 0; k1 < xyz.Count; k1++)
                    {
                        if (((xyz[k1] - r4).Length <= 5e-3 && (r1 - r4).Length > 5e-3 && (r2 - r4).Length > 5e-3) || ((xyz[k1] - r3).Length <= 5e-3 && (r1 - r3).Length > 5e-3 && (r2 - r3).Length > 5e-3))
                        {
                            k = k1; break;
                        }
                        ;
                    }
                }
                List <GH_Number> ijkllist = new List <GH_Number>();
                ijkllist.Add(new GH_Number(i)); ijkllist.Add(new GH_Number(j)); ijkllist.Add(new GH_Number(k)); ijkllist.Add(new GH_Number(l));
                if (mat2[0] == -9999)
                {
                    ijkllist.Add(new GH_Number(0));
                }
                else
                {
                    ijkllist.Add(new GH_Number(mat2[e]));
                }
                if (t[0] == -9999)
                {
                    ijkllist.Add(new GH_Number(0.15));
                }
                else
                {
                    ijkllist.Add(new GH_Number(t[e]));
                }
                ijkl.AppendRange(ijkllist, new GH_Path(e));
            }
            for (int e = 0; e < slines.Count; e++)
            {
                var r1 = slines[e].From; var r2 = slines[e].To; int i = 0; int j = 0;
                for (i = 0; i < xyz.Count; i++)
                {
                    if ((xyz[i] - r1).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                for (j = 0; j < xyz.Count; j++)
                {
                    if ((xyz[j] - r2).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                List <GH_Number> slist = new List <GH_Number>(); slist.Add(new GH_Number(i)); slist.Add(new GH_Number(j));
                if (E[0][0].Value == -9999)
                {
                    slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000)); slist.Add(new GH_Number(1000));
                }
                else
                {
                    slist.Add(new GH_Number(E[e][0])); slist.Add(new GH_Number(E[e][1])); slist.Add(new GH_Number(E[e][2])); slist.Add(new GH_Number(E[e][3])); slist.Add(new GH_Number(E[e][4])); slist.Add(new GH_Number(E[e][5])); slist.Add(new GH_Number(E[e][6])); slist.Add(new GH_Number(E[e][7])); slist.Add(new GH_Number(E[e][8])); slist.Add(new GH_Number(E[e][9]));
                    if (E[e].Count == 11)
                    {
                        slist.Add(new GH_Number(E[e][10]));
                    }
                }
                spring.AppendRange(slist, new GH_Path(e));
            }
            for (int e = 0; e < dlines.Count; e++)
            {
                var r1 = dlines[e].From; var r2 = dlines[e].To; int i = 0; int j = 0;
                for (i = 0; i < xyz.Count; i++)
                {
                    if ((xyz[i] - r1).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                for (j = 0; j < xyz.Count; j++)
                {
                    if ((xyz[j] - r2).Length <= 5e-3)
                    {
                        break;
                    }
                    ;
                }
                List <GH_Number> dlist = new List <GH_Number>(); dlist.Add(new GH_Number(i)); dlist.Add(new GH_Number(j));
                if (KCa[0][0].Value == -9999)
                {
                    dlist.Add(new GH_Number(25000)); dlist.Add(new GH_Number(450)); dlist.Add(new GH_Number(0.3));
                }
                else
                {
                    dlist.Add(new GH_Number(KCa[e][0])); dlist.Add(new GH_Number(KCa[e][1])); dlist.Add(new GH_Number(KCa[e][2]));
                }
                damper.AppendRange(dlist, new GH_Path(e));
            }
            DA.SetDataTree(0, r);
            if (lines.Count != 0)
            {
                DA.SetDataTree(1, ij);
            }
            if (shells.Count != 0)
            {
                DA.SetDataTree(2, ijkl);
            }
            if (slines.Count != 0)
            {
                DA.SetDataTree(3, spring);
            }
            if (dlines.Count != 0)
            {
                DA.SetDataTree(4, damper);
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            #region variables
            string          alignmentname = "N/A";
            List <Vector3d> globalZvector = new List <Vector3d>();
            List <double>   offsetY       = new List <double>();
            List <double>   offsetZ       = new List <double>();

            #endregion

            #region input

            if (!DA.GetData(0, ref alignmentname))
            {
                return;
            }
            if (!DA.GetDataList(1, globalZvector))
            {
                return;
            }
            if (!DA.GetDataList(2, offsetY))
            {
                return;
            }
            if (!DA.GetDataList(3, offsetZ))
            {
                return;
            }

            #endregion

            #region solve

            List <int> listlengths = new List <int>();
            listlengths.Add(globalZvector.Count);
            listlengths.Add(offsetY.Count);
            listlengths.Add(offsetZ.Count);
            listlengths.Sort();

            List <Align> simplAlign = new List <Align>();

            simplAlign.Add(new Align(alignmentname, globalZvector[0], offsetY[0], offsetZ[0]));



            if (Functions.CheckInputValidity(listlengths))
            {
                for (int i = 0; i < listlengths[2]; i++)
                {
                }
            }
            else
            {
                //ADD A ERROR MESSAGE SAYING: Listlength of offset y, offset z and globalzvector must be either 1 or similar to the larges. (And must be similar to the length of the member)
            }

            #endregion

            #region output
            DA.SetData(0, new Align(alignmentname, globalZvector[0], offsetY[0], offsetZ[0]));
            #endregion
        }
示例#53
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)
        {
            string defaultDir = "C:\\\\ant\\\\_03_LinearModel\\\\_04_SVM\\\\";

            string dataFile   = null;
            string targetFile = null;
            string resultFile = "result.txt";
            string workingDir = null;
            bool   fit        = false;
            string Logs       = "";

            //Optional Data:

            double C          = 1.0;
            double epsilon    = 1.0;
            string kernel     = "rbf";
            int    degree     = 3;
            double gamma      = 0.0;
            double coef0      = 0.0;
            bool   shrinking  = true;
            double tol        = 1e-3;
            double cache_size = 200;
            bool   verbose    = false;
            int    max_iter   = -1;

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


            if (!DA.GetData(0, ref dataFile))
            {
                return;
            }
            if (dataFile == null)
            {
                return;
            }
            if (!DA.GetData(1, ref targetFile))
            {
                return;
            }
            if (targetFile == null)
            {
                return;
            }
            if (!DA.GetData(2, ref workingDir))
            {
                return;
            }
            if (workingDir == null)
            {
                return;
            }
            if (!DA.GetDataList(3, predicTData))
            {
                return;
            }
            if (predicTData == null)
            {
                return;
            }
            if (!DA.GetData(4, ref fit))
            {
                return;
            }
            if (fit == false)
            {
                return;
            }

            long ticks0 = DateTime.Now.Ticks;

            try
            {
                DA.GetData(5, ref C);
                DA.GetData(6, ref epsilon);
                DA.GetData(7, ref kernel);
                DA.GetData(8, ref degree);
                DA.GetData(9, ref gamma);
                DA.GetData(10, ref coef0);
                DA.GetData(11, ref shrinking);
                DA.GetData(12, ref tol);
                DA.GetData(13, ref cache_size);
                DA.GetData(14, ref verbose);
                DA.GetData(15, ref max_iter);
            }
            catch (Exception ex)
            {
                var st = new StackTrace(ex, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
                Logs += line.ToString() + "\n";
            }

            // 01 Specify the working directory at which pythonFile exists, note that this Python file should run separately using Proccess2 (see 5).
            process2.StartInfo.WorkingDirectory = workingDir;
            try
            {
                // 02 Initiate helperFunctions
                HelperFunction helpFunctions = new HelperFunction();

                // Put inputData in one list of strings.
                List <string> dataInput = new List <string>(new string[] {
                    C.ToString(),
                    epsilon.ToString(),
                    @"'" + kernel + @"'",
                    degree.ToString(),
                    gamma.ToString(),
                    coef0.ToString(),
                    shrinking == true?"True":"False",
                    tol.ToString(),
                    cache_size.ToString(),
                    verbose == true?"True":"False",
                    max_iter.ToString(),
                });

                // 03 Convert data from grasshopper syntax to python NumPy like array.
                string newString = helpFunctions.dataInput2Python(workingDir, predicTData);

                // 04 Write the Python file in the working directory
                helpFunctions.PythonFile(defaultDir, dataFile, targetFile, workingDir, resultFile, newString, "True", workingDir + "logFile.txt", allResources._04_SupportVectorRegression, dataInput);
            }
            catch (Exception e)
            {
                this.Message = e.ToString();
            }

            // 05 Start running Python file. and wait until it is closed i.e. raising the process_Exited event.
            process2.Start();

            while (!processhasexit)
            {
            }
            try
            {
                doc.Load(workingDir + "res.xml");

                //TODO : add all the output variables here
                //AllData = {"prediction":result, "score":sroce, "support":support, "support_vectors":support_vectors, "n_support": n_support, "dual_coef": dual_coef, "coef": coeff, "intercept":intercept}

                XmlNode res_node             = doc.DocumentElement.SelectSingleNode("/result/prediction");
                XmlNode score_node           = doc.DocumentElement.SelectSingleNode("/result/score");
                XmlNode support_node         = doc.DocumentElement.SelectSingleNode("/result/support");
                XmlNode support_vectors_node = doc.DocumentElement.SelectSingleNode("/result/support_vectors");
                XmlNode dual_coef_node       = doc.DocumentElement.SelectSingleNode("/result/dual_coef");
                XmlNode coeff_node           = doc.DocumentElement.SelectSingleNode("/result/coef");
                XmlNode intercept_node       = doc.DocumentElement.SelectSingleNode("/result/intercept");


                string res             = res_node.InnerText;
                string score           = score_node.InnerText;
                string support         = support_node.InnerText;
                string support_vectors = support_vectors_node.InnerText;
                string dual_coef       = dual_coef_node.InnerText;
                string coeff           = coeff_node.InnerText;
                string intercept       = intercept_node.InnerText;



                //string res = System.IO.File.ReadAllText(workingDir + "result.txt");
                res = res.Replace("[", "").Replace("]", "");
                DA.SetData(1, res);
                DA.SetData(2, score);
                DA.SetData(3, support);
                DA.SetData(4, support_vectors);
                DA.SetData(5, dual_coef);
                DA.SetData(6, coeff);
                DA.SetData(7, intercept);

                long   ticks1       = DateTime.Now.Ticks;
                double timeElaspsed = ((double)ticks1 - (double)ticks0) / 10000000;
                Logs += "Success !! in : " + timeElaspsed + " Seconds\n ";
            }
            catch (Exception e)
            {
                var st = new StackTrace(e, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
                Logs += e.Message + line.ToString() + "\n";
            }
            DA.SetData(0, Logs);
            processhasexit = false;
        }
示例#54
0
        /// <summary>
        /// Wrap input geometry into module cages.
        /// </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)
        {
            var modules    = new List <Module>();
            var allowed    = new List <Rule>();
            var disallowed = new List <Rule>();

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

            if (!DA.GetDataList(1, allowed))
            {
                return;
            }

            DA.GetDataList(2, disallowed);

            var modulesClean = new List <Module>();

            foreach (var module in modules)
            {
                if (module == null || !module.IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The module is null or invalid.");
                }
                else
                {
                    modulesClean.Add(module);
                }
            }

            Module.GenerateEmptySingleModule(Config.OUTER_MODULE_NAME,
                                             Config.INDIFFERENT_TAG,
                                             new Rhino.Geometry.Vector3d(1, 1, 1),
                                             out var moduleOut,
                                             out var rulesOut);

            var allowedClean = allowed.Concat(
                rulesOut.Select(ruleExplicit => new Rule(ruleExplicit))
                );

            modulesClean.Add(moduleOut);


            if (allowed.Any(rule => rule == null || !rule.IsValid))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Some of the allowed Rules are null or invalid.");
            }

            var allowedOriginalClean = allowedClean
                                       .Where(rule => rule.IsValidWithModules(modulesClean))
                                       .Distinct();

            if (disallowed == null || !disallowed.Any())
            {
                var earlyRules = allowedOriginalClean.ToList();
                earlyRules.Sort();
                DA.SetDataList(0, earlyRules);
                return;
            }

            if (disallowed.Any(rule => rule == null || !rule.IsValid))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Some of the disallowed rules are null or invalid.");
            }

            var allowedExplicit = allowedOriginalClean
                                  .Where(rule => rule.IsExplicit)
                                  .Select(rule => rule.Explicit)
                                  .ToList();
            var allowedTyped = allowedOriginalClean
                               .Where(rule => rule.IsTyped)
                               .Select(rule => rule.Typed);

            var disallowedOriginalClean = disallowed
                                          .Where(rule => rule.IsValidWithModules(modulesClean))
                                          .Distinct();

            var disallowedExplicit = disallowedOriginalClean
                                     .Where(rule => rule.IsExplicit)
                                     .Select(rule => rule.Explicit)
                                     .ToList();
            var disallowedTyped = disallowedOriginalClean
                                  .Where(rule => rule.IsTyped)
                                  .Select(rule => rule.Typed);

            var allTypedRules = allowedTyped.Concat(disallowedTyped);

            var allTypedByType = new Dictionary <string, List <RuleTyped> >();

            foreach (var rule in allTypedRules)
            {
                var type = rule.ConnectorType;
                if (allTypedByType.ContainsKey(type))
                {
                    allTypedByType[type].Add(rule);
                }
                else
                {
                    allTypedByType.Add(type, new List <RuleTyped>()
                    {
                        rule
                    });
                }
            }

            var disallowedTypedByType = new Dictionary <string, List <RuleTyped> >();

            foreach (var rule in disallowedTyped)
            {
                var type = rule.ConnectorType;
                if (disallowedTypedByType.ContainsKey(type))
                {
                    disallowedTypedByType[type].Add(rule);
                }
                else
                {
                    disallowedTypedByType.Add(type, new List <RuleTyped>()
                    {
                        rule
                    });
                }
            }

            // unwrap disallowed typed rules and add them to disallowedExplicit
            foreach (var entry in allTypedByType)
            {
                var type  = entry.Key;
                var rules = entry.Value;
                if (disallowedTypedByType.ContainsKey(type))
                {
                    var rulesExplicit   = rules.SelectMany(rule => rule.ToRulesExplicit(rules, modulesClean));
                    var disallowedRules = disallowedTypedByType[type];
                    foreach (var rule in rulesExplicit)
                    {
                        if (disallowedRules.Any(disallowedRule =>
                                                (disallowedRule.ModuleName == rule.SourceModuleName &&
                                                 disallowedRule.ConnectorIndex == rule.SourceConnectorIndex) ||
                                                (disallowedRule.ModuleName == rule.TargetModuleName &&
                                                 disallowedRule.ConnectorIndex == rule.TargetConnectorIndex)))
                        {
                            disallowedExplicit.Add(rule);
                        }
                    }
                }
            }

            // unwrap all typed rules
            foreach (var rule in allTypedRules)
            {
                var rulesExplicit = rule.ToRulesExplicit(allTypedRules, modulesClean);
                allowedExplicit.AddRange(rulesExplicit);
            }

            var finalExplicit = new List <RuleExplicit>();

            foreach (var rule in allowedExplicit)
            {
                if (!disallowedExplicit.Any(disallowedRule => disallowedRule.Equals(rule)))
                {
                    finalExplicit.Add(rule);
                }
            }

            var outputRules = finalExplicit
                              .Where(rule => !(rule.SourceModuleName == Config.OUTER_MODULE_NAME && rule.TargetModuleName == Config.OUTER_MODULE_NAME))
                              .Distinct()
                              .Select(explicitRule => new Rule(explicitRule))
                              .ToList();

            outputRules.Sort();

            foreach (var rule in outputRules)
            {
                if (!rule.IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, rule.IsValidWhyNot);
                }
            }

            DA.SetDataList(0, outputRules);
        }
示例#55
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)
        {
            //CheckType();
            // Get inputs.
            string       message;
            List <Mesh>  inputMeshes = new List <Mesh>();
            List <Color> inputColor  = new List <Color>();
            Connection   connect     = null;

            if (!DA.GetDataList(0, inputMeshes))
            {
                return;
            }
            DA.GetDataList(1, inputColor);
            if (!DA.GetData <Connection>(2, ref connect))
            {
                return;
            }
            // Check inputs.
            if ((inputColor.Count > 1) && (inputColor.Count != inputMeshes.Count))
            {
                message = (inputColor.Count > inputMeshes.Count) ?
                          "The number of Colors does not match the number of Mesh objects. Extra colors will be ignored." :
                          "The number of Colors does not match the number of Mesh objects. The last color will be repeated.";
                UniversalDebug(message, GH_RuntimeMessageLevel.Warning);
            }
            ////////////////////////////////////////////////////////////////////

            // If connection open start acting.
            if (connect.status)
            {
                // Encode mesh data.
                List <MeshData> inputMeshData = new List <MeshData> {
                };
                for (int i = 0; i < inputMeshes.Count; i++)
                {
                    Color currentColor = inputColor[Math.Min(i, inputColor.Count)];
                    inputMeshData.Add(MeshUtilities.EncodeMesh(inputMeshes[i], currentColor));
                }
                // Send mesh data.
                byte[] bytes = EncodeUtilities.EncodeData("MESHSTREAMING", inputMeshData, out string currentMessage);
                if (this.flagForce || (this.lastMessage != currentMessage))
                {
                    //bool success = false;
                    if (this.sourceType == SourceType.TCP)
                    {
                        connect.tcpSender.QueueUpData(bytes);
                        //success = connect.tcpSender.flagSuccess;
                        //message = connect.tcpSender.debugMessages[connect.tcpSender.debugMessages.Count-1];
                    }
                    else
                    {
                        connect.udpSender.QueueUpData(bytes);
                        //success = connect.udpSender.flagSuccess;
                        //message = connect.udpSender.debugMessages[connect.udpSender.debugMessages.Count-1];
                    }
                    //if (success)
                    //	this.lastMessage = currentMessage;
                    //UniversalDebug(message, (success) ? GH_RuntimeMessageLevel.Remark : GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                this.lastMessage = string.Empty;
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'", GH_RuntimeMessageLevel.Warning);
            }

            // Output.
                        #if DEBUG
            DA.SetData(0, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            //// Expire Solution.
            //if ((connect.status) && (connect.PendingMessages)) {
            //	GH_Document document = this.OnPingDocument();
            //	if (document != null)
            //		document.ScheduleSolution(MeshStreaming.expireDelay, ScheduleCallback);
            //}
        }
示例#56
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)
        {
            //Set the data from the input params
            bool         useEntrance = true;
            int          iCount      = 0;
            Brep         brepVoid    = null;
            Point3d      ptRandom    = Point3d.Unset;
            List <Curve> cCurves     = new List <Curve>();
            Brep         brepEnter   = null;

            //Acces the data from the input
            DA.GetData("UseEntrance", ref useEntrance);
            DA.GetData("iCount", ref iCount);
            DA.GetData("brepVoid", ref brepVoid);
            DA.GetData("randomPoint", ref ptRandom);
            DA.GetDataList("cCurves", cCurves);
            DA.GetData("brepEntrance", ref brepEnter);

            List <Cone>    conesList  = new List <Cone>();
            List <Point3d> ptsList    = new List <Point3d>();
            List <Curve>   curvesList = new List <Curve>();

            //Add the first point
            ptsList.Add(ptRandom);

            List <Point3d> ptsListNew = new List <Point3d>();
            List <Line>    linesList  = new List <Line>();
            double         dx         = 0.0;

            for (int i = 0; i < ptsList.Count; i++)
            {
                if (ptsList.Count < iCount)
                {
                    if (GetTheTangent(ptsList[i], brepVoid, out dx))
                    {
                    }
                    List <Cone> cones = (GetExtendedCones(brepVoid, ptsList[i], dx));
                    foreach (var c in cones)
                    {
                        conesList.Add(c);
                    }
                    ;

                    for (int j = 0; j < cones.Count; j++)
                    {
                        List <Point3d> pt = GetIntersecetionPoints(brepVoid, ptsList[i], cCurves, cones[j]);
                        foreach (var p in pt)
                        {
                            linesList.Add(new Line(p, ptsList[i]));
                            ptsList.Add(p);
                        }
                    }
                }
                else
                {
                    break;
                }
            }

            for (int i = 0; i < linesList.Count; i++)
            {
                curvesList.Add(linesList[i].ToNurbsCurve());
            }

            if (useEntrance)
            {
                curvesList = GetNotIntersectingCurves(curvesList, brepEnter);
            }

            DA.SetDataList(0, conesList);
            DA.SetDataList(1, ptsList);
            DA.SetDataList(2, curvesList);
        }
示例#57
0
        /// <summary>
        /// Wrap input geometry into module cages.
        /// </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)
        {
            var geometryRaw = new List <IGH_GeometricGoo>();
            var module      = new Module();
            var basePlane   = new Plane();

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

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

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

            if (module == null || !module.IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Module is null or invalid.");
                return;
            }

            // Transform the geometry to be oriented to world XYZ fore easier scanning
            var geometryTransform = Transform.PlaneToPlane(basePlane, Plane.WorldXY);
            var geometryClean     = geometryRaw
                                    .Select(goo => GH_Convert.ToGeometryBase(goo))
                                    .Where(geo => geo != null)
                                    .Select(geo => {
                var transformedGeometry = geo.Duplicate();
                transformedGeometry.Transform(geometryTransform);
                return(transformedGeometry);
            }).ToList();

            if (!geometryClean.Any())
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "Failed to collect any valid geometry to scan.");
                return;
            }

            var moduleGeometry = module.Geometry
                                 .Concat(module.ReferencedGeometry);

            if (!moduleGeometry.Any())
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "Module \"" + module.Name + "\" contains " +
                                  "no geometry and therefore will be skipped.");
                return;
            }

            var moduleGeometryBBoxes = moduleGeometry.Select(geo => geo.GetBoundingBox(true));

            var bBoxUnionModule = BoundingBox.Empty;

            bBoxUnionModule.Union(module.Pivot.Origin);
            foreach (var moduleBBox in moduleGeometryBBoxes)
            {
                bBoxUnionModule.Union(moduleBBox);
            }
            var moduleDimensionSafetyBuffer = new Point3i(
                (int)Math.Ceiling(bBoxUnionModule.Diagonal.X / module.PartDiagonal.X) + 1,
                (int)Math.Ceiling(bBoxUnionModule.Diagonal.Y / module.PartDiagonal.Y) + 1,
                (int)Math.Ceiling(bBoxUnionModule.Diagonal.Z / module.PartDiagonal.Z) + 1);

            var geometryBBoxes    = geometryClean.Select(geo => geo.GetBoundingBox(true)).ToList();
            var bBoxUnionGeometry = BoundingBox.Empty;

            foreach (var bBox in geometryBBoxes)
            {
                bBoxUnionGeometry.Union(bBox);
            }

            var slots = new List <Slot>();

            for (int z = (int)Math.Floor(bBoxUnionGeometry.Min.Z / module.PartDiagonal.Z) - moduleDimensionSafetyBuffer.Z;
                 z < Math.Ceiling(bBoxUnionGeometry.Max.Z / module.PartDiagonal.Z) + moduleDimensionSafetyBuffer.Z;
                 z++)
            {
                for (int y = (int)Math.Floor(bBoxUnionGeometry.Min.Y / module.PartDiagonal.Y) - moduleDimensionSafetyBuffer.Y;
                     y < Math.Ceiling(bBoxUnionGeometry.Max.Y / module.PartDiagonal.Y) + moduleDimensionSafetyBuffer.Y;
                     y++)
                {
                    for (int x = (int)Math.Floor(bBoxUnionGeometry.Min.X / module.PartDiagonal.X) - moduleDimensionSafetyBuffer.X;
                         x < Math.Ceiling(bBoxUnionGeometry.Max.X / module.PartDiagonal.X) + moduleDimensionSafetyBuffer.X;
                         x++)
                    {
                        var currentRelativePosition = new Point3i(x, y, z);
                        var currentPivot            = Plane.WorldXY;
                        currentPivot.Origin = currentRelativePosition.ToCartesian(Plane.WorldXY, module.PartDiagonal);

                        var transformModuleToCurrentPivot      = Transform.PlaneToPlane(module.Pivot, currentPivot);
                        var moduleGeometryBBoxesAtCurrentPivot = moduleGeometryBBoxes.Select(bBox => {
                            var transformedBBox = bBox;
                            transformedBBox.Transform(transformModuleToCurrentPivot);
                            return(transformedBBox);
                        });

                        var indicesOfSimilarBBoxes = moduleGeometryBBoxesAtCurrentPivot.Select(moduleGeometryBBox =>
                                                                                               geometryBBoxes.Select((geometryBBox, index) => {
                            var moduleCorners   = moduleGeometryBBox.GetCorners().ToList();
                            var geometryCorners = geometryBBox.GetCorners().ToList();
                            moduleCorners.Sort();
                            geometryCorners.Sort();
                            if (Enumerable.SequenceEqual(moduleCorners, geometryCorners))
                            {
                                return(index);
                            }
                            else
                            {
                                return(-1);
                            }
                        }).Where(index => index != -1)
                                                                                               );

                        // If any module geometry doesn't have a bbox similar to any geometry, then early continue
                        if (!indicesOfSimilarBBoxes.All(similarBBoxes => similarBBoxes.Any()))
                        {
                            continue;
                        }

                        // Heavy calculations

                        var transformedModuleGeometry = moduleGeometry.Select(geo => {
                            var transformedGeometry = geo.Duplicate();
                            transformedGeometry.Transform(transformModuleToCurrentPivot);
                            return(transformedGeometry);
                        });

                        var geometriesToCheck = indicesOfSimilarBBoxes.Select(indices => indices.Select(index => geometryClean[index]));

                        var geometryEqualityPattern = transformedModuleGeometry
                                                      .Zip(geometriesToCheck, (current, others) => others.Any(other =>
                                                                                                              // TODO: when the original geometry is moved, the meshes become unequal
                                                                                                              // TODO: replace with visual similarity check (pull random points to geometry)
                                                                                                              // TODO: check if the two are of the same type first
                                                                                                              GeometryBase.GeometryEquals(current, other)
                                                                                                              ));

                        if (geometryEqualityPattern.All(equal => equal))
                        {
                            var firstModulePartRelativeCenter = module.PartCenters[0];
                            var modulePartsRelativeCentersRelativeToModulePivot = module.PartCenters.Select(center => center - firstModulePartRelativeCenter);

                            var currentModuleSlots = modulePartsRelativeCentersRelativeToModulePivot
                                                     .Zip(
                                module.PartNames,
                                (partCenter, partName) => new Slot(basePlane,
                                                                   currentRelativePosition + partCenter,
                                                                   module.PartDiagonal,
                                                                   false,
                                                                   new List <string>()
                            {
                                module.Name
                            },
                                                                   new List <string>()
                            {
                                partName
                            },
                                                                   0));
                            slots.AddRange(currentModuleSlots);
                        }
                    }
                }
            }

            if (!Slot.AreSlotLocationsUnique(slots))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Slot centers are not unique.");
            }

            DA.SetDataList(0, slots);
        }
示例#58
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // ===============================================================================================
            // Read input parameters
            // ===============================================================================================

            bool          iReset               = true;
            bool          iPlay                = false;
            bool          i3D                  = false;
            int           iCount               = 0;
            double        iTimestep            = 0.0;
            double        iNeighbourhoodRadius = 0.0;
            double        iAlignment           = 0.0;
            double        iCohesion            = 0.0;
            double        iSeparation          = 0.0;
            double        iSeparationDistance  = 0.0;
            List <Circle> iRepellers           = new List <Circle>();
            bool          iUseParallel         = false;
            bool          iUseRTree            = false;

            //bool iUseKDTree = false;
            //Brep AgentBox = new Brep();


            if (!DA.GetData("Reset", ref iReset))
            {
                return;
            }
            if (!DA.GetData("Play", ref iPlay))
            {
                return;
            }
            if (!DA.GetData("3D", ref i3D))
            {
                return;
            }
            if (!DA.GetData("Count", ref iCount))
            {
                return;
            }
            if (!DA.GetData("Timestep", ref iTimestep))
            {
                return;
            }
            if (!DA.GetData("Neighbourhood Radius", ref iNeighbourhoodRadius))
            {
                return;
            }
            if (!DA.GetData("Alignment", ref iAlignment))
            {
                return;
            }
            if (!DA.GetData("Cohesion", ref iCohesion))
            {
                return;
            }
            if (!DA.GetData("Separation", ref iSeparation))
            {
                return;
            }
            if (!DA.GetData("Separation Distance", ref iSeparationDistance))
            {
                return;
            }
            if (!DA.GetDataList("Repellers", iRepellers))
            {
                return;
            }
            if (!DA.GetData("Use Parallel", ref iUseParallel))
            {
                return;
            }
            if (!DA.GetData("Use R-Tree", ref iUseRTree))
            {
                return;
            }
            //if (!DA.GetData("Use KD-Tree", ref iUseKDTree)) return;
            //if (!DA.GetData("BoundingBox", ref AgentBox)) return;

            // ===============================================================================================
            // Validate Data
            // ===============================================================================================

            if (iAlignment < 0.0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Cohesion>Seperation for flocking");
                return;
            }

            if (iCohesion < 0.0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Cohesion>Seperation for flocking");
                return;
            }

            if (iSeparation < 0.0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Cohesion>Seperation for flocking");
                return;
            }


            // ===============================================================================================
            // Read input parameters
            // ===============================================================================================

            if (iReset || flockSystem == null)
            {
                flockSystem = new FlockSystem(iCount, i3D);
            }
            else
            {
                // ===============================================================================================
                // Assign the input parameters to the corresponding variables in the  "flockSystem" object
                // ===============================================================================================

                flockSystem.Timestep            = iTimestep;
                flockSystem.NeighbourhoodRadius = iNeighbourhoodRadius;
                flockSystem.AlignmentStrength   = iAlignment;
                flockSystem.CohesionStrength    = iCohesion;
                flockSystem.SeparationStrength  = iSeparation;
                flockSystem.SeparationDistance  = iSeparationDistance;
                flockSystem.Repellers           = iRepellers;
                flockSystem.UseParallel         = iUseParallel;
                flockSystem.UseRTree            = iUseRTree;


                // ===============================================================================
                // Update the flock
                // ===============================================================================

                if (iUseRTree)
                {
                    flockSystem.UpdateUsingRTree();
                }
                else
                {
                    flockSystem.Update();
                }

                if (iPlay)
                {
                    ExpireSolution(true);
                }
            }

            // ===============================================================================
            // Output the agent positions and velocities so we can see them on display
            // ===============================================================================

            List <GH_Point>  positions  = new List <GH_Point>();
            List <GH_Vector> velocities = new List <GH_Vector>();

            foreach (FlockAgent agent in flockSystem.Agents)
            {
                positions.Add(new GH_Point(agent.Position));
                velocities.Add(new GH_Vector(agent.Velocity));
            }

            DA.SetDataList("Positions", positions);
            DA.SetDataList("Velocities", velocities);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var run        = false;
            var geometry   = new List <IGH_GeometricGoo>();
            var exportPath = "";
            var atts       = new List <ObjectAttributes>();
            var layerNames = new List <string>();

            if (!DA.GetData("Run", ref run))
            {
                return;
            }
            if (!DA.GetDataList("Geometry to Export", geometry))
            {
                return;
            }
            if (!DA.GetData("Export Path", ref exportPath))
            {
                return;
            }
            var hasAtts      = DA.GetDataList("Attributes", atts);
            var hasLayerName = DA.GetDataList("Layer Names", layerNames);

            if (hasAtts && hasLayerName)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Supply EITHER layer names or attributes - not both. Since both are supplied, layer names will be ignored.");
            }

            if (!run)
            {
                var inputButtons = Params.Input[0].Sources.OfType <Grasshopper.Kernel.Special.GH_ButtonObject>();
                foreach (var btn in inputButtons)
                {
                    Grasshopper.Instances.ActiveCanvas.ActiveObject = null;
                }
                return;
            }

            var addedLayers   = new List <Layer>();
            var RhinoDocument = Rhino.RhinoDoc.ActiveDoc;
            var layerTable    = RhinoDocument.Layers;

            if (hasLayerName && !hasAtts)
            {
                foreach (var layerName in layerNames)
                {
                    int index;
                    //var index = RhinoDocument.Layers.Find(layerName, true);
                    Rhino.DocObjects.Layer layer = layerTable.FindName(layerName);
                    //if (index < 0)
                    //{
                    //    index = RhinoDocument.Layers.Add(layerName, Color.Black);
                    //    addedLayers.Add(RhinoDocument.Layers[index]);
                    //}
                    if (layer == null)
                    {
                        index = layerTable.Add(layerName, Color.Black);
                        addedLayers.Add(layerTable[index]);
                    }
                    else
                    {
                        index = layer.Index;
                    }

                    atts.Add(new ObjectAttributes
                    {
                        LayerIndex = index
                    });
                }
            }

            if (atts.Count == 0)
            {
                atts.Add(new ObjectAttributes());
            }

            //bake everything
            var bakedObjects = new List <ObjRef>();

            for (var i = 0; i < geometry.Count; i++)
            {
                var goo      = geometry[i];
                var bakeable = goo as IGH_BakeAwareData;
                if (bakeable != null)
                {
                    try
                    {
                        bakeable.BakeGeometry(RhinoDocument, atts[Math.Min(i, atts.Count - 1)], out Guid guid);
                        bakedObjects.Add(new ObjRef(guid));
                    }
                    catch
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some objects failed to bake.");
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some objects were not bakeable.");
                }
            }

            //select and export everything
            RhinoDocument.Objects.UnselectAll();
            RhinoDocument.Objects.Select(bakedObjects.Where(o => o.ObjectId != Guid.Empty));
            var    extension = Path.GetExtension(exportPath).ToUpper();
            String script;

            switch (extension)
            {
            case ".OBJ":
                script = $"-_Export \"{exportPath}\" _Enter _Enter _Enter";
                break;

            case ".AI":
            case ".3DS":
            case ".FBX":
                script = $"-_Export \"{exportPath}\" _Enter _Enter";
                break;

            case ".3DM":
                script = $"-_Export \"{exportPath}\" _Enter";
                break;

            case ".DWG":
            case ".SAT":
            default:
                script = $"-_Export \"{exportPath}\" Default _Enter";
                break;
            }

            RhinoApp.RunScript(script, false);
            bakedObjects.ForEach(o => RhinoDocument.Objects.Delete(o, true));
            foreach (var layer in addedLayers)
            {
                RhinoDocument.Layers.Delete(layer.Index, true);
            }
        }
示例#60
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)
        {
            List <Curve>            curves         = new List <Curve>();
            List <Polyline>         polylines      = new List <Polyline>();
            List <V2GPrintPolyline> printPolylines = new List <V2GPrintPolyline>();
            List <Point3d>          points         = new List <Point3d>();

            List <double> MaterialAmount = new List <double>();
            List <double> Speed          = new List <double>();
            List <int>    Toolhead       = new List <int>();
            List <double> MixPercentage  = new List <double>();

            if (!DA.GetDataList(0, curves))
            {
                return;
            }
            if (!DA.GetDataList(1, MaterialAmount))
            {
                return;
            }
            if (!DA.GetDataList(2, Speed))
            {
                return;
            }
            if (!DA.GetDataList(3, Toolhead))
            {
                return;
            }
            if (!DA.GetDataList(4, MixPercentage))
            {
                return;
            }

            foreach (Curve c in curves)
            {
                if (c.IsPolyline())
                {
                    Polyline pl;
                    if (c.TryGetPolyline(out pl))
                    {
                        polylines.Add(pl);

                        /*foreach (Point3d p in pl)
                         * {
                         *  points.Add(p);
                         * }*/
                    }
                }
            }

            int    idx             = 0;
            double _Speed          = Speed[0];
            double _MaterialAmount = MaterialAmount[0];
            int    _Head           = Toolhead[0];
            double _MixPercentage  = MixPercentage[0];

            foreach (Polyline pl in polylines)
            {
                if (Speed.Count - 1 >= idx)
                {
                    _Speed = Speed[idx];
                }
                if (MaterialAmount.Count - 1 >= idx)
                {
                    _MaterialAmount = MaterialAmount[idx];
                }
                if (Toolhead.Count - 1 >= idx)
                {
                    _Head = Toolhead[idx];
                }
                if (MixPercentage.Count - 1 >= idx)
                {
                    _MixPercentage = MixPercentage[idx];
                }

                V2GPrintPolyline ppl = new V2GPrintPolyline();
                foreach (Point3d p in pl)
                {
                    ppl.AddPrintPosition(new V2GPoint(p.X, p.Y, p.Z), _Speed, _MaterialAmount, _Head, _MixPercentage);
                }
                printPolylines.Add(ppl);
                idx++;
            }

            DA.SetDataList(0, printPolylines);
            DA.SetDataList(1, polylines);
        }