private Brep ApplyWallOpen(IEnumerable <StbOpen> opens, StbWall wall, IReadOnlyList <Point3d> wallPts, Brep brep)
        {
            if (brep == null)
            {
                return(brep);
            }

            double   thickness   = BrepMaker.Wall.GetThickness(_sections, wall);
            var      centerCurve = new PolylineCurve(wallPts);
            Vector3d normal      = Vector3d.CrossProduct(centerCurve.TangentAtEnd, centerCurve.TangentAtStart);
            var      openIds     = new List <string>();

            if (wall.StbOpenIdList != null)
            {
                openIds.AddRange(wall.StbOpenIdList.Select(openId => openId.id));
                foreach (string id in openIds)
                {
                    StbOpen         open         = opens.First(o => o.id == id);
                    Point3d[]       openCurvePts = GetOpenCurvePts(wallPts, open);
                    PolylineCurve[] openCurve    = GetOpenCurve(thickness, normal, openCurvePts);
                    Brep            openBrep     = Brep.CreateFromLoft(openCurve, Point3d.Unset, Point3d.Unset, LoftType.Straight, false)[0].CapPlanarHoles(_tolerance[0]);
                    CheckBrepOrientation(openBrep);

                    brep = Brep.CreateBooleanDifference(brep, openBrep, 1)[0];
                }
            }

            return(brep);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var go0 = new GetObject();

            go0.SetCommandPrompt("Select surface or polysurface to subtract from");
            go0.GeometryFilter  = ObjectType.Surface | ObjectType.PolysrfFilter;
            go0.SubObjectSelect = false;
            go0.Get();
            if (go0.CommandResult() != Result.Success)
            {
                return(go0.CommandResult());
            }

            var brep0 = go0.Object(0).Brep();

            if (null == brep0)
            {
                return(Result.Failure);
            }

            var go1 = new GetObject();

            go1.SetCommandPrompt("Select surface or polysurface to subtract with");
            go1.GeometryFilter  = ObjectType.Surface | ObjectType.PolysrfFilter;
            go1.SubObjectSelect = false;
            go1.EnablePreSelect(false, true);
            go1.DeselectAllBeforePostSelect = false;
            go1.Get();
            if (go1.CommandResult() != Result.Success)
            {
                return(go1.CommandResult());
            }

            var brep1 = go1.Object(0).Brep();

            if (null == brep1)
            {
                return(Result.Failure);
            }

            var tolerance = doc.ModelAbsoluteTolerance;
            var out_breps = Brep.CreateBooleanDifference(brep0, brep1, tolerance);

            if (null != out_breps && out_breps.Length > 0)
            {
                foreach (var b in out_breps)
                {
                    doc.Objects.AddBrep(b);
                }

                doc.Objects.Delete(go0.Object(0).ObjectId, true);
                doc.Objects.Delete(go1.Object(0).ObjectId, true);
            }

            doc.Views.Redraw();
            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            const double height    = 20.0;
            var          tolerance = doc.ModelAbsoluteTolerance;

            var points0 = new List <Point3d>
            {
                new Point3d(-1.0, 0.0, 0.0),
                new Point3d(-1.0, -1.0, 0.0),
                new Point3d(-2.0, -1.0, 0.0),
                new Point3d(-2.0, -2.0, 0.0),
                new Point3d(2.0, -2.0, 0.0),
                new Point3d(1.0, -1.0, 0.0),
                new Point3d(1.0, 0.0, 0.0),
                new Point3d(-1.0, 0.0, 0.0)
            };

            var brep0 = CreateBrep(points0, height, tolerance);

            if (null == brep0)
            {
                return(Result.Failure);
            }

            var points1 = new List <Point3d>
            {
                new Point3d(-1.0, 0.0, 0.0),
                new Point3d(-1.0, -1.0, 0.0),
                new Point3d(1.0, -1.0, 0.0),
                new Point3d(1.0, 0.0, 0.0),
                new Point3d(-1.0, 0.0, 0.0)
            };

            var brep1 = CreateBrep(points1, height, tolerance);

            if (null == brep1)
            {
                return(Result.Failure);
            }

            brep1.Rotate((Math.PI * 0.5), new Vector3d(1.0, 0.0, 0.0), new Point3d(0.0, 0.0, (0.5 * height)));
            brep1.Translate(new Vector3d(0.0, -1.0, 5.0));

            var results = Brep.CreateBooleanDifference(brep0, brep1, tolerance);

            if (null != results)
            {
                foreach (var rc in results)
                {
                    doc.Objects.AddBrep(rc);
                }
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Exemplo n.º 4
0
        private void CutWithReinforcement()
        {
            RhinoDoc doc = RhinoDoc.ActiveDoc;


            List <Reinforcement>   reinfList = new List <Reinforcement>();
            List <GeometrySegment> segList   = new List <GeometrySegment>();

            foreach (IBrepGeometry brepGeometry in GeometryList)
            {
                if (brepGeometry.GetType() == typeof(Reinforcement))
                {
                    reinfList.Add((Reinforcement)brepGeometry);
                }
                else
                {
                    segList.Add((GeometrySegment)brepGeometry);
                }
            }
            GeometryList = new List <IBrepGeometry>();
            Brep[] reinfBrepList = reinfList.Select(o => o.BrepGeometry).ToArray();

            foreach (GeometryLarge seg in GeometryLarges)
            {
                //if (seg.Material.GetType() == typeof(SteelMaterial)) continue;
                if (seg.Material.GetType() == typeof(ConcreteMaterial) || seg.Material.GetType() == typeof(SteelMaterial))
                {
                    Brep[] tempList = Brep.CreateBooleanDifference(new[] { seg.BaseBrep }, reinfBrepList, doc.ModelAbsoluteTolerance);

                    Brep cuttedBrep;
                    if (tempList == null || tempList.Length == 0)
                    {
                        cuttedBrep = seg.BaseBrep;
                    }
                    else
                    {
                        cuttedBrep = tempList[0];
                    }

                    List <Brep> slicedBrep = CurveAndBrepManipulation.CutBrep(cuttedBrep, Plane.WorldXY, Axis.XAxis);

                    //TODO update the correct material addition to here
                    foreach (Brep brep in slicedBrep)
                    {
                        GeometryList.Add(new GeometrySegment(brep, seg.Material));
                    }
                }
                else
                {
                    RhinoApp.WriteLine($"Cutting of material is not implemented for {seg.Material.GetType()}");
                }
            }
            GeometryList.AddRange(reinfList);
        }
        /// <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);
        }
        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);
            }
        }
Exemplo n.º 7
0
        public void genBaseMass()
        {
            PolylineCurve outerCrv    = new PolylineCurve(outerPtLi);
            double        outerAr     = AreaMassProperties.Compute(outerCrv).Area;
            PolylineCurve innerCrv    = new PolylineCurve(innerPtLi);
            double        innerAr     = AreaMassProperties.Compute(innerCrv).Area;
            double        diffAr      = outerAr - innerAr;
            int           numBaseFlrs = (int)(SITE_AR * baseFsr / diffAr) + 1;
            double        baseHt      = numBaseFlrs * flrHt;
            Extrusion     outerExtr   = Extrusion.Create(outerCrv, baseHt, true);
            Extrusion     innerExtr   = Extrusion.Create(innerCrv, baseHt, true);

            Brep[] outerBrep = { outerExtr.ToBrep() };
            Brep[] innerBrep = { innerExtr.ToBrep() };
            Brep[] diffBrep  = Brep.CreateBooleanDifference(outerBrep, innerBrep, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);
            for (int i = 0; i < diffBrep.Length; i++)
            {
                globalBrepLi.Add(diffBrep[i]);
            }

            globalBaseCrvLi = new List <Curve>();
            double spineHt = 0.0;

            for (int i = 0; i < numBaseFlrs; i++)
            {
                Curve outerCrvDup = outerCrv.DuplicateCurve();
                Rhino.Geometry.Transform xform = Rhino.Geometry.Transform.Translation(0, 0, spineHt);
                outerCrvDup.Transform(xform);
                Curve innerCrvDup = innerCrv.DuplicateCurve();
                innerCrvDup.Transform(xform);
                globalBaseCrvLi.Add(innerCrvDup);
                globalBaseCrvLi.Add(outerCrvDup);
                spineHt += flrHt;
            }
            BaseMassHt = baseHt;
        }
Exemplo n.º 8
0
        public List <Brep> Compute()
        {
            globalBaseCrvLi  = new List <Curve>(); // global parameter
            globalTowerCrvLi = new List <Curve>(); // global parameter
            globalPtCrvLi    = new List <Point3d>();
            double[]       p    = c2.DivideByCount(numDiv, true);
            List <Point3d> ptLi = new List <Point3d>();         // points on the site boundary

            for (int i = 0; i < p.Length; i++)
            {
                Point3d pts = c2.PointAt(p[i]);
                ptLi.Add(pts);
                globalPtCrvLi.Add(pts);
            }

            // GENERATE NORMALS FROM THE POINT - SCALE=SETBACK DISTANCE
            List <LineCurve> lineLi = new List <LineCurve>();

            for (int i = 0; i < ptLi.Count; i++)
            {
                Point3d P = Point3d.Unset;
                Point3d Q = Point3d.Unset;
                if (i == 0)
                {
                    P = ptLi[ptLi.Count - 1];
                    Q = ptLi[0];
                }
                else
                {
                    P = ptLi[i - 1];
                    Q = ptLi[i];
                }
                double  sc  = 1 / P.DistanceTo(Q);
                double  sc2 = OFFSET_INP;
                double  dx  = P.X - (Q.Y - P.Y) * sc;
                double  dy  = P.Y + (Q.X - P.X) * sc;
                Point3d u   = new Point3d(dx, dy, 0);
                double  dx2 = P.X - (Q.Y - P.Y) * sc * sc2;
                double  dy2 = P.Y + (Q.X - P.X) * sc * sc2;
                double  ex2 = P.X + (Q.Y - P.Y) * sc * sc2;
                double  ey2 = P.Y - (Q.X - P.X) * sc * sc2;
                Point3d u2  = new Point3d(dx2, dy2, 0);
                Point3d v2  = new Point3d(ex2, ey2, 0);
                Rhino.Geometry.PointContainment contU = c2.Contains(u, Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);
                if (contU.ToString() == "Inside")
                {
                    LineCurve linePu = new LineCurve(P, u2);
                    lineLi.Add(linePu);
                }
                else
                {
                    LineCurve linePu = new LineCurve(P, v2);
                    lineLi.Add(linePu);
                }
            }

            // FIND INTX - NORMAL x SETBACK CURVE; REMOVE OTHER NORMALS
            List <LineCurve> fLineLi = new List <LineCurve>();

            for (int i = 0; i < lineLi.Count; i++)
            {
                double t   = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;
                var    evt = Rhino.Geometry.Intersect.Intersection.CurveCurve(OFFSET_CRV, lineLi[i], t, t);
                try
                {
                    Point3d   A    = lineLi[i].PointAtStart;
                    Point3d   pA   = evt[0].PointA;
                    LineCurve line = new LineCurve(A, pA);
                    fLineLi.Add(line);
                }
                catch (Exception) { }
            }

            // JOIN ADJACENT NORMAL SEGMENTS TO FORM POLYGONS
            // 1st point is point on site, 2nd = normal @ setback dist
            List <PolylineCurve> polyCrvLi = new List <PolylineCurve>();

            for (int i = 0; i < lineLi.Count; i++)
            {
                if (i == 0)
                {
                    LineCurve     A    = lineLi[lineLi.Count - 1];
                    LineCurve     B    = lineLi[0];
                    Point3d       a0   = A.PointAtStart;
                    Point3d       a1   = A.PointAtEnd;
                    Point3d       b0   = B.PointAtStart;
                    Point3d       b1   = B.PointAtEnd;
                    Point3d[]     pts  = { a0, b0, b1, a1, a0 };
                    PolylineCurve poly = new PolylineCurve(pts);
                    double        ar2  = AreaMassProperties.Compute(poly).Area;
                    if (ar2 > minTowerAr)
                    {
                        polyCrvLi.Add(poly);
                    }
                    //polyCrvLi.Add(poly);
                }
                else
                {
                    LineCurve     A    = lineLi[i - 1];
                    LineCurve     B    = lineLi[i];
                    Point3d       a0   = A.PointAtStart;
                    Point3d       a1   = A.PointAtEnd;
                    Point3d       b0   = B.PointAtStart;
                    Point3d       b1   = B.PointAtEnd;
                    Point3d[]     pts  = { a0, b0, b1, a1, a0 };
                    PolylineCurve poly = new PolylineCurve(pts);
                    double        ar2  = AreaMassProperties.Compute(poly).Area;
                    if (ar2 > minTowerAr)
                    {
                        polyCrvLi.Add(poly);
                    }
                    //polyCrvLi.Add(poly);
                }
            }
            double      baseExtrHt = 0.0;
            double      spineHt    = 0.0;
            List <Brep> fbrepLi    = new List <Brep>();

            try
            {   // BASE PROCESSES= EXTRUSION & COPY
                double c2Area     = AreaMassProperties.Compute(c2).Area;
                double offsetArea = AreaMassProperties.Compute(OFFSET_CRV).Area;
                double flrAr      = c2Area - offsetArea;
                int    numFlrs2   = (int)(SITE_AR * baseFsr / flrAr) + 1;
                baseExtrHt = numFlrs2 * flrHt;
                for (int i = 0; i < numFlrs2; i++)
                {
                    Curve c2_copy = c2.DuplicateCurve();
                    Rhino.Geometry.Transform xform = Rhino.Geometry.Transform.Translation(0, 0, spineHt);
                    c2_copy.Transform(xform);
                    Curve OFFSET_CRV_copy = OFFSET_CRV.DuplicateCurve();
                    OFFSET_CRV_copy.Transform(xform);
                    spineHt += flrHt;
                    globalBaseCrvLi.Add(c2_copy);
                    globalBaseCrvLi.Add(OFFSET_CRV_copy);
                }

                // base extrusions
                Extrusion outerExtr = Rhino.Geometry.Extrusion.Create(c2, baseExtrHt, true);
                var       t0        = outerExtr.GetBoundingBox(true);
                if (t0.Max.Z <= 0)
                {
                    outerExtr = Rhino.Geometry.Extrusion.Create(c2, baseExtrHt, true);
                }
                Brep outerBrep = outerExtr.ToBrep();

                Extrusion innerExtr = Rhino.Geometry.Extrusion.Create(OFFSET_CRV, -baseExtrHt, true);
                var       t1        = innerExtr.GetBoundingBox(true);
                if (t1.Max.Z <= 0)
                {
                    innerExtr = Rhino.Geometry.Extrusion.Create(OFFSET_CRV, baseExtrHt, true);
                }
                Brep   innerBrep  = innerExtr.ToBrep();
                Brep[] netBrepArr = Brep.CreateBooleanDifference(outerBrep, innerBrep, 0.01);
                Brep   netBrep    = netBrepArr[0];
                fbrepLi.Add(netBrep);
            }
            catch (Exception) { }

            // Tower POLY FOR THE TOWERS
            List <Curve>         towerPolyLi = new List <Curve>();
            List <PolylineCurve> fPolyLi     = new List <PolylineCurve>();
            int numSel = numTowers;

            double cumuArPoly = 0.0;

            for (int i = 0; i < numSel; i++)
            {
                int idx = rnd.Next(polyCrvLi.Count);
                fPolyLi.Add(polyCrvLi[idx]);
                cumuArPoly += AreaMassProperties.Compute(polyCrvLi[idx]).Area;
            }
            // Tower POLY EXTRUSION
            double towerHtReq = SITE_AR * towerFsr / cumuArPoly;

            for (int i = 0; i < fPolyLi.Count; i++)
            {
                PolylineCurve crv   = fPolyLi[i];
                Extrusion     extr0 = Extrusion.Create(crv, -towerHtReq * flrHt, true);
                var           t0    = extr0.GetBoundingBox(true);
                if (t0.Max.Z <= 0)
                {
                    extr0 = Extrusion.Create(crv, towerHtReq * flrHt, true);
                }
                Brep      brep  = extr0.ToBrep();
                Transform xform = Rhino.Geometry.Transform.Translation(0, 0, baseExtrHt);
                brep.Transform(xform);
                fbrepLi.Add(brep);
            }
            // Tower POLY FLOOR COPIES
            // spineHt initialized above & updated from base curve copies
            int numFlrs = (int)(SITE_AR * towerFsr / cumuArPoly) + 1;

            for (int i = 0; i < numFlrs; i++)
            {
                for (int j = 0; j < fPolyLi.Count; j++)
                {
                    Curve crv = fPolyLi[j].DuplicateCurve();
                    Rhino.Geometry.Transform xform = Rhino.Geometry.Transform.Translation(0, 0, spineHt);
                    crv.Transform(xform);
                    globalTowerCrvLi.Add(crv);
                }
                spineHt += flrHt;
            }
            return(fbrepLi);
        }
Exemplo n.º 9
0
        public static Brep BrepSlice(this Brep b, Brep slicer, bool flip = false)
        {
            double tol = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;

            /*
             * Curve[] iCrvs;
             * Point3d[] iPts;
             * if (!Rhino.Geometry.Intersect.Intersection.BrepBrep(b, slicer, tol, out iCrvs, out iPts))
             *  return new Brep();
             */
            //if (b.IsSolid && b.SolidOrientation !=)

            if (slicer.IsSolid)
            {
                Brep[] boolean = Brep.CreateBooleanDifference(b, slicer, tol);

                if (boolean == null || boolean.Length < 1)
                {
                    return(b);
                }
                return(boolean[0]);
            }

            if (b.SolidOrientation != BrepSolidOrientation.Outward)
            {
                b.Faces.Flip(true);
            }

            slicer.Faces.StandardizeFaceSurfaces();
            if (slicer.Faces[0].OrientationIsReversed)
            {
                flip = !flip;
            }

            Brep[] sliced = b.Split(slicer, tol);

            if (sliced == null || sliced.Length < 1)
            {
                return(b);
            }

            Brep[] cap = slicer.Trim(b, tol);

            Brep brep = null;

            if (flip)
            {
                brep = sliced[1];
            }
            else
            {
                brep = sliced[0];
            }

            if (cap != null && cap.Length > 0)
            {
                Brep[] joined = Brep.JoinBreps(cap, tol);
                brep.Join(joined[0], tol, true);
            }

            return(brep);
        }
Exemplo n.º 10
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <GH_Brep> sBreps = new GH_Structure <GH_Brep>();

            DA.GetDataTree <GH_Brep>(0, out sBreps);

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

            DA.GetDataTree <GH_Brep>(1, out dBreps);

            double tol = DocumentTolerance();

            ///Reserve one processor for GUI
            int totalMaxConcurrancy = System.Environment.ProcessorCount - 1;

            ///Tells us how many threads were using
            Message = totalMaxConcurrancy + " threads";

            ///Declare dictionaries that work in parallel to hold the successful boolean results and
            ///the unsuccessful boolean cutters
            var mainBrepsMT = new System.Collections.Concurrent.ConcurrentDictionary <GH_Path, GH_Brep>();
            var badBrepsMT  = new System.Collections.Concurrent.ConcurrentDictionary <GH_Path, List <GH_Brep> >();

            ///Start of the parallel engine
            ///Cast to GH_Brep to Brep and back in parallel engine to avoid speed hit when casting all at once later
            System.Threading.Tasks.Parallel.ForEach(sBreps.Paths, new System.Threading.Tasks.ParallelOptions
            {
                MaxDegreeOfParallelism = totalMaxConcurrancy
            },
                                                    pth =>
            {
                List <GH_Brep> badBrep = new List <GH_Brep>();

                Brep mainBrep = new Brep();
                GH_Convert.ToBrep(sBreps.get_Branch(pth)[0], ref mainBrep, 0);
                List <Brep> diffBreps = new List <Brep>();
                foreach (var d_GH in dBreps.get_Branch(pth))
                {
                    Brep d_Rhino = new Brep();
                    GH_Convert.ToBrep(d_GH, ref d_Rhino, 0);
                    diffBreps.Add(d_Rhino);
                }


                ///Difference one cutter brep at a time from the main brep in the branch.
                ///This allows the boolean operation to continue without failing
                ///and bad cutter breps can be discarded to a list that can be used for troubleshooting
                ///haven't noticed a hit big hit on performance
                foreach (Brep b in diffBreps)
                {
                    Brep[] breps = new Brep[] { };
                    breps        = Brep.CreateBooleanDifference(mainBrep, b, tol);
                    if ((breps == null) || (breps.Length < 1))
                    {
                        badBrep.Add(new GH_Brep(b));
                    }
                    else
                    {
                        mainBrep = breps[0];
                    }
                }
                mainBrepsMT[pth] = new GH_Brep(mainBrep);
                badBrepsMT[pth]  = badBrep;
            });
            ///End of the parallel engine
            ///

            //convert dictionaries to regular old data trees
            GH_Structure <GH_Brep> mainBreps = new GH_Structure <GH_Brep>();
            GH_Structure <GH_Brep> badBreps  = new GH_Structure <GH_Brep>();

            foreach (KeyValuePair <GH_Path, GH_Brep> p in mainBrepsMT)
            {
                mainBreps.Append(p.Value, p.Key);
            }

            foreach (KeyValuePair <GH_Path, List <GH_Brep> > b in badBrepsMT)
            {
                badBreps.AppendRange(b.Value, b.Key);
            }

            DA.SetDataTree(0, mainBreps);
            DA.SetDataTree(1, badBreps);
        }
        private Result CreateTubeCoupler(RhinoDoc doc, XmlNode compNd, double stackLength)
        {
            Result      result     = Rhino.Commands.Result.Failure;
            XmlElement  compEle    = compNd as XmlElement;
            XmlNodeList subCompNds = compNd.SelectNodes("subcomponents/*");

            double       length          = 0;
            double       thickness       = 0;
            double       position        = 0;
            PositionType positionType    = PositionType.Top;
            double       radialPosition  = 0;
            double       radialDirection = 0;
            double       outerRadius     = 0;

            foreach (XmlNode nd in compEle.ChildNodes)
            {
                if (nd.Name == "length")
                {
                    length = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "thickness")
                {
                    thickness = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "position")
                {
                    position     = Double.Parse(nd.InnerText);
                    positionType = (PositionType)Enum.Parse(typeof(PositionType), ((XmlElement)nd).GetAttribute("type"), true);
                }
                else if (nd.Name == "radialposition")
                {
                    radialPosition = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "radialdirection")
                {
                    radialDirection = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "outerradius")
                {
                    outerRadius = Double.Parse(nd.InnerText);
                }
            }

            Brep brep = null;

            double innerRadius = outerRadius - thickness;

            Plane  planeCyl = new Plane(new Point3d(0, 0, 0), Vector3d.XAxis);
            Circle innerCir = new Circle(planeCyl, innerRadius);
            Circle outerCir = new Circle(planeCyl, outerRadius);

            Cylinder innerCyl = new Cylinder(innerCir, length);
            Cylinder outerCyl = new Cylinder(outerCir, length);

            Brep brepInner = Brep.CreateFromCylinder(innerCyl, true, true);
            Brep brepOuter = Brep.CreateFromCylinder(outerCyl, true, true);

            Brep[] tube = Brep.CreateBooleanDifference(brepOuter, brepInner, 0.0001);

            brep = tube[0];
            double xLoc = 0;

            switch (positionType)
            {
            case PositionType.Top:
                xLoc = 0 + length + position;
                break;

            case PositionType.Bottom:
                xLoc = stackLength - length + position;
                break;

            case PositionType.Middle:
                xLoc = stackLength - length / 2 + position;
                break;

            case PositionType.After:
                xLoc = stackLength + length + position;
                break;

            case PositionType.Absolute:
                xLoc = position;
                break;
            }
            Transform trans = Transform.Translation(new Vector3d(xLoc, 0, 0));

            brep.Transform(trans);

            if (doc.Objects.AddBrep(brep) != Guid.Empty)
            {
                doc.Views.Redraw();
                result = Rhino.Commands.Result.Success;
            }

            foreach (XmlNode subNd in subCompNds)
            {
                if (subNd.Name == "bulkhead")
                {
                    result = CreateBulkhead(doc, subNd, outerRadius, xLoc, xLoc + length);
                }
            }

            return(result);
        }
        private Result CreateBodyTube(RhinoDoc doc, XmlNode compNd, ref double stackLength)
        {
            Result      result     = Rhino.Commands.Result.Failure;
            XmlElement  compEle    = compNd as XmlElement;
            XmlNodeList subCompNds = compNd.SelectNodes("subcomponents/*");

            double length    = 0;
            double thickness = 0;
            double radius    = 0;

            foreach (XmlNode nd in compEle.ChildNodes)
            {
                if (nd.Name == "length")
                {
                    length = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "thickness")
                {
                    thickness = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "radius")
                {
                    if (nd.InnerText == "auto")
                    {
                        bool found = false;

                        foreach (XmlNode sibNd in compNd.ParentNode.ChildNodes)
                        {
                            foreach (XmlNode sibChild in sibNd.ChildNodes)
                            {
                                if (sibChild.Name == "radius" || sibChild.Name == "aftradius")
                                {
                                    found  = true;
                                    radius = Double.Parse(sibChild.InnerText);
                                }
                            }
                            if (found)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        radius = Double.Parse(nd.InnerText);
                    }
                }
            }

            Brep   brep        = null;
            double innerRadius = radius - thickness;
            Plane  planeCyl    = new Plane(new Point3d(0, 0, 0), Vector3d.XAxis);
            Circle innerCir    = new Circle(planeCyl, innerRadius);
            Circle outerCir    = new Circle(planeCyl, radius);

            Cylinder innerCyl = new Cylinder(innerCir, length);
            Cylinder outerCyl = new Cylinder(outerCir, length);

            Brep brepInner = Brep.CreateFromCylinder(innerCyl, true, true);
            Brep brepOuter = Brep.CreateFromCylinder(outerCyl, true, true);

            Brep[] tube = Brep.CreateBooleanDifference(brepOuter, brepInner, 0.0001);
            brep = tube[0];

            Transform trans = Transform.Translation(new Vector3d(stackLength, 0, 0));

            brep.Transform(trans);

            if (doc.Objects.AddBrep(brep) != Guid.Empty)
            {
                doc.Views.Redraw();
                result = Rhino.Commands.Result.Success;
            }

            stackLength += length;

            foreach (XmlNode subNd in subCompNds)
            {
                if (subNd.Name == "bulkhead")
                {
                    result = CreateBulkhead(doc, subNd, radius, stackLength - length, stackLength);
                }
                else if (subNd.Name == "tubecoupler")
                {
                    result = CreateTubeCoupler(doc, subNd, stackLength);
                }
                else if (subNd.Name == "centeringring")
                {
                    result = CreateCenteringRing(doc, subNd, radius, stackLength - length, stackLength);
                }
                else if (subNd.Name == "innertube")
                {
                    result = CreateInnerTube(doc, subNd, stackLength - length, stackLength);
                }
                else if (subNd.Name == "freeformfinset")
                {
                    result = CreateFreeFormFin(doc, subNd, radius, stackLength - length, stackLength);
                }
                else if (subNd.Name == "ellipticalfinset")
                {
                    result = CreateEllipticalFin(doc, subNd, radius, stackLength - length, stackLength);
                }
                else if (subNd.Name == "trapezoidfinset")
                {
                    result = CreateTrapezoidFin(doc, subNd, radius, stackLength - length, stackLength);
                }
            }

            return(result);
        }
        private Result CreateNoseCone(RhinoDoc doc, XmlNode compNd, ref double stackLength)
        {
            Result      result     = Rhino.Commands.Result.Failure;
            XmlElement  compEle    = compNd as XmlElement;
            XmlNodeList subCompNds = compNd.SelectNodes("subcomponents/*");

            double            length               = 0;
            double            thickness            = 0;
            NoseConeShapeType shape                = NoseConeShapeType.Ogive;
            double            shapeParameter       = 0;
            double            aftRadius            = 0;
            double            aftShoulderRadius    = 0;
            double            aftShoulderLength    = 0;
            double            aftShoulderThickness = 0;
            bool aftShoulderCapped = false;

            foreach (XmlNode nd in compEle.ChildNodes)
            {
                if (nd.Name == "length")
                {
                    length = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "thickness")
                {
                    thickness = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "shape")
                {
                    shape = (NoseConeShapeType)Enum.Parse(typeof(NoseConeShapeType), nd.InnerText, true);
                }
                else if (nd.Name == "shapeparameter")
                {
                    shapeParameter = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "aftradius")
                {
                    if (nd.InnerText == "auto")
                    {
                        XmlNode sibNd = compNd.NextSibling;
                        foreach (XmlNode sibChild in sibNd.ChildNodes)
                        {
                            if (sibNd.Name == "bodytube" && sibChild.Name == "radius")
                            {
                                aftRadius = Double.Parse(sibChild.InnerText);
                            }
                        }
                    }
                    else
                    {
                        aftRadius = Double.Parse(nd.InnerText);
                    }
                }
                else if (nd.Name == "aftshoulderradius")
                {
                    aftShoulderRadius = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "aftshoulderlength")
                {
                    aftShoulderLength = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "aftshoulderthickness")
                {
                    aftShoulderThickness = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "aftshouldercapped")
                {
                    aftShoulderCapped = Boolean.Parse(nd.InnerText);
                }
            }

            // generate geometry and create solid.
            int            numberDivisions = 100;
            OgiveCurve     ogive           = new OgiveCurve(aftRadius, length);
            double         xa     = ogive.SphericalCapApex(0);
            double         delta  = (length - xa) / (numberDivisions - 1);
            double         x      = xa;
            double         y      = 0;
            List <Point3d> points = new List <Point3d>();

            for (int i = 0; i < numberDivisions; i++)
            {
                double angle = (double)i * System.Math.PI / (double)numberDivisions;
                y = ogive.Evaluate(x);

                points.Add(new Point3d(x, y, 0));

                x += delta;
            }

            Polyline curve = new Polyline(points);

            NurbsCurve nbCurve = curve.ToNurbsCurve();

            Curve[] offsetsCurves = nbCurve.Offset(new Plane(new Point3d(0, 0, 0), Vector3d.XAxis, Vector3d.YAxis), thickness, 0.0001, CurveOffsetCornerStyle.None);

            Plane plane = new Plane(new Point3d(0, 0, 0), Vector3d.XAxis, Vector3d.ZAxis);

            Curve[] splits = offsetsCurves[0].Split(new PlaneSurface(plane, new Interval(0, 100), new Interval(0, 100)), 0.0001);

            LineCurve line1 = new LineCurve(nbCurve.PointAtStart, splits[1].PointAtStart);
            LineCurve line2 = new LineCurve(nbCurve.PointAtEnd, splits[1].PointAtEnd);

            List <Curve> curves = new List <Curve>()
            {
                nbCurve, splits[1], line1, line2
            };

            Curve[] joined = Curve.JoinCurves(curves);

            RevSurface revsrf = RevSurface.Create(joined[0], new Line(new Point3d(0, 0, 0), new Point3d(length, 0, 0)), 0, 2 * Math.PI);
            Brep       brep   = Brep.CreateFromRevSurface(revsrf, true, true);

            brep.Flip();

            if (aftShoulderLength > 0)
            {
                double innerRadius = aftShoulderRadius - aftShoulderThickness;
                double outerRadius = aftShoulderRadius;
                Plane  planeCyl    = new Plane(new Point3d(0, 0, 0), Vector3d.XAxis);
                Circle innerCir    = new Circle(planeCyl, innerRadius);
                Circle outerCir    = new Circle(planeCyl, outerRadius);

                Cylinder innerCyl = new Cylinder(innerCir, aftShoulderThickness + aftShoulderLength);
                Cylinder outerCyl = new Cylinder(outerCir, aftShoulderThickness + aftShoulderLength);

                Brep brepInner = Brep.CreateFromCylinder(innerCyl, true, true);
                Brep brepOuter = Brep.CreateFromCylinder(outerCyl, true, true);

                Brep[]    tube  = Brep.CreateBooleanDifference(brepOuter, brepInner, 0.0001);
                Transform trans = Transform.Translation(new Vector3d(length - aftShoulderThickness, 0, 0));

                tube[0].Transform(trans);

                Brep[] withShoulder = Brep.CreateBooleanUnion(new List <Brep>()
                {
                    brep, tube[0]
                }, 0.001);
                brep = withShoulder[0];
            }


            if (doc.Objects.AddBrep(brep) != Guid.Empty)
            {
                doc.Views.Redraw();
                result = Rhino.Commands.Result.Success;
            }

            stackLength = length; // cone seems to start a new stack

            foreach (XmlNode subNd in subCompNds)
            {
                if (subNd.Name == "tubecoupler")
                {
                    result = CreateTubeCoupler(doc, subNd, stackLength);
                }
            }

            return(result);
        }
Exemplo n.º 14
0
        public static Brep Cut(this Brep brep, IEnumerable <Brep> cutters, double tolerance = 0.01)
        {
            var solids = new List <Brep>();
            var surfs  = new List <Brep>();

            if (brep == null)
            {
                throw new Exception("Brep is null in CutBrep()");
            }

            if (brep.SolidOrientation != BrepSolidOrientation.Outward)
            {
                brep.Flip();
            }

            for (int i = 0; i < brep.Faces.Count; ++i)
            {
                //brep.Surfaces[i].Reverse(0, true);

                //x.Faces.Flip(false);
                //if (brep.Faces[i].OrientationIsReversed)
                //    brep.Faces[i].Reverse(0, true);
            }

            foreach (Brep ctr in cutters)
            {
                if (ctr == null)
                {
                    continue;
                }
                if (ctr.IsSolid)
                {
                    if (ctr.SolidOrientation != BrepSolidOrientation.Outward)
                    {
                        ctr.Flip();
                    }

                    solids.Add(ctr);
                }
                else
                {
                    surfs.Add(ctr);
                }
            }

            Brep[] pieces;
            if (surfs.Count > 0)
            {
                pieces = Brep.CreateBooleanSplit(new Brep[] { brep }, surfs, tolerance);
                if (pieces.Length < 1)
                {
                    pieces = new Brep[] { brep }
                }
                ;
            }
            else
            {
                pieces = new Brep[] { brep };
            }

            int    index  = -1;
            double volume = 0;

            for (int i = 0; i < pieces.Length; ++i)
            {
                if (pieces[i] == null || !pieces[i].IsSolid)
                {
                    continue;
                }

                var vmp = Rhino.Geometry.VolumeMassProperties.Compute(pieces[i], true, false, false, false);
                if (vmp == null)
                {
                    continue;
                }

                if (vmp.Volume > volume)
                {
                    index  = i;
                    volume = vmp.Volume;
                }
            }

            Brep largest;

            if (index >= 0)
            {
                largest = pieces[index];
            }
            else
            {
                largest = brep;
            }
            //largest = pieces[0];

            var diff = Brep.CreateBooleanDifference(new Brep[] { largest }, solids, 0.1);

            if (diff == null || diff.Length < 1)
            {
                return(largest);
            }
            else
            {
                return(diff[0]);
            }
        }
    }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Defaults
            mySpheres = new List <MySphere>();
            rand      = new Random();

            area             = 50;
            maxRadius        = 10;
            minRadius        = 5;
            maxGrowth        = 0.3;
            minGrowth        = 0.05;
            maxOverLap       = -0.5;
            MaxSpawnFailures = 100;

            // Loop Stuff
            bool isFinished     = false;
            int  spawnFailCount = 0;

            // Plugin Arguments
            DA.GetData(0, ref area);
            DA.GetData(1, ref maxRadius);
            DA.GetData(2, ref minRadius);
            DA.GetData(3, ref maxGrowth);
            DA.GetData(4, ref minGrowth);
            DA.GetData(5, ref maxOverLap);
            DA.GetData(6, ref MaxSpawnFailures);

            while (!isFinished)
            {
                if (SpawnSphere())
                {
                    spawnFailCount = 0;
                }
                else
                {
                    spawnFailCount++;
                }

                // Controls the growth of the spheres, stops the sphere it overlaps with another
                for (int i = 0; i < mySpheres.Count; i++)
                {
                    for (int j = i + 1; j < mySpheres.Count; j++)
                    {
                        if ((mySpheres[i].CentrePoint.DistanceTo(mySpheres[j].CentrePoint)) < (mySpheres[i].Radius + mySpheres[j].Radius - maxOverLap))
                        {
                            mySpheres[i].StopGrow();
                            mySpheres[j].StopGrow();
                        }
                    }
                    if (mySpheres[i].CanGrow & mySpheres[i].Radius >= maxRadius)
                    {
                        mySpheres[i].StopGrow();
                    }
                }

                bool finishGrowing = true;

                foreach (MySphere aSphere in mySpheres)
                {
                    aSphere.Grow();
                    if (aSphere.CanGrow)
                    {
                        finishGrowing = false;
                    }
                }

                if (finishGrowing && spawnFailCount > MaxSpawnFailures)
                {
                    isFinished = true;
                }
            }

            List <Brep> spheres = new List <Brep>();
            List <Brep> aCube   = new List <Brep>();

            aCube.Add(Brep.CreateFromBox(new BoundingBox(new Point3d(minRadius, minRadius, minRadius), new Point3d(area + (2 * minRadius), area + (2 * minRadius), area + (2 * minRadius)))));

            for (int i = 0; i < mySpheres.Count; i++)
            {
                spheres.Add(mySpheres[i].RhinoSphere());
            }

            Brep[] cheesed = Brep.CreateBooleanDifference(aCube, spheres, 0.001);

            Rhino.RhinoApp.WriteLine(mySpheres.Count.ToString());

            DA.SetDataList(0, cheesed);
        }
        private Result CreateCenteringRing(RhinoDoc doc, XmlNode compNd, double parentRadius, double xStart, double xEnd)
        {
            Result      result     = Rhino.Commands.Result.Failure;
            XmlElement  compEle    = compNd as XmlElement;
            XmlNodeList subCompNds = compNd.SelectNodes("subcomponents/*");

            double       length          = 0;
            PositionType positionType    = PositionType.Top;
            double       position        = 0;
            double       radialPosition  = 0;
            double       radialDirection = 0;
            double       innerRadius     = 0;
            double       outerRadius     = 0;

            foreach (XmlNode nd in compEle.ChildNodes)
            {
                if (nd.Name == "length")
                {
                    length = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "position")
                {
                    position     = Double.Parse(nd.InnerText);
                    positionType = (PositionType)Enum.Parse(typeof(PositionType), ((XmlElement)nd).GetAttribute("type"), true);
                }
                else if (nd.Name == "radialposition")
                {
                    radialPosition = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "radialdirection")
                {
                    radialDirection = Double.Parse(nd.InnerText);
                }
                else if (nd.Name == "outerradius")
                {
                    if (nd.InnerText == "auto")
                    {
                        outerRadius = parentRadius;
                    }
                    else
                    {
                        outerRadius = Double.Parse(nd.InnerText);
                    }
                }
                else if (nd.Name == "innerradius")
                {
                    if (nd.InnerText == "auto")
                    {
                        bool found = false;

                        foreach (XmlNode sibNd in compNd.ParentNode.ChildNodes)
                        {
                            if (sibNd.Name == "innertube")
                            {
                                foreach (XmlNode sibChild in sibNd.ChildNodes)
                                {
                                    if (sibChild.Name == "outerradius")
                                    {
                                        found       = true;
                                        innerRadius = Double.Parse(sibChild.InnerText);
                                    }
                                }
                                if (found)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        innerRadius = Double.Parse(nd.InnerText);
                    }
                }
            }

            Brep brep = null;

            Plane    planeCyl = new Plane(new Point3d(0, 0, 0), Vector3d.XAxis);
            Circle   innerCir = new Circle(planeCyl, innerRadius);
            Circle   outerCir = new Circle(planeCyl, outerRadius);
            Cylinder innerCyl = new Cylinder(innerCir, length);
            Cylinder outerCyl = new Cylinder(outerCir, length);

            Brep brepInner = Brep.CreateFromCylinder(innerCyl, true, true);
            Brep brepOuter = Brep.CreateFromCylinder(outerCyl, true, true);

            Brep[] tube = Brep.CreateBooleanDifference(brepOuter, brepInner, 0.0001);
            brep = tube[0];

            double xLoc = 0;

            switch (positionType)
            {
            case PositionType.Top:
                xLoc = xStart + position;
                break;

            case PositionType.Bottom:
                xLoc = xEnd - length + position;
                break;

            case PositionType.Middle:
                xLoc = (xEnd - xStart) / 2 + position;
                break;

            case PositionType.After:
                xLoc = xEnd - length + position;
                break;

            case PositionType.Absolute:
                xLoc = position;
                break;
            }
            Transform trans = Transform.Translation(new Vector3d(xLoc, 0, 0));

            brep.Transform(trans);

            if (doc.Objects.AddBrep(brep) != Guid.Empty)
            {
                doc.Views.Redraw();
                result = Rhino.Commands.Result.Success;
            }

            return(result);
        }
Exemplo n.º 17
0
        public static GeometryLarge CreateGeometry(MaterialType mType, string mName)

        {
            RhinoDoc doc = RhinoDoc.ActiveDoc;

            //Allow user to pick multiple objects
            const Rhino.DocObjects.ObjectType geometryFilter = Rhino.DocObjects.ObjectType.Curve;

            Rhino.Input.Custom.GetObject go = new Rhino.Input.Custom.GetObject()
            {
                GeometryFilter              = geometryFilter,
                GroupSelect                 = true,
                SubObjectSelect             = false,
                DeselectAllBeforePostSelect = false
            };
            go.SetCommandPrompt("Pick one or two closed curves.");
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);

            bool bHavePreselectedObjects = false;

            for (;;)
            {
                Rhino.Input.GetResult res = go.GetMultiple(1, 0);
                if (go.ObjectsWerePreselected)
                {
                    bHavePreselectedObjects = true;
                    go.EnablePreSelect(false, true);
                    continue;
                }
                break;
            }

            //Unselects the preselected objects
            if (bHavePreselectedObjects)
            {
                for (int i = 0; i < go.ObjectCount; i++)
                {
                    RhinoObject rhinoObject = go.Object(i).Object();
                    if (null != rhinoObject)
                    {
                        rhinoObject.Select(false);
                    }
                }

                doc.Views.Redraw();
            }

            ObjRef[]     objs           = go.Objects();
            List <Curve> selectedCurves = new List <Curve>();

            foreach (ObjRef objRef in objs)
            {
                if (objRef.Curve() == null)
                {
                    RhinoApp.WriteLine("One of the selected objects was invalid.");
                    continue;
                }
                else if (!objRef.Curve().IsClosed)
                {
                    RhinoApp.WriteLine("One of the selected curves was not closed.");
                    continue;
                }
                selectedCurves.Add(objRef.Curve());
            }

            GeometryLarge larg;

            //if the curve is not closed do nothing
            switch (selectedCurves.Count)
            {
            case 0:
                Rhino.RhinoApp.WriteLine("No valid geometries was found.");
                return(null);

            case 1:
                larg = DrawAndSaveUserAttr(Brep.CreatePlanarBreps(selectedCurves)[0], doc, mType, mName);
                break;

            case 2:
                Brep brep1 = Brep.CreatePlanarBreps(new[] { selectedCurves[0] })[0];
                Brep brep2 = Brep.CreatePlanarBreps(new[] { selectedCurves[1] })[0];

                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)
                {
                    Brep brep = Brep.CreateBooleanDifference(brep1, brep2, doc.ModelAbsoluteTolerance)[0];
                    larg = DrawAndSaveUserAttr(brep, doc, mType, mName);
                    break;
                }

                else if (area > 0.999 * brep2Area && area < 1.001 * brep2Area)
                {
                    Brep brep = Brep.CreateBooleanDifference(brep1, brep2, doc.ModelAbsoluteTolerance)[0];
                    larg = DrawAndSaveUserAttr(brep, doc, mType, mName);
                    break;
                }
                else
                {
                    RhinoApp.WriteLine("The curves were not inside one another.");
                    return(null);
                }

            default:
                return(null);
            }

            foreach (ObjRef objRef in objs)
            {
                doc.Objects.Delete(objRef, false);
            }
            return(larg);
        }
Exemplo n.º 18
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Create class instances
            Curve       centreCrv   = new PolylineCurve();
            int         floors      = 1;
            double      thickness   = 1;
            double      levelHeight = 1;
            Rectangle3d garden      = new Rectangle3d();
            Point3d     accessPt    = new Point3d();

            //Get Data
            if (!DA.GetData(0, ref centreCrv))
            {
                return;
            }
            if (!DA.GetData(1, ref floors))
            {
                return;
            }
            if (!DA.GetData(2, ref thickness))
            {
                return;
            }
            if (!DA.GetData(3, ref levelHeight))
            {
                return;
            }
            if (!DA.GetData(4, ref garden))
            {
                return;
            }
            if (!DA.GetData(5, ref accessPt))
            {
                return;
            }


            //Set properties
            PlotPlanning.ObjectModel.MultiFamily house = new ObjectModel.MultiFamily();
            house.Floors      = floors;
            house.Thickness   = thickness;
            house.LevelHeight = levelHeight;
            house.GardenBound = garden.ToPolyline();
            house.AccessPoint = accessPt;

            //Create geometry.
            Brep[] b = Engine.Geometry.Compute.Sweep(centreCrv, thickness, 2);

            //Get and join all brep edges
            Curve[] En    = b[0].DuplicateNakedEdgeCurves(true, true);
            Curve[] bound = Curve.JoinCurves(En);

            // TODO: make sure all the bounding curves are clockwise. This is to ensure extrution in the correct diection
            // For now I used a neg sign before extrution height....
            Extrusion ex = Extrusion.Create(bound[0], -levelHeight * floors, true);

            if (centreCrv.IsClosed)
            {
                //Sort profiles by length. The longer curve will be the outer profile. The shorter the inner.
                Curve     innerCrv = bound.ToList().OrderBy(x => x.GetLength()).First();
                Extrusion exInner  = Extrusion.Create(innerCrv, levelHeight * floors, true);
                Brep[]    diff     = Brep.CreateBooleanDifference(ex.ToBrep(), exInner.ToBrep(), ObjectModel.Tolerance.Distance);
                house.HouseGeom = diff[0];
            }
            else
            {
                house.HouseGeom = ex.ToBrep();
            }


            //Set data
            DA.SetData(0, house);
        }
Exemplo n.º 19
0
        private static Brep GetCrscDBShape(string name)
        {
            Structure    IStr    = null;
            List <Curve> rCurves = new List <Curve>();

            try
            {
                /*
                 * IStr = (Structure)Marshal.GetActiveObject("RFEM3.Structure");
                 * // IStr.rfGetApplication().rfLockLicence();
                 * IrfStructuralData IData = IStr.rfGetStructuralData();
                 * IrfDatabaseCrSc db = IData.rfGetDatabaseCrSc();
                 *
                 * IrfCrossSectionDB2 crsc = (IrfCrossSectionDB2) db.rfGetCrossSection(name);
                 *
                 * List<Curve> rTempCurves = new List<Curve>();
                 *
                 *
                 * CURVE_2D[] curves = (CURVE_2D[]) crsc.rfGetShape();
                 *
                 * foreach (CURVE_2D curve in curves)
                 *  {
                 *  IPOINT_2D[] points = curve.arrPoints as IPOINT_2D[];
                 *  if (curve.type == CURVE_TYPE.CT_LINE)
                 *  {
                 *      rTempCurves.Add(new Rhino.Geometry.Line(new Point3d(points[0].x,points[0].y,0),
                 *          new Point3d(points[1].x,points[1].y,0)).ToNurbsCurve());
                 *  }
                 *  if (curve.type == CURVE_TYPE.CT_ARC)
                 *      rTempCurves.Add(new Arc(new Point3d(points[0].x, points[0].y, 0),
                 *          new Point3d(points[1].x, points[1].y, 0),
                 *          new Point3d(points[2].x, points[2].y, 0)).ToNurbsCurve());
                 *  if (curve.type == CURVE_TYPE.CT_CIRCLE){
                 *      double radius = (new Vector3d(points[0].x, points[0].y, 0) -
                 *          new Vector3d(points[1].x, points[1].y, 0)).Length;
                 *      rTempCurves.Add(new Circle(new Point3d(points[0].x, points[0].y, 0),
                 *          radius).ToNurbsCurve());
                 *  }
                 *
                 * }
                 * rCurves.AddRange(Curve.JoinCurves(rTempCurves));
                 */
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                //Release COM object
                if (IStr != null)
                {
                    IStr.rfGetApplication().rfUnlockLicence();
                    IStr = null;
                }
                //Cleans Garbage collector for releasing all COM interfaces and objects
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }

            rCurves.Add(new Circle(Plane.WorldXY, 155).ToNurbsCurve());
            Brep cutter;
            Brep shape;

            if (rCurves.Count == 1)
            {
                shape = Brep.CreatePlanarBreps(rCurves[0])[0];
            }

            else if (rCurves.Count > 1)
            {
                if (!rCurves.TrueForAll(o => o.IsClosed))
                {
                    return(null);
                }
                List <double> areas = new List <double>();
                foreach (Curve curve in rCurves)
                {
                    AreaMassProperties am = AreaMassProperties.Compute(curve);
                    areas.Add(am.Area);
                }
                double maxArea = areas.Max();
                int    index   = areas.IndexOf(maxArea);
                Curve  outline = rCurves[index];
                shape = Brep.CreatePlanarBreps(outline)[0];
                for (int i = 0; i < rCurves.Count; i++)
                {
                    if (i != index)
                    {
                        cutter = Brep.CreatePlanarBreps(rCurves[i])[0];

                        shape = Brep.CreateBooleanDifference(shape, cutter, 0.001)[0];
                    }
                }
            }
            else
            {
                shape = new Brep();
            }

            Transform tr = Transform.Scale(new Point3d(0, 0, 0), 0.001);

            shape.Transform(tr);
            return(shape);
        }
Exemplo n.º 20
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve  siteCrv          = null;
            double fsr              = double.NaN;
            double flrHt            = double.NaN;
            double setback          = double.NaN;
            double bayDepth         = double.NaN;
            double slendernessRatio = double.NaN;

            if (!DA.GetData(0, ref siteCrv))
            {
                return;
            }
            if (!DA.GetData(1, ref fsr))
            {
                return;
            }
            if (!DA.GetData(2, ref flrHt))
            {
                return;
            }
            if (!DA.GetData(3, ref setback))
            {
                return;
            }
            if (!DA.GetData(4, ref bayDepth))
            {
                return;
            }
            if (!DA.GetData(5, ref slendernessRatio))
            {
                return;
            }

            Curve   c0_ = siteCrv.DuplicateCurve();
            Curve   c0  = Curve.ProjectToPlane(c0_, Plane.WorldXY);
            Point3d cen = AreaMassProperties.Compute(c0).Centroid;

            Curve[] outerCrvArr = c0.Offset(cen, Vector3d.ZAxis, setback, 0.01, CurveOffsetCornerStyle.Sharp);
            Curve[] innerCrvArr = outerCrvArr[0].Offset(cen, Vector3d.ZAxis, bayDepth, 0.01, CurveOffsetCornerStyle.Sharp);

            string debugMsg = "";

            try
            {
                if (innerCrvArr.Length != 1)
                {
                    debugMsg += "\ninner crv error"; return;
                }
                if (outerCrvArr.Length != 1)
                {
                    debugMsg += "\nouter crv error"; return;
                }
                double siteAr              = AreaMassProperties.Compute(siteCrv).Area;
                double GFA                 = siteAr * fsr;
                double outerAr             = AreaMassProperties.Compute(outerCrvArr[0]).Area;
                double innerAr             = AreaMassProperties.Compute(innerCrvArr[0]).Area;
                double netAr               = outerAr - innerAr;
                double numFlrs             = GFA / netAr;
                double reqHt               = numFlrs * flrHt;
                double gotSlendernessRatio = reqHt / netAr;
                if (gotSlendernessRatio < slendernessRatio)
                {
                    return;
                }
                if (setback > 0 && bayDepth > 0 && flrHt > 0)
                {
                    List <string> numFlrReqLi = new List <string>();
                    List <Curve>  crvLi       = new List <Curve>();
                    double        flrCounter  = 0.0;
                    for (int i = 0; i < numFlrs; i++)
                    {
                        Curve c0crv = outerCrvArr[0].DuplicateCurve();
                        Curve c1crv = innerCrvArr[0].DuplicateCurve();
                        Rhino.Geometry.Transform xform = Rhino.Geometry.Transform.Translation(0, 0, flrCounter);
                        c0crv.Transform(xform);
                        c1crv.Transform(xform);
                        crvLi.Add(c0crv);
                        crvLi.Add(c1crv);
                        flrCounter += flrHt;
                    }
                    numFlrReqLi.Add(flrCounter.ToString());

                    List <Brep> brepLi    = new List <Brep>();
                    Extrusion   outerMass = Rhino.Geometry.Extrusion.Create(outerCrvArr[0], reqHt, true);
                    var         B         = outerMass.GetBoundingBox(true);
                    if (B.Max.Z < 0.01)
                    {
                        outerMass = Extrusion.Create(outerCrvArr[0], -reqHt, true);
                    }
                    Brep outerBrep = outerMass.ToBrep();

                    Extrusion innerMass = Rhino.Geometry.Extrusion.Create(innerCrvArr[0], reqHt, true);
                    var       B2        = innerMass.GetBoundingBox(true);
                    if (B2.Max.Z < 0.01)
                    {
                        innerMass = Extrusion.Create(innerCrvArr[0], -reqHt, true);
                    }
                    Brep innerBrep = innerMass.ToBrep();

                    Brep[] netBrep = Brep.CreateBooleanDifference(outerBrep, innerBrep, 0.1);
                    try { brepLi.Add(netBrep[0]); }
                    catch (Exception)
                    {
                        debugMsg += "Error in brep subtraction";
                    }
                    DA.SetDataList(0, crvLi);
                    DA.SetDataList(1, brepLi);
                }
            }
            catch (Exception)
            {
                debugMsg += "Error in system";
            }
            // DA.SetDataList(2, debugMsg);
        }