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;
    }
 public void CurveCP(Brep x, Curve y, int V, int U)
 {
     int u = bitmap1.Size.Width;
     int v = bitmap1.Size.Height;
     Graphics g = Graphics.FromImage(bitmap1);
     g.FillRectangle(new SolidBrush(Color.White), 0, 0, u, v);
     System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(Color.Black);
     float step1 = u / U;
     float step2 = v / V;
     for (float i = 25; i < u - 25; i += step1)
     {
         for (float j = 25; j < v - 25; j += step2)
         {
             double Umin = x.Faces[0].Domain(0).Min;
             double Umax = x.Faces[0].Domain(0).Max;
             double Vmin = x.Faces[0].Domain(1).Min;
             double Vmax = x.Faces[0].Domain(1).Max;
             Point3d pos = x.Faces[0].PointAt(i / u * (Umax - Umin) + Umin, j / v * (Vmax - Vmin) + Vmin);
             double t; float R;
             if (y.ClosestPoint(pos, out t, 200))
             {
                 double dis = y.PointAt(t).DistanceTo(pos);
                 dis /= 200;
                 R = (float)(1 / dis * 2);
                 if (R > 40) R = 40;
             }
             else { R = 20; }
             g.FillEllipse(myBrush, i - R, v - j - R, R * 2, R * 2);
         }
     }
     myBrush.Dispose();
     g.Dispose();
 }
 /// <summary>
 /// Initializes a new instance of the WorldBoxEnvironmentComponent class.
 /// </summary>
 public PolysurfaceEnvironmentComponent()
   : base("Polysurface Environment", "PolysrfEnv",
       "A 3D Polysurface Environment.", RS.icon_polysurfaceEnvironment, "646e7585-d3b0-4ebd-8ce3-8efc5cd6b7d9")
 {
   brep = new Brep();
   borderDir = Vector3d.Zero;
 }
  public static Rhino.Commands.Result AddTwistedCube(Rhino.RhinoDoc doc)
  {
    Point3d[] points = new Point3d[8];
    points[0] = new Point3d(0.0, 0.0, 0.0);   // point A = geometry for vertex 0
    points[1] = new Point3d(10.0, 0.0, 0.0);  // point B = geometry for vertex 1
    points[2] = new Point3d(10.0, 8.0, -1.0); // point C = geometry for vertex 2
    points[3] = new Point3d(0.0, 6.0, 0.0);   // point D = geometry for vertex 3
    points[4] = new Point3d(1.0, 2.0, 11.0);  // point E = geometry for vertex 4
    points[5] = new Point3d(10.0, 0.0, 12.0); // point F = geometry for vertex 5
    points[6] = new Point3d(10.0, 7.0, 13.0); // point G = geometry for vertex 6
    points[7] = new Point3d(0.0, 6.0, 12.0);  // point H = geometry for vertex 7

    Brep brep = new Brep();

    // Create eight vertices located at the eight points
    for (int vi = 0; vi < 8; vi++)
      brep.Vertices.Add(points[vi], 0.0);

    // Create 3d curve geometry - the orientations are arbitrarily chosen
    // so that the end vertices are in alphabetical order.
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[A], points[B])); // line AB
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[B], points[C])); // line BC
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[C], points[D])); // line CD
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[A], points[D])); // line AD
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[E], points[F])); // line EF
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[F], points[G])); // line FG
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[G], points[H])); // line GH
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[E], points[H])); // line EH
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[A], points[E])); // line AE
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[B], points[F])); // line BF
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[C], points[G])); // line CG
    brep.Curves3D.Add(TwistedCubeEdgeCurve(points[D], points[H])); // line DH

    // Create the 12 edges that connect the corners of the cube.
    MakeTwistedCubeEdges(ref brep);

    // Create 3d surface geometry - the orientations are arbitrarily chosen so
    // that some normals point into the cube and others point out of the cube.
    brep.AddSurface(TwistedCubeSideSurface(points[A], points[B], points[C], points[D])); // ABCD
    brep.AddSurface(TwistedCubeSideSurface(points[B], points[C], points[G], points[F])); // BCGF
    brep.AddSurface(TwistedCubeSideSurface(points[C], points[D], points[H], points[G])); // CDHG
    brep.AddSurface(TwistedCubeSideSurface(points[A], points[D], points[H], points[E])); // ADHE
    brep.AddSurface(TwistedCubeSideSurface(points[A], points[B], points[F], points[E])); // ABFE
    brep.AddSurface(TwistedCubeSideSurface(points[E], points[F], points[G], points[H])); // EFGH

    // Create the CRhinoBrepFaces
    MakeTwistedCubeFaces(ref brep);

    if (brep.IsValid)
    {
      doc.Objects.AddBrep(brep);
      doc.Views.Redraw();
      return Rhino.Commands.Result.Success;
    }
    return Rhino.Commands.Result.Failure;
  }
 private void RunScript(int x, double y, Brep z, ref object A)
 {
     List<branch> bls = new List<branch>();
     //  List<branch> Temp = new List<branch>();
     bls.Add(new branch(Plane.WorldXY, length, Math.PI / y));
     for (int i = 0; i < x; i++)
     {
       bls.AddRange(branch.grow(bls, z));
     }
     A = branch.DisplayBranches(bls);
 }
    private static DataTree<Brep> BrepArray2DToDatatree(Brep[][] array)
    {
      DataTree<Brep> tree = new DataTree<Brep>();
      GH_Path trunk = new GH_Path();

      for (int i = 0; i < array.Length; i++)
      {
        GH_Path branch = trunk.AppendElement(i);

        for (int j = 0; j < array[i].Length; j++)
        {
          tree.Add(array[i][j], branch);
        }
      }
      return tree;
    }
示例#7
0
        private Brep[] calculateOffsetSolids()
        {
            Brep[] cappedBreps = new Brep[refMesh.faces.Count];
            for (int i = 0; i < offsetEdges.Length; i++)
            {
                List<Brep> brepsToMerge = new List<Brep>();
                refMesh.faces[i].faceNormal.Unitize();
                //better to translate and then just create on.

                Transform moveToAdjustForThickness = Transform.Translation(Vector3d.Multiply(thickness/2,refMesh.faces[i].faceNormal));

                offsetEdges[i].ToNurbsCurve().Transform(moveToAdjustForThickness);

                cappedBreps[i] = Surface.CreateExtrusion(offsetEdges[i].ToNurbsCurve(), Vector3d.Multiply(-thickness, refMesh.faces[i].faceNormal)).ToBrep().CapPlanarHoles(0.1);

            }
            return cappedBreps;
        }
    private Brep[][] CreateBorderWalls()
    {
      Curve[] borderCrvs = GetNakedEdges();

      int n = borderCrvs.Length;

      Point3d[][] edgePtsArray = new Point3d[n][];
      for (int i = 0; i < n; i++)
      {
        edgePtsArray[i] = DivByAngle(borderCrvs[i], 1.0).ToArray();
      }

      Vector3d[][] normalsArray = new Vector3d[n][];
      for (int i = 0; i < n; i++)
      {
        if (borderDir.Equals(Vector3d.Zero))
        {
          normalsArray[i] = GetBrepNormals(edgePtsArray[i]).ToArray();
        }
        else
        {
          int m = edgePtsArray[i].Length;
          normalsArray[i] = new Vector3d[m];
          for (int j = 0; j < m; j++)
          {
            normalsArray[i][j] = borderDir;
          }
        }
        
      }

      double borderSize = environment.GetBoundingBox(Plane.WorldXY).Diagonal.Length / 10;

      Brep[][] borderWallsArray = new Brep[n][];
      for (int i = 0; i < n; i++)
      {
        borderWallsArray[i] = GetBorderWalls(borderCrvs[i], edgePtsArray[i], normalsArray[i], borderSize);
      }
      return borderWallsArray;
    }
        //Make the extended cone to intersect with
        public Cone GetExtendedCone(Brep _brepVoid, Point3d _ptRandom, double _extraBcTangent)
        {
            var brepVoid       = _brepVoid;
            var ptRandom       = _ptRandom;
            var extraBcTangent = _extraBcTangent;

            var bb  = brepVoid.GetBoundingBox(true);
            var sph = new Sphere(bb.Center, (bb.Max.X - bb.Min.X) / 2);

            var centerPoint          = sph.Center;
            var sphereRadius         = sph.Radius;
            var sphereRadiusExtended = sphereRadius + extraBcTangent;

            var vectorCone = centerPoint - ptRandom;
            var planeCone  = new Plane(ptRandom, vectorCone);
            //Cone cone = new Cone(planeCone, vectorCone.Length, sphereRadius);

            int  iExtend      = 10;
            Cone coneExtended = new Cone(planeCone, vectorCone.Length * iExtend, sphereRadiusExtended * iExtend);

            return(coneExtended);
        }
        // generate far 5-20
        public void buildingGenerator3(double density)
        {
            // offset 2m
            Curve[] outeroffset = this.Outline.ToNurbsCurve().Offset(this.Center, Vector3d.ZAxis, 2, inter_tol, CurveOffsetCornerStyle.Sharp);
            this.OuterBorder = outeroffset[0];
            // density * offsetmax
            double off = density * (this.offsetMax() - 2);

            // offset the outerborder
            Curve[] inneroffset = outeroffset[0].Offset(this.Center, Vector3d.ZAxis, off, inter_tol, CurveOffsetCornerStyle.Sharp);
            this.InnerBorder = inneroffset[0];
            // loft, extrude
            Brep[] loft = Brep.CreatePlanarBreps(new List <Curve>()
            {
                this.OuterBorder, this.InnerBorder
            }, inter_tol);
            //double floor = Math.Floor(this.FAR / density);
            double floor = 5;
            Brep   ex    = loft[0].Faces[0].CreateExtrusion(new Line(0, 0, 0, 0, 0, floor * 3).ToNurbsCurve(), true);

            this.Structure = ex;
        }
        /// <summary>
        /// This Method converts the two input curvelist to a meshlist
        /// </summary>
        /// <param name="sidewalkList"></param>
        /// <param name="_FootprintList"></param>
        /// <returns></returns>
        private static List <Mesh> SidewalkCrvToMesh(List <Curve> sidewalkList, List <Curve> _FootprintList)
        {
            List <Brep> outLine = new List <Brep>();
            List <Brep> inLine  = new List <Brep>();


            foreach (Curve sw in sidewalkList)
            {
                Curve  sidewalk           = sw.Simplify(CurveSimplifyOptions.All, 1, 2);
                Brep[] planarSidewalkList = Brep.CreatePlanarBreps(sidewalk, 1.0);

                outLine.AddRange(from Brep planarSidewalk in planarSidewalkList
                                 select planarSidewalk);
            }

            Curve[] footprintCrvList = Curve.CreateBooleanUnion(_FootprintList, 1.0);

            foreach (Curve footprint in footprintCrvList)
            {
                Brep[] planarBuildingList = Brep.CreatePlanarBreps(footprint, 1.0);

                inLine.AddRange(from Brep planarFootprints in planarBuildingList
                                select planarFootprints);
            }

            Brep[]      sidewalks      = Brep.CreateBooleanDifference(outLine, inLine, 1.0);
            List <Mesh> sidewalkMeshes = new List <Mesh>();

            foreach (Brep sw in sidewalks)
            {
                Mesh[] sideWalkMeshList = Mesh.CreateFromBrep(sw, MeshingParameters.FastRenderMesh);

                sidewalkMeshes.AddRange(from Mesh mesh in sideWalkMeshList
                                        select mesh);
                BrepEdgeList edges = sw.Edges;
            }

            return(sidewalkMeshes);
        }
示例#12
0
        public void renderPatch()
        {
            //Brep patchSurface = Brep.CreatePatch(curvelist, 4, 4, mScene.rhinoDoc.ModelAbsoluteTolerance);
            Brep patchSurface = Brep.CreatePatch(allPoints, 10, 10, mScene.rhinoDoc.ModelAbsoluteTolerance);
            Guid planGuid     = UtilOld.addRhinoObjectSceneNode(ref mScene, ref patchSurface, ref mesh_m, "patchSurface", out planeSN);

            //clear profile curves
            foreach (Guid id in curveGuids)
            {
                foreach (SceneNode sn in mScene.tableGeometry.children)
                {
                    if (sn.guid == id)
                    {
                        mScene.tableGeometry.children.Remove(sn);
                        break;
                    }
                }
            }

            allPoints.Clear();
            curvelist.Clear();
        }
示例#13
0
    Brep Cube4Pt(Point3d A, Point3d B, Point3d C, Point3d D)
    {
        List <Brep> srfs = new List <Brep>();

        Point3d E = new Point3d(0, 0, 0);
        Point3d F = new Point3d(0, 0, 0);
        Point3d G = new Point3d(0, 0, 0);

        E = Point3d.Add(E, (B + C - A));
        F = Point3d.Add(F, (B + D - A));
        G = Point3d.Add(G, (C + D - A));

        srfs.Add(Brep.TryConvertBrep(Srf3Pt(A, B, C)));
        srfs.Add(Brep.TryConvertBrep(Srf3Pt(A, B, D)));
        srfs.Add(Brep.TryConvertBrep(Srf3Pt(A, C, D)));
        srfs.Add(Brep.TryConvertBrep(Srf3Pt(D, F, G)));
        srfs.Add(Brep.TryConvertBrep(Srf3Pt(B, F, E)));
        srfs.Add(Brep.TryConvertBrep(Srf3Pt(C, E, G)));

        Brep[] Brs = Brep.JoinBreps(srfs, 0.01);
        return(Brs[0]);
    }
        private GH_Brep CreateSlabBrep(double depth, IList <PolylineCurve> curveList, IEnumerable <Point3d> topPts)
        {
            if (depth > 0)
            {
                Vector3d normal = Vector3d.CrossProduct(curveList[0].TangentAtEnd, curveList[0].TangentAtStart);
                curveList[1] = new PolylineCurve(topPts.Select(pt => pt - normal * depth));
                Brep loftBrep  = Brep.CreateFromLoft(curveList, Point3d.Unset, Point3d.Unset, LoftType.Straight, false)[0];
                Brep capedBrep = loftBrep.CapPlanarHoles(_tolerance[0]);

                if (capedBrep == null)
                {
                    return(NonPlanarBrep(depth, curveList));
                }
                CheckBrepOrientation(capedBrep);

                return(new GH_Brep(capedBrep));
            }

            return(new GH_Brep(curveList[0].IsPlanar()
                     ? Brep.CreatePlanarBreps(curveList[0], _tolerance[0])[0]
                     : Brep.CreatePatch(new[] { curveList[0] }, 5, 5, _tolerance[0])));
        }
示例#15
0
        public static (Point3d Center, Vector3d Normal) GetSrfCenPtandNormal(this Brep inBrep)
        {
            var brepFace = inBrep.Faces[0];

            double centerU, centerV;

            if (brepFace.IsPlanar() && brepFace.IsSurface)
            {
                centerU = brepFace.Domain(0).Mid;
                centerV = brepFace.Domain(1).Mid;
            }
            else
            {
                var centroid = AreaMassProperties.Compute(brepFace).Centroid;
                brepFace.ClosestPoint(centroid, out centerU, out centerV);
            }

            Point3d  centerPt     = brepFace.PointAt(centerU, centerV);
            Vector3d normalVector = brepFace.NormalAt(centerU, centerU);

            return(centerPt, normalVector);
        }
示例#16
0
文件: open.cs 项目: pgovindraj/WizFDS
        private static bool CheckContainment(Editor ed, Brep brp, Point3d pt, ref List <Point3d> faceBoundary)
        {
            bool res = false;
            // Use the BRep API to get the lowest level
            // container for the point
            PointContainment pc;
            BrepEntity       be = brp.GetPointContainment(pt, out pc);

            using (be)
            {
                // Only if the point is on a boundary...
                if (pc == PointContainment.OnBoundary)
                {
                    // And only if the boundary is a face...
                    BrFace face = be as BrFace;
                    if (face != null)
                    {
                        // ... do we attempt to do something
                        try
                        {
#if BRX_APP
                            //faceBoundary.Add(face.BoundBlock.GetMinimumPoint());
                            //faceBoundary.Add(face.BoundBlock.GetMaximumPoint());
                            res = true;
#elif ARX_APP
                            faceBoundary.Add(face.BoundBlock.GetMinimumPoint());
                            faceBoundary.Add(face.BoundBlock.GetMaximumPoint());
                            res = true;
#endif
                        }
                        catch (BrException)
                        {
                            res = false;
                        }
                    }
                }
            }
            return(res);
        }
示例#17
0
        private void RhinoDocOnBeforeTransformObjects(object sender, RhinoTransformObjectsEventArgs ea)
        {
            RhinoObject[] rhinoObjects = ea.Objects;
            Vector3d      traslation;
            Transform     transform;

            ea.Transform.DecomposeAffine(out transform, out traslation);
            transform = transform.Transpose();

            for (int i = 0; i < rhinoObjects.Length; i++)
            {
                //Se il guid é presente nella lista allora fa parte delle jitter forme
                if (RigidBodyManager.GuidList.Contains(rhinoObjects[i].Id))
                {
                    int index = RigidBodyManager.GuidList.IndexOf(rhinoObjects[i].Id);
                    //If it is a rigid transformation (so translation and rotation)
                    if (ea.Transform.RigidType == TransformRigidType.Rigid)
                    {   //Rotate the body
                        JMatrix rotation = RigidBodyManager.RigidBodies[index].Orientation * new JMatrix((float)transform.M00, (float)transform.M01, (float)transform.M02, (float)transform.M10, (float)transform.M11, (float)transform.M12, (float)transform.M20, (float)transform.M21, (float)transform.M22);
                        RigidBodyManager.RigidBodies[index].Orientation = rotation;
                        //Move the center of mass of Jitter shape on the center of the BBox of rhino shape
                        Brep rhinoobj = (Brep)(ea.Objects[i].Geometry).Duplicate();
                        rhinoobj.Transform(ea.Transform);
                        Point3d centerBbox = rhinoobj.GetBoundingBox(true).Center;
                        RigidBodyManager.RigidBodies[index].Position = RigidBodyManager.Point3dtoJVector(centerBbox);
                        //Find the difference between rhino bbx center and jitter bbox center
                        JVector bboxjitter = RigidBodyManager.RigidBodies[index].BoundingBox.Center;
                        JVector diff       = bboxjitter - RigidBodyManager.Point3dtoJVector(centerBbox);
                        //Align the center of both bboxes
                        RigidBodyManager.RigidBodies[index].Position -= diff;
                    }
                    else
                    {
                        RhinoApp.WriteLine("You can't apply a non rigid transformation to a shape that has a rigid body property");
                        rigidTransf = false;
                    }
                }
            }
        }
示例#18
0
        private Brep MakeFrameBox(Brep[] frame)
        {
            Mesh m = new Mesh();
            Mesh f = new Mesh();

            for (int i = 0; i < meshnodes.Count; i++)
            {
                for (int j = 0; j < meshnodes[i].Count; j++)
                {
                    if (i < meshnodes.Count - 1 && j < meshnodes[i].Count - 1)
                    {
                        List <Point3d> points = new List <Point3d>()
                        {
                            meshnodes[i][j].point, meshnodes[i][j + 1].point, meshnodes[i + 1][j + 1].point, meshnodes[i + 1][j].point
                        };
                        FourNodeMesh(ref m, points);

                        List <Point3d> pointsF = new List <Point3d>()
                        {
                            frameGrid[i][j], frameGrid[i][j + 1], frameGrid[i + 1][j + 1], frameGrid[i + 1][j]
                        };
                        FourNodeMesh(ref f, pointsF);
                    }
                }
            }
            Brep        front = Brep.CreateFromMesh(m, false);
            Brep        back  = Brep.CreateFromMesh(f, false);
            List <Brep> breps = new List <Brep>();

            breps.Add(front);
            breps.Add(back);
            foreach (Brep b in frame)
            {
                breps.Add(b);
            }
            Brep[] box = Brep.JoinBreps(breps, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);

            return(box[0]);
        }
        // generat far 0.5-2
        public void buildingGenerator1(double density)
        {
            // density * offsetmax
            double off = (1 - density) * this.offsetMax();

            Curve[]  offset   = this.Outline.ToNurbsCurve().Offset(this.Center, Vector3d.ZAxis, off, inter_tol, CurveOffsetCornerStyle.Sharp);
            BrepFace basement = Brep.CreatePlanarBreps(offset[0], inter_tol)[0].Faces[0];
            double   floor    = Math.Floor(this.FAR / density);
            double   len      = this.Outline.Length;

            if (floor >= 1 && off < len / 20)
            {
                Brep ex = basement.CreateExtrusion(new Line(0, 0, 0, 0, 0, floor * 3).ToNurbsCurve(), true);
                this.Structure = ex;
            }
            else
            {
                Brep ex = basement.CreateExtrusion(new Line(0, 0, 0, 0, 0, 3).ToNurbsCurve(), true);
                this.Structure = ex;
            }
            this.OuterBorder = offset[0];
        }
示例#20
0
        public static string GrasshopperExport(Brep brep)
        {
            RhinoDoc.ActiveDoc.Objects.UnselectAll();

            var gh_brep = new GH_Brep(brep);

            Guid brepGuid = Guid.Empty;

            gh_brep.BakeGeometry(RhinoDoc.ActiveDoc, new ObjectAttributes(), ref brepGuid);

            RhinoDoc.ActiveDoc.Objects.Select(brepGuid, true);

            string exportName = GetTempFileName("stp");

            string exportCmd = "!_-Export _SaveSmall=Yes _GeometryOnly=Yes _SaveTextures=No _SavePlugInData=Yes " + "\"" + exportName + "\"" + " _Schema=AP214AutomotiveDesign _ExportParameterSpaceCurves=Yes _SplitClosedSurfaces=No _LetImportingApplicationSetColorForBlackObjects=Yes " + " _Enter";

            RhinoApp.RunScript(exportCmd, false);

            RhinoDoc.ActiveDoc.Objects.Delete(brepGuid, true);

            return(exportName);
        }
示例#21
0
        private List <Object> ToBrep(Topology topology, double tolerance)
        {
            IList <Face> faces          = topology.Faces;
            List <Brep>  ghBrepSurfaces = new List <Brep>();

            foreach (Face face in faces)
            {
                Brep ghBrepSurface = ToSurface(face, tolerance);
                ghBrepSurfaces.Add(ghBrepSurface);
            }

            if (ghBrepSurfaces.Count == 0)
            {
                return(null);
            }

            Brep[]        ghJoinedBreps          = Brep.JoinBreps(ghBrepSurfaces, 0.1);
            List <Object> ghJoinedBrepsAsObjects = new List <Object>();

            ghJoinedBrepsAsObjects.AddRange(ghJoinedBreps);
            return(ghJoinedBrepsAsObjects);
        }
示例#22
0
        public static Brep CreateNonPlanarBrep(IEnumerable <Curve> boundary, double startTolerance)
        {
            // Iterates tolerance values until a valid surface is created!
            var tolerance = startTolerance;
            var counter   = 0;
            var myBrep    = new Brep[0];

            while (counter < 1000)
            {
                myBrep = Brep.CreatePlanarBreps(boundary, tolerance);
                if (myBrep != null)
                {
                    return(myBrep[0]);
                }
                else
                {
                    tolerance *= 1.1;
                    counter   += 1;
                }
            }
            return(null);
        }
示例#23
0
        /// <summary>
        /// Example function
        /// </summary>
        public static int ExampleFunction(Brep brep, int x, int y, out Point3d[] points, out Line[] lines)
        {
            if (null == brep)
            {
                throw new ArgumentNullException(nameof(brep));
            }

            // Get the native ON_Brep pointer
            var const_ptr_brep = Interop.NativeGeometryConstPointer(brep);

            // Creates a ON_3dPointArray wrapper class instance
            var points_array = new Rhino.Runtime.InteropWrappers.SimpleArrayPoint3d();
            // Get a non-const point to this class
            var ptr_points_array = points_array.NonConstPointer();

            // Creates a ON_SimpleArray<ON_Line> wrapper class instance
            var lines_array = new Rhino.Runtime.InteropWrappers.SimpleArrayLine();
            // Get a non-const point to this class
            var ptr_lines_array = lines_array.NonConstPointer();

            var rc = UnsafeNativeMethods.MooseFunction(const_ptr_brep, x, y, ptr_points_array, ptr_lines_array);

            if (rc > 0)
            {
                points = points_array.ToArray();
                lines  = lines_array.ToArray();
            }
            else
            {
                points = new Point3d[0];
                lines  = new Line[0];
            }

            points_array.Dispose();
            lines_array.Dispose();

            return(rc);
        }
示例#24
0
        public static List <Brep> DrawCorridor(Apartment apartment)
        {
            List <Brep> output = new List <Brep>();

            #region P3Corridor
            if (apartment.AGtype == "PT-3")
            {
                List <Brep>  courtCorridorBrep = new List <Brep>();
                List <Curve> centerLine        = apartment.AptLines;
                double       width             = apartment.ParameterSet.Parameters[2];

                for (int i = 0; i < apartment.Household.Count; i++)
                {
                    for (int j = 0; j < apartment.Household[i].Count; j++)
                    {
                        List <Household> currentDongHouseholds = apartment.Household[i][j];
                        Curve            currentCenterLine     = centerLine[j];
                        Curve            currentInnerLine      = currentCenterLine.Offset(Plane.WorldXY, width / 2, 1, CurveOffsetCornerStyle.Sharp)[0];
                        Curve            corridorOutline       = currentInnerLine.Offset(Plane.WorldXY, Consts.corridorWidth, 1, CurveOffsetCornerStyle.Sharp)[0];

                        Brep corridorFloorBrep = Brep.CreatePlanarBreps(new List <Curve> {
                            currentInnerLine, corridorOutline
                        }).First();
                        Surface corridorWallSurface = Surface.CreateExtrusion(corridorOutline, Vector3d.Multiply(Vector3d.ZAxis, Consts.corridorWallHeight));
                        Brep    corridorWallBrep    = corridorWallSurface.ToBrep();

                        corridorWallBrep.Translate(Vector3d.Multiply(Vector3d.ZAxis, currentDongHouseholds[0].Origin.Z));
                        corridorFloorBrep.Translate(Vector3d.Multiply(Vector3d.ZAxis, currentDongHouseholds[0].Origin.Z));
                        courtCorridorBrep.Add(corridorWallBrep);
                        courtCorridorBrep.Add(corridorFloorBrep);
                    }
                }
                output = courtCorridorBrep;
            }
            #endregion P3Corridor

            return(output);
        }
示例#25
0
        public Surface[] FindSurfaces(List <Point3d> corners, Surface[] surfaces)
        {
            Surface[] sortedSurfaces = new Surface[6];

            corners = RoundPointsList(corners);

            Point3d[] surf0 = new Point3d[] { corners[0], corners[1], corners[4], corners[5] };
            Point3d[] surf1 = new Point3d[] { corners[1], corners[2], corners[5], corners[6] };
            Point3d[] surf2 = new Point3d[] { corners[2], corners[3], corners[6], corners[7] };
            Point3d[] surf3 = new Point3d[] { corners[0], corners[3], corners[4], corners[7] };

            for (int i = 0; i < surfaces.Length; i++)
            {
                Brep      surf       = surfaces[i].ToBrep();
                Point3d[] cornerSurf = surf.DuplicateVertices();

                cornerSurf = RoundPoints(cornerSurf);

                if (cornerSurf.All(surf0.Contains))
                {
                    sortedSurfaces[0] = surfaces[i];
                }
                if (cornerSurf.All(surf1.Contains))
                {
                    sortedSurfaces[1] = surfaces[i];
                }
                if (cornerSurf.All(surf2.Contains))
                {
                    sortedSurfaces[2] = surfaces[i];
                }
                if (cornerSurf.All(surf3.Contains))
                {
                    sortedSurfaces[3] = surfaces[i];
                }
            }

            return(sortedSurfaces);
        }
示例#26
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //---variables---

            List <Curve> curves = new List <Curve>();
            MeshGeometry mesh   = new MeshGeometry();

            //---input---

            if (!DA.GetDataList(0, curves))
            {
                return;
            }
            if (!DA.GetData(1, ref mesh))
            {
                return;
            }

            //---setup---

            Brep   origBrep  = mesh.GetOrigBrep();
            double volume    = origBrep.GetVolume();
            double sqrt3     = (double)1 / 3;
            double refLength = Math.Pow(volume, sqrt3);

            (List <string> texts, List <Plane> planes) = CreateTextAndPlane(curves, refLength);

            Color colorText = Color.Orange;

            double size = (double)refLength / 7;

            //---output---

            DA.SetDataList(0, texts);
            DA.SetData(1, size);
            DA.SetDataList(2, planes);
            DA.SetData(3, colorText);
        }
示例#27
0
文件: Util.cs 项目: yasenRK/ThePipe
        public static Brep GetTrimmedBrep(pps.Surface surface, SurfaceConverter surfConv, CurveConverter curveConv)
        {
            var rhSurf = surfConv.FromPipe <Surface, pps.Surface>(surface);
            var brep   = Brep.CreateFromSurface(rhSurf);

            if (!brep.IsValid)
            {
                brep.Repair(Rhino.RhinoMath.ZeroTolerance);
            }
            if (typeof(pps.NurbsSurface).IsAssignableFrom(surface.GetType()) &&
                ((pps.NurbsSurface)surface).TrimCurves.Count > 0)
            {
                List <ppc.Curve> trims = ((pps.NurbsSurface)surface).TrimCurves;
                List <ppc.Curve> loops = brep.Faces.First().Loops.Select((l) =>
                                                                         curveConv.ToPipe <Curve, ppc.Curve>(l.To3dCurve())).ToList();

                if (!PipeDataUtil.EqualIgnoreOrder(loops, trims))
                {
                    var rhTrims = trims.Select((c) => {
                        var cur   = curveConv.FromPipe <Curve, ppc.Curve>(c);
                        var cur2d = rhSurf.Pullback(cur, Rhino.RhinoMath.ZeroTolerance);
                        return(rhSurf.Pushup(cur2d, Rhino.RhinoMath.ZeroTolerance));
                    }).ToList();
                    var faceToSplit = brep.Faces.First();
                    var brep2       = faceToSplit.Split(rhTrims, Rhino.RhinoMath.ZeroTolerance);
                    if (brep2 != null && !brep2.IsValid)
                    {
                        brep2.Repair(Rhino.RhinoMath.ZeroTolerance);
                    }
                    if (brep2 != null && brep2.IsValid)
                    {
                        brep = GetEnclosedFacesAsBrep(brep2, rhTrims) ?? brep2;
                    }
                }
            }

            return(brep);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve curve = null;
            Brep  brep  = new Brep();

            if (!DA.GetData(0, ref curve))
            {
                return;
            }
            if (!DA.GetData(1, ref brep))
            {
                return;
            }

            double sqrt3      = (double)1 / 3;
            double refLength  = Math.Pow(brep.GetVolume(), sqrt3);
            double adjustment = 5 / refLength; //the length should give 5

            int surface = Convert.ToInt32(curve.GetLength() * adjustment);

            surface = surface > max ? max : surface;
            Surface surf = brep.Surfaces[surface];

            var           tuple     = CreateText(curve, refLength);
            List <string> text      = tuple.Item1;
            List <double> size      = tuple.Item2;
            List <Plane>  textPlane = tuple.Item3;
            Color         color     = tuple.Item4;

            Sphere sphere = new Sphere(curve.PointAtEnd, (double)(size[0] / 2));

            DA.SetData(0, surf);
            DA.SetDataList(1, text);
            DA.SetDataList(2, size);
            DA.SetDataList(3, textPlane);
            DA.SetData(4, color);
            DA.SetData(5, sphere);
        }
        public static DB.GeometryObject[] ToShape(this GeometryBase geometry, double factor)
        {
            switch (geometry)
            {
            case Point point:
                return(new DB.GeometryObject[] { point.ToPoint(factor) });

            case PointCloud pointCloud:
                return(pointCloud.ToPoints(factor));

            case Curve curve:
                return(curve.ToCurveMany(factor).SelectMany(x => x.ToBoundedCurves()).OfType <DB.GeometryObject>().ToArray());

            case Brep brep:
                return(ToGeometryObjectMany(BrepEncoder.ToRawBrep(brep, factor)).OfType <DB.GeometryObject>().ToArray());

            case Extrusion extrusion:
                return(ToGeometryObjectMany(ExtrusionEncoder.ToRawBrep(extrusion, factor)).OfType <DB.GeometryObject>().ToArray());

            case SubD subD:
                return(ToGeometryObjectMany(SubDEncoder.ToRawBrep(subD, factor)).OfType <DB.GeometryObject>().ToArray());;

            case Mesh mesh:
                return(new DB.GeometryObject[] { MeshEncoder.ToMesh(MeshEncoder.ToRawMesh(mesh, factor)) });

            default:
                if (geometry.HasBrepForm)
                {
                    var brepForm = Brep.TryConvertBrep(geometry);
                    if (BrepEncoder.EncodeRaw(ref brepForm, factor))
                    {
                        return(ToGeometryObjectMany(brepForm).OfType <DB.GeometryObject>().ToArray());
                    }
                }

                return(new DB.GeometryObject[0]);
            }
        }
示例#30
0
        public void CreateBreps()
        {
            // Surface At Top
            SurfaceAtTop = Brep.CreatePlanarBreps(CurvesAtTop);

            // Surface At Bottom
            SurfaceAtBottom = Brep.CreatePlanarBreps(CurvesAtBottom);

            // Surface At Top Plate
            if (PointsAtTopPlate != null)
            {
                SurfaceAtTopPlate = Brep.CreatePlanarBreps(CurvesAtTopPlate);
            }

            // Surface At Bottom Plate
            if (PointsAtBottomPlate != null)
            {
                SurfaceAtBottomPlate = Brep.CreatePlanarBreps(CurvesAtBottomPlate);
            }

            // Surface At Top Plate
            SurfaceAtLoop = Brep.CreateFromLoft(CurvesAtLoop, Point3d.Unset, Point3d.Unset, LoftType.Normal, false);
        }
示例#31
0
        public static GH_Structure <GH_Curve> GetJoined(IList <Brep> inBreps)
        {
            GH_Structure <GH_Curve> joinedCurves = new GH_Structure <GH_Curve>();

            for (int i = 0; i < inBreps.Count; i++)
            {
                GH_Path      path        = new GH_Path(i);
                Brep         brep        = inBreps[i];
                List <Curve> curvesToAdd = new List <Curve>();
                curvesToAdd.AddRange(BrepBorderExtractor.GetJoined(brep));

                foreach (Curve curve in curvesToAdd)
                {
                    GH_Curve ghCurve = null;
                    if (GH_Convert.ToGHCurve(curve, GH_Conversion.Both, ref ghCurve))
                    {
                        joinedCurves.Append(ghCurve, path);
                    }
                }
            }

            return(joinedCurves);
        }
示例#32
0
        public DirectShape BrepToDirectShape(Brep brep, BuiltInCategory cat = BuiltInCategory.OST_GenericModel)
        {
            var revitDs = DirectShape.CreateElement(Doc, new ElementId(cat));

            try
            {
                var solid = BrepToNative(brep);
                if (solid == null)
                {
                    throw new Exception("Could not convert Brep to Solid");
                }
                revitDs.SetShape(new List <GeometryObject> {
                    solid
                });
            }
            catch (Exception e)
            {
                var mesh = MeshToNative(brep.displayValue);
                revitDs.SetShape(mesh);
                ConversionErrors.Add(new Error(e.Message, e.InnerException?.Message ?? "No details available."));
            }
            return(revitDs);
        }
示例#33
0
文件: Network2.cs 项目: tsvilans/tas
        /// <summary>
        /// Orient nodes to match the surface normals of a Brep.
        /// </summary>
        /// <param name="brep">Brep to orient to.</param>
        /// <param name="max_range">Maximum search range.</param>
        /// <returns>Number of nodes changed.</returns>
        public int OrientNodes(Brep brep, double max_range = 0.0)
        {
            int            N = 0;
            Vector3d       normal;
            double         s, t;
            ComponentIndex ci;
            Point3d        cp;
            Transform      rot;

            foreach (Node n in NodeList)
            {
                if (n.Frame.IsValid)
                {
                    if (brep.ClosestPoint(n.Frame.Origin, out cp, out ci, out s, out t, max_range, out normal))
                    {
                        rot = Transform.Rotation(n.Frame.ZAxis, normal, n.Frame.Origin);
                        n.Frame.Transform(rot);
                        N++;
                    }
                }
            }
            return(N);
        }
示例#34
0
        private void ProcessSurfaceObject(RhinoObject obj)
        {
            Brep brp = obj.Geometry as Brep;

            if (brp.Surfaces.Count == 1) // test as floor first and then wall if this is a single face brp
            {
                if (IsViableObject(SupportedSchema.Floor, obj))
                {
                    SchemaDictionary[SupportedSchema.Floor.ToString()].Add(obj);
                }
                else if (IsViableObject(SupportedSchema.Wall, obj))
                {
                    SchemaDictionary[SupportedSchema.Wall.ToString()].Add(obj);
                }
            }
            else // if multi surface, test if it may be a wall
            {
                if (IsViableObject(SupportedSchema.Wall, obj))
                {
                    SchemaDictionary[SupportedSchema.Wall.ToString()].Add(obj);
                }
            }
        }
示例#35
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.GetDataTree("nodal_coordinates", out GH_Structure <GH_Number> _r); var r = _r.Branches;
            var surfaces = new List <Brep>(); DA.GetDataList("S", surfaces);
            var rigid    = new GH_Structure <GH_Number>();

            for (int i = 0; i < surfaces.Count; i++)
            {
                var surf = surfaces[i]; var face = surf.Faces[0];
                var solid = Brep.CreateFromOffsetFace(face, 0.1, 5e-3, true, true);
                var nodes = new List <GH_Number>();
                for (int j = 0; j < r.Count; j++)
                {
                    var p = new Point3d(r[j][0].Value, r[j][1].Value, r[j][2].Value);
                    if (solid.IsPointInside(p, 5e-3, false) == true)
                    {
                        nodes.Add(new GH_Number(j));
                    }
                }
                rigid.AppendRange(nodes, new GH_Path(i));
            }
            DA.SetDataTree(0, rigid);
        }
示例#36
0
文件: Profile.cs 项目: paireks/T-Rex
        public Profile(string name, List <Point3d> points, double tolerance)
        {
            Tolerance     = tolerance;
            ProfilePoints = points;

            List <Point3d> pointsForPolyline = points;

            pointsForPolyline.Add(points[0]);

            Polyline polyline = new Polyline(pointsForPolyline);

            if (!polyline.IsClosed)
            {
                throw new ArgumentException("Polyline should be closed");
            }

            Line[]       lines  = polyline.GetSegments();
            List <Curve> curves = lines.Select(line => line.ToNurbsCurve()).Cast <Curve>().ToList();

            BoundarySurfaces = Brep.CreatePlanarBreps(curves, tolerance);
            ProfileCurve     = polyline.ToNurbsCurve();
            Name             = name;
        }
        public static Brep CreateHollowBrep(Curve curve1, Curve curve2)
        {
            Brep     brep1     = Brep.CreatePlanarBreps(new[] { curve1 })[0];
            Brep     brep2     = Brep.CreatePlanarBreps(new[] { curve2 })[0];
            RhinoDoc doc       = RhinoDoc.ActiveDoc;
            double   area      = Brep.CreateBooleanUnion(new[] { brep1, brep2 }, 0.001)[0].GetArea();
            double   brep1Area = brep1.GetArea();
            double   brep2Area = brep2.GetArea();

            if (area > 0.999 * brep1Area && area < 1.001 * brep1Area)
            {
                return(Brep.CreateBooleanDifference(brep1, brep2, doc.ModelAbsoluteTolerance)[0]);
            }

            else if (area > 0.999 * brep2Area && area < 1.001 * brep2Area)
            {
                return(Brep.CreateBooleanDifference(brep1, brep2, doc.ModelAbsoluteTolerance)[0]);
            }
            else
            {
                return(null);
            }
        }
示例#38
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Brep brep = null;

            if (!DA.GetData(0, ref brep))
            {
                return;
            }
            Curve[] edges  = brep.DuplicateNakedEdgeCurves(true, true);
            Curve[] curves = Curve.JoinCurves(edges);

            Shape shape = new Shape(curves.ToList());

            Graphic graphic = Graphics.FillBlack;

            if (DA.GetData(1, ref graphic))
            {
                shape.Graphic = new Graphic(graphic);
            }
            ;

            DA.SetData(0, shape);
        }
 /// <summary>
 /// Draws a shaded mesh representation of a brep.
 /// </summary>
 /// <param name="brep">Brep to draw.</param>
 /// <param name="material">Material to draw faces with.</param>
 public void DrawBrepShaded(Brep brep, DisplayMaterial material)
 {
   IntPtr pBrep = brep.ConstPointer();
   IntPtr pMaterial = IntPtr.Zero;
   if (null != material)
     pMaterial = material.ConstPointer();
   UnsafeNativeMethods.CRhinoDisplayPipeline_DrawShadedBrep(m_ptr, pBrep, pMaterial);
 }
示例#40
0
    /// <summary>
    /// Compute the VolumeMassProperties for a single Brep.
    /// </summary>
    /// <param name="brep">Brep to measure.</param>
    /// <returns>The VolumeMassProperties for the given Brep or null on failure.</returns>
    /// <exception cref="System.ArgumentNullException">When brep is null.</exception>
    public static VolumeMassProperties Compute(Brep brep)
    {
      if (brep == null)
        throw new ArgumentNullException("brep");

      IntPtr pBrep = brep.ConstPointer();
      const double relativeTolerance = 1.0e-6;
      const double absoluteTolerance = 1.0e-6;
      IntPtr rc = UnsafeNativeMethods.ON_Brep_MassProperties(false, pBrep, relativeTolerance, absoluteTolerance);
      return IntPtr.Zero == rc ? null : new VolumeMassProperties(rc, false);
    }
示例#41
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;
    }
    /// <summary>
    /// Intersects a Brep and a Surface.
    /// </summary>
    /// <param name="brep">A brep to be intersected.</param>
    /// <param name="surface">A surface to be intersected.</param>
    /// <param name="tolerance">A tolerance value.</param>
    /// <param name="intersectionCurves">The intersection curves array argument. This out reference is assigned during the call.</param>
    /// <param name="intersectionPoints">The intersection points array argument. This out reference is assigned during the call.</param>
    /// <returns>true on success; false on failure.</returns>
    public static bool BrepSurface(Brep brep, Surface surface, double tolerance, out Curve[] intersectionCurves, out Point3d[] intersectionPoints)
    {
      intersectionCurves = new Curve[0];
      intersectionPoints = new Point3d[0];

      Runtime.InteropWrappers.SimpleArrayPoint3d outputPoints = new Runtime.InteropWrappers.SimpleArrayPoint3d();
      IntPtr outputPointsPtr = outputPoints.NonConstPointer();

      Runtime.InteropWrappers.SimpleArrayCurvePointer outputCurves = new Runtime.InteropWrappers.SimpleArrayCurvePointer();
      IntPtr outputCurvesPtr = outputCurves.NonConstPointer();

      IntPtr brepPtr = brep.ConstPointer();
      IntPtr surfacePtr = surface.ConstPointer();

      bool rc = UnsafeNativeMethods.ON_Intersect_BrepSurface(brepPtr, surfacePtr, tolerance, outputCurvesPtr, outputPointsPtr);

      if (rc)
      {
        intersectionCurves = outputCurves.ToNonConstArray();
        intersectionPoints = outputPoints.ToArray();
      }

      outputPoints.Dispose();
      outputCurves.Dispose();

      return rc;
    }
  static void MakeTwistedCubeTrimmingLoop( ref Brep brep, ref BrepFace face, // Indices of corner vertices listed in SW, SE, NW, NE order
  int eSi,     // index of edge on south side of surface
  int eS_dir,  // orientation of edge with respect to surface trim
  int eEi,     // index of edge on south side of surface
  int eE_dir,  // orientation of edge with respect to surface trim
  int eNi,     // index of edge on south side of surface
  int eN_dir,  // orientation of edge with respect to surface trim
  int eWi,     // index of edge on south side of surface
  int eW_dir   // orientation of edge with respect to surface trim
                               )
  {
    Surface srf = brep.Surfaces[face.SurfaceIndex];
    var loop = brep.Loops.Add(BrepLoopType.Outer, face);

    // Create trimming curves running counter clockwise around the surface's domain.
    // Start at the south side
    // side: 0=south, 1=east, 2=north, 3=west
    for (int side = 0; side < 4; side++)
    {
      Curve trimming_curve = TwistedCubeTrimmingCurve(srf, side);
      int curve_index = brep.Curves2D.Add(trimming_curve);

      int ei = 0;
      bool reverse = false;
      IsoStatus iso = IsoStatus.None;
      switch (side)
      {
        case 0: // south
          ei = eSi;
          reverse = (eS_dir == -1);
          iso = IsoStatus.South;
          break;
        case 1: // east
          ei = eEi;
          reverse = (eE_dir == -1);
          iso = IsoStatus.East;
          break;
        case 2: // north
          ei = eNi;
          reverse = (eN_dir == -1);
          iso = IsoStatus.North;
          break;
        case 3: // west
          ei = eWi;
          reverse = (eW_dir == -1);
          iso = IsoStatus.West;
          break;
      }

      BrepEdge edge = brep.Edges[ei];
      BrepTrim trim = brep.Trims.Add(edge, reverse, loop, curve_index);
      trim.IsoStatus = iso;
      trim.TrimType = BrepTrimType.Mated; // This b-rep is closed, so all trims have mates.
      trim.SetTolerances(0, 0); // This simple example is exact - for models with
      // non-exact data, set tolerance as explained in
      // definition of BrepTrim.
    }
  }
示例#44
0
    /// <summary>
    /// Projects a Curve onto a Brep along a given direction.
    /// </summary>
    /// <param name="curve">Curve to project.</param>
    /// <param name="brep">Brep to project onto.</param>
    /// <param name="direction">Direction of projection.</param>
    /// <param name="tolerance">Tolerance to use for projection.</param>
    /// <returns>An array of projected curves or empty array if the projection set is empty.</returns>
    public static Curve[] ProjectToBrep(Curve curve, Brep brep, Vector3d direction, double tolerance)
    {
      IntPtr brep_ptr = brep.ConstPointer();
      IntPtr curve_ptr = curve.ConstPointer();

      using (SimpleArrayCurvePointer rc = new SimpleArrayCurvePointer())
      {
        IntPtr rc_ptr = rc.NonConstPointer();
        return UnsafeNativeMethods.RHC_RhinoProjectCurveToBrep(brep_ptr, curve_ptr, direction, tolerance, rc_ptr) ? rc.ToNonConstArray() : new Curve[0];
      }
    }
    public TestSurfaceDirConduit(Brep brep)
    {
        m_brep = brep;
        Flip = false;

        const int SURFACE_ARROW_COUNT = 5;
        int face_count = m_brep.Faces.Count;
        int capacity = face_count * SURFACE_ARROW_COUNT * SURFACE_ARROW_COUNT;
        m_points = new List<Point3d>(capacity);
        m_normals = new List<Vector3d>(capacity);

        for (int i = 0; i < face_count; i++)
        {
          var face = brep.Faces[i];
          var loop = face.OuterLoop;
          if (loop == null)
        continue;

          var udomain = face.Domain(0);
          var vdomain = face.Domain(1);
          var loop_bbox = loop.GetBoundingBox(true);
          if (loop_bbox.IsValid)
          {
        Interval domain = new Interval(loop_bbox.Min.X, loop_bbox.Max.X);
        domain = Interval.FromIntersection(domain, udomain);
        if (domain.IsIncreasing)
          udomain = domain;
        domain = new Interval(loop_bbox.Min.Y, loop_bbox.Max.Y);
        domain = Interval.FromIntersection(domain, vdomain);
        if (domain.IsIncreasing)
          vdomain = domain;
          }

          bool bUntrimmed = face.IsSurface;
          bool bRev = face.OrientationIsReversed;
          for (double u = 0; u < SURFACE_ARROW_COUNT; u += 1.0)
          {
        double d = u / (SURFACE_ARROW_COUNT - 1.0);
        double s = udomain.ParameterAt(d);

        var intervals = face.TrimAwareIsoIntervals(1, s);
        if (bUntrimmed || intervals.Length > 0)
        {
          for (double v = 0; v < SURFACE_ARROW_COUNT; v += 1.0)
          {
            d = v / (SURFACE_ARROW_COUNT - 1.0);
            double t = vdomain.ParameterAt(d);
            bool bAdd = bUntrimmed;
            for (int k = 0; !bAdd && k < intervals.Length; k++)
            {
              if (intervals[k].IncludesParameter(t))
                bAdd = true;
            }
            if (bAdd)
            {
              var pt = face.PointAt(s, t);
              var vec = face.NormalAt(s, t);
              m_points.Add(pt);
              if (bRev)
                vec.Reverse();
              m_normals.Add(vec);
            }
          }
        }
          }
        }
    }
 /// <summary>
 /// Draws all the wireframe curves of a brep object.
 /// </summary>
 /// <param name="brep">Brep to draw.</param>
 /// <param name="color">Color of Wireframe curves.</param>
 public void DrawBrepWires(Brep brep, System.Drawing.Color color)
 {
   DrawBrepWires(brep, color, 1);
 }
示例#47
0
 public Polyline Project(Polyline pl, Brep sf)
 {
     Mesh[] meshes = Mesh.CreateFromBrep(sf);
     if (meshes.Length > 0) return Project(pl, meshes[0]);
     return null;
 }
  static void MakeTwistedCubeFaces(ref Brep brep)
  {
    MakeTwistedCubeFace(ref brep,
      ABCD,       // Index of surface ABCD
      +1, // Indices of vertices listed in SW,SE,NW,NE order
      AB, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (AB)
      BC, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (BC)
      CD, +1,     // South side edge and its orientation with respect to
      // to the trimming curve   (CD)
      AD, -1      // South side edge and its orientation with respect to
      // to the trimming curve   (AD)
      );

    MakeTwistedCubeFace(ref brep,
      BCGF,       // Index of surface BCGF
      -1, // Indices of vertices listed in SW,SE,NW,NE order
      BC, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (BC)
      CG, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (CG)
      FG, -1,     // South side edge and its orientation with respect to
      // to the trimming curve   (FG)
      BF, -1      // South side edge and its orientation with respect to
      // to the trimming curve   (BF)
      );

    MakeTwistedCubeFace(ref brep,
      CDHG,       // Index of surface CDHG
      -1, // Indices of vertices listed in SW,SE,NW,NE order
      CD, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (CD)
      DH, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (DH)
      GH, -1,     // South side edge and its orientation with respect to
      // to the trimming curve   (GH)
      CG, -1      // South side edge and its orientation with respect to
      // to the trimming curve   (CG)
      );

    MakeTwistedCubeFace(ref brep,
      ADHE,       // Index of surface ADHE
      +1, // Indices of vertices listed in SW,SE,NW,NE order
      AD, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (AD)
      DH, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (DH)
      EH, -1,     // South side edge and its orientation with respect to
      // to the trimming curve   (EH)
      AE, -1      // South side edge and its orientation with respect to
      // to the trimming curve   (AE)
      );

    MakeTwistedCubeFace(ref brep,
      ABFE,       // Index of surface ABFE
      -1, // Indices of vertices listed in SW,SE,NW,NE order
      AB, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (AB)
      BF, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (BF)
      EF, -1,     // South side edge and its orientation with respect to
      // to the trimming curve   (EF)
      AE, -1      // South side edge and its orientation with respect to
      // to the trimming curve   (AE)
      );

    MakeTwistedCubeFace(ref brep,
      EFGH,       // Index of surface EFGH
      -1, // Indices of vertices listed in SW,SE,NW,NE order
      EF, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (EF)
      FG, +1,     // South side edge and its orientation with respect to
      // to the trimming curve.  (FG)
      GH, +1,     // South side edge and its orientation with respect to
      // to the trimming curve   (GH)
      EH, -1      // South side edge and its orientation with respect to
      // to the trimming curve   (EH)
      );
  }
        // ====================================================================
        //---- 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];
        }
 static void MakeTwistedCubeEdges(ref Brep brep)
 {
   // In this simple example, the edge indices exactly match the 3d curve
   // indices.  In general,the correspondence between edge and curve indices
   // can be arbitrary.  It is permitted for multiple edges to use different
   // portions of the same 3d curve.  The orientation of the edge always
   // agrees with the natural parametric orientation of the curve.
   brep.Edges.Add(A, B, AB, 0); // Edge that runs from A to B
   brep.Edges.Add(B, C, BC, 0); // Edge that runs from B to C
   brep.Edges.Add(C, D, CD, 0); // Edge that runs from C to D
   brep.Edges.Add(A, D, AD, 0); // Edge that runs from A to D
   brep.Edges.Add(E, F, EF, 0); // Edge that runs from E to F
   brep.Edges.Add(F, G, FG, 0); // Edge that runs from F to G
   brep.Edges.Add(G, H, GH, 0); // Edge that runs from G to H
   brep.Edges.Add(E, H, EH, 0); // Edge that runs from E to H
   brep.Edges.Add(A, E, AE, 0); // Edge that runs from A to E
   brep.Edges.Add(B, F, BF, 0); // Edge that runs from B to F
   brep.Edges.Add(C, G, CG, 0); // Edge that runs from C to G
   brep.Edges.Add(D, H, DH, 0); // Edge that runs from D to H
 }
 /// <summary>
 /// Draws all the wireframe curves of a brep object.
 /// </summary>
 /// <param name="brep">Brep to draw.</param>
 /// <param name="color">Color of Wireframe curves.</param>
 /// <param name="wireDensity">
 /// "Density" of wireframe curves.
 /// <para>-1 = no internal wires.</para>
 /// <para> 0 = default internal wires.</para>
 /// <para>>0 = custom high density.</para>
 /// </param>
 public void DrawBrepWires(Brep brep, System.Drawing.Color color, int wireDensity)
 {
   int argb = color.ToArgb();
   IntPtr pBrep = brep.ConstPointer();
   UnsafeNativeMethods.CRhinoDisplayPipeline_DrawBrep(m_ptr, pBrep, argb, wireDensity);
 }
示例#52
0
 /// <summary>
 /// Copies the unmanaged array to a managed counterpart.
 /// </summary>
 /// <returns>The managed array.</returns>
 public Geometry.Brep[] ToNonConstArray()
 {
   int count = Count;
   if (count < 1)
     return new Geometry.Brep[0]; //MSDN guidelines prefer empty arrays
   IntPtr ptr = ConstPointer();
   Brep[] rc = new Brep[count];
   for (int i = 0; i < count; i++)
   {
     IntPtr pBrep = UnsafeNativeMethods.ON_BrepArray_Get(ptr, i);
     if (IntPtr.Zero != pBrep)
       rc[i] = new Brep(pBrep, null);
   }
   return rc;
 }
示例#53
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;
            }
        }
    /// <summary>
    /// Intersects a Brep with an (infinite) plane.
    /// </summary>
    /// <param name="brep">Brep to intersect.</param>
    /// <param name="plane">Plane to intersect with.</param>
    /// <param name="tolerance">Tolerance to use for intersections.</param>
    /// <param name="intersectionCurves">The intersection curves will be returned here.</param>
    /// <param name="intersectionPoints">The intersection points will be returned here.</param>
    /// <returns>true on success, false on failure.</returns>
    public static bool BrepPlane(Brep brep, Plane plane, double tolerance, out Curve[] intersectionCurves, out Point3d[] intersectionPoints)
    {
      intersectionPoints = null;
      intersectionCurves = null;

      //David sez: replace this logic with the dedicated Geometry/Plane intersector methods in Rhino5.
      if (!plane.IsValid)
        return false;

      PlaneSurface section = ExtendThroughBox(plane, brep.GetBoundingBox(false), 1.0); //should this be 1.0 or 100.0*tolerance?
      bool rc = false;
      if (section != null)
      {
        rc = BrepSurface(brep, section, tolerance, out intersectionCurves, out intersectionPoints);
        section.Dispose();
      }
      return rc;
    }
示例#55
0
    /// <summary>
    /// Splits a curve into pieces using a polysurface.
    /// </summary>
    /// <param name="cutter">A cutting surface or polysurface.</param>
    /// <param name="tolerance">A tolerance for computing intersections.</param>
    /// <returns>An array of curves. This array can be empty.</returns>
    public Curve[] Split(Brep cutter, double tolerance)
    {
      if (cutter == null) throw new ArgumentNullException("cutter");

      IntPtr pConstThis = ConstPointer();
      IntPtr pConstBrep = cutter.ConstPointer();
      using (Rhino.Runtime.InteropWrappers.SimpleArrayCurvePointer pieces = new SimpleArrayCurvePointer())
      {
        IntPtr pPieces = pieces.NonConstPointer();
        UnsafeNativeMethods.RHC_RhinoCurveSplit(pConstThis, pConstBrep, tolerance, pPieces);
        return pieces.ToNonConstArray();
      }
    }
    /// <summary>
    /// Intersects a curve with a Brep. This function returns the 3D points of intersection
    /// and 3D overlap curves. If an error occurs while processing overlap curves, this function 
    /// will return false, but it will still provide partial results.
    /// </summary>
    /// <param name="curve">Curve for intersection.</param>
    /// <param name="brep">Brep for intersection.</param>
    /// <param name="tolerance">Fitting and near miss tolerance.</param>
    /// <param name="overlapCurves">The overlap curves will be returned here.</param>
    /// <param name="intersectionPoints">The intersection points will be returned here.</param>
    /// <returns>true on success, false on failure.</returns>
    /// <example>
    /// <code source='examples\vbnet\ex_elevation.vb' lang='vbnet'/>
    /// <code source='examples\cs\ex_elevation.cs' lang='cs'/>
    /// <code source='examples\py\ex_elevation.py' lang='py'/>
    /// </example>
    public static bool CurveBrep(Curve curve, Brep brep, double tolerance, out Curve[] overlapCurves, out Point3d[] intersectionPoints)
    {
      overlapCurves = new Curve[0];
      intersectionPoints = new Point3d[0];

      Runtime.InteropWrappers.SimpleArrayPoint3d outputPoints = new Runtime.InteropWrappers.SimpleArrayPoint3d();
      IntPtr outputPointsPtr = outputPoints.NonConstPointer();

      Runtime.InteropWrappers.SimpleArrayCurvePointer outputCurves = new Runtime.InteropWrappers.SimpleArrayCurvePointer();
      IntPtr outputCurvesPtr = outputCurves.NonConstPointer();

      IntPtr curvePtr = curve.ConstPointer();
      IntPtr brepPtr = brep.ConstPointer();

      bool rc = UnsafeNativeMethods.ON_Intersect_CurveBrep(curvePtr, brepPtr, tolerance, outputCurvesPtr, outputPointsPtr);

      if (rc)
      {
        overlapCurves = outputCurves.ToNonConstArray();
        intersectionPoints = outputPoints.ToArray();
      }

      outputPoints.Dispose();
      outputCurves.Dispose();

      return rc;
    }
示例#57
0
 protected CustomBrepObject(Brep brep)
   : base(true)
 {
   IntPtr pConstBrep = brep.ConstPointer();
   m_pRhinoObject = UnsafeNativeMethods.CRhinoCustomObject_New2(pConstBrep);
 }
  static void MakeTwistedCubeFace( ref Brep brep, int surfaceIndex,
    int s_dir,   // Indices of corner vertices listed in SW, SE, NW, NE order
    int southEdgeIndex,
    int eS_dir,  // orientation of edge with respect to surface trim
    int eastEdgeIndex,
    int eE_dir,  // orientation of edge with respect to surface trim
    int northEdgeIndex,
    int eN_dir,  // orientation of edge with respect to surface trim
    int westEdgeIndex,
    int eW_dir   // orientation of edge with respect to surface trim
    )
  {
    var face = brep.Faces.Add(surfaceIndex);

    MakeTwistedCubeTrimmingLoop(
      ref brep,
      ref face,
      southEdgeIndex, eS_dir,
      eastEdgeIndex, eE_dir,
      northEdgeIndex, eN_dir,
      westEdgeIndex, eW_dir
      );

    face.OrientationIsReversed = (s_dir == -1);
  }
            public override void Register_Edges(IEnumerable<Hare.Geometry.Point> S, IEnumerable<Hare.Geometry.Point> R)
            {
                //Collect Edge Curves
                List<Curve> Naked_Edges = new List<Curve>();
                List<Brep> Naked_Breps = new List<Brep>();
                List<double> Lengths = new List<double>();
                List<double[]> EdgeDomains = new List<double[]>();
                List<int> Brep_IDS = new List<int>();
                //Brep.JoinBreps()

                for (int q = 0; q < BrepList.Count; q++)
                {
                    foreach (BrepEdge be in BrepList[q].Edges)
                    {                                    
                        int[] EdgeMembers = be.AdjacentFaces();
                        switch (be.Valence)
                        {
                            case EdgeAdjacency.Interior:
                                ///This probably doesn't do any work anymore... Kept for future reference (and because it is harmless to do so...).
                                if (be.IsLinear())
                                {
                                    if (be.IsSmoothManifoldEdge()) continue; //ignore this condition...
                                    if (BrepList[q].Faces[EdgeMembers[0]].IsPlanar() && BrepList[q].Faces[EdgeMembers[1]].IsPlanar())
                                    {
                                        //Curve is straight, and surfaces are planar (Monolithic Edge)
                                        //Determine if surfaces are coplanar.//////////
                                        Brep[] BR = new Brep[2] { BrepList[q].Faces[EdgeMembers[0]].DuplicateFace(false), BrepList[q].Faces[EdgeMembers[1]].DuplicateFace(false) };
                                        //Rhino.RhinoDoc.ActiveDoc.Objects.Add(BR[0]);
                                        //Rhino.RhinoDoc.ActiveDoc.Objects.Add(BR[1]);
                                        Edge_Nodes.Add(new Edge_Straight(ref S, ref R, this.Env_Prop, BR, new int[2]{q, q}, be));///TODO: Confirm SoundSpeed Approach suitability...
                                    }
                                    else
                                    {
                                        ///Edge Curved Condition
                                        Brep[] BR = new Brep[2] { BrepList[q].Faces[EdgeMembers[0]].DuplicateFace(false), BrepList[q].Faces[EdgeMembers[1]].DuplicateFace(false) };
                                        Edge_Nodes.Add(new Edge_Curved(ref S, ref R, this.Env_Prop, BR, new int[2]{q, q}, be));///TODO: Confirm SoundSpeed Approach suitability...                                        
                                    }
                                }
                                break;
                            case EdgeAdjacency.Naked:
                                //Sorted edges allow us to assume a relationship between curves...
                                double l = be.GetLength();
                                bool register_anyway = true;
                                for (int i = 0; i < Naked_Edges.Count; i++)
                                {
                                    if (l < Lengths[i]) 
                                    {
                                        Naked_Breps.Insert(0, BrepList[q].Faces[EdgeMembers[0]].DuplicateFace(false));
                                        Naked_Edges.Insert(0, be);
                                        EdgeDomains.Insert(0, new double[] { be.Domain[0], be.Domain[1] });
                                        Lengths.Insert(0, l);
                                        Brep_IDS.Insert(0, q);
                                        register_anyway = false;
                                        ////////////////
                                        //Rhino.RhinoDoc.ActiveDoc.Objects.AddCurve(be);
                                        ////////////////
                                        break;
                                    }
                                }
                                if (register_anyway)
                                { 
                                    Naked_Breps.Add(BrepList[q].Faces[EdgeMembers[0]].DuplicateFace(false));
                                    Naked_Edges.Add(be);
                                    EdgeDomains.Add(new double[] { be.Domain[0], be.Domain[1] });
                                    Lengths.Add(l);
                                    Brep_IDS.Add(q);
                                    ////////////////
                                    //Rhino.RhinoDoc.ActiveDoc.Objects.AddCurve(be);
                                    ////////////////
                                }
                                break;
                            case EdgeAdjacency.None:
                                //Ignore this edge...
                                //What kind of edge, is neither Naked, nor Interior, nor NonManifold??
                                continue;
                            case EdgeAdjacency.NonManifold:
                                //Ignore tnis edge, but alert the user...
                                System.Windows.Forms.MessageBox.Show("Non-Manifold Edges. Could you please send a copy of this model to [email protected]? Also - if you know how you built this, please don't do it again...");
                                break;
                        }
                    }
                }

                ///In descending order by length - first edge will always be the longer one.
                Naked_Breps.Reverse();
                Naked_Edges.Reverse();
                EdgeDomains.Reverse();
                Brep_IDS.Reverse();
                Lengths.Reverse();

                //Handle Naked Edges... (this is now probably the only work being done by this function... this is where the magic happens...)
                double tolerance = 0.001;
                List<Curve> Orphaned_Edge = new List<Curve>();
                List<Brep> Orphaned_Brep = new List<Brep>();
                while (Naked_Edges.Count > 0)
                {
                    bool orphaned = true; //Orphaned until proven otherwise...

                    while (Naked_Edges[0] == null)
                    {
                        Naked_Edges.RemoveAt(0);
                        Naked_Breps.RemoveAt(0);
                        EdgeDomains.RemoveAt(0);
                        Lengths.RemoveAt(0);
                        Brep_IDS.RemoveAt(0);
                        continue;
                    }

                    List<Curve> ToAdd = new List<Curve>();
                    List<Brep> ToAddMembers = new List<Brep>();
                    List<int> ToAddIDS = new List<int>();

                    for (int shortid = 1; shortid < Naked_Edges.Count; shortid++)
                    {
                        Brep[] BR = new Brep[2] { Naked_Breps[shortid], Naked_Breps[0] };
                        int[] B_IDS = new int[2] { Brep_IDS[shortid], Brep_IDS[0] };

                        //Check for Match Case: (simplest edge coincidence)
                        if (Naked_Edges[0].GetLength() - Naked_Edges[shortid].GetLength() < 0.01)
                        {
                            //Curves are effectively the same length... this might be very easy.
                            if (((Naked_Edges[0].PointAtStart - Naked_Edges[shortid].PointAtStart).SquareLength < 0.0001) && ((Naked_Edges[0].PointAtEnd - Naked_Edges[shortid].PointAtEnd).SquareLength < 0.0001) ||
                            ((Naked_Edges[0].PointAtStart - Naked_Edges[shortid].PointAtEnd).SquareLength < 0.0001) && ((Naked_Edges[0].PointAtEnd - Naked_Edges[shortid].PointAtStart).SquareLength < 0.0001))
                            {
                                //Curves are effectively coincident...
                                if (Naked_Edges[shortid].IsLinear()) Edge_Nodes.Add(new Edge_Straight(ref S, ref R, this.Env_Prop, BR, B_IDS, Naked_Edges[shortid]));
                                else Edge_Nodes.Add(new Edge_Curved(ref S, ref R, this.Env_Prop, BR, B_IDS, Naked_Edges[0]));

                                Naked_Edges.RemoveAt(shortid);
                                Naked_Breps.RemoveAt(shortid);
                                EdgeDomains.RemoveAt(shortid);
                                Lengths.RemoveAt(shortid);
                                Brep_IDS.RemoveAt(shortid);
                                Naked_Edges.RemoveAt(0);
                                Naked_Breps.RemoveAt(0);
                                EdgeDomains.RemoveAt(0);
                                Lengths.RemoveAt(0);
                                Brep_IDS.RemoveAt(0);
                                orphaned = false;
                                break;
                            }
                        }

                        //if (Naked_Edges[shortid] == null) continue;
                        //Does start or end point fall on longer curve...
                        double t1;
                        double dir;
                        double domstart;
                        Point3d Start;

                        if (Naked_Edges[0].ClosestPoint(Naked_Edges[shortid].PointAtStart, out t1, tolerance) && Naked_Edges[0].TangentAt(t1).IsParallelTo(Naked_Edges[shortid].TangentAtStart) > 0)
                        {
                            //Does start id on short curve intersect?
                            //if (Naked_Edges[shortid].TangentAt(t1).IsParallelTo(Naked_Edges[0].TangentAtStart) == 0) continue;
                            dir = .1;
                            Start = Naked_Edges[shortid].PointAtStart;
                            domstart = EdgeDomains[shortid][0];
                        }
                        else if (Naked_Edges[0].ClosestPoint(Naked_Edges[shortid].PointAtEnd, out t1, tolerance) && Naked_Edges[0].TangentAt(t1).IsParallelTo(Naked_Edges[shortid].TangentAtEnd) > 0)
                        {
                            //Does end point on short curve intersect?
                            //if (Naked_Edges[shortid].TangentAt(t1).IsParallelTo(Naked_Edges[0].TangentAtEnd) == 0) continue;
                            Start = Naked_Edges[shortid].PointAtEnd;
                            dir = -.1;
                            domstart = EdgeDomains[shortid][1];
                        }
                        else
                        {
                            //Does any point on curves intersect?
                            int g;
                            Point3d p1, p2;
                            if (!Naked_Edges[0].ClosestPoints(new Curve[] { Naked_Edges[shortid] }, out p1, out p2, out g, 0.01)) continue;
                            dir = .1;
                            Start = Naked_Edges[shortid].PointAtStart;
                            t1 = Naked_Edges[shortid].Domain.T0;
                            domstart = EdgeDomains[shortid][0];
                        }

                        //Iterate across curves, Dog-Man style.
                        double tsS = t1, tsE = t1;
                        
                        while (true)
                        {
                            ////if curves are not merged
                            //////Go to the next point on the short curve and keep looking, till the short curve is exhausted. 
                            tsS = tsE;
                            double tlS;

                            Point3d pt = Naked_Edges[shortid].PointAt(tsS);
                            if (!Naked_Edges[0].ClosestPoint(pt, out tlS, 0.02))
                            {
                                //They don't match up.
                                if (Naked_Edges[0].Domain.IncludesParameter(tsS))
                                {
                                    //We are still on the long curve: Keep checking in case it may match up later...
                                    tsE += dir;
                                    continue;
                                }
                                break;
                            }

                            double tlE = tlS;

                            if (Math.Abs(Rhino.Geometry.Vector3d.Multiply(Naked_Edges[shortid].TangentAt(tsS), Naked_Edges[0].TangentAt(tlS))) < 0.98)
                            {
                                // edges may meet here, but the curves are not even remotely parallel... they might be some kind of corner junction. Go to the next curve.
                                tsE += dir;
                                continue;
                            }

                            ////If curves are merged, iterate through points until curves do not merge, or entire section of one or other is exhausted.
                            
                            tsE += dir;
                            pt = Naked_Edges[shortid].PointAt(tsE);

                            double tl2, ts2 = t1;
                            while (Naked_Edges[0].ClosestPoint(pt, out tl2, 0.01))
                            {
                                double d = Naked_Edges[0].PointAt(tl2).DistanceTo(pt);
                                if (d > 0.01) break;
                                //Curves are merged - increment check and try again.
                                tlE = tl2;
                                tsE = ts2;
                                ts2 += dir;
                                pt = Naked_Edges[shortid].PointAt(tsE);
                            }

                            if (tsS > tsE)
                            {
                                double t = tsE;
                                tsE = tsS;
                                tsS = t;
                            }

                            if (tlS > tlE)
                            {
                                double t = tlE;
                                tlE = tlS;
                                tlS = t;
                            }

                            Curve newEdge = Naked_Edges[shortid].Trim(new Interval(tsS, tsE));

                            if (newEdge == null || newEdge.GetLength() < 0.01) continue;

                            if (newEdge.IsLinear()) Edge_Nodes.Add(new Edge_Straight(ref S, ref R, this.Env_Prop, BR, B_IDS, newEdge));
                            else Edge_Nodes.Add(new Edge_Curved(ref S, ref R, this.Env_Prop, BR, B_IDS, newEdge));

                                newEdge = Naked_Edges[shortid].Trim(new Interval(tsE, Naked_Edges[shortid].Domain.T1));
                                if (newEdge != null)
                                {
                                    ToAdd.Add(newEdge);
                                    ToAddMembers.Add(Naked_Breps[shortid]);
                                    ToAddIDS.Add(Brep_IDS[shortid]);
                                }
                                newEdge = Naked_Edges[shortid].Trim(new Interval(Naked_Edges[shortid].Domain.T0, tsS));
                                if (newEdge != null)
                                {
                                    ToAdd.Add(newEdge);
                                    ToAddMembers.Add(Naked_Breps[shortid]);
                                    ToAddIDS.Add(Brep_IDS[shortid]);
                                }

                            newEdge = Naked_Edges[0].Trim(new Interval(tlE, Naked_Edges[0].Domain.T1));
                            if (newEdge != null)
                            {
                                ToAdd.Add(newEdge);
                                ToAddMembers.Add(Naked_Breps[0]);
                                ToAddIDS.Add(Brep_IDS[0]);
                            }
                            newEdge = Naked_Edges[0].Trim(new Interval(Naked_Edges[0].Domain.T0, tlS));
                            if (newEdge != null)
                            {
                                ToAdd.Add(newEdge);
                                ToAddMembers.Add(Naked_Breps[0]);
                                ToAddIDS.Add(Brep_IDS[0]);
                            }

                            ///////If curves diverge... trim merged extent from one, and record as edge. Cut this portion out of existing curves, and re-enter into sorted curve list.
                            orphaned = false;
                            Naked_Edges.RemoveAt(shortid);
                            Naked_Breps.RemoveAt(shortid);
                            EdgeDomains.RemoveAt(shortid);
                            Brep_IDS.RemoveAt(shortid);
                            Lengths.RemoveAt(shortid);
                            Naked_Edges.RemoveAt(0);
                            Naked_Breps.RemoveAt(0);
                            EdgeDomains.RemoveAt(0);
                            Brep_IDS.RemoveAt(0);
                            Lengths.RemoveAt(0);

                            for (int k = 0; k < ToAdd.Count; k++)
                            {
                                bool added = false;
                                ///////////
                                Rhino.RhinoDoc.ActiveDoc.Objects.AddCurve(ToAdd[k]);
                                ///////////
                                double l = ToAdd[k].GetLength();
                                for (int i = 0; i < Naked_Edges.Count; i++)
                                {
                                    if (l < Lengths[i])
                                    {
                                        Naked_Breps.Insert(i, ToAddMembers[k]);
                                        Naked_Edges.Insert(i, ToAdd[k]);
                                        EdgeDomains.Insert(i, new double[] { ToAdd[k].Domain.T0, ToAdd[k].Domain.T1 });
                                        Lengths.Insert(i, l);
                                        Brep_IDS.Insert(i, ToAddIDS[k]);
                                        added = true;
                                        break;
                                    }
                                }
                                if (added) continue;
                                Naked_Breps.Add(ToAddMembers[k]);
                                Naked_Edges.Add(ToAdd[k]);
                                EdgeDomains.Add(new double[] { ToAdd[k].Domain[0], ToAdd[k].Domain[1] });
                                Lengths.Add(l);
                                Brep_IDS.Add(ToAddIDS[k]);
                            }
                            break;
                        }
                        if (ToAdd.Count > 0) break;
                    }
                    if (orphaned)
                    {
                        //Check for intersecting geometry. (T-section)
                        for (int i = 0; i < this.BrepList.Count; i++ )
                        {
                            Curve[] crv;
                            Point3d[] pts;
                            Rhino.Geometry.Intersect.Intersection.CurveBrep(Naked_Edges[0], BrepList[i], 0.01, out crv, out pts);
                        }

                        Rhino.RhinoApp.WriteLine("Orphaned Edge... Assuming thin plate in free air. (Warning: T-Intersects not yet implemented.)");

                        //Create thin plate...
                        Brep Converse = Naked_Breps[0].Duplicate() as Brep;
                        Converse.Surfaces[0].Reverse(0, true);
                        if (Naked_Edges[0].IsLinear()) Edge_Nodes.Add(new Edge_Straight(ref S, ref R, this.Env_Prop, new Brep[] { Naked_Breps[0], Naked_Breps[0] }, new int[2] { Brep_IDS[0], Brep_IDS[0] }, Naked_Edges[0]));
                        else Edge_Nodes.Add(new Edge_Curved(ref S, ref R, this.Env_Prop, new Brep[] { Naked_Breps[0], Converse }, new int[2] { Brep_IDS[0], Brep_IDS[0] }, Naked_Edges[0]));
                        //Remove this edge from Naked_Edges
                        Naked_Edges.RemoveAt(0);
                        Naked_Breps.RemoveAt(0);
                        EdgeDomains.RemoveAt(0);
                        Brep_IDS.RemoveAt(0);
                        Lengths.RemoveAt(0);
                    }
                }
            }
 protected CustomBrepObject(Brep brep)
   : base(true)
 {
   Guid type_id = GetType().GUID;
   IntPtr pConstBrep = brep.ConstPointer();
   m_pRhinoObject = UnsafeNativeMethods.CRhinoCustomObject_New2(type_id, pConstBrep);
 }