Example #1
0
        bool IGH_TypeHint.Cast(object data, out object target)
        {
            bool toReturn = base.Cast(data, out target);

              if (m_component.DocStorageMode == DocReplacement.DocStorage.AutomaticMarshal && target != null)
              {
            Type t = target.GetType();

            if (t == typeof (Line))
              target = new LineCurve((Line) target);

            else if (t == typeof (Arc))
              target = new ArcCurve((Arc) target);

            else if (t == typeof (Circle))
              target = new ArcCurve((Circle) target);

            else if (t == typeof (Ellipse))
              target = ((Ellipse) target).ToNurbsCurve();

            else if (t == typeof (Box))
              target = Brep.CreateFromBox((Box) target);

            else if (t == typeof (BoundingBox))
              target = Brep.CreateFromBox((BoundingBox) target);

            else if (t == typeof (Rectangle3d))
              target = ((Rectangle3d) target).ToNurbsCurve();

            else if (t == typeof (Polyline))
              target = new PolylineCurve((Polyline) target);
              }

              return toReturn;
        }
Example #2
0
        public void AddSlit(Point3d from, Point3d to, double thickness, double deeper)
        {
            var cut = new LineCurve(from, to);

            var points = Curves.SelectMany(o => SlitPoints(o, cut)).OrderBy(o => o.T).ToList();

            var yUnit = cut.Line.UnitTangent;
            var xUnit = Vector3d.CrossProduct(yUnit, Plane.Normal);

            for (int i = 1; i < points.Count; i += 1)
            {
                var slitA = points[i - 1];
                var slitB = points[i++];

                var a = slitA.Point;
                var b = slitB.Point;

                var mid = a + (b - a) / 2 + deeper * yUnit;
                var end = a - (b - a) / 2;

                var p00 = mid - thickness / 2 * xUnit;
                var p10 = p00 + thickness * xUnit;
                var p01 = end - thickness / 2 * xUnit;
                var p11 = p01 + thickness * xUnit;

                var slit = new[] { p00, p10, p11, p01, p00 }.ToPolygon(Plane, Unit);

                Slits.Add(slit);
            }
        }
Example #3
0
        bool IGH_TypeHint.Cast(object data, out object target)
        {
            bool toReturn = base.Cast(data, out target);

              if (toReturn && target != null)
              {
            Type t = target.GetType();

            if (t == typeof(Line))
              target = new LineCurve((Line)target);

            else if (t == typeof(Arc))
              target = new ArcCurve((Arc)target);

            else if (t == typeof(Circle))
              target = new ArcCurve((Circle)target);

            else if (t == typeof(Ellipse))
              target = ((Ellipse)target).ToNurbsCurve();

            else if (t == typeof(Box))
              target = Brep.CreateFromBox((Box)target);

            else if (t == typeof(BoundingBox))
              target = Brep.CreateFromBox((BoundingBox)target);

            else if (t == typeof(Rectangle3d))
              target = ((Rectangle3d)target).ToNurbsCurve();

            else if (target is Polyline)
              target = new PolylineCurve((Polyline)target);
              }

              return toReturn;
        }
Example #4
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Point3d startPoint = new Rhino.Geometry.Point3d();
            DA.GetData(0, ref startPoint);

            Rhino.Geometry.Vector3d directionVector = new Rhino.Geometry.Vector3d();
            DA.GetData(1, ref directionVector);

            double lineDistance = 0;

            DA.GetData(2, ref lineDistance);

            double startingVectorLength = directionVector.Length;
            double scalingFactor        = lineDistance / startingVectorLength;

            Rhino.Geometry.Vector3d newDirectionVector = directionVector * scalingFactor;

            double deltaX = newDirectionVector.X;
            double deltaY = newDirectionVector.Y;

            double baseX = startPoint.X;
            double baseY = startPoint.Y;

            Rhino.Geometry.Point2d outputCurveEndPoint   = new Rhino.Geometry.Point2d(baseX + deltaX, baseY + deltaY);
            Rhino.Geometry.Point2d outputCurveStartPoint = new Rhino.Geometry.Point2d(baseX - deltaX, baseY - deltaY);

            Rhino.Geometry.Curve outputCurve = new Rhino.Geometry.LineCurve(outputCurveStartPoint, outputCurveEndPoint) as Rhino.Geometry.Curve;

            DA.SetData(0, outputCurve);
        }
    private static double? MaxZIntersectionMethod(Brep brep, double x, double y, double tolerance)
    {
        double? max_z = null;

        var bbox = brep.GetBoundingBox(true);
        var max_dist_from_xy = (from corner in bbox.GetCorners() select corner.Z)
                            // furthest Z from XY plane.
                            // Here you might be tempted to use .Max() to get the largest Z value but that doesn't work because
                            // Z might be negative.  This custom aggregate returns the max Z independant of the sign.  If it had a name
                            // it could be MaxAbs()
                            .Aggregate((z1, z2) => Math.Abs(z1) > Math.Abs(z2) ? z1 : z2);
        // multiply distance by 2 to make sure line intersects completely
        var line_curve = new LineCurve(new Point3d(x, y, 0), new Point3d(x, y, max_dist_from_xy*2));

        Curve[] overlap_curves;
        Point3d[] inter_points;
        if (Intersection.CurveBrep(line_curve, brep, tolerance, out overlap_curves, out inter_points))
        {
          if (overlap_curves.Length > 0 || inter_points.Length > 0)
          {
        // grab all the points resulting frem the intersection.
        //    1st set: points from overlapping curves,
        //    2nd set: points when there was no overlap
        //    .Aggregate: furthest Z from XY plane.
        max_z = (from c in overlap_curves select Math.Abs(c.PointAtEnd.Z) > Math.Abs(c.PointAtStart.Z) ? c.PointAtEnd.Z : c.PointAtStart.Z)
                .Union
                (from p in inter_points select p.Z)
                 // Here you might be tempted to use .Max() to get the largest Z value but that doesn't work because
                 // Z might be negative.  This custom aggregate returns the max Z independant of the sign.  If it had a name
                 // it could be MaxAbs()
                .Aggregate((z1, z2) => Math.Abs(z1) > Math.Abs(z2) ? z1 : z2);
          }
        }
        return max_z;
    }
 /// <summary>
 /// Constructs a new surface of revolution from a generatrix line and an axis.
 /// <para>This overload accepts a slice start and end angles.</para>
 /// <para>Results can be (truncated) cones, cylinders and circular hyperboloids, or can fail.</para>
 /// </summary>
 /// <param name="revoluteLine">A generatrix.</param>
 /// <param name="axisOfRevolution">An axis.</param>
 /// <param name="startAngleRadians">An angle in radias for the start.</param>
 /// <param name="endAngleRadians">An angle in radias for the end.</param>
 /// <returns>A new surface of revolution, or null if any of the inputs is invalid or on error.</returns>
 public static RevSurface Create(Line revoluteLine, Line axisOfRevolution, double startAngleRadians, double endAngleRadians)
 {
   using (LineCurve lc = new LineCurve(revoluteLine))
   {
     return Create(lc, axisOfRevolution, startAngleRadians, endAngleRadians);
   }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="LineCurve"/> class, by
 /// copying values from another linear curve.
 /// </summary>
 public LineCurve(LineCurve other)
 {
   IntPtr pOther = IntPtr.Zero;
   if( null != other )
     pOther = other.ConstPointer();
   IntPtr ptr = UnsafeNativeMethods.ON_LineCurve_New(pOther);
   ConstructNonConstObject(ptr);
 }
Example #8
0
        /***************************************************/

        public static bool IsEqual(this BHG.Line bhLine, RHG.LineCurve rhLine, double tolerance = BHG.Tolerance.Distance)
        {
            if (bhLine == null & rhLine == null)
            {
                return(true);
            }

            return(bhLine.IsEqual(rhLine.Line, tolerance));
        }
Example #9
0
        /***************************************************/

        public static BHG.Line FromRhino(this RHG.LineCurve line)
        {
            if (line == null)
            {
                return(null);
            }

            return(new BHG.Line {
                Start = line.PointAtStart.FromRhino(), End = line.PointAtEnd.FromRhino()
            });
        }
Example #10
0
 /// <summary>
 /// Convert a Rhino line to a Nucleus one
 /// </summary>
 /// <param name="line">The line to be converted</param>
 /// <returns>A new line if the input is valid, else null</returns>
 public static Line Convert(RC.LineCurve line)
 {
     if (line.IsValid)
     {
         return(new Line(Convert(line.PointAtStart), Convert(line.PointAtEnd)));
     }
     else
     {
         return(null);
     }
 }
  private static Rhino.Geometry.NurbsCurve GetSpirial1()
  {
    var railStart = new Rhino.Geometry.Point3d(0, 0, 0);
    var railEnd = new Rhino.Geometry.Point3d(0, 0, 10);
    var railCurve = new Rhino.Geometry.LineCurve(railStart, railEnd);

    double t0 = railCurve.Domain.Min;
    double t1 = railCurve.Domain.Max;

    var radiusPoint = new Rhino.Geometry.Point3d(1, 0, 0);

    return Rhino.Geometry.NurbsCurve.CreateSpiral(railCurve, t0, t1, radiusPoint, 1, 10, 1.0, 1.0, 12);
  }
Example #12
0
    private static Rhino.Geometry.NurbsCurve GetSpirial1()
    {
        var railStart = new Rhino.Geometry.Point3d(0, 0, 0);
        var railEnd   = new Rhino.Geometry.Point3d(0, 0, 10);
        var railCurve = new Rhino.Geometry.LineCurve(railStart, railEnd);

        double t0 = railCurve.Domain.Min;
        double t1 = railCurve.Domain.Max;

        var radiusPoint = new Rhino.Geometry.Point3d(1, 0, 0);

        return(Rhino.Geometry.NurbsCurve.CreateSpiral(railCurve, t0, t1, radiusPoint, 1, 10, 1.0, 1.0, 12));
    }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Point3d M = Point3d.Origin;
            Point3d A = Point3d.Origin;
            Point3d B = Point3d.Origin;

            DA.GetData<Point3d>(0, ref M);
            DA.GetData<Point3d>(1, ref A);
            DA.GetData<Point3d>(2, ref B);

            LineCurve AB = new LineCurve(A, B);
            double t;
            AB.ClosestPoint(M, out t);

            DA.SetData(0, Utils.ClosestPointOnLine(M, A, B));
            DA.SetData(1, AB.PointAt(t));
        }
Example #14
0
        /***************************************************/

        public static BHG.IGeometry FromRhino(this RHG.Extrusion extrusion)
        {
            if (extrusion == null)
            {
                return(null);
            }

            RHG.LineCurve line    = extrusion.PathLineCurve();
            BHG.Vector    extrVec = BH.Engine.Geometry.Create.Vector(line.PointAtStart.FromRhino(), line.PointAtEnd.FromRhino());

            List <BHG.Extrusion> extrs = new List <BHG.Extrusion>();

            // Exploits the fact that GetWireframe returns first the "profile" curves of the extrusion.
            var profileCurves = extrusion.GetWireframe();

            for (int i = 0; i < extrusion.ProfileCount; i++)
            {
                var           profileConverted = profileCurves.ElementAt(i).FromRhino();
                BHG.Extrusion extr             = BH.Engine.Geometry.Create.Extrusion(profileConverted, extrVec, extrusion.IsCappedAtBottom && extrusion.IsCappedAtTop);

                extrs.Add(extr);
            }


            if (extrs.Count == 1)
            {
                return(extrs[0]);
            }

            if (extrs.Count > 1)
            {
                return new BH.oM.Geometry.CompositeGeometry()
                       {
                           Elements = extrs.OfType <BH.oM.Geometry.IGeometry>().ToList()
                       }
            }
            ;

            BH.Engine.Reflection.Compute.RecordError("Could not convert the extrusion.");
            return(null);
        }
    public static Rhino.Commands.Result AddTruncatedCone(Rhino.RhinoDoc doc)
    {
        Point3d bottom_pt = new Point3d(0,0,0);
        const double bottom_radius = 2;
        Circle bottom_circle = new Circle(bottom_pt, bottom_radius);

        Point3d top_pt = new Point3d(0,0,10);
        const double top_radius = 6;
        Circle top_circle = new Circle(top_pt, top_radius);

        LineCurve shapeCurve = new LineCurve(bottom_circle.PointAt(0), top_circle.PointAt(0));
        Line axis = new Line(bottom_circle.Center, top_circle.Center);
        RevSurface revsrf = RevSurface.Create(shapeCurve, axis);
        Brep tcone_brep = Brep.CreateFromRevSurface(revsrf, true, true);
        if( doc.Objects.AddBrep(tcone_brep) != Guid.Empty )
        {
          doc.Views.Redraw();
          return Rhino.Commands.Result.Success;
        }
        return Rhino.Commands.Result.Failure;
    }
        // ====================================================================
        //---- END CONSTRUCTOR-------------------------------------------------
        // ====================================================================
        // Added by Gene
        public void RunSingleSrf()
        {
            Point3d pLeft = curvesLeft.PointAtStart;
            Point3d pRight = curvesRight.PointAtStart;
            LineCurve rail = new LineCurve(pLeft, pRight);

            Point3d pLeft2 = curvesLeft.PointAtEnd;
            Point3d pRight2 = curvesRight.PointAtEnd;
            LineCurve rail2 = new LineCurve(pLeft2, pRight2);

            loop = Brep.CreateFromSweep(curvesLeft, curvesRight, new List<Curve>() { rail, rail2 }, false, documentTolerance)[0];
            //loop = Brep.CreateFromLoftRebuild(new List<Curve>() { curvesLeft, curvesRight }, Point3d.Unset, Point3d.Unset, LoftType.Normal, false, 50)[0];
            //loop = Brep.CreateFromLoft(new List<Curve>() { curvesLeft, curvesRight }, Point3d.Unset, Point3d.Unset, LoftType.Normal, false )[0];

            Brep[] loops;
            double offsetAmount = 0.002;
            //double offsetAmount2 = 0.02;
            Vector3d normal1, normal2;

            normal1 = Vector3d.CrossProduct(cuttingPts[0] - cuttingPts[4], cuttingPts[0] - cuttingPts[2]);
            normal2 = Vector3d.CrossProduct(cuttingPts[1] - cuttingPts[3], cuttingPts[1] - cuttingPts[5]);

            Point3d A_ = cuttingPts[7] + offsetAmount * normal2;
            Point3d B_ = cuttingPts[6] + offsetAmount * normal1;

            //Brep cutter1 = Brep.CreateFromCornerPoints(cuttingPts[0], cuttingPts[1], cuttingPts[2], cuttingPts[3], documentTolerance);
            //Brep cutter2 = Brep.CreateFromCornerPoints(cuttingPts[0], cuttingPts[1], cuttingPts[4], cuttingPts[5], documentTolerance);

            loops = loop.Trim(new Plane(A_, cuttingPts[1], cuttingPts[3]), documentTolerance);
            //loops = loop.Trim(cutter1, documentTolerance);

            if (loops.Length > 0) loop = loops[0];
            //else { return; }

            loops = loop.Trim(new Plane(A_, cuttingPts[5], cuttingPts[1]), documentTolerance);

            if (loops.Length > 0) loop = loops[0];
            //else { return; }

            loops = loop.Trim(new Plane(B_, cuttingPts[2], cuttingPts[0]), documentTolerance);
            if (loops.Length > 0) loop = loops[0];

            loops = loop.Trim(new Plane(B_, cuttingPts[0], cuttingPts[4]), documentTolerance);
            if (loops.Length > 0) loop = loops[0];
        }
Example #17
0
        /***************************************************/

        public static void RenderRhinoWires(RHG.LineCurve line, Rhino.Display.DisplayPipeline pipeline, Color bhColour, int thickness)
        {
            pipeline.DrawLine(line.Line, bhColour, thickness);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and 
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // 1. Retrieve and validate data
            var cell = new UnitCell();
            double radius = 0;
            double height = 0;
            int nU = 0;
            int nV = 0;
            int nW = 0;
            bool morphed = false;

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

            if (!cell.isValid) { return; }
            if (radius == 0) { return; }
            if (height == 0) { return; }
            if (nU == 0) { return; }
            if (nV == 0) { return; }
            if (nW == 0) { return; }

            // 2. Initialize the lattice
            var lattice = new Lattice();
            // Will contain the morphed uv spaces (as surface-surface, surface-axis or surface-point)
            var spaceTree = new DataTree<GeometryBase>(); 
            
            // 3. Define cylinder
            Plane basePlane = Plane.WorldXY;
            Surface cylinder = ( new Cylinder(new Circle(basePlane, radius), height) ).ToNurbsSurface();
            cylinder = cylinder.Transpose();
            LineCurve axis = new LineCurve(basePlane.Origin, basePlane.Origin + height*basePlane.ZAxis);

            // 4. Package the number of cells in each direction into an array
            float[] N = new float[3] { nU, nV, nW };

            // 5. Normalize the UV-domain
            Interval unitDomain = new Interval(0, 1);
            cylinder.SetDomain(0, unitDomain); // surface u-direction
            cylinder.SetDomain(1, unitDomain); // surface v-direction
            axis.Domain = unitDomain;

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

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

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

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

                            if (isOutsideCell || isOutsideSpace)
                            {
                                nodeList.Add(null);
                            }
                            else
                            {
                                Point3d pt1, pt2;
                                Vector3d[] derivatives;

                                // Construct z-position vector
                                Vector3d vectorZ = height * basePlane.ZAxis * uvw[0] / N[0];
                                // Compute pt1 (on axis)
                                pt1 = basePlane.Origin + vectorZ;
                                // Compute pt2 (on surface)
                                cylinder.Evaluate(uvw[0] / N[0], uvw[1] / N[1], 2, out pt2, out derivatives);       

                                // Create vector joining these two points
                                Vector3d wVect = pt2 - pt1;
                                // Instantiate new node
                                var newNode = new LatticeNode(pt1 + wVect * uvw[2] / N[2]);
                                // Add new node to tree
                                nodeList.Add(newNode); 
                            }
                        }
                    }

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

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

            // 9. Set output
            DA.SetDataList(0, lattice.Struts);            
        }
Example #19
0
        public static void Main()
        {
            List<Curve> L = new List<Curve>();

            int S = 0;
            List<double> Rs = new List<double>();
            List<double> Re = new List<double>();
            double D = 0;
            double ND = 0;
            int RP = 0;
            bool O = false;

            double Sides = (double)S;
            double Tol = RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;

            List<ExoNode> ExoNodes = new List<ExoNode>();
            List<ExoStrut> ExoStruts = new List<ExoStrut>();

            //ExoNodes.Add(new ExoNode());
            Rhino.Collections.Point3dList NodeLookup = new Rhino.Collections.Point3dList();
            int IdxL = 0;

            ExoNodes.Add(new ExoNode(L[0].PointAtStart));
            NodeLookup.Add(ExoNodes[0].Point3d);

            //cycle through each input curve to find unique nodes and assign struts to each node
            foreach (Curve StartL in L)
            {
                //strut as linecurve, and
                LineCurve StartLC = new LineCurve(StartL.PointAtStart, StartL.PointAtEnd);
                Plane StartPlane;
                StartLC.PerpendicularFrameAt(0, out StartPlane);

                //create paired struts for each input curve
                for (int I = 0; I <= 1; I++)
                {

                    Point3d TestPoint;
                    double StrutRadius;
                    bool IsEnd;

                    //set variables based on whether the strut is the start or end strut
                    if (I == 0)
                    {
                        IsEnd = false;
                        TestPoint = StartL.PointAtStart;
                        if (Rs.Count - 1 > IdxL) StrutRadius = Rs[IdxL];
                        else StrutRadius = Rs.Last();
                    }
                    else
                    {
                        IsEnd = true;
                        TestPoint = StartL.PointAtEnd;
                        if (Re.Count - 1 > IdxL) StrutRadius = Re[IdxL];
                        else StrutRadius = Re.Last();
                    }

                    //register new nodes
                    int TestIndex = NodeLookup.ClosestIndex(TestPoint);
                    int NodeIndex = -1;
                    if (ExoNodes[TestIndex].Point3d.DistanceTo(TestPoint) < Tol)
                    {
                        NodeIndex = TestIndex;
                        ExoNodes[TestIndex].StrutIndices.Add(ExoStruts.Count);
                    }
                    else
                    {
                        NodeIndex = ExoNodes.Count;
                        ExoNodes.Add(new ExoNode(TestPoint));
                        ExoNodes.Last().StrutIndices.Add(ExoStruts.Count);
                    }

                    int LastStrut = ExoNodes[NodeIndex].StrutIndices.Last();
                    //register new struts
                    ExoStruts.Add(new ExoStrut(IsEnd, StrutRadius, StrutRadius / Math.Cos(Math.PI / Sides),
                        StartLC, StartPlane));

                    //test each new strut in a given node against all of the other struts in a given node to calculate both local
                    //and global vertex offsets, both for hulling operation and for relocating vertices post-hull
                    if (ExoNodes[NodeIndex].StrutIndices.Count > 1)
                    {
                        foreach (int StrutIndex in ExoNodes[NodeIndex].StrutIndices)
                        {
                            if (StrutIndex != LastStrut)
                            {
                                double Radius = Math.Max(ExoStruts[LastStrut].HullRadius, ExoStruts[StrutIndex].HullRadius);
                                double Theta = Vector3d.VectorAngle(ExoStruts[LastStrut].Normal, ExoStruts[StrutIndex].Normal);
                                double TestOffset = Radius * Math.Cos(Theta * 0.5) / Math.Sin(Theta * 0.5);
                                if (TestOffset > ExoNodes[NodeIndex].HullOffset) ExoNodes[NodeIndex].HullOffset = TestOffset;
                                if (ExoNodes[NodeIndex].MaxRadius < Radius) ExoNodes[NodeIndex].MaxRadius = Radius;

                                double Offset1 = 0;
                                double Offset2 = 0;

                                ExoTools.OffsetCalculator(Theta, ExoStruts[LastStrut].HullRadius,
                                    ExoStruts[StrutIndex].HullRadius, ref Offset1, ref Offset2);

                                Offset1 = Math.Max(ND, Offset1);
                                Offset2 = Math.Max(ND, Offset1);

                                if (ExoStruts[LastStrut].FixOffset < Offset1) ExoStruts[LastStrut].FixOffset = Offset1;
                                if (ExoStruts[StrutIndex].FixOffset < Offset1) ExoStruts[StrutIndex].FixOffset = Offset2;

                                double KnuckleMinSet = Math.Min(ExoStruts[LastStrut].Radius, ExoStruts[StrutIndex].Radius);
                                if (ExoNodes[NodeIndex].KnuckleMin < Tol || ExoNodes[NodeIndex].KnuckleMin > KnuckleMinSet) ExoNodes[NodeIndex].KnuckleMin = KnuckleMinSet;
                            }
                        }
                    }
                                    }
                IdxL +=1;
            }

            foreach (ExoNode HullNode in ExoNodes)
            {
                if (HullNode.StrutIndices.Count == 2)
                {
                    if (Vector3d.VectorAngle(ExoStruts[HullNode.StrutIndices[0]].Normal, ExoStruts[HullNode.StrutIndices[1]].Normal) - Math.PI < RhinoDoc.ActiveDoc.ModelAbsoluteTolerance)
                    { HullNode.HullOffset = HullNode.MaxRadius * 0.5; }
                }

                for (int HV = 0; HV < S; HV++)
                {
                    foreach (int StrutIdx in HullNode.StrutIndices)
                    {
                        if (HV == 0)
                        {
                            ExoStruts[StrutIdx].HullPlane.Origin = ExoStruts[StrutIdx].HullPlane.Origin + (ExoStruts[StrutIdx].Normal * HullNode.HullOffset);
                            HullNode.HullPoints.Add(HullNode.Point3d + (-ExoStruts[StrutIdx].Normal * (HullNode.HullOffset *0.5)));
                            HullNode.HullVertexStrut.Add(-1);
                        }
                        HullNode.HullPoints.Add(ExoStruts[StrutIdx].HullPlane.PointAt(Math.Cos((HV / Sides) * Math.PI * 2) * ExoStruts[StrutIdx].Radius, Math.Sin((HV / Sides) * Math.PI * 2) * ExoStruts[StrutIdx].Radius));
                        HullNode.HullVertexStrut.Add(StrutIdx);
                    }
                }

                HullNode.HullVertexLookup.AddRange(HullNode.HullPoints);

            }
        }
Example #20
0
    internal static GeometryBase CreateGeometryHelper(IntPtr pGeometry, object parent, int subobject_index)
    {
      if (IntPtr.Zero == pGeometry)
        return null;

      int type = UnsafeNativeMethods.ON_Geometry_GetGeometryType(pGeometry);
      if (type < 0)
        return null;
      GeometryBase rc = null;

      switch (type)
      {
        case idxON_Curve: //1
          rc = new Curve(pGeometry, parent, subobject_index);
          break;
        case idxON_NurbsCurve: //2
          rc = new NurbsCurve(pGeometry, parent, subobject_index);
          break;
        case idxON_PolyCurve: // 3
          rc = new PolyCurve(pGeometry, parent, subobject_index);
          break;
        case idxON_PolylineCurve: //4
          rc = new PolylineCurve(pGeometry, parent, subobject_index);
          break;
        case idxON_ArcCurve: //5
          rc = new ArcCurve(pGeometry, parent, subobject_index);
          break;
        case idxON_LineCurve: //6
          rc = new LineCurve(pGeometry, parent, subobject_index);
          break;
        case idxON_Mesh: //7
          rc = new Mesh(pGeometry, parent);
          break;
        case idxON_Point: //8
          rc = new Point(pGeometry, parent);
          break;
        case idxON_TextDot: //9
          rc = new TextDot(pGeometry, parent);
          break;
        case idxON_Surface: //10
          rc = new Surface(pGeometry, parent);
          break;
        case idxON_Brep: //11
          rc = new Brep(pGeometry, parent);
          break;
        case idxON_NurbsSurface: //12
          rc = new NurbsSurface(pGeometry, parent);
          break;
        case idxON_RevSurface: //13
          rc = new RevSurface(pGeometry, parent);
          break;
        case idxON_PlaneSurface: //14
          rc = new PlaneSurface(pGeometry, parent);
          break;
        case idxON_ClippingPlaneSurface: //15
          rc = new ClippingPlaneSurface(pGeometry, parent);
          break;
        case idxON_Annotation2: // 16
          rc = new AnnotationBase(pGeometry, parent);
          break;
        case idxON_Hatch: // 17
          rc = new Hatch(pGeometry, parent);
          break;
        case idxON_TextEntity2: //18
          rc = new TextEntity(pGeometry, parent);
          break;
        case idxON_SumSurface: //19
          rc = new SumSurface(pGeometry, parent);
          break;
        case idxON_BrepFace: //20
          {
            int faceindex = -1;
            IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref faceindex);
            if (pBrep != IntPtr.Zero && faceindex >= 0)
            {
              Brep b = new Brep(pBrep, parent);
              rc = b.Faces[faceindex];
            }
          }
          break;
        case idxON_BrepEdge: // 21
          {
            int edgeindex = -1;
            IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref edgeindex);
            if (pBrep != IntPtr.Zero && edgeindex >= 0)
            {
              Brep b = new Brep(pBrep, parent);
              rc = b.Edges[edgeindex];
            }
          }
          break;
        case idxON_InstanceDefinition: // 22
          rc = new InstanceDefinitionGeometry(pGeometry, parent);
          break;
        case idxON_InstanceReference: // 23
          rc = new InstanceReferenceGeometry(pGeometry, parent);
          break;
#if USING_V5_SDK
        case idxON_Extrusion: //24
          rc = new Extrusion(pGeometry, parent);
          break;
#endif
        case idxON_LinearDimension2: //25
          rc = new LinearDimension(pGeometry, parent);
          break;
        case idxON_PointCloud: // 26
          rc = new PointCloud(pGeometry, parent);
          break;
        case idxON_DetailView: // 27
          rc = new DetailView(pGeometry, parent);
          break;
        case idxON_AngularDimension2: // 28
          rc = new AngularDimension(pGeometry, parent);
          break;
        case idxON_RadialDimension2: // 29
          rc = new RadialDimension(pGeometry, parent);
          break;
        case idxON_Leader: // 30
          rc = new Leader(pGeometry, parent);
          break;
        case idxON_OrdinateDimension2: // 31
          rc = new OrdinateDimension(pGeometry, parent);
          break;
        case idxON_Light: //32
          rc = new Light(pGeometry, parent);
          break;
        case idxON_PointGrid: //33
          rc = new Point3dGrid(pGeometry, parent);
          break;
        case idxON_MorphControl: //34
          rc = new MorphControl(pGeometry, parent);
          break;
        case idxON_BrepLoop: //35
          {
            int loopindex = -1;
            IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref loopindex);
            if (pBrep != IntPtr.Zero && loopindex >= 0)
            {
              Brep b = new Brep(pBrep, parent);
              rc = b.Loops[loopindex];
            }
          }
          break;
        case idxON_BrepTrim: // 36
          {
            int trimindex = -1;
            IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref trimindex);
            if (pBrep != IntPtr.Zero && trimindex >= 0)
            {
              Brep b = new Brep(pBrep, parent);
              rc = b.Trims[trimindex];
            }
          }
          break;
        default:
          rc = new UnknownGeometry(pGeometry, parent, subobject_index);
          break;
      }

      return rc;
    }
        private List <Rhino.Geometry.Curve> CreateRhinoCurves(string selectedLineList)
        {
            //defining the list with lines that will have to be returned later on
            List <Rhino.Geometry.Curve> rhOutputCurves = new List <Rhino.Geometry.Curve>();


            // Gets interface to running RFEM application.
            app = Marshal.GetActiveObject("RFEM5.Application") as IApplication;
            // Locks RFEM licence
            app.LockLicense();

            // Gets interface to active RFEM model.
            model = app.GetActiveModel();

            // Gets interface to model data.
            IModelData data = model.GetModelData();

            //Create new array for Rhino Curve objects
            List <Rhino.Geometry.Curve> rhinoLineList = new List <Rhino.Geometry.Curve>();

            //Create new array for Rhino point objects
            List <Rhino.Geometry.Point3d> rhinoPointArray = new List <Rhino.Geometry.Point3d>();


            try
            {
                for (int index = 0; index < data.GetLineCount(); index++)
                {
                    Dlubal.RFEM5.Line currentLine = data.GetLine(index, ItemAt.AtIndex).GetData();

                    // the code below converts string describing nodes used in line definition into
                    // list fo all used node numbers. e.g. converts "1,2,4-7,9" into "1,2,4,5,6,7,9"
                    string     lineNodes = currentLine.NodeList;
                    List <int> nodesList = new List <int>();

                    foreach (string tempLineNode in lineNodes.Split(','))
                    {
                        if (tempLineNode.Contains('-'))
                        {
                            string[] tempLineNodeDashes = new string[2];
                            tempLineNodeDashes = tempLineNode.Split('-');
                            int startNumber = Int32.Parse(tempLineNodeDashes[0]);
                            int endNumber   = Int32.Parse(tempLineNodeDashes[1]);

                            for (int i = startNumber; i <= endNumber; i++)
                            {
                                nodesList.Add(i);
                            }
                        }
                        else
                        {
                            nodesList.Add(Int32.Parse(tempLineNode));
                        }
                    }

                    //currently component only reads "polyline" type from RFEM, i.e. straight lines

                    if (currentLine.Type == LineType.PolylineType)
                    {
                        for (int i = 0; i < nodesList.Count - 1; i++)
                        {
                            //getting data for start point and end point from RFEM
                            Dlubal.RFEM5.Node rfemStartPoint = data.GetNode(nodesList[i], ItemAt.AtNo).GetData();
                            Dlubal.RFEM5.Node rfemEndPoint   = data.GetNode(nodesList[i + 1], ItemAt.AtNo).GetData();

                            //creating Rhino Objects
                            Point3d rhinoStartPoint = new Point3d(rfemStartPoint.X, rfemStartPoint.Y, rfemStartPoint.Z);
                            Point3d rhinoEndPoint   = new Point3d(rfemEndPoint.X, rfemEndPoint.Y, rfemEndPoint.Z);

                            Rhino.Geometry.LineCurve currentRhinoCurve = new Rhino.Geometry.LineCurve(rhinoStartPoint, rhinoEndPoint);

                            rhOutputCurves.Add(currentRhinoCurve);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // Releases interface to RFEM model.
            model = null;

            // Unlocks licence and releases interface to RFEM application.
            if (app != null)
            {
                app.UnlockLicense();
                app = null;
            }

            // Cleans Garbage Collector and releases all cached COM interfaces.
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();

            //list with all Rhino Curves is prepared for output
            return(rhOutputCurves);
        }
Example #22
0
        public bool lineWithinRegion(Brep region, LineCurve line)
        {
            //Check if line is completely within a planar region
            int agreement = 0;

            Point3d midPt = line.PointAt((line.Domain.Max-line.Domain.Min)/2);

            foreach (BrepLoop loop in region.Loops)
            {
                if (loop.LoopType == BrepLoopType.Outer)
                {
                    Curve iLoop = loop.To3dCurve();

                    PointContainment ptcontain = iLoop.Contains(midPt);

                    if (ptcontain != PointContainment.Inside)
                    {
                        agreement += 1;
                    }
                }

                if (loop.LoopType == BrepLoopType.Inner)
                {
                    Curve iLoop = loop.To3dCurve();

                    PointContainment ptcontain = iLoop.Contains(midPt);

                    if (ptcontain != PointContainment.Outside)
                    {
                        agreement += 1;
                    }
                }

                if (loop.LoopType == BrepLoopType.Slit)
                {
                    break;
                }

                if (loop.LoopType == BrepLoopType.Unknown)
                {
                    break;
                }
            }

            if (agreement == 0)
            {
                bool inside = true;
                return inside;
            }
            else
            {
                bool inside = false;
                return inside;
            }
        }
Example #23
0
 public override GeometryBase GetGeometry(GH_Model model)
 {
     LineCurve line = new LineCurve(model.Points[Start.Index], model.Points[End.Index]);
     return line;
 }
Example #24
0
 public override GeometryBase GetDeformedGeometry(GH_Model model)
 {
     LineCurve line = new LineCurve(model.GetDisplacedPoint(Start.Index), model.GetDisplacedPoint(End.Index));
     return line;
 }
Example #25
0
        protected override Rhino.Commands.Result RunCommand(RhinoDoc doc, Rhino.Commands.RunMode mode)
        {
            nishanchiPlugin pluginObj = ((nishanchiPlugin)this.PlugIn);

            Boolean selectedObjectIsBrep = false;
            Boolean selectedObjectIsCurve = false;

            if (!pluginObj.trackerConnected)
            {
                RhinoApp.WriteLine("Tracker disconnected");
                return Rhino.Commands.Result.Failure;
            }
            connectKbEvt();

            //Ask the user to select Breps to print.
            //Result rc = Rhino.Input.RhinoGet.GetMultipleObjects("Select the surfaces to print",
            //false, Rhino.DocObjects.ObjectType.Surface, out objrefs);

            Rhino.Input.Custom.GetObject go = new Rhino.Input.Custom.GetObject();

            go.SetCommandPrompt("Select the entity to print");
            go.GroupSelect = true;

            //Set this to go.GetMultiple(0,0) if you want to allow multiple entities to be selected
            go.GetMultiple(0, 1);

            Result rc = go.CommandResult();

            if (rc != Rhino.Commands.Result.Success)
            {
                disconnectKbEvt();
                return rc;
            }

            List<Rhino.Geometry.Brep> breps = new List<Rhino.Geometry.Brep>();
            List<Rhino.Geometry.Curve> curves = new List<Rhino.Geometry.Curve>();

            for (int i = 0; i < go.ObjectCount; i++)
            {
                ObjRef tmpRef = new ObjRef(go.Object(i).ObjectId);
                Rhino.Geometry.Brep brep = tmpRef.Brep();
                if (brep != null)
                {
                    breps.Add(brep);
                    selectedObjectIsBrep = true;
                }

                Rhino.Geometry.Curve curve = tmpRef.Curve();
                if (curve != null)
                {
                    curves.Add(curve);
                    selectedObjectIsCurve = true;
                }

            }
            if (selectedObjectIsBrep)
                RhinoApp.WriteLine("Selected " + breps.Count + " surfaces! Good! No, not, really, I'm just a program, I couldn't care less.");

            if (selectedObjectIsCurve)
                RhinoApp.WriteLine("Selected " + curves.Count + " curves! Good! No, not, really, I'm just a program, I couldn't care less.");

            createEntities(doc);

            fastrak trackerObj = pluginObj.trackerObj;
            int numPoints = 0;
            int numIntersections = 0;
            Boolean retval;

            RhinoApp.WriteLine(string.Format("Starting continuous mode on the tracker."));
            pluginObj.trackerObj.setContinuous();
            RhinoApp.WriteLine(string.Format("Printing mode enabled now."));

            Curve[] intersectionCurves;
            Point3d[] intersectionPoints;

            running = true;
            while (running)
            {
                retval = trackerObj.readFrame();
                if (retval)
                {
                    //q0,q1,q2,q3 Quaternion begin
                    //Compute the rotation matrix
                    rxTxTx = new Point3d(trackerObj.x, trackerObj.y, trackerObj.z);
                    orientationQuat = new Quaternion(trackerObj.q0, trackerObj.q1, trackerObj.q2, trackerObj.q3);
                    orientationQuat.GetRotation(out angle, out axis);
                    rotMat = Transform.Rotation(angle, axis, origin);

                    // Compute the new positions for the nozzlePoints and also compute the new lines
                    for (int i = 0; i < numNozzles; i++)
                    {
                        nozzleStartPointRxTx[i] = rotMat * nozzleStartPointRxRx[i];
                        nozzleStartPointTxTx[i] = nozzleStartPointRxTx[i] + rxTxTx;

                        nozzleEndPointRxTx[i] = rotMat * nozzleEndPointRxRx[i];
                        nozzleEndPointTxTx[i] = nozzleEndPointRxTx[i] + rxTxTx;

                        nozzleLinesTx[i] = new Line(nozzleStartPointTxTx[i], nozzleEndPointTxTx[i]);
                        nozzleCurves[i] = new LineCurve(nozzleLinesTx[i]);
                    }

                    numIntersections = 0;
                    if (selectedObjectIsBrep)
                    {
                        for (int i = 0; i < numNozzles; i++)
                        {
                            foreach (Brep b in breps)
                            {
                                try
                                {
                                    Intersection.CurveBrep(nozzleCurves[i], b, nozzleTolerance, out intersectionCurves, out intersectionPoints);
                                    if (intersectionPoints.Length > 0)
                                    {
                                        intersectionsBits[i] = 1;
                                        numIntersections++;
                                    }
                                    else
                                    {
                                        intersectionsBits[i] = 0;
                                    }
                                }
                                catch (Exception e)
                                {
                                    RhinoApp.WriteLine(e.Message);
                                }
                            }
                        }
                    }

                    if (selectedObjectIsCurve)
                    {
                        for (int i = 0; i < numNozzles; i++)
                        {
                            foreach (Curve c in curves)
                            {
                                try
                                {
                                    var events = Intersection.CurveCurve(nozzleCurves[i], c, nozzleTolerance, nozzleTolerance);
                                    if (events != null)
                                    {
                                        if (events.Count >= 1)
                                        {
                                            intersectionsBits[i] = 1;
                                            numIntersections++;
                                        }
                                        else
                                        {
                                            intersectionsBits[i] = 0;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    RhinoApp.WriteLine(e.Message);
                                }
                            }
                        }
                    }

                    if (pluginObj.printHeadConnected)
                    {
                        // I print
                        if (((numPoints % 5) == 0)&&(numIntersections > 0))
                        {
                            string p = printCommand();
                            //RhinoApp.WriteLine(p);
                            pluginObj.printHeadObj.printFrame(p);
                            //pluginObj.printHeadObj.printFullLine();
                        }
                    }

                    numPoints++;
                }

                //And, I move the printer like thing on the screen
                if ((numPoints % 10) == 0)
                {
                    for (int i = 0; i < numNozzles; i++)
                    {
                        doc.Objects.Delete(lineGuids[i],false);
                        lineGuids[i] = doc.Objects.AddLine(nozzleLinesTx[i]);
                    }
                    doc.Objects.Delete(ballGuid, false);
                    ball = new Sphere(rxTxTx, ballRadius);
                    ballGuid = doc.Objects.AddSphere(ball);

                    doc.Views.ActiveView.Redraw();
                    RhinoApp.Wait();
                }
            }

            running = false;
            removeEntities(doc);

            RhinoApp.WriteLine(string.Format("Stopping continuous mode on the tracker."));
            pluginObj.trackerObj.stopContinuous();
            disconnectKbEvt();
            RhinoApp.WriteLine(string.Format("I guess you don't wanna print anymore, well who cares! Not me!"));
            return Rhino.Commands.Result.Success;
        }
Example #26
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            FemDesign.Results.FDfea fdFeaModel = null;
            DA.GetData("FdFeaModel", ref fdFeaModel);
            if (fdFeaModel == null)
            {
                return;
            }

            // Read the Shell Result
            var result = FemDesign.Results.FeaBar.DeconstructFeaBar(fdFeaModel.FeaBar);

            // Extract the results from the Dictionary
            var id        = (List <string>)result["Identifier"];
            var elementId = (List <int>)result["ElementId"];
            var nodei     = (List <int>)result["Nodei"];
            var nodej     = (List <int>)result["Nodej"];

            // clean Identifier List
            // some of the elements are null
            int    i          = 0;
            int    j          = 0;
            string currentId  = null;
            var    uniqueId   = id.Where(x => x != "").ToList();
            var    identifier = new List <string>();

            for (i = 0; i < id.Count(); i++)
            {
                if (id.ElementAt(i) != "")
                {
                    identifier.Add(uniqueId.ElementAt(j));
                    currentId = uniqueId.ElementAt(j);
                    j++;
                }
                else
                {
                    identifier.Add(currentId);
                }
            }


            var lines = new List <Rhino.Geometry.LineCurve>();

            for (i = 0; i < nodei.Count(); i++)
            {
                var posStartX = fdFeaModel.FeaNode.ElementAt(nodei.ElementAt(i) - 1).X;
                var posStartY = fdFeaModel.FeaNode.ElementAt(nodei.ElementAt(i) - 1).Y;
                var posStartZ = fdFeaModel.FeaNode.ElementAt(nodei.ElementAt(i) - 1).Z;
                var pointi    = new Rhino.Geometry.Point3d(posStartX, posStartY, posStartZ);

                var posEndX = fdFeaModel.FeaNode.ElementAt(nodej.ElementAt(i) - 1).X;
                var posEndY = fdFeaModel.FeaNode.ElementAt(nodej.ElementAt(i) - 1).Y;
                var posEndZ = fdFeaModel.FeaNode.ElementAt(nodej.ElementAt(i) - 1).Z;
                var pointj  = new Rhino.Geometry.Point3d(posEndX, posEndY, posEndZ);

                var line = new Rhino.Geometry.LineCurve(pointi, pointj);
                lines.Add(line);
            }

            var identifierTree = new DataTree <object>();
            var nodeiTree      = new DataTree <object>();
            var nodejTree      = new DataTree <object>();
            var elementIdTree  = new DataTree <object>();
            var lineTree       = new DataTree <object>();

            i = 0;
            foreach (var ids in uniqueId)
            {
                identifierTree.Add(ids);

                var indexes = identifier.Select((value, index) => new { value, index })
                              .Where(a => string.Equals(a.value, ids))
                              .Select(a => a.index);
                foreach (int index in indexes)
                {
                    //loadCasesTree.Add(loadCases.ElementAt(index), new GH_Path(i));
                    nodeiTree.Add(nodei.ElementAt(index), new GH_Path(i));
                    nodejTree.Add(nodej.ElementAt(index), new GH_Path(i));
                    elementIdTree.Add(elementId.ElementAt(index), new GH_Path(i));
                    lineTree.Add(lines.ElementAt(index), new GH_Path(i));
                }
                i++;
            }


            // Set output
            DA.SetDataTree(0, identifierTree);
            DA.SetDataTree(1, elementIdTree);
            DA.SetDataTree(2, nodeiTree);
            DA.SetDataTree(3, nodejTree);

            DA.SetDataTree(4, lineTree);
        }
Example #27
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // --- Input

            var mesh = default(Mesh);
            var planes = new List<Plane>();
            var thickness = default(double);
            var deeper = default(double);

            DA.GetData(0, ref mesh);
            DA.GetDataList(1, planes);
            DA.GetData(2, ref thickness);
            DA.GetData(3, ref deeper);


            // --- Execute

            var tolerance = DocumentTolerance();

            var slitPlanes = new SlitPlane[planes.Count];

            for (int i = 0; i < planes.Count; i++)
                slitPlanes[i] = new SlitPlane(mesh, planes[i], tolerance);

            var bbox = mesh.GetBoundingBox(false);
            var dmax = bbox.Diagonal.Length;
                      
            for (int i = 0; i < planes.Count; i++)
            {
                for (int j = i + 1; j < planes.Count; j++)
                {
                    var a = planes[i];
                    var b = planes[j];

                    var origin = default(Vector3d);
                    var direction = default(Vector3d);

                    if (a.Normal.IsParallelTo(b.Normal) != 0)
                        continue;

                    IntersectPlanes(a, b, out origin, out direction);

                    var cPlane = new Plane(bbox.Center, direction);
                    origin = (Vector3d)cPlane.ClosestPoint((Point3d)origin);                    

                    var originA = origin.Map2D(a);
                    var directionA = direction.Map2D(a);

                    var originB = origin.Map2D(b);
                    var directionB = direction.Map2D(b);

                    var line = new LineCurve((Point3d)(origin - dmax * direction), ((Point3d)origin + dmax * direction));

                    var alpha = Vector3d.VectorAngle(a.Normal, b.Normal);
                    var t = thickness * Math.Tan(alpha / 2);

                    slitPlanes[i].AddSlit(line.PointAtStart, line.PointAtEnd, t, deeper);
                    slitPlanes[j].AddSlit(line.PointAtEnd, line.PointAtStart, t, deeper);
                }
            }


            // --- Output

            DA.SetEnum2D(0, slitPlanes.Select(o => o.GetResult()));
        }
Example #28
0
        IEnumerable<SlitPoint> SlitPoints(Curve curve, LineCurve line)
        {
            if (curve.IsClosed)
            {
                var points = Rhino.Geometry.Intersect.Intersection.CurveCurve(line, curve, Unit, Unit);
                
                foreach (var item in points)
                {
                    if (item.IsOverlap)
                        if (item.OverlapA.T0 < item.OverlapA.T1)
                            yield return new SlitPoint(item.OverlapA.T0, item.PointA);
                        else
                            yield return new SlitPoint(item.OverlapA.T1, item.PointA2);
                    else
                        yield return new SlitPoint(item.ParameterA, item.PointA);
                }

                if (points.Count % 2 == 1)
                    yield return new SlitPoint(line.GetLength(), line.PointAtEnd);
            }
            else
                foreach (var item in Rhino.Geometry.Intersect.Intersection.CurveCurve(line, curve, Unit, Unit))
                {
                    var unit = line.Domain.Length / line.GetLength();
                    var dir = line.Line.Direction;
                    dir.Unitize();

                    if (item.IsOverlap)
                        if (item.OverlapA.T0 < item.OverlapA.T1)
                        {
                            yield return new SlitPoint(item.OverlapA.T0 - unit, item.PointA - dir);
                            yield return new SlitPoint(item.OverlapA.T0 + unit, item.PointA + dir);
                        }
                        else
                        {
                            yield return new SlitPoint(item.OverlapA.T1 - unit, item.PointA2 - dir);
                            yield return new SlitPoint(item.OverlapA.T1 + unit, item.PointA2 + dir);
                        }
                    else
                    {
                        yield return new SlitPoint(item.ParameterA - unit, item.PointA - dir);
                        yield return new SlitPoint(item.ParameterA + unit, item.PointA + dir);
                    }
                }
        }
Example #29
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp      = commandData.Application;
            UIDocument    uidoc      = uiapp.ActiveUIDocument;
            Application   app        = uiapp.Application;
            Document      doc        = uidoc.Document;
            View          activeView = doc.ActiveView;

            //duplicated in the helper file! remember to change both
            double scale = 304.8;

            //string path = @"C:\Users\gbrog\Desktop\test.3dm";

            string path = @"C:\Users\giovanni.brogiolo\Desktop\ST00-0221.3dm";

            File3dm rhinoModel = File3dm.Read(path);

            List <Rhino.DocObjects.Layer> m_layers = rhinoModel.AllLayers.ToList();

            List <string> layers = Get_RhinoLayerNames(rhinoModel);

            File3dmObject[] rhinoObjects = Get_RhinoObjects(rhinoModel);

            List <Rhino.Geometry.LineCurve> rh_lines = new List <Rhino.Geometry.LineCurve>();

            List <Rhino.Geometry.ArcCurve> rh_arc = new List <Rhino.Geometry.ArcCurve>();

            List <Rhino.Geometry.TextEntity> rh_text = new List <TextEntity>();

            List <Rhino.Geometry.Leader> rh_textLeader = new List <Rhino.Geometry.Leader>();

            List <Rhino.Geometry.LinearDimension> rh_linearDimension = new List <LinearDimension>();

            List <List <Rhino.Geometry.Point3d> > rh_polylineCurvePoints = new List <List <Point3d> >();

            List <Tuple <string, XYZ> > rh_Blocks = new List <Tuple <string, XYZ> >();

            foreach (var item in rhinoObjects)
            {
                GeometryBase geo = item.Geometry;

                // check if geometry is a curve
                if (geo is Rhino.Geometry.LineCurve)
                {
                    // add curve to list
                    Rhino.Geometry.LineCurve ln = geo as Rhino.Geometry.LineCurve;
                    rh_lines.Add(ln);
                }

                if (geo is Rhino.Geometry.ArcCurve)
                {
                    // add curve to list
                    Rhino.Geometry.ArcCurve arc = geo as Rhino.Geometry.ArcCurve;
                    rh_arc.Add(arc);
                }


                if (!item.Attributes.IsInstanceDefinitionObject && geo is Rhino.Geometry.PolylineCurve)
                {
                    PolylineCurve pc = geo as PolylineCurve;

                    Polyline pl = pc.ToPolyline();

                    rh_polylineCurvePoints.Add(pl.ToList());
                }

                if (geo is Rhino.Geometry.TextEntity)
                {
                    TextEntity te = geo as Rhino.Geometry.TextEntity;
                    rh_text.Add(te);
                }

                if (geo is Rhino.Geometry.Leader)
                {
                    rh_textLeader.Add(geo as Rhino.Geometry.Leader);

                    //var text = geo as Rhino.Geometry.Leader;

                    //TaskDialog.Show("r", text.PlainText);
                }

                if (geo is Rhino.Geometry.AnnotationBase)
                {
                    var text = geo as Rhino.Geometry.AnnotationBase;

                    //TaskDialog.Show("r", text.PlainText);
                }

                if (geo is Rhino.Geometry.LinearDimension)
                {
                    LinearDimension ld = geo as Rhino.Geometry.LinearDimension;
                    rh_linearDimension.Add(ld);
                }

                if (geo is Rhino.Geometry.InstanceReferenceGeometry)
                {
                    InstanceReferenceGeometry refGeo = (InstanceReferenceGeometry)geo;

                    // Lookup the parent block definition
                    System.Guid blockDefId         = refGeo.ParentIdefId;
                    InstanceDefinitionGeometry def = rhinoModel.AllInstanceDefinitions.FindId(blockDefId);

                    // block definition name
                    string defname = def.Name;

                    //TaskDialog.Show("R", defname);

                    // transform data for block instance
                    Rhino.Geometry.Transform xform = refGeo.Xform;

                    double x = refGeo.Xform.M03 / scale;
                    double y = refGeo.Xform.M13 / scale;

                    XYZ placementPt = new XYZ(x, y, 0);

                    rh_Blocks.Add(new Tuple <string, XYZ>(defname, placementPt));
                }
            }

            //TaskDialog.Show("r", rh_linearDimension.Count.ToString());

            Rhynamo.clsGeometryConversionUtils rh_ds = new Rhynamo.clsGeometryConversionUtils();

            using (Transaction t = new Transaction(doc, "Convert lines"))
            {
                t.Start();

                rh_ds.Convert_rhLinesToRevitDetailCurve(doc, rh_lines, "3 Arup Continuous Line");

                rh_ds.Convert_PolycurveToLines(doc, rh_polylineCurvePoints, "1 Arup Continuous Line");

                rh_ds.Convert_ArcsToDS(doc, rh_arc);

                rh_ds.RhinoTextToRevitNote(doc, rh_text);

                rh_ds.RhinoLeaderToRevitNote(doc, rh_textLeader);

                rh_ds.RhinoToRevitDimension(doc, rh_linearDimension);

                rh_ds.Convert_rhBlocks(doc, rh_Blocks);

                t.Commit();
            }

            TaskDialog.Show("r", "Done");

            return(Result.Succeeded);
        }
Example #30
0
        DataTree<Object> GetStepTree(Mesh terrainMesh, List<double> contourZList, DataTree<Curve> contourTree, List<Brep> brepList)
        {
            DataTree<Object> stepTree = new DataTree<Object>();
            Plane basePlane = Plane.WorldXY;
            basePlane.OriginZ = terrainMesh.GetBoundingBox(true).Min.Z;

            // For each contour-plane
            for (int i = 0; i < contourTree.BranchCount; i++)
            {

                // create higher-Z pt list
                Point3dList winPtList = new Point3dList();

                foreach (Curve contourCrv in contourTree.Branches[i])
                {

                    Plane frm;
                    double t;
                    contourCrv.NormalizedLengthParameter(0.5, out t);
                    contourCrv.FrameAt(t, out frm);
                    frm.Transform(Rhino.Geometry.Transform.PlanarProjection(basePlane));

                    Point3d samplePt0, samplePt1;
                    samplePt0 = frm.Origin;
                    samplePt1 = frm.Origin;
                    samplePt0 += doc.ModelAbsoluteTolerance * frm.YAxis;
                    samplePt1 -= doc.ModelAbsoluteTolerance * frm.YAxis;
                    Ray3d ray0 = new Ray3d(samplePt0, Vector3d.ZAxis);
                    Ray3d ray1 = new Ray3d(samplePt1, Vector3d.ZAxis);
                    double rayParam0 = Rhino.Geometry.Intersect.Intersection.MeshRay(terrainMesh, ray0);
                    double rayParam1 = Rhino.Geometry.Intersect.Intersection.MeshRay(terrainMesh, ray1);

                    winPtList.Add(((rayParam0 > rayParam1) ? samplePt0 : samplePt1));
                }

                // For each splitted region in contour-plane
                foreach (BrepFace brepFace in brepList[i].Faces)
                {
                    Brep testBrep = brepFace.DuplicateFace(false);

                    foreach (Point3d pt in winPtList)
                    {

                        LineCurve testRay = new LineCurve(new Line(pt, Vector3d.ZAxis, 1000));
                        Point3d[] outPts;
                        Curve[] outCrvs;

                        bool ix = Rhino.Geometry.Intersect.Intersection.CurveBrep(testRay, testBrep, doc.ModelAbsoluteTolerance, out outCrvs, out outPts);
                        if (outPts.Length != 0)
                        {
                            stepTree.Add(testBrep, new GH_Path(i));
                            break;
                        }
                    }
                }
            }

            return stepTree;
        }
Example #31
0
        /***************************************************/

        public static Rhino.Geometry.Surface ToRhino(this BHG.Extrusion extrusion)
        {
            if (!extrusion.Curve.IIsPlanar())
            {
                BH.Engine.Reflection.Compute.RecordError("The provided BHoM Extrusion has a base curve that is not planar.");
                return(null);
            }

            var planarCurve = extrusion.Curve.IToRhino();

            RHG.Plane curvePlane;
            planarCurve.TryGetPlane(out curvePlane);

            double angle = RHG.Vector3d.VectorAngle(curvePlane.Normal, extrusion.Direction.ToRhino());

            double tolerance = 0.001;

            if (angle < tolerance || (2 * Math.PI - tolerance < angle && angle < 2 * Math.PI + tolerance))
            {
                // It can be represented by a Rhino extrusion (which enforces perpendicularity btw Curve plane and Vector)

                double extrHeight = extrusion.Direction.Length();

                if (angle > Math.PI)
                {
                    extrHeight = -extrHeight;
                }

                RHG.Extrusion extr = Rhino.Geometry.Extrusion.Create(planarCurve, extrHeight, extrusion.Capped);

                return(extr);
            }

            // Otherwise, provide a Sweep to cover extrusion with a base curve that is not orthogonal to the extr direction

            // Create a Line to be the sweep rail. Use centroid/mid-point of base curve as start point.
            RHG.Point3d centrePoint;
            if (planarCurve.IsClosed)
            {
                var areaProp = Rhino.Geometry.AreaMassProperties.Compute(planarCurve);
                centrePoint = areaProp.Centroid;
            }
            else
            {
                centrePoint = planarCurve.PointAt(0.5);
            }

            RHG.Point3d endPoint = centrePoint + extrusion.Direction.ToRhino();
            var         rail     = new RHG.LineCurve(centrePoint, endPoint);

            var joinedSweep = new RHG.SweepOneRail()
                              .PerformSweep(rail, planarCurve)
                              .Aggregate((b1, b2) => { b1.Join(b2, tolerance, true); return(b1); });

            if (joinedSweep.IsSurface)
            {
                return(joinedSweep.Surfaces[0]);
            }

            BH.Engine.Reflection.Compute.RecordError("Could not convert this BHoM Extrusion to a Rhino Surface. The extrusion direction is not perpendicular to the base curve, and the base curve is too complex for a Sweep to return a valid Surface.");


            return(null);
        }
Example #32
0
 public ExoStrut(bool IsEnd, double SetRadius, double SetHullRadius, LineCurve SetStrut, Plane SetPlane)
 {
     Radius = SetRadius;
     HullRadius = SetHullRadius;
     Strut = SetStrut;
     Strut.PerpendicularFrameAt(0.0, out HullPlane);
     Normal = Normal;
     if (IsEnd)
     {
         Strut.Reverse();
         HullPlane.Origin = Strut.PointAtStart;
         Normal *= -1;
     }
     FixPlane = HullPlane;
 }
Example #33
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve rectangle = null;
            DA.GetData(0, ref rectangle);

            bool closedBool = rectangle.IsClosed;
            int  spans      = rectangle.SpanCount;
            int  degree     = rectangle.Degree;

            List <Rhino.Geometry.Point2d> originalPoints = new List <Point2d>();

            List <double> xVals = new List <double>();
            List <double> yVals = new List <double>();

            if (closedBool != true || spans != 4 || degree != 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input curve is not a closed, linear quadrilateral.");

                return;
            }

            for (int i = 0; i < spans; i++)
            {
                Rhino.Geometry.Point3d cornerPoint          = rectangle.PointAt(rectangle.SpanDomain(i).Min);
                Rhino.Geometry.Point2d flattenedCornerPoint = new Rhino.Geometry.Point2d(cornerPoint);
                originalPoints.Add(flattenedCornerPoint);

                xVals.Add(flattenedCornerPoint.X);
                yVals.Add(flattenedCornerPoint.Y);
            }

            Rhino.Geometry.LineCurve testCurveA = new Rhino.Geometry.LineCurve(originalPoints[0], originalPoints[2]);
            Rhino.Geometry.LineCurve testCurveB = new Rhino.Geometry.LineCurve(originalPoints[1], originalPoints[3]);

            if (testCurveA.GetLength() != testCurveB.GetLength())
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input curve is not orthogonal, results are not guaranteed.");
            }

            Rhino.Geometry.Point2d topRightPoint = new Rhino.Geometry.Point2d(xVals.Max(), yVals.Max());
            DA.SetData(1, topRightPoint);

            Rhino.Geometry.Point2d topLeftPoint = new Rhino.Geometry.Point2d(xVals.Min(), yVals.Max());
            DA.SetData(2, topLeftPoint);

            Rhino.Geometry.Point2d bottomLeftPoint = new Rhino.Geometry.Point2d(xVals.Min(), yVals.Min());
            DA.SetData(3, bottomLeftPoint);

            Rhino.Geometry.Point2d bottomRightPoint = new Rhino.Geometry.Point2d(xVals.Max(), yVals.Min());
            DA.SetData(4, bottomRightPoint);

            List <Rhino.Geometry.Point2d> orderedPoints = new List <Point2d>();

            orderedPoints.Add(topRightPoint);
            orderedPoints.Add(topLeftPoint);
            orderedPoints.Add(bottomLeftPoint);
            orderedPoints.Add(bottomRightPoint);

            DA.SetDataList(0, orderedPoints);

            //TODO: Check for rotation. No warnings will be raised if input is orthogonal rotated object, but corners will not be accurate.
        }
Example #34
0
        //HATCH FILL REGION - infills a planar region with a hatching pattern
        public void Filler(List<double> infDens, List<double> infRot)
        {
            double tolerance = 0.001;
            //double overlaptol = 0.0;
            double crossSecHyp = Math.Sqrt(Math.Pow(crossSec, 2) * 2);

            curveInfill = new List<Curve>[planarBreps.Count];

            //Create List of Infill Curves for each Planar Region
            for (int u = 0; u < planarBreps.Count; u++)
            {

                    //Rotate Plane for Filling
                    double rotationRad = infRot[u] * 0.0174532925;
                    Plane plane = Plane.WorldXY;

                    plane.Rotate(rotationRad, Plane.WorldXY.ZAxis);

                    //Create Bounding Box
                    Box bbox = new Box();
                    planarBreps[u].GetBoundingBox(plane, out bbox);

                    //Get Corners
                    Point3d[] cornerPts = bbox.GetCorners();

                    //Draw Parallel Lines
                    LineCurve baseLine = new LineCurve(cornerPts[0], cornerPts[1]);
                    LineCurve baseLine2 = new LineCurve(cornerPts[3], cornerPts[2]);
                    //int nPts = (int)Math.Round((baseLine.Line.Length/crossSec),0);
                    Point3d[] basePts = new Point3d[0];
                    Point3d[] basePts2 = new Point3d[0];

                    double length = baseLine.Line.Length;
                    double floatdivisions = length / crossSec;
                    double density = infDens[u];

                    int divisions = (int)Math.Round((floatdivisions * density));

                    //Divide Lines by Fill Density ratio
                    baseLine.DivideByCount(divisions, true, out basePts);
                    baseLine2.DivideByCount(divisions, true, out basePts2);

                    if (divisions == 0)
                    {
                        curveInfill[u] = new List<Curve>();
                        return;
                    }

                    Curve[][] intCurve = new Curve[basePts.Length][];

                    List<Curve> intCurves = new List<Curve>();
                    for (int i = 0; i < basePts.Length; i++)
                    {

                        LineCurve intLine = new LineCurve(basePts[i], basePts2[i]);

                        Point3d[] intPts = new Point3d[0];
                        BrepFace r_Infill = planarBreps[u].Faces[0];

                        Curve[] int_Curve = new Curve[0];

                        //Intersect Curves with Regions
                        Intersection.CurveBrepFace(intLine, r_Infill, tolerance, out int_Curve, out intPts);
                        intCurve[i] = int_Curve;

                        //Convert resulting Curves into LineCurves
                        for (int j = 0; j < int_Curve.Length; j++)
                        {
                            LineCurve line = new LineCurve(int_Curve[j].PointAtStart, int_Curve[j].PointAtEnd);
                            intCurve[i][j] = line;
                            //intCurves[j].Add(int_Curve[j]);
                            intCurves.Add(line);
                        }

                    }

                    //Rotate Array
                    List<Curve>[] int_Curves = RotatetoListArray(intCurve);

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

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

                    for (int l = 0; l < int_Curves.Length; l++)
                    {
                        for (int k = 1; k < int_Curves[l].Count; k += 2)
                        {

                            int_Curves[l][k].Reverse();

                        }
                    }

                //Create a list of points for all connected lines in the infill.  Do this for each seperate string of segments
                    for (int l = 0; l < int_Curves.Length; l++)
                    {
                        List<Point3d> plinePts = new List<Point3d>();
                        if (int_Curves[l].Count > 0)
                        {
                            plinePts.Add(int_Curves[l][0].PointAtStart);
                            for (int k = 1; k < int_Curves[l].Count; k++)
                            {
                                plinePts.Add(int_Curves[l][k - 1].PointAtEnd);

                                plinePts.Add(int_Curves[l][k].PointAtStart);
                                plinePts.Add(int_Curves[l][k].PointAtEnd);
                            }

                            PolylineCurve plCurve = new PolylineCurve(plinePts);
                            Curve curve = plCurve.ToNurbsCurve();
                            p_lines.Add(curve);
                        }
                    }

                    List<Curve> curve_s = p_lines;
                    curveInfill[u] = p_lines;

            }
        }
Example #35
0
        /// <summary>
        /// Maps cell topology to the node grid and trims to the design space.
        /// </summary>
        public void UniformMapping(UnitCell cell, GeometryBase designSpace, int spaceType, float[] N, double minStrutLength, double maxStrutLength)
        {
            double tol = RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;

            for (int u = 0; u <= N[0]; u++)
            {
                for (int v = 0; v <= N[1]; v++)
                {
                    for (int w = 0; w <= N[2]; w++)
                    {
                        // We're inside a unit cell
                        // Loop through all pairs of nodes that make up struts
                        foreach (IndexPair nodePair in cell.NodePairs)
                        {
                            // Prepare the path of the nodes (path in tree)
                            // First, get relative paths of nodes (with respect to current unit cell)
                            int[] IRel = cell.NodePaths[nodePair.I];
                            int[] JRel = cell.NodePaths[nodePair.J];
                            // Next, compute absolute paths
                            GH_Path IPath = new GH_Path(u + IRel[0], v + IRel[1], w + IRel[2]);
                            GH_Path JPath = new GH_Path(u + JRel[0], v + JRel[1], w + JRel[2]);

                            // Make sure the cell exists
                            if (Nodes.PathExists(IPath) && Nodes.PathExists(JPath))
                            {
                                LatticeNode node1 = Nodes[IPath, IRel[3]];
                                LatticeNode node2 = Nodes[JPath, JRel[3]];
                                // Make sure both nodes exist:
                                // Null nodes either belong to other cells, or are beyond the upper uvw boundary
                                if (node1 != null && node2 != null)
                                {
                                    Curve fullCurve = new LineCurve(node1.Point3d, node2.Point3d);

                                    // If both nodes are inside, add full strut
                                    if (node1.IsInside && node2.IsInside)
                                    {
                                        Struts.Add(fullCurve);
                                    }
                                    // If neither node is inside, skip to next loop
                                    else if (!node1.IsInside && !node2.IsInside)
                                    {
                                        continue;
                                    }
                                    // Else, strut requires trimming
                                    else
                                    {
                                        // We are going to find the intersection point with the design space
                                        Point3d[] intersectionPts = null;
                                        Curve[] overlapCurves = null;
                                        LineCurve strutToTrim = null;

                                        switch (spaceType)
                                        {
                                            // Brep design space
                                            case 1:
                                                strutToTrim = new LineCurve(node1.Point3d, node2.Point3d);
                                                // Find intersection point
                                                Intersection.CurveBrep(strutToTrim, (Brep)designSpace, tol, out overlapCurves, out intersectionPts);
                                                break;
                                            // Mesh design space
                                            case 2:
                                                // Dummy faceIds variable for MeshLine call
                                                int[] faceIds;
                                                strutToTrim = new LineCurve(node1.Point3d, node2.Point3d);
                                                // Find intersection point
                                                intersectionPts = Intersection.MeshLine((Mesh)designSpace, strutToTrim.Line, out faceIds);
                                                break;
                                            // Solid surface design space
                                            case 3:
                                                // Dummy overlapCurves variable for CurveBrep call
                                                overlapCurves = null;
                                                strutToTrim = new LineCurve(node1.Point3d, node2.Point3d);
                                                // Find intersection point
                                                Intersection.CurveBrep(strutToTrim, ((Surface)designSpace).ToBrep(), tol, out overlapCurves, out intersectionPts);
                                                break;
                                        }

                                        LineCurve testLine = null;
                                        // Now, if an intersection point was found, trim the strut
                                        if (intersectionPts.Length > 0)
                                        {
                                            testLine = AddTrimmedStrut(node1, node2, intersectionPts[0], minStrutLength, maxStrutLength);
                                            // If the strut was succesfully trimmed, add it to the list
                                            if (testLine != null)
                                            {
                                                Struts.Add(testLine);
                                            }
                                        }
                                        else if (overlapCurves != null && overlapCurves.Length > 0)
                                        {
                                            Struts.Add(overlapCurves[0]);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #36
0
        //RING FILL REGION - infills a region with a decreasing perimiter ring, this creates a spiral from the outer shape
        public void Skinner(List<double> spacing)
        {
            double tolerance = 0.001;
            List<Curve>[] outPerimeter = new List<Curve>[planarBreps.Count];

            //For each planar region extract the outer edge and offset until the curve is no longer in the region, or is invalid
            for (int z = 0; z < planarBreps.Count; z++ )
            {
                Curve Shape = planarBreps[z].Loops[0].To3dCurve();

                outPerimeter[z] = new List<Curve>();

                List<Curve> startshapes = new List<Curve>();
                startshapes.Add(Shape);

                bool stop = false;
                do
                {

                    Plane frame = horizFrame(Shape, 0.5);
                    List<Curve> Shapes = new List<Curve>();

                    //Catch possibility of offset not working
                    if (Shape.Offset(frame, spacing[z], Tolerance, CurveOffsetCornerStyle.Sharp) == null)
                    {
                        break;
                    }

                    Shapes = Shape.Offset(frame, spacing[z], Tolerance, CurveOffsetCornerStyle.Sharp).ToList();

                    Curve[] iCurves = new Curve[0];
                    Point3d[] iPoints = new Point3d[0];

                    Intersection.CurveBrep(Shapes[0], planarBreps[z], tolerance, out iCurves, out iPoints);

                    if (iCurves.Length < 1)
                    {
                        stop = true;
                        break;
                    }

                    if (iCurves.Length > 0)
                    {
                        if (iCurves[0] == null)

                        {
                        stop = true;
                        break;

                        }

                        //if (!iCurves[0].IsClosed)
                        //{
                        //    stop = true;
                        //    break;
                        //}
                    }

                    Shape = Shapes[0];
                    startshapes.Add(Shape);

                } while (!stop);

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

                //open the resulting offset closed curves, to join into a spiral path
                foreach (Curve closed in startshapes)
                {
                    if (unClose(closed, crossSec) != null)
                    {
                        unclosed.Add(unClose(closed, crossSec));
                    }
                }

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

                joinedPerimeter.Add(unclosed[0]);

                //Join ends of offset curves together to create spiral path
                for (int j = 1; j < unclosed.Count; j++)
                {

                    LineCurve join = new LineCurve(unclosed[j - 1].PointAtEnd, unclosed[j].PointAtStart);

                        joinedPerimeter.Add(join);

                        joinedPerimeter.Add(unclosed[j]);

                }

                //Catch exception
                if (Curve.JoinCurves(joinedPerimeter, 0.1, false) == null)
                {
                    outPerimeter[z].AddRange(joinedPerimeter);
                    continue;
                }

                Curve[] allLines = Curve.JoinCurves(joinedPerimeter, 0.1, false);

                outPerimeter[z].AddRange(allLines.ToList());
            }

            curvePerimeter = outPerimeter;
        }
Example #37
0
        /// <summary>
        /// Trims strut with known intersection point, returning  the trimmed LineCurve which is inside the space.
        /// </summary>
        public LineCurve AddTrimmedStrut(LatticeNode node1, LatticeNode node2, Point3d intersectionPt, double minLength, double maxLength)
        {

            LineCurve testStrut = new LineCurve(new Line(node1.Point3d, node2.Point3d), 0, 1);  // set line, with curve parameter domain [0,1]

            if (node1.IsInside)
            {
                double trimmedLength = intersectionPt.DistanceTo(node1.Point3d);
                if (trimmedLength > minLength && trimmedLength < maxLength)
                {
                    Nodes.Add(new LatticeNode(intersectionPt, LatticeNodeState.Boundary));
                    return new LineCurve(node1.Point3d, intersectionPt);
                }
                else
                {
                    node1.State = LatticeNodeState.Boundary;
                }
            }
            
            if (node2.IsInside)
            {
                double trimmedLength = intersectionPt.DistanceTo(node2.Point3d);
                if (trimmedLength > minLength && trimmedLength < maxLength)
                {
                    Nodes.Add(new LatticeNode(intersectionPt, LatticeNodeState.Boundary));
                    return new LineCurve(node2.Point3d, intersectionPt);
                }
                else
                {
                    node2.State = LatticeNodeState.Boundary;
                }
            }

            return null;
        }
Example #38
0
        /// <summary>
        /// Maps cell topology to UVWi node map (linear struts).         
        /// </summary>
        public void ConformMapping(UnitCell cell, float[] N)
        {
            for (int u = 0; u <= N[0]; u++)
            {
                for (int v = 0; v <= N[1]; v++)
                {
                    for (int w = 0; w <= N[2]; w++)
                    {
                        // We're inside a unit cell
                        // Loop through all pairs of nodes that make up struts
                        foreach (IndexPair nodePair in cell.NodePairs)
                        {
                            // Prepare the path of the nodes (path in tree)
                            // First, get relative paths of nodes (with respect to current unit cell)
                            int[] IRel = cell.NodePaths[nodePair.I];
                            int[] JRel = cell.NodePaths[nodePair.J];
                            // Next, compute absolute paths
                            GH_Path IPath = new GH_Path(u + IRel[0], v + IRel[1], w + IRel[2]);
                            GH_Path JPath = new GH_Path(u + JRel[0], v + JRel[1], w + JRel[2]);

                            // Make sure the cell exists
                            // No cells exist beyond the boundary + 1
                            if (Nodes.PathExists(IPath) && Nodes.PathExists(JPath))
                            {
                                LatticeNode node1 = Nodes[IPath, IRel[3]];
                                LatticeNode node2 = Nodes[JPath, JRel[3]];
                                // Make sure both nodes exist:
                                // Null nodes either belong to other cells, or are beyond the upper uvw boundary
                                if (node1 != null && node2 != null)
                                {
                                    LineCurve curve = new LineCurve(node1.Point3d, node2.Point3d);
                                    if (curve != null && curve.IsValid)
                                    {
                                        Struts.Add(curve);
                                    }
                                }
                            }
                            
                        }
                    }
                }
            }
        }
Example #39
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool centeredBool = false;

            DA.GetData(2, ref centeredBool);

            double distance = 0;

            DA.GetData(1, ref distance);

            Rhino.Geometry.Curve curveToOffset = null;
            DA.GetData(0, ref curveToOffset);

            Rhino.Geometry.Point3d firstStartPoint = curveToOffset.PointAtStart;
            Rhino.Geometry.Point3d firstEndPoint   = curveToOffset.PointAtEnd;

            Rhino.Geometry.Plane defaultPlane = Plane.WorldXY;

            Rhino.Geometry.Curve[] offsetCurves         = curveToOffset.Offset(defaultPlane, distance, 0.1, CurveOffsetCornerStyle.Sharp);
            Rhino.Geometry.Curve[] mirroredOffsetCurves = curveToOffset.Offset(defaultPlane, distance * -1, 0.1, CurveOffsetCornerStyle.Sharp);

            if (offsetCurves.Length > 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Curve is not clean.");

                return;
            }

            if (centeredBool == true && mirroredOffsetCurves.Length > 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Curve is not clean.");

                return;
            }

            Rhino.Geometry.Curve   offsetCurve   = offsetCurves[0];
            Rhino.Geometry.Point3d newStartPoint = offsetCurve.PointAtStart;
            Rhino.Geometry.Point3d newEndPoint   = offsetCurve.PointAtEnd;

            Rhino.Geometry.Curve   mirroredOffsetCurve   = mirroredOffsetCurves[0];
            Rhino.Geometry.Point3d mirroredNewStartPoint = mirroredOffsetCurve.PointAtStart;
            Rhino.Geometry.Point3d mirroredNewEndPoint   = mirroredOffsetCurve.PointAtEnd;

            Rhino.Geometry.Curve startCapCurve = null;
            Rhino.Geometry.Curve endCapCurve   = null;

            List <Rhino.Geometry.Curve> regionCurvePieces = new List <Curve>();

            if (centeredBool == false)
            {
                startCapCurve = new Rhino.Geometry.LineCurve(firstStartPoint, newStartPoint) as Rhino.Geometry.Curve;
                endCapCurve   = new Rhino.Geometry.LineCurve(firstEndPoint, newEndPoint) as Rhino.Geometry.Curve;

                regionCurvePieces.Add(curveToOffset);
            }
            else if (centeredBool == true)
            {
                startCapCurve = new Rhino.Geometry.LineCurve(mirroredNewStartPoint, newStartPoint) as Rhino.Geometry.Curve;
                endCapCurve   = new Rhino.Geometry.LineCurve(mirroredNewEndPoint, newEndPoint) as Rhino.Geometry.Curve;

                regionCurvePieces.Add(mirroredOffsetCurve);
            }

            regionCurvePieces.Add(startCapCurve);
            regionCurvePieces.Add(offsetCurve);
            regionCurvePieces.Add(endCapCurve);

            Rhino.Geometry.Curve[] regionOffset = Curve.JoinCurves(regionCurvePieces);

            if (regionOffset.Length > 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Join was unsuccessful.");

                return;
            }

            DA.SetData(0, regionOffset[0]);
        }