Esempio n. 1
0
        public void SplittingTest()
        {
            Rectangle3d rect     = new Rectangle3d(Plane.WorldXY, 5000, 1000);
            Curve       Boundary = rect.ToNurbsCurve();

            List <Plane> splitPlanes = new List <Plane>();

            for (int i = 1; i < 5; i++)
            {
                Point3d planeOrigin = new Point3d(i * 500, 0, 0);
                Plane   splitPlane  = new Plane(planeOrigin, Vector3d.XAxis);
                splitPlanes.Add(splitPlane);
            }

            List <Curve> splitCurves = Curves.DivideCurve(Boundary, splitPlanes);

            Assert.Equal <int>(5, splitCurves.Count);
            Assert.All <Curve>(splitCurves, result => Assert.True(result.IsClosed));

            double boundaryArea = AreaMassProperties.Compute(Boundary).Area;

            double splitAreas = 0;

            foreach (Curve crv in splitCurves)
            {
                double crvArea = AreaMassProperties.Compute(crv).Area;
                splitAreas += crvArea;
            }

            Assert.Equal <double>(Math.Round(boundaryArea, 0), Math.Round(splitAreas, 0));
        }
Esempio n. 2
0
        public static Curve RectangleWHC(double width, double height, Point3d center)
        {
            double deltaX = width / 2;
            double deltaY = height / 2;

            double centerX = center.X;
            double centerY = center.Y;

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

            Point3d TopRightPoint    = new Point3d(centerX + deltaX, centerY + deltaY, 0);
            Point3d TopLeftPoint     = new Point3d(centerX - deltaX, centerY + deltaY, 0);
            Point3d BottomLeftPoint  = new Point3d(centerX - deltaX, centerY - deltaY, 0);
            Point3d BottomRightPoint = new Point3d(centerX + deltaX, centerY - deltaY, 0);

            CornerPoints.Add(TopRightPoint);
            CornerPoints.Add(TopLeftPoint);
            CornerPoints.Add(BottomLeftPoint);
            CornerPoints.Add(BottomRightPoint);
            CornerPoints.Add(TopRightPoint);

            Rectangle3d Rectangle = new Rectangle3d(new Plane(center, Vector3d.ZAxis), TopRightPoint, BottomLeftPoint);

            return(Rectangle.ToNurbsCurve());
        }
Esempio n. 3
0
        public static void BoundingSquare(CurveRelation source)
        {
            var box = source.Geometry.GetBoundingBox(Plane.WorldXY);

            var rect = new Rectangle3d(Plane.WorldXY, box.Min, new Point3d(box.Max.X, box.Min.Y, 0));

            source.Properties.BoundingSquare = rect.ToNurbsCurve();
        }
Esempio n. 4
0
        //THIS FUNCTION IS TEMPORARY. The function generates a box or a sweep. This determined by the linearity of the curve.
        public Brep MakeBrep()
        {
            Brep Geometri = new Brep();

            double[] parameter = { 0.0, 2.2 };


            Plane tempPlane = new Plane(elemLine.PointAtStart, elemLine.TangentAtStart);

            Ali.rotationVectorToPoint(elemLine.PointAtStart);
            Vector3d alignvector = Ali.Rotation;
            //Getting rotation angle
            double angle = Rhino.Geometry.Vector3d.VectorAngle(tempPlane.XAxis, alignvector, tempPlane);

            tempPlane.Rotate(angle, tempPlane.Normal, tempPlane.Origin);
            tempPlane.Translate(tempPlane.XAxis * Ali.OffsetY);
            tempPlane.Translate(tempPlane.YAxis * Ali.OffsetZ);



            Interval iz = new Interval();
            Interval iy = new Interval();
            Interval ix = new Interval();

            double HalfWidth  = rectSec.Width / 2;
            double HalfHeight = rectSec.Height / 2;

            iz = new Interval(-HalfHeight, HalfHeight);
            iy = new Interval(-HalfWidth, HalfWidth);
            ix = new Interval(0, elemLine.GetLength());



            if (elemLine.IsLinear())
            {
                Box boxen = new Box(tempPlane, iy, iz, ix);
                Geometri = boxen.ToBrep();
            }
            else
            {
                SweepOneRail tempsweep = new SweepOneRail();
                Rectangle3d  rect      = new Rectangle3d(tempPlane, iy, iz);
                rect.ToPolyline();

                var sweep = tempsweep.PerformSweep(elemLine, rect.ToNurbsCurve());


                Geometri = sweep[0];
            }



            return(Geometri);
        }
Esempio n. 5
0
        private Rectangle3d TranslateRect(Point3d pt, Rectangle3d r0)
        {
            Vector3d c0 = new Vector3d(AreaMassProperties.Compute(r0.ToNurbsCurve()).Centroid);
            Vector3d tg = new Vector3d(pt);
            Vector3d t0 = Vector3d.Subtract(tg, c0);

            Rectangle3d rNew0 = new Rectangle3d(r0.Plane, r0.Width, r0.Height);

            rNew0.Transform(Transform.Translation(t0));

            return(rNew0);
        }
Esempio n. 6
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)
        {
            IGH_Goo     Z = null;
            Rectangle3d R = new Rectangle3d(Plane.WorldXY, 150, 150);

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

            Bitmap A = null;

            if (Z != null)
            {
                Z.CastTo(out A);
            }

            // Check if is pline
            Curve C = R.ToNurbsCurve();

            BoundingBox B = C.GetBoundingBox(true);
            wPoint      O = new wPoint(B.Center.X, B.Center.Y, B.Center.Z);

            wShape           Shape  = new wShape(new wRectangle());
            wShapeCollection Shapes = new wShapeCollection(Shape);

            wPlane Pln = new wPlane().XYPlane();

            Pln.Origin = O;

            Shapes.Boundary = new wRectangle(Pln, B.Diagonal.X, B.Diagonal.Y);
            //Shapes.Type = Crv.GetCurveType;

            if (C.IsClosed)
            {
                Shapes.Graphics = new wGraphic().BlackFill();
            }
            else
            {
                Shapes.Graphics = new wGraphic().BlackOutline();
            }
            Shapes.Effects = new wEffects();


            wObject WindObject = new wObject(Shapes, "Hoopoe", Shapes.Type);

            DA.SetData(0, WindObject);
        }
Esempio n. 7
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve  iRail    = null;
            Curve  iProfile = null;
            double iX       = 0.0;
            double iY       = 0.0;

            if (!DA.GetData(0, ref iRail))
            {
                return;
            }
            if (!DA.GetData(0, ref iProfile))
            {
                return;
            }
            if (!DA.GetData(1, ref iX))
            {
                return;
            }
            if (!DA.GetData(2, ref iY))
            {
                return;
            }

            Plane pln = new Plane();

            iRail.PerpendicularFrameAt(0.0, out pln);
            var rect = new Rectangle3d(pln, iX, iY);

            Plane Orig   = new Plane(0, 0, 1, 0);
            var   xform1 = Rhino.Geometry.Transform.PlaneToPlane(Orig, pln);


            var rectC = rect.ToNurbsCurve();

            if (iProfile != null)
            {
                iProfile.Transform(xform1);
                rectC = iProfile.ToNurbsCurve();
            }

            var sweep = new Rhino.Geometry.SweepOneRail();

            sweep.AngleToleranceRadians = 0.017453;
            sweep.ClosedSweep           = false;
            sweep.SweepTolerance        = 0.001;
            sweep.SetToRoadlikeTop();
            var breps = sweep.PerformSweep(iRail, rectC);

            DA.SetDataList(0, breps);
        }
Esempio n. 8
0
        public override List <Brep> GetLamellaBreps()
        {
            double Length = Centreline.GetLength();
            double hW     = Data.NumWidth * Data.LamWidth / 2;
            double hH     = Data.NumHeight * Data.LamHeight / 2;

            double[] DivParams = new double[] { Centreline.Domain.Min, Centreline.Domain.Max };

            List <Curve>[,] LoftCurves = new List <Curve> [Data.NumWidth, Data.NumHeight];
            List <Brep> LamellaBreps = new List <Brep>();

            // Initialize curve lists
            for (int i = 0; i < Data.NumWidth; ++i)
            {
                for (int j = 0; j < Data.NumHeight; ++j)
                {
                    LoftCurves[i, j] = new List <Curve>();
                }
            }

            for (int i = 0; i < DivParams.Length; ++i)
            {
                Plane p = GetPlane(DivParams[i]);

                for (int j = 0; j < Data.NumWidth; ++j)
                {
                    for (int k = 0; k < Data.NumHeight; ++k)
                    {
                        Rectangle3d rec = new Rectangle3d(p,
                                                          new Interval(-hW + j * Data.LamWidth, -hW + (j + 1) * Data.LamWidth),
                                                          new Interval(-hH + k * Data.LamHeight, -hH + (k + 1) * Data.LamHeight));
                        LoftCurves[j, k].Add(rec.ToNurbsCurve());
                    }
                }
            }

            for (int i = 0; i < Data.NumWidth; ++i)
            {
                for (int j = 0; j < Data.NumHeight; ++j)
                {
                    Brep[] brep = Brep.CreateFromLoft(LoftCurves[i, j], Point3d.Unset, Point3d.Unset, LoftType.Normal, false);
                    if (brep != null && brep.Length > 0)
                    {
                        LamellaBreps.Add(brep[0].CapPlanarHoles(Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance));
                    }
                }
            }
            return(LamellaBreps);
        }
Esempio n. 9
0
            private static List <Polyline> DrawCorridor(List <Point3d> anchors, List <Line> baseAxis, double subLength)
            {
                List <Polyline> corridor = new List <Polyline>();

                Rectangle3d subCorridor  = RectangleTools.DrawP2PRect(anchors[0], anchors[1], subLength, CorridorDimension.TwoWayWidth);
                Rectangle3d mainCorridor = RectangleTools.DrawP2PRect(anchors[1], anchors[2], CorridorDimension.TwoWayWidth, subLength);

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

                forUnion.Add(subCorridor.ToNurbsCurve());
                forUnion.Add(mainCorridor.ToNurbsCurve());

                corridor.Add(CurveTools.ToPolyline(Curve.CreateBooleanUnion(forUnion)[0]));

                return(corridor);
            }
Esempio n. 10
0
        private static int inCheck(Point3d midPoint, double width, double ratio, Polyline outline)
        {
            Rectangle3d    rect   = new Rectangle3d(Plane.WorldXY, new Point3d(midPoint.X - width, midPoint.Y - width * ratio, 0), new Point3d(midPoint.X + width, midPoint.Y + width * ratio, 0));
            List <Point3d> no     = new List <Point3d>();
            List <Point3d> mids   = new List <Point3d>();
            Curve          curveA = rect.ToNurbsCurve();
            Curve          curveB = outline.ToNurbsCurve();
            List <Point3d> points = new List <Point3d>();
            int            k      = Rhino.Geometry.Intersect.Intersection.CurveCurve(curveA, curveB, 0, 0).Count;

            if (k == 0)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Esempio n. 11
0
        public static Dictionary <string, DataTree <object> > CreatedMeshFromSlicedDomain(
            Box domain,
            double location,
            double gridSize,
            List <Brep> excludeGeometry,
            string sliceDirection)
        {
            var normal = new Vector3d();
            var origin = new Point3d();
            var width  = new Interval();
            var height = new Interval();

            if (sliceDirection == "x")
            {
                normal.X = 1;
                origin.X = location;
                width    = domain.Y;
                height   = domain.Z;
            }
            else if (sliceDirection == "y")
            {
                normal.Y = 1;
                origin.Y = location;
                width    = domain.Z;
                height   = domain.X;
            }
            else
            {
                normal.Z = 1;
                origin.Z = location;
                width    = domain.X;
                height   = domain.Y;
            }

            var cutPlane  = new Plane(origin, normal);
            var rectangle = new Rectangle3d(cutPlane, width, height);
            var surface   = Brep.CreatePlanarBreps(rectangle.ToNurbsCurve(), 0.1).ToList();

            return(CreateAnalysisMesh(surface, gridSize, excludeGeometry, 0.0, "z"));
        }
Esempio n. 12
0
        private static List <Curve> CreateNamecardForm(Point3d CenterPoint)
        {
            List <Curve> output = new List <Curve>();

            Rectangle3d outLine = new Rectangle3d(Plane.WorldXY, new Interval(-2000, 2000), new Interval(-500, 500));

            List <Curve> box = outLine.ToNurbsCurve().DuplicateSegments().ToList();

            output.AddRange(box);

            output.Add(new LineCurve(new Point3d(-2000, 0, 0), new Point3d(2000, 0, 0)));

            output.Add(new LineCurve(Point3d.Origin, new Point3d(0, -500, 0)));

            for (int i = 0; i < output.Count(); i++)
            {
                Curve tempCurveToMove = output[i].DuplicateCurve();

                tempCurveToMove.Transform(Transform.Translation(new Vector3d(CenterPoint)));
                output[i] = tempCurveToMove;
            }

            return(output);
        }
Esempio n. 13
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///Gather GHA inputs
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            string shpFilePath = string.Empty;

            DA.GetData <string>("Vector Data Location", ref shpFilePath);

            bool cropIt = true;

            DA.GetData <Boolean>("Crop file", ref cropIt);

            string userSRStext = "WGS84";

            DA.GetData <string>(2, ref userSRStext);


            ///GDAL setup
            ///Some preliminary testing has been done to read SHP, GeoJSON, OSM, KML, MVT, GML and GDB
            ///It can be spotty with KML, MVT and GML and doesn't throw informative errors.  Likely has to do with getting a valid CRS and
            ///TODO: resolve errors with reading KML, MVT, GML.

            DataSource   dataSource = CreateDataSource(shpFilePath);
            List <Layer> layerSet   = GetLayers(dataSource);

            ///Declare trees
            GH_Structure <GH_Rectangle> recs = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    spatialReferences = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fnames            = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fset = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>     gset = new GH_Structure <GH_Point>();

            GH_Structure <GH_Point>     gsetUser = new GH_Structure <GH_Point>();
            GH_Structure <GH_Rectangle> recsUser = new GH_Structure <GH_Rectangle>();

            GH_Structure <GH_String>        gtype = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGoo  = new GH_Structure <IGH_GeometricGoo>();


            ///Loop through each layer. Layers usually occur in Geodatabase GDB format. SHP usually has only one layer.
            for (int iLayer = 0; iLayer < dataSource.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = dataSource.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine($"Couldn't fetch advertised layer {iLayer}");
                    System.Environment.Exit(-1);
                }

                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);



                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Layer #{iLayer} {layer.GetName()} has {featureCount} features");

                ///Get the spatial reference of the input vector file and set to WGS84 if not known
                ///
                OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference(Osr.SRS_WKT_WGS84);
                string spatialReference = GetSpatialReference(layer, iLayer, dataSource, sourceSRS);
                spatialReferences.Append(new GH_String(spatialReference), new GH_Path(iLayer));


                ///Set transform from input spatial reference to Rhino spatial reference
                ///TODO: look into adding a step for transforming to CRS set in SetCRS
                OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
                rhinoSRS.SetWellKnownGeogCS("WGS84");

                ///TODO: verify the userSRS is valid
                ///TODO: use this as override of global SetSRS
                OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
                userSRS.SetFromUserInput(userSRStext);

                ///These transforms move and scale in order to go from userSRS to XYZ and vice versa
                Transform userSRSToModelTransform   = Heron.Convert.GetUserSRSToModelTransform(userSRS);
                Transform modelToUserSRSTransform   = Heron.Convert.GetModelToUserSRSTransform(userSRS);
                Transform sourceToModelSRSTransform = Heron.Convert.GetUserSRSToModelTransform(sourceSRS);
                Transform modelToSourceSRSTransform = Heron.Convert.GetModelToUserSRSTransform(sourceSRS);

                ///Get OGR envelope of the data in the layer in the sourceSRS
                OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
                layer.GetExtent(ext, 1);

                OSGeo.OGR.Geometry extMinSourceOgr = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint);
                extMinSourceOgr.AddPoint(ext.MinX, ext.MinY, 0.0);
                extMinSourceOgr.AssignSpatialReference(sourceSRS);

                OSGeo.OGR.Geometry extMaxSourceOgr = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint);
                extMaxSourceOgr.AddPoint(ext.MaxX, ext.MaxY, 0.0);
                extMaxSourceOgr.AssignSpatialReference(sourceSRS);

                ///Get extents in Rhino SRS
                Point3d extPTmin = Heron.Convert.OgrPointToPoint3d(extMinSourceOgr, sourceToModelSRSTransform);
                Point3d extPTmax = Heron.Convert.OgrPointToPoint3d(extMaxSourceOgr, sourceToModelSRSTransform);

                Rectangle3d rec = new Rectangle3d(Plane.WorldXY, extPTmin, extPTmax);
                recs.Append(new GH_Rectangle(rec), new GH_Path(iLayer));

                ///Get extents in userSRS
                ///Can give odd results if crosses 180 longitude
                extMinSourceOgr.TransformTo(userSRS);
                extMaxSourceOgr.TransformTo(userSRS);

                Point3d extPTminUser = Heron.Convert.OgrPointToPoint3d(extMinSourceOgr, userSRSToModelTransform);
                Point3d extPTmaxUser = Heron.Convert.OgrPointToPoint3d(extMaxSourceOgr, userSRSToModelTransform);

                Rectangle3d recUser = new Rectangle3d(Plane.WorldXY, extPTminUser, extPTmaxUser);
                recsUser.Append(new GH_Rectangle(recUser), new GH_Path(iLayer));


                if (boundary.Count == 0 && cropIt == true)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Define a boundary or set cropIt to False");
                }

                else if (boundary.Count == 0 && cropIt == false)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipping boundary has not been defined. File extents will be used instead");
                    boundary.Add(rec.ToNurbsCurve());
                }



                ///Loop through input boundaries
                for (int i = 0; i < boundary.Count; i++)
                {
                    OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn();

                    ///Get the field names
                    List <string> fieldnames = new List <string>();
                    for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                    {
                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                        fnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(i, iLayer));
                    }

                    ///Check if boundary is contained in extent
                    if (!rec.IsValid || ((rec.Height == 0) && (rec.Width == 0)))
                    {
                        ///Get field data if even if no geometry is present in the layer
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more vector datasource bounds are not valid.");
                        OSGeo.OGR.Feature feat;
                        int m = 0;

                        while ((feat = layer.GetNextFeature()) != null)
                        {
                            ///Loop through field values
                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                fdef.Dispose();
                            }
                            m++;
                            feat.Dispose();
                        }
                    }

                    else if (boundary[i] == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " not set.");
                    }

                    else if (!boundary[i].IsValid)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + "  is not valid.");
                    }

                    else if (rec.IsValid && Curve.PlanarClosedCurveRelationship(rec.ToNurbsCurve(), boundary[i], Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance) == RegionContainment.Disjoint)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more clipping boundaries may be outside the bounds of the vector datasource.");
                    }

                    else
                    {
                        ///Create bounding box for clipping geometry
                        Point3d min = boundary[i].GetBoundingBox(true).Min;
                        Point3d max = boundary[i].GetBoundingBox(true).Max;
                        min.Transform(modelToSourceSRSTransform);
                        max.Transform(modelToSourceSRSTransform);
                        double[] minpT = new double[3];
                        double[] maxpT = new double[3];

                        minpT[0] = min.X;
                        minpT[1] = min.Y;
                        minpT[2] = min.Z;
                        maxpT[0] = max.X;
                        maxpT[1] = max.Y;
                        maxpT[2] = max.Z;


                        OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                        ///Create bounding box for clipping geometry
                        ///Not working on MVT type files
                        //boundary[i].Transform(modelToSourceSRSTransform);
                        //OSGeo.OGR.Geometry ebbox = Heron.Convert.CurveToOgrPolygon(boundary[i]);


                        ///Clip Shapefile
                        ///http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                        OSGeo.OGR.Layer clipped_layer = layer;

                        if (cropIt)
                        {
                            clipped_layer.SetSpatialFilter(ebbox);
                        }

                        ///Loop through geometry
                        OSGeo.OGR.Feature feat;
                        def = clipped_layer.GetLayerDefn();

                        int m = 0;
                        while ((feat = clipped_layer.GetNextFeature()) != null)
                        {
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone();
                            OSGeo.OGR.Geometry sub_geomUser;

                            ///reproject geometry to WGS84 and userSRS
                            ///TODO: look into using the SetCRS global variable here
                            if (geom.GetSpatialReference() == null)
                            {
                                geom.AssignSpatialReference(sourceSRS);
                            }
                            if (geomUser.GetSpatialReference() == null)
                            {
                                geomUser.AssignSpatialReference(sourceSRS);
                            }

                            geom.TransformTo(rhinoSRS);
                            geomUser.TransformTo(userSRS);
                            gtype.Append(new GH_String(geom.GetGeometryName()), new GH_Path(i, iLayer, m));

                            if (feat.GetGeometryRef() != null)
                            {
                                ///Convert GDAL geometries to IGH_GeometricGoo
                                gGoo.AppendRange(Heron.Convert.OgrGeomToGHGoo(geomUser, userSRSToModelTransform), new GH_Path(i, iLayer, m));

                                /// Get Feature Values
                                if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                {
                                    fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                }
                                for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                {
                                    OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                    if (feat.IsFieldSet(iField))
                                    {
                                        fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                    }
                                    else
                                    {
                                        fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                    }
                                }
                                ///End get Feature Values


                                ///Start get points if open polylines and points
                                for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                                {
                                    ///Loop through geometry points for Rhino SRS
                                    double[] ogrPt = new double[3];
                                    geom.GetPoint(gpc, ogrPt);
                                    Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]);
                                    pt3D.Transform(Heron.Convert.WGSToXYZTransform());

                                    gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m));

                                    ///Loop through geometry points for User SRS
                                    double[] ogrPtUser = new double[3];
                                    geomUser.GetPoint(gpc, ogrPtUser);
                                    Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                    pt3DUser.Transform(userSRSToModelTransform);

                                    gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m));

                                    ///End loop through geometry points


                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                ///End getting points if open polylines or points


                                ///Start getting points if closed polylines and multipolygons
                                for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                                {
                                    sub_geom = geom.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geom;

                                    sub_geomUser = geomUser.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geomUser;

                                    if (sub_geom.GetGeometryCount() > 0)
                                    {
                                        for (int n = 0; n < sub_geom.GetGeometryCount(); n++)
                                        {
                                            subsub_geom     = sub_geom.GetGeometryRef(n);
                                            subsub_geomUser = sub_geomUser.GetGeometryRef(n);

                                            for (int ptnum = 0; ptnum < subsub_geom.GetPointCount(); ptnum++)
                                            {
                                                ///Loop through geometry points
                                                double[] ogrPt = new double[3];
                                                subsub_geom.GetPoint(ptnum, ogrPt);
                                                Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]);
                                                pt3D.Transform(Heron.Convert.WGSToXYZTransform());

                                                gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m, gi, n));

                                                ///Loop through geometry points for User SRS
                                                double[] ogrPtUser = new double[3];
                                                subsub_geomUser.GetPoint(ptnum, ogrPtUser);
                                                Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                                pt3DUser.Transform(userSRSToModelTransform);

                                                gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi, n));

                                                ///End loop through geometry points
                                            }
                                            subsub_geom.Dispose();
                                            subsub_geomUser.Dispose();
                                        }
                                    }

                                    else
                                    {
                                        for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                                        {
                                            ///Loop through geometry points
                                            double[] ogrPt = new double[3];
                                            sub_geom.GetPoint(ptnum, ogrPt);
                                            Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]);
                                            pt3D.Transform(Heron.Convert.WGSToXYZTransform());

                                            gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m, gi));

                                            ///Loop through geometry points for User SRS
                                            double[] ogrPtUser = new double[3];
                                            sub_geomUser.GetPoint(ptnum, ogrPtUser);
                                            Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                            pt3DUser.Transform(userSRSToModelTransform);

                                            gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi));

                                            ///End loop through geometry points
                                        }
                                    }

                                    sub_geom.Dispose();
                                    sub_geomUser.Dispose();


                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }


                                //m++;
                            }
                            m++;
                            geom.Dispose();
                            geomUser.Dispose();
                            feat.Dispose();
                        } ///end while loop through features
                    }     ///end clipped layer else statement
                }         ///end loop through boundaries

                layer.Dispose();
            }///end loop through layers

            dataSource.Dispose();

            DA.SetDataTree(0, recs);
            DA.SetDataTree(1, spatialReferences);
            DA.SetDataTree(2, fnames);
            DA.SetDataTree(3, fset);
            DA.SetDataTree(4, gset);

            DA.SetDataTree(5, gsetUser);
            DA.SetDataTree(6, recsUser);

            DA.SetDataTree(7, gGoo);
            DA.SetDataTree(8, gtype);
        }
Esempio n. 14
0
        public List <Brep> KDGmaker(List <Curve> segs, Curve boundary, List <Point3d> roadPoints, double scalefactor)
        {
            //split surface
            Rhino.RhinoDoc.ActiveDoc.Layers.SetCurrentLayerIndex(Rhino.RhinoDoc.ActiveDoc.Layers.Find("ZC304", true), true);
            List <Point3d> bboxPts = new List <Point3d>();

            foreach (Curve c in segs)
            {
                bboxPts.Add(c.PointAtStart);
                bboxPts.Add(c.PointAtEnd);
            }
            var          bbox = new BoundingBox(bboxPts);
            Rectangle3d  rect = new Rectangle3d(Plane.WorldXY, bbox.Min, bbox.Max);
            List <Curve> crvs = new List <Curve>();

            crvs.Add(rect.ToNurbsCurve());
            Brep        brep  = Brep.CreatePlanarBreps(rect.ToNurbsCurve())[0];
            var         temp1 = brep.Faces[0].Split(segs, 0.1).Faces;
            List <Brep> temp2 = new List <Brep>();

            foreach (BrepFace bf in temp1)
            {
                temp2.Add(bf.DuplicateFace(false));
            }


            //get edge polylines
            List <Polyline>    edges = new List <Polyline>();
            List <Rectangle3d> rects = new List <Rectangle3d>();

            foreach (Brep b in temp2)
            {
                Polyline polyTemp;
                Curve.JoinCurves(b.DuplicateEdgeCurves().ToList(), 1)[0].TryGetPolyline(out polyTemp);

                bool isRoad = false;
                for (int i = 0; i < roadPoints.Count; i++)
                {
                    if (polyTemp.ToNurbsCurve().Contains(roadPoints[i]) != Rhino.Geometry.PointContainment.Outside)
                    {
                        isRoad = true;
                        break;
                    }
                }

                if (!isRoad && boundary.Contains(polyTemp.CenterPoint()) == Rhino.Geometry.PointContainment.Outside)
                {
                    edges.Add(polyTemp);
                }
            }

            //create building mass
            Random      rand      = new Random(segs.Count);
            List <Brep> buildings = new List <Brep>();
            double      pil       = 3300;
            double      flr       = 2800;

            foreach (Polyline c in edges)
            {
                Curve   cTemp = c.ToNurbsCurve();
                Curve[] temp  = cTemp.Offset(Plane.WorldXY, -5000, 1, CurveOffsetCornerStyle.Sharp);
                if (temp != null && temp.Length != 0)
                {
                    cTemp = temp[0];
                    double  _scalefactor = 1.7 * scalefactor;
                    Curve[] temptemp     = cTemp.Offset(Plane.WorldXY, _scalefactor, 1, CurveOffsetCornerStyle.Sharp);



                    //try
                    //{
                    //    temptemp[0] = Rhino.RhinoDoc.ActiveDoc.Objects.ElementAt(0).Geometry as Curve;
                    //}
                    //catch (NullReferenceException e)
                    //{
                    //    Rhino.RhinoApp.WriteLine(e.Message);
                    //    return null;
                    //}



                    if (temptemp.Length != 0)
                    {
                        cTemp = temptemp[0];
                        if (cTemp.IsClosed == true)
                        {
                            buildings.Add(Surface.CreateExtrusion(cTemp, Vector3d.ZAxis * ((scalefactor / 1700) * pil + flr * rand.Next(3, 5))).ToBrep().CapPlanarHoles(1));
                        }
                    }
                }
            }



            Rhino.RhinoDoc.ActiveDoc.Layers.SetCurrentLayerIndex(Rhino.RhinoDoc.ActiveDoc.Layers.Find("Default", true), true);
            return(buildings);
        }
Esempio n. 15
0
        private IList <Rectangle3d> CheckFit(BoundingBox bx, Rectangle3d rect, Curve boundary, double offset, bool withRotation, List <Point3d> outPts, double searchSpacing, bool axisAligned, List <Vector3d> vs)
        {
            bool IsRotated = false;
            bool searching = true;

            double angle = 1.5708;

            List <double>       spacing = FindSpacing(rect, offset);
            IList <Rectangle3d> tRects  = new List <Rectangle3d>();

            double  dX   = searchSpacing;
            double  dY   = searchSpacing;
            double  xMin = bx.Min.X;
            double  yMin = bx.Min.Y;
            Point3d p    = new Point3d(xMin, yMin, 0.0);

            Vector3d translationVector = new Vector3d(rect.Plane.XAxis.X, rect.Plane.YAxis.Y, 1);

            translationVector.Unitize();

            for (double y = yMin; y < bx.Max.Y; y += dY)
            {
                for (double x = xMin; x < bx.Max.X; x += dX)
                {
                    Vector3d v  = new Vector3d(x, y, 0.0);
                    Vector3d pv = new Vector3d(p);

                    if (axisAligned)
                    {
                        pv = new Vector3d(translationVector.X * dX, translationVector.Y * dY, 1);
                    }
                    Vector3d toVector = Vector3d.Add(v, pv);
                    Point3d  pNew     = new Point3d(toVector);

                    p = pNew;

                    PointContainment pc = boundary.Contains(p, Plane.WorldXY, 0.1);

                    if (pc == PointContainment.Inside)
                    {
                        // Translate rect to new position
                        Rectangle3d tRect = TranslateRect(p, rect);

                        // Check containment of rect
                        bool IsContained = BoundaryContainsCurve(tRect.ToNurbsCurve(), boundary);

                        if (!IsContained && withRotation && !searching)
                        {
                            tRect.Transform(Transform.Rotation(angle, p));
                            IsContained = BoundaryContainsCurve(tRect.ToNurbsCurve(), boundary);
                            IsRotated   = true;
                        }

                        if (IsContained)
                        {
                            if (searching)
                            {
                                searching = false;
                                dX        = spacing[0];
                                dY        = spacing[1];
                                xMin      = (1 - bx.Min.X % p.X) * p.X;
                            }
                            outPts.Add(p);
                            vs.Add(pv);
                            tRects.Add(tRect);
                        }
                        if (IsRotated && withRotation)
                        {
                            // Update spacing
                            double t = dX;
                            dX        = dY;
                            dY        = t;
                            IsRotated = false;
                        }
                    }
                }
            }

            return(tRects);
        }
Esempio n. 16
0
        public List <Brep> KDGmaker(List <Curve> segs, Curve boundary)
        {
            //split surface
            List <Point3d> bboxPts = new List <Point3d>();

            foreach (Curve c in segs)
            {
                bboxPts.Add(c.PointAtStart);
                bboxPts.Add(c.PointAtEnd);
            }
            var          bbox = new BoundingBox(bboxPts);
            Rectangle3d  rect = new Rectangle3d(Plane.WorldXY, bbox.Min, bbox.Max);
            List <Curve> crvs = new List <Curve>();

            crvs.Add(rect.ToNurbsCurve());
            Brep        brep  = Brep.CreatePlanarBreps(rect.ToNurbsCurve())[0];
            var         temp1 = brep.Faces[0].Split(segs, 0.1).Faces;
            List <Brep> temp2 = new List <Brep>();

            foreach (BrepFace bf in temp1)
            {
                temp2.Add(bf.DuplicateFace(false));
            }

            //get edge polylines
            List <Polyline>    edges = new List <Polyline>();
            List <Rectangle3d> rects = new List <Rectangle3d>();

            foreach (Brep b in temp2)
            {
                Polyline polyTemp;
                Curve.JoinCurves(b.DuplicateEdgeCurves().ToList(), 1)[0].TryGetPolyline(out polyTemp);

                Rectangle3d rectTemp = outerRectFinder(polyTemp);

                double ratio = rectTemp.Height / rectTemp.Width;
                if (ratio < 1)
                {
                    ratio = 1 / ratio;
                }

                if (rectTemp.Area * 0.51 < getArea(polyTemp) && ratio < 1.5 && boundary.Contains(polyTemp.CenterPoint()) == Rhino.Geometry.PointContainment.Outside)
                {
                    edges.Add(polyTemp);
                    rects.Add(rectTemp);
                }
            }


            //create building mass
            List <Brep> buildings = new List <Brep>();

            foreach (Polyline c in edges)
            {
                Curve cTemp = c.ToNurbsCurve();
                cTemp.Transform(Transform.Translation(-new Vector3d(c.CenterPoint())));
                cTemp.Scale(0.8);
                cTemp.Transform(Transform.Translation(new Vector3d(c.CenterPoint())));
                buildings.Add(Surface.CreateExtrusion(cTemp, Vector3d.ZAxis * 20000).ToBrep().CapPlanarHoles(1));
            }
            Rhino.RhinoApp.WriteLine(" temp2 = " + temp2.Count + "edges = " + edges.Count + " buildings = " + buildings.Count);
            return(buildings);
        }
 internal void AddPreviewItem(string bitmap, Rectangle3d bounds)
 {
     AddPreviewItem(bitmap, bounds.ToNurbsCurve(), bounds);
 }
Esempio n. 18
0
        public override bool Construct(bool append = false)
        {
            debug = new List <object>();
            var cutterInterval = new Interval(-CutterSize, CutterSize);

            var beams = Parts.Select(x => (x.Element as BeamElement).Beam).ToArray();

            var kplane = beams[2].GetPlane(Parts[2].Parameter);

            debug.Add(kplane);

            var dirs   = new Vector3d[2];
            var planes = new Plane[2];

            for (int i = 0; i < 2; ++i)
            {
                var d0 = beams[i].Centreline.PointAt(beams[i].Centreline.Domain.Mid) - kplane.Origin;
                //debug.Add(new Line(kplane.Origin, d0));
                planes[i] = beams[i].GetPlane(Parts[i].Parameter);
                //debug.Add(planes[i]);
                int signX = 1, signY = 1, signZ = 1;

                if (planes[i].ZAxis * d0 < 0)
                {
                    signZ = -1;
                }
                if (planes[i].YAxis * kplane.YAxis < 0)
                {
                    signY = -1;
                }

                planes[i] = new Plane(planes[i].Origin, planes[i].XAxis * signX * signZ, planes[i].YAxis * signY);
                dirs[i]   = planes[i].ZAxis;
                debug.Add(planes[i]);
            }

            // dsum is actually the plate insertion direction
            var dsum = dirs[0] + dirs[1];

            dsum.Unitize();

            var xside = dsum * kplane.XAxis < 0 ? -1 : 1;

            // Check the order of the V-beams and flip if necessary.
            // This is important for getting correct Seam and Outside planes, among other things.
            if (((dirs[0] * kplane.ZAxis) < (dirs[1] * kplane.ZAxis) && xside > 0) ||
                ((dirs[0] * kplane.ZAxis) > (dirs[1] * kplane.ZAxis) && xside < 0))
            {
                var dirTemp = dirs[0];
                dirs[0] = dirs[1];
                dirs[1] = dirTemp;

                var planeTemp = planes[0];
                planes[0] = planes[1];
                planes[1] = planeTemp;

                var beamTemp = beams[0];
                beams[0] = beams[1];
                beams[1] = beamTemp;

                var partTemp = Parts[0];
                Parts[0] = Parts[1];
                Parts[1] = partTemp;
            }

            debug.Add(new Line(kplane.Origin, dsum * 200.0));
            //debug.Add(new Line(kplane.Origin, dirs[0] * 200.0));
            //debug.Add(new Line(kplane.Origin, dirs[1] * 200.0));

            // Find correct plane axis
            Vector3d xaxis;
            double   dotx = kplane.XAxis * dsum;
            double   doty = kplane.YAxis * dsum;
            double   width;

            if (Math.Abs(dotx) > Math.Abs(doty))
            {
                width = beams[2].Width;
                if (dotx < 0)
                {
                    xaxis = -kplane.XAxis;
                }
                else
                {
                    xaxis = kplane.XAxis;
                }
            }
            else
            {
                width = beams[2].Height;
                if (doty < 0)
                {
                    xaxis = -kplane.YAxis;
                }
                else
                {
                    xaxis = kplane.YAxis;
                }
            }

            var yaxis = kplane.YAxis;

            this.Plane = new Plane(kplane.Origin, xaxis, kplane.ZAxis);

            // plane0 is the plane on top of the sill beam, where the two V-beams meet
            var plane0 = new Plane(kplane.Origin + xaxis * width * 0.5, kplane.ZAxis, kplane.YAxis);
            // planeOffset0 is the safety plane for making cutters with a slight overlap
            var planeOffset0 = new Plane(plane0.Origin - plane0.ZAxis * 3.0, plane0.XAxis, plane0.YAxis);
            //debug.Add(plane0);
            // dowelPlane is the plane on which all the dowel points lie
            var dowelPlane = new Plane(plane0.Origin + xaxis * DowelPosition, plane0.XAxis, plane0.YAxis);

            //debug.Add(dowelPlane);

            // Create sill cutters
            for (int i = 0; i < 2; ++i)
            {
                Point3d xpt;
                var     res = Rhino.Geometry.Intersect.Intersection.CurvePlane(beams[i].Centreline, plane0, 0.01);
                if (res != null && res.Count > 0)
                {
                    xpt = res[0].PointA;
                }
                else
                {
                    xpt = plane0.ClosestPoint(planes[i].Origin);
                }

                var cutterPlane = new Plane(xpt, plane0.XAxis, plane0.YAxis);
                var cutterRec   = new Rectangle3d(cutterPlane, cutterInterval, cutterInterval);
                var cutterBrep  = Brep.CreatePlanarBreps(new Curve[] { cutterRec.ToNurbsCurve() }, 0.01)[0];

                Parts[i].Geometry.Add(cutterBrep);
            }

            // END sill cutters

            // Find the seam between the V-beams

            // Find all seam and outside planes, including offsets

            double PlaneOffset      = 5.0;
            var    seamPlanes       = new Plane[2];
            var    seamOffsetPlanes = new Plane[2];

            var endPlanes = new Plane[2];
            var endPts    = new Point3d[2];

            endPts[0] = planes[0].Origin;
            endPts[0].Transform(dowelPlane.ProjectAlongVector(planes[0].ZAxis));
            endPts[0] = endPts[0] + planes[0].ZAxis * 30.0;

            endPts[1] = planes[1].Origin;
            endPts[1].Transform(dowelPlane.ProjectAlongVector(planes[1].ZAxis));
            endPts[1] = endPts[1] + planes[1].ZAxis * 30.0;

            endPlanes[0] = new Plane(endPts[0], planes[0].XAxis, planes[0].YAxis);
            endPlanes[1] = new Plane(endPts[1], planes[1].XAxis, planes[1].YAxis);

            //debug.Add(endPlanes[0]);
            //debug.Add(endPlanes[1]);

            seamPlanes[0] = new Plane(planes[0].Origin + planes[0].XAxis * beams[0].Width * 0.5, planes[0].ZAxis, planes[0].YAxis);
            seamPlanes[1] = new Plane(planes[1].Origin - planes[1].XAxis * beams[1].Width * 0.5, planes[1].ZAxis, planes[1].YAxis);


            var outPlanes       = new Plane[2];
            var outOffsetPlanes = new Plane[2];

            outPlanes[0] = new Plane(planes[0].Origin - planes[0].XAxis * beams[0].Width * 0.5, planes[0].ZAxis, planes[0].YAxis);
            outPlanes[1] = new Plane(planes[1].Origin + planes[1].XAxis * beams[1].Width * 0.5, planes[1].ZAxis, planes[1].YAxis);

            int sign = -1;

            for (int i = 0; i < 2; ++i)
            {
                sign += i * 2;
                seamOffsetPlanes[i] = new Plane(seamPlanes[i].Origin + seamPlanes[i].ZAxis * sign * PlaneOffset, seamPlanes[i].XAxis, seamPlanes[i].YAxis);
                outOffsetPlanes[i]  = new Plane(outPlanes[i].Origin - outPlanes[i].ZAxis * sign * PlaneOffset, outPlanes[i].XAxis, outPlanes[i].YAxis);

                //debug.Add(seamPlanes[i]);
                //debug.Add(outPlanes[i]);
                //debug.Add(seamOffsetPlanes[i]);
                //debug.Add(outOffsetPlanes[i]);
            }

            Plane       seamPlane;
            Rectangle3d seamRec;
            Brep        seamBrep;

            // Pick method of intersecting the 2 arms beams
            switch (Mode)
            {
            case (-1):     // beam0 into the side of beam1
                seamRec  = new Rectangle3d(seamPlanes[1], cutterInterval, cutterInterval);
                seamBrep = Brep.CreatePlanarBreps(new Curve[] { seamRec.ToNurbsCurve() }, 0.01)[0];
                Parts[0].Geometry.Add(seamBrep);
                break;

            case (1):     // beam1 into the side of beam0
                seamRec  = new Rectangle3d(seamPlanes[0], cutterInterval, cutterInterval);
                seamBrep = Brep.CreatePlanarBreps(new Curve[] { seamRec.ToNurbsCurve() }, 0.01)[0];
                Parts[1].Geometry.Add(seamBrep);
                break;

            default:     // centre split
                Line seam;
                Rhino.Geometry.Intersect.Intersection.PlanePlane(seamPlanes[0], seamPlanes[1], out seam);

                seamPlane = new Plane(seam.From, seam.Direction, dsum);

                seamRec  = new Rectangle3d(seamPlane, cutterInterval, cutterInterval);
                seamBrep = Brep.CreatePlanarBreps(new Curve[] { seamRec.ToNurbsCurve() }, 0.01)[0];

                Parts[0].Geometry.Add(seamBrep);
                Parts[1].Geometry.Add(seamBrep);
                break;
            }

            // END seam

            // Find plate plane and figure out geometry
            var platePlane = new Plane(kplane.Origin, dsum, dirs[0]);

            platePlane.Origin = platePlane.Origin - platePlane.ZAxis * PlateThickness * 0.5;
            var sillproj = plane0.ProjectAlongVector(dsum);

            var pts = new Point3d[9];

            var proj0 = platePlane.ProjectAlongVector(planes[0].YAxis);
            var proj1 = platePlane.ProjectAlongVector(planes[1].YAxis);

            // Get first arm of plate
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(endPlanes[0], outOffsetPlanes[0], platePlane, out pts[0]);
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(endPlanes[0], seamOffsetPlanes[0], platePlane, out pts[1]);

            if (SingleInsertionDirection)
            {
                pts[1] = pts[0];
                pts[1].Transform(seamOffsetPlanes[0].ProjectAlongVector(dsum));
            }

            // Get point on seam
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(seamOffsetPlanes[0], seamOffsetPlanes[1], platePlane, out pts[2]);

            // Get second arm of plate
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(endPlanes[1], outOffsetPlanes[1], platePlane, out pts[3]);
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(endPlanes[1], seamOffsetPlanes[1], platePlane, out pts[4]);

            if (SingleInsertionDirection)
            {
                pts[4] = pts[3];
                pts[4].Transform(seamOffsetPlanes[1].ProjectAlongVector(dsum));
            }

            // Get intersection of first arm and sill
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(outOffsetPlanes[0], planeOffset0, platePlane, out pts[5]);
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(outOffsetPlanes[1], planeOffset0, platePlane, out pts[6]);

            for (int i = 0; i < 9; ++i)
            {
                debug.Add(pts[i]);
            }

            // Create outline for arms
            var plateOutline0 = new Polyline()
            {
                pts[0], pts[1], pts[2], pts[4], pts[3], pts[6], pts[5], pts[0]
            };

            //plateOutline0.
            debug.Add(plateOutline0);

            var plateSrf0 = Brep.CreateTrimmedPlane(platePlane, plateOutline0.ToNurbsCurve());

            Brep[] outBlends, outWalls;
            var    plateBreps = Brep.CreateOffsetBrep(plateSrf0, PlateThickness, true, true, 0.01, out outBlends, out outWalls);

            if (plateBreps != null && plateBreps.Length > 0)
            {
                if (plateBreps[0].SolidOrientation != BrepSolidOrientation.Outward)
                {
                    plateBreps[0].Flip();
                }

                for (int i = 0; i < 2; ++i)
                {
                    Parts[i].Geometry.Add(plateBreps[0]);
                }
            }

            //var plateBrep0 = Brep.CreateOffsetBrep(plateSrf0, PlateThickness, true, true, 0.01, out outBlends, out outWalls)[0];
            //plateBrep0.Flip();

            //for (int i = 0; i < 2; ++i)
            //{
            //  Parts[i].Geometry.Add(plateBrep0);
            //}

            // Create outline for sill
            planeOffset0.Origin = plane0.Origin + plane0.ZAxis * 5.0;
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(outPlanes[0], plane0, platePlane, out pts[0]);
            Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(outPlanes[1], plane0, platePlane, out pts[1]);

            pts[2] = pts[1] - dsum * PlateDepth;
            pts[3] = pts[0] - dsum * PlateDepth;

            pts[0] = pts[0] + dsum * 10.0;
            pts[1] = pts[1] + dsum * 10.0;

            var plateOutline1 = new Polyline()
            {
                pts[0], pts[1], pts[2], pts[3], pts[0]
            };

            debug.Add(plateOutline1);

            var plateSrf1 = Brep.CreateTrimmedPlane(platePlane, plateOutline1.ToNurbsCurve());

            plateBreps = Brep.CreateOffsetBrep(plateSrf1, PlateThickness, true, true, 0.01, out outBlends, out outWalls);
            if (plateBreps != null && plateBreps.Length > 0)
            {
                if (plateBreps[0].SolidOrientation != BrepSolidOrientation.Outward)
                {
                    plateBreps[0].Flip();
                }

                this.Beam.Geometry.Add(plateBreps[0]);
            }

            //var plateBrep1 = Brep.CreateOffsetBrep(plateSrf1, PlateThickness, true, true, 0.01, out outBlends, out outWalls)[0];
            //plateBrep1.Flip();

            //this.Beam.Geometry.Add(plateBrep1);

            // Create dowels
            var dowelPoints = new Point3d[3];

            var dproj0 = dowelPlane.ProjectAlongVector(planes[0].ZAxis);
            var dproj1 = dowelPlane.ProjectAlongVector(planes[1].ZAxis);

            dowelPoints[0] = planes[0].PointAt(0, 0, DowelPosition); dowelPoints[0].Transform(dproj0);
            dowelPoints[1] = planes[1].PointAt(0, 0, DowelPosition); dowelPoints[1].Transform(dproj1);
            dowelPoints[2] = kplane.Origin;

            var dowelPlane2 = new Plane(dowelPoints[2] - kplane.YAxis * DowelLength * 0.5, kplane.YAxis);
            var dowelCyl2   = new Cylinder(
                new Circle(dowelPlane2, DowelDiameter * 0.5), DowelLength).ToBrep(true, true);

            this.Beam.Geometry.Add(dowelCyl2);

            for (int i = 0; i < 2; ++i)
            {
                var dowelPlane01 = new Plane(dowelPoints[i] - planes[i].YAxis * DowelLength * 0.5, planes[i].YAxis);
                var dowelCyl     = new Cylinder(
                    new Circle(dowelPlane01, DowelDiameter * 0.5), DowelLength).ToBrep(true, true);

                Parts[i].Geometry.Add(dowelCyl);
            }

            // END plate

            return(true);
        }
Esempio n. 19
0
        private static bool CreateUnderGroundParking_Ramp(ref List <List <ParkingLine> > parkingLines, ref List <ParkingLineMaker.ParkingLotType> parkingLotTypes, ref Curve Ramp)
        {
            if (parkingLines.Count <= 0)
            {
                return(false);
            }

            List <int> parkingLineCount = (from i in parkingLines
                                           select i.Count()).ToList();
            List <int> parkingLineCountCopy = new List <int>(parkingLineCount);

            parkingLineCountCopy.Sort();

            int Index = parkingLineCount.IndexOf(parkingLineCountCopy.Max());

            int I = parkingLotTypes.Count();

            while (true)
            {
                if (parkingLotTypes[Index] == ParkingLineMaker.ParkingLotType.perpendicular)
                {
                    break;
                }

                Index = parkingLineCount.IndexOf(parkingLineCountCopy[(parkingLineCountCopy.IndexOf(parkingLineCount[Index]) - 1 + parkingLineCountCopy.Count()) % parkingLineCountCopy.Count()]);
            }

            if (parkingLines[Index].Count() >= 16)
            {
                List <ParkingLine> removedParkingLines = new List <ParkingLine>();

                for (int i = 0; i < 16; i++)
                {
                    removedParkingLines.Add(parkingLines[Index][parkingLines[Index].Count() - 1]);
                    parkingLines[Index].RemoveAt(parkingLines[Index].Count() - 1);
                }

                removedParkingLines.Reverse();

                List <Curve>   tempSegmentsOfStart = removedParkingLines[0].Boundary.ToNurbsCurve().DuplicateSegments().ToList();
                List <Point3d> tempPointsOfStart   = (from i in tempSegmentsOfStart
                                                      select i.PointAt(i.Domain.T0)).ToList();

                Point3d  tempOrigin  = tempPointsOfStart[0];
                Vector3d tempXVector = new Vector3d(tempPointsOfStart[1] - tempPointsOfStart[0]);
                Vector3d tempYVector = new Vector3d(tempPointsOfStart[3] - tempPointsOfStart[0]);
                tempXVector = tempXVector / tempXVector.Length;
                tempYVector = tempYVector / tempYVector.Length;

                tempOrigin = tempOrigin + tempXVector * (16 * 2300 - 20000 / 2);
                Rectangle3d tempRampRectangle = new Rectangle3d(new Plane(tempOrigin, tempXVector, tempYVector), 20000, 5000);

                Ramp = tempRampRectangle.ToNurbsCurve();

                return(true);
            }
            else
            {
                Ramp = (new Rectangle3d()).ToNurbsCurve();
                return(false);
            }
        }
Esempio n. 20
0
        private void createModel()
        {
            /*
             * Rhino.Geometry.Point3d origin = Util.openTkToRhinoPoint(Util.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(0, 0, 0)));
             * Rhino.Geometry.Point3d normalP1 = Util.openTkToRhinoPoint(Util.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(0, 0, -0.05f)));
             * Rhino.Geometry.Point3d normalP2 = Util.openTkToRhinoPoint(Util.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(0, 0, -1)));
             * Rhino.Geometry.Vector3d normal = new Rhino.Geometry.Vector3d(normalP2.X - normalP1.X, normalP2.Y - normalP1.Y, normalP2.Z - normalP1.Z);
             * Plane plane = new Plane(origin, normal);
             * float radius = 20;
             * Rhino.Geometry.Circle circle = new Rhino.Geometry.Circle(plane, origin, radius);
             * NurbsCurve circleCurve = circle.ToNurbsCurve();
             *
             * //compute transform to follow controllers
             * OpenTK.Matrix4 tansform = mScene.robotToPlatform * mScene.vrToRobot * Util.getControllerTipPosition(ref mScene, primaryControllerIdx == mScene.leftControllerIdx);
             * Transform t = Util.OpenTKToRhinoTransform(tansform);
             * circleCurve.Transform(t);
             * Brep[] shapes = Brep.CreatePlanarBreps(circleCurve);
             * Brep circle_s = shapes[0];
             * Brep circleBrep = circle_s;
             *
             * Guid renderObjId = Util.addSceneNode(ref mScene, circleBrep, ref mesh_m, "circle");
             */


            //offset the point a little bit to make the plane better
            OpenTK.Vector4 controller_p      = UtilOld.getControllerTipPosition(ref mScene, primaryControllerIdx == mScene.leftControllerIdx) * new OpenTK.Vector4(0, 0, -0.05f, 1);
            OpenTK.Vector4 controller_pZ     = UtilOld.getControllerTipPosition(ref mScene, primaryControllerIdx == mScene.leftControllerIdx) * new OpenTK.Vector4(0, 0, -1, 1);
            Point3d        controller_pRhino = UtilOld.openTkToRhinoPoint(UtilOld.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(controller_p.X, controller_p.Y, controller_p.Z)));
            Point3d        controller_pZRhin = UtilOld.openTkToRhinoPoint(UtilOld.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(controller_pZ.X, controller_pZ.Y, controller_pZ.Z)));


            //fix the x and y axis of the model Plane
            OpenTK.Vector4 controller_x1      = UtilOld.getControllerTipPosition(ref mScene, primaryControllerIdx == mScene.leftControllerIdx) * new OpenTK.Vector4(1, 0, 0, 1);
            OpenTK.Vector4 controller_y1      = UtilOld.getControllerTipPosition(ref mScene, primaryControllerIdx == mScene.leftControllerIdx) * new OpenTK.Vector4(0, 1, 0, 1);
            Point3d        controller_x1Rhino = UtilOld.openTkToRhinoPoint(UtilOld.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(controller_x1.X, controller_x1.Y, controller_x1.Z)));
            Point3d        controller_y1Rhino = UtilOld.openTkToRhinoPoint(UtilOld.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(controller_y1.X, controller_y1.Y, controller_y1.Z)));

            OpenTK.Vector4 controller_o      = UtilOld.getControllerTipPosition(ref mScene, primaryControllerIdx == mScene.leftControllerIdx) * new OpenTK.Vector4(0, 0, 0, 1);
            Point3d        controller_oRhino = UtilOld.openTkToRhinoPoint(UtilOld.vrToPlatformPoint(ref mScene, new OpenTK.Vector3(controller_o.X, controller_o.Y, controller_o.Z)));

            Rhino.Geometry.Vector3d normal = new Rhino.Geometry.Vector3d(controller_pZRhin.X - controller_oRhino.X, controller_pZRhin.Y - controller_oRhino.Y, controller_pZRhin.Z - controller_oRhino.Z);
            normal.Unitize();
            modelPlane = new Plane(controller_oRhino, normal);

            if (shapeType == ShapeType.Circle)
            {
                Rhino.Geometry.Circle circle = new Rhino.Geometry.Circle(modelPlane, controller_oRhino, radius);
                modelcurve = circle.ToNurbsCurve();
            }
            else if (shapeType == ShapeType.Rect)
            {
                Rhino.Geometry.Vector3d xAxis = new Rhino.Geometry.Vector3d(controller_x1Rhino.X - controller_oRhino.X, controller_x1Rhino.Y - controller_oRhino.Y, controller_x1Rhino.Z - controller_oRhino.Z);
                xAxis.Unitize();
                Rhino.Geometry.Vector3d yAxis = new Rhino.Geometry.Vector3d(controller_y1Rhino.X - controller_oRhino.X, controller_y1Rhino.Y - controller_oRhino.Y, controller_y1Rhino.Z - controller_oRhino.Z);
                yAxis.Unitize();

                modelPlane.XAxis = xAxis;
                modelPlane.YAxis = yAxis;

                //Rectangle3d rect = new Rectangle3d(modelPlane, width, height);
                Rectangle3d rect = new Rectangle3d(modelPlane, new Interval(-width / 2, width / 2), new Interval(-height / 2, height / 2));
                modelcurve = rect.ToNurbsCurve();
            }

            if (modelcurve != null)
            {
                Brep[] shapes = Brep.CreatePlanarBreps(modelcurve);
                modelBrep = shapes[0];
                UtilOld.updateSceneNode(ref mScene, modelBrep, ref mesh_m, "3D-" + shapeType.ToString(), ref previewObjSN);
            }
        }
Esempio n. 21
0
        // use
        public List <Brep> KDGmaker(List <Curve> segs, Curve boundary, List <Point3d> roadPoints, Brep ground)
        {
            double depth = 3000;

            var groundMesh = Mesh.CreateFromBrep(ground);


            //long mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("init : {0}", mem1);
            //split surface
            List <Point3d> bboxPts = new List <Point3d>();

            foreach (Curve c in segs)
            {
                bboxPts.Add(c.PointAtStart);
                bboxPts.Add(c.PointAtEnd);
            }
            var          bbox = new BoundingBox(bboxPts);
            Rectangle3d  rect = new Rectangle3d(Plane.WorldXY, bbox.Min, bbox.Max);
            List <Curve> crvs = new List <Curve>();

            crvs.Add(rect.ToNurbsCurve());

            Brep brep = Brep.CreatePlanarBreps(rect.ToNurbsCurve())[0];


            // mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("BeforeSplit : {0}", mem1);


            var temp1 = brep.Faces[0].Split(segs, 0.1).Faces;
            //mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("AfterSplit : {0}", mem1);
            List <Brep> temp2 = new List <Brep>();

            foreach (BrepFace bf in temp1)
            {
                temp2.Add(bf.DuplicateFace(false));
            }


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

            //get edge polylines
            List <Polyline>    edges     = new List <Polyline>();
            List <Polyline>    edgesRoad = new List <Polyline>();
            List <Polyline>    edgesPlot = new List <Polyline>();
            List <Rectangle3d> rects     = new List <Rectangle3d>();

            //mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("BeforeD : {0}", mem1);
            foreach (Brep b in temp2)
            {
                Polyline polyTemp;
                Curve.JoinCurves(b.DuplicateEdgeCurves().ToList(), 1)[0].TryGetPolyline(out polyTemp);

                bool isRoad = false;
                for (int i = 0; i < roadPoints.Count; i++)
                {
                    if (polyTemp.ToNurbsCurve().Contains(roadPoints[i]) != Rhino.Geometry.PointContainment.Outside)
                    {
                        isRoad = true;
                        break;
                    }
                }

                if (!isRoad && boundary.Contains(polyTemp.CenterPoint()) == Rhino.Geometry.PointContainment.Outside)
                {
                    edges.Add(polyTemp);
                }
                else if (isRoad)
                {
                    edgesRoad.Add(polyTemp);
                }
                else
                {
                    edgesPlot.Add(polyTemp);
                }
            }
            // mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("AfterD : {0}", mem1);


            //create plot ground
            List <double> groundHeight = new List <double>();
            List <Brep>   grounds      = new List <Brep>();

            foreach (Polyline c in edgesPlot)
            {
                List <Point3d> ptl = new List <Point3d>();
                List <Brep>    bl  = new List <Brep>();
                ptl.Add(c.CenterPoint());
                bl.Add(ground);

                //LoadManager.getInstance().DrawObjectWithSpecificLayer(bl, LoadManager.NamedLayer.Guide);
                //Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Redraw();

                Point3d projectedPoint = Rhino.Geometry.Intersect.Intersection.ProjectPointsToMeshes(groundMesh, ptl, Vector3d.ZAxis, 0)[0];
                groundHeight.Add(projectedPoint.Z);

                //Brep groundPiece = Brep.CreatePlanarBreps(c.ToNurbsCurve())[0];
                Brep groundPiece = Surface.CreateExtrusion(c.ToNurbsCurve(), Vector3d.ZAxis * (-depth)).ToBrep().CapPlanarHoles(1);
                grounds.Add(groundPiece);
            }
            double averageHeight = groundHeight.Sum() / groundHeight.Count;

            //create building mass and ground
            Random      rand      = new Random(segs.Count);
            List <Brep> buildings = new List <Brep>();

            double pil = Consts.PilotiHeight;
            double flr = Consts.FloorHeight;



            //mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("BeforeEdge : {0}", mem1);
            foreach (Polyline c in edges)
            {
                if (getArea(c) > 1)
                {
                    List <Point3d> ptl = new List <Point3d>();
                    List <Brep>    bl  = new List <Brep>();
                    ptl.Add(c.CenterPoint());
                    bl.Add(ground);
                    Point3d projectedPoint;

                    //LoadManager.getInstance().DrawObjectWithSpecificLayer(bl, LoadManager.NamedLayer.Guide);
                    //Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Redraw();

                    //dtsasdfasdf

                    projectedPoint = Rhino.Geometry.Intersect.Intersection.ProjectPointsToMeshes(groundMesh, ptl, Vector3d.ZAxis, 0)[0];

                    //~dtsasdfasdf
                    //Brep groundPiece = Brep.CreatePlanarBreps(c.ToNurbsCurve())[0];
                    Brep groundPiece = Surface.CreateExtrusion(c.ToNurbsCurve(), Vector3d.ZAxis * (-depth)).ToBrep().CapPlanarHoles(1);
                    if (groundPiece == null)
                    {
                        continue;
                    }
                    groundPiece.Translate(Vector3d.ZAxis * (projectedPoint.Z - averageHeight));
                    grounds.Add(groundPiece);

                    Curve   cTemp = c.ToNurbsCurve();
                    Curve[] temp  = cTemp.Offset(Plane.WorldXY, -3002, 1, CurveOffsetCornerStyle.Sharp);
                    if (temp != null && temp.Length != 0)
                    {
                        cTemp = temp[0];
                        Curve[] temptemp = cTemp.Offset(Plane.WorldXY, 2, 1, CurveOffsetCornerStyle.Sharp);
                        if (temptemp.Length != 0)
                        {
                            cTemp = temptemp[0];
                            Polyline pTemp;
                            cTemp.TryGetPolyline(out pTemp);

                            if (getArea(pTemp) < getArea(c) * 0.6)
                            {
                                Curve[] temptemptemp = cTemp.Offset(Plane.WorldXY, 1000, 1, CurveOffsetCornerStyle.Sharp);
                                if (temptemptemp != null)
                                {
                                    cTemp = temptemptemp[0];
                                }
                            }
                            if (cTemp.IsClosed == true && cTemp.GetBoundingBox(false).Diagonal.Length < bbox.Diagonal.Length)
                            {
                                Brep tempBrep = Surface.CreateExtrusion(cTemp, Vector3d.ZAxis * (pil + flr * rand.Next(3, 5))).ToBrep().CapPlanarHoles(1);
                                tempBrep.Translate(Vector3d.ZAxis * (projectedPoint.Z - averageHeight));
                                buildings.Add(tempBrep);
                            }
                        }
                    }
                }
            }

            //mem1 = GC.GetTotalMemory(false);
            // Rhino.RhinoApp.WriteLine("AfterEdge : {0}", mem1);

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

            //mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("BeforeRoadEdge : {0}", mem1);

            foreach (Polyline c in edgesRoad)
            {
                Curve        road1 = Curve.ProjectToMesh(c.ToNurbsCurve(), groundMesh, Vector3d.ZAxis, 0.01)[0];
                List <Curve> roadl = new List <Curve>();
                roadl.Add(road1);

                //LoadManager.getInstance().DrawObjectWithSpecificLayer(ground, LoadManager.NamedLayer.Model);

                //Curve road2 = Curve.ProjectToMesh(c.ToNurbsCurve(), Mesh.CreateFromBrep(ground)[0], Vector3d.ZAxis, 0)[0];
                road1.Translate(Vector3d.ZAxis * (-averageHeight));
                Brep groundPiece = Surface.CreateExtrusion(road1.ToNurbsCurve(), Vector3d.ZAxis * (-depth)).ToBrep().CapPlanarHoles(1);
                Guid guid        = LoadManager.getInstance().DrawObjectWithSpecificLayer(road1, LoadManager.NamedLayer.ETC);

                //Rhino.RhinoDoc.ActiveDoc.Objects.Select(guid,true,true);
                //Rhino.RhinoApp.RunScript("_-Patch '_Enter", true);

                //Rhino.RhinoDoc.ActiveDoc.Objects.Delete(guid, true);

                //LoadManager.getInstance().DrawObjectWithSpecificLayer(temp, LoadManager.NamedLayer.Guide);
                grounds.Add(groundPiece);

                projectedRoads.Add(road1);
            }

            //mem1 = GC.GetTotalMemory(false);
            //Rhino.RhinoApp.WriteLine("AfterRoadEdge : {0}", mem1);


            List <Mesh> projectedRoadMesh = GetRoadPatch(projectedRoads, groundMesh[0]);

            for (int i = 0; i < projectedRoadMesh.Count; i++)
            {
                if (projectedRoadMesh[i] != null)
                {
                    LoadManager.getInstance().DrawObjectWithSpecificLayer(projectedRoadMesh[i], LoadManager.NamedLayer.ETC);
                }
            }


            Point3d test = new Point3d(1, 1, 1);



            //test
            buildings.AddRange(grounds);

            return(buildings);
        }
Esempio n. 22
0
        public List <GeometryBase> Draw(Plane plane, Vector3d vec)
        {
            List <GeometryBase> list = new List <GeometryBase>();
            Rectangle3d         rec  = new Rectangle3d(
                plane,
                ZERO_DEGREE.GetLength(),
                ZERO_DEGREE.GetWidth());
            Vector3d move = new Vector3d(rec.Center.X - plane.Origin.X, rec.Center.Y - plane.Origin.Y, rec.Center.Z - plane.Origin.Z);

            move.Reverse();
            rec.Transform(Transform.Translation(move));
            if (!isDoubleRow)
            {
                list.Add(rec.ToNurbsCurve());
            }
            else
            {
                // 分裂
                NurbsCurve stallUp   = rec.ToNurbsCurve();
                NurbsCurve stallDown = rec.ToNurbsCurve();
                Vector3d   vecUp     = new Vector3d(vec);

                // 平面几何余弦定理
                Vector3d a = new Vector3d(rec.Corner(3) - rec.Corner(0));
                Vector3d b = new Vector3d((rec.Corner(2) - rec.Corner(3)));

                if (degree == Math.PI / 2)
                {
                    vecUp = b / 2;
                }
                else if (degree == 0)
                {
                    vecUp = a / 2;
                }
                else
                {
                    b.Unitize();
                    b     = b * (length - width / Math.Tan(degree)); // () is the b length
                    vecUp = new Vector3d(a + b) / 2;
                }
                Vector3d vecDown;

                /*
                 * // dist
                 * double dist;
                 * if (degree == 0)
                 * {
                 *  dist = width / 2;
                 * } else if (degree == Math.PI / 2)
                 * {
                 *  dist = length / 2;
                 * } else
                 * {
                 *  dist = length * Math.Sin(degree) / 2;
                 * }
                 */
                // vecUp.Unitize();
                // vecUp = new Vector3d(vecUp.X * dist, vecUp.Y*dist, vecUp.Z*dist);
                stallUp.Transform(Transform.Translation(vecUp));
                list.Add(stallUp);

                vecDown = new Vector3d(vecUp);
                vecDown.Reverse();
                stallDown.Transform(Transform.Translation(vecDown));
                list.Add(stallDown);
            }
            return(list);
        }
Esempio n. 23
0
        protected override void onClickOculusTrigger(ref VREvent_t vrEvent)
        {
            primaryDeviceIndex = vrEvent.trackedDeviceIndex;
            if (currentState != State.READY || targetPRhObjID == Guid.Empty)
            {
                return;
            }

            pointOnObjRef = new ObjRef(targetPRhObjID);
            //chage to only raycasting to the obj where we draw, if not snap to the origin
            if (!(projectP.X == 0 && projectP.Y == 0 && projectP.Z == 0))
            {
                rayCastingObjs.Clear();
                rayCastingObjs.Add(pointOnObjRef);
            }

            //testing
            Vector3 projectPVR = UtilOld.platformToVRPoint(ref mScene, UtilOld.RhinoToOpenTKPoint(projectP));

            mScene.iPointList.Add(UtilOld.platformToVRPoint(ref mScene, projectPVR)); //not use at the current version, point is VR coordinate
            pointsList.Add(projectP);

            //render edit points in VR
            Geometry.Geometry geo = new Geometry.DrawPointMarker(new Vector3(0, 0, 0));
            Material.Material m   = new Material.SingleColorMaterial(0, 1, 0, 1);
            SceneNode         editPointSN;

            UtilOld.MarkPointVR(ref mScene, projectPVR, ref geo, ref m, out editPointSN);
            pointMarkers.Add(editPointSN);

            //TODO-hide two other design plane
            if (pointMarkers.Count == 1)
            {
                if (pointOnObjRef != null && drawnType == DrawnType.Plane)
                {
                    if (!(projectP.X == 0 && projectP.Y == 0 && projectP.Z == 0))
                    {
                        UtilOld.hideOtherPlanes(ref mScene, pointOnObjRef.Object().Attributes.Name);
                    }
                    computeContourCurve();
                }
                //TODO- how to find the curvePlane on the surface like teapot body, using the normal of first point?
                //do we need to use different ways for patch surface and other generated surface
                else if (pointOnObjRef != null && drawnType == DrawnType.Surface)
                {
                    computeContourCurve();
                }
            }

            if (maxNumPoint == pointMarkers.Count)
            {
                //Assume we always can find a curvePlane sicnce we use a huge tolerance
                NurbsCurve modelcurve = null;
                Brep       modelBrep;
                string     modelName = "";
                if (shapeType == ShapeType.Circle)
                {
                    float  radius = (float)Math.Sqrt(Math.Pow(pointsList[1].X - pointsList[0].X, 2) + Math.Pow(pointsList[1].Y - pointsList[0].Y, 2) + Math.Pow(pointsList[1].Z - pointsList[0].Z, 2));
                    Circle circle = new Rhino.Geometry.Circle(curvePlane, pointsList[0], radius);
                    modelcurve = circle.ToNurbsCurve();
                    modelName  = "Circle";
                }
                else if (shapeType == ShapeType.Rect)
                {
                    Vector3 rectDiagonalV = new Vector3((float)(pointsList[0].X - pointsList[1].X), (float)(pointsList[0].Y - pointsList[1].Y), (float)(pointsList[0].Z - pointsList[1].Z));
                    float   lenDiagonal   = rectDiagonalV.Length;
                    Vector3 rectLeftTop   = new Vector3((float)pointsList[0].X, (float)pointsList[0].Y, (float)pointsList[0].Z) + lenDiagonal * rectDiagonalV.Normalized();
                    Point3d topLeftP      = new Point3d(rectLeftTop.X, rectLeftTop.Y, rectLeftTop.Z);

                    Rectangle3d rect = new Rectangle3d(curvePlane, topLeftP, pointsList[1]);

                    //using top-left cornel and bottom right

                    //Rectangle3d rect = new Rectangle3d(curvePlane, pointsList[0], pointsList[1]);

                    modelcurve = rect.ToNurbsCurve();
                    modelName  = "Rect";
                }

                /*
                 * Brep[] shapes = Brep.CreatePlanarBreps(modelcurve);
                 * modelBrep = shapes[0];
                 * Guid guid = Util.addRhinoObjectSceneNode(ref mScene, ref modelBrep, ref profile_m, modelName, out renderObjSN);
                 */

                //generate new curveOnObj for mvoingPlane cases sicne and move the XYZPlanes to origial positons
                if (drawnType == DrawnType.Plane)
                {
                    Rhino.Geometry.Vector3d newNormal = new Rhino.Geometry.Vector3d();;
                    Point3d newOrigin   = new Point3d();
                    String  planeName   = pointOnObjRef.Object().Attributes.Name;
                    Point3d planeOrigin = pointOnObjRef.Object().Geometry.GetBoundingBox(true).Center;
                    if (planeName.Contains("planeXY"))
                    {
                        newNormal = new Rhino.Geometry.Vector3d(0, 0, 1);
                        newOrigin = new Point3d(0, 0, planeOrigin.Z);
                    }
                    else if (planeName.Contains("planeYZ"))
                    {
                        newNormal = new Rhino.Geometry.Vector3d(1, 0, 0);
                        newOrigin = new Point3d(planeOrigin.X, 0, 0);
                    }
                    else if (planeName.Contains("planeXZ"))
                    {
                        newNormal = new Rhino.Geometry.Vector3d(0, 1, 0);
                        newOrigin = new Point3d(0, planeOrigin.Y, 0);
                    }

                    Plane        newPlane      = new Plane(newOrigin, newNormal);
                    int          size          = 240;
                    PlaneSurface plane_surface = new PlaneSurface(newPlane, new Interval(-size, size), new Interval(-size, size));
                    Brep         newPlaneBrep  = Brep.CreateFromSurface(plane_surface);

                    Guid newPlaneID = UtilOld.addRhinoObject(ref mScene, ref newPlaneBrep, "MoveP");
                    //might be better to use Replace(), just need to be careful about the referece count
                    pointOnObjRef = null;
                    pointOnObjRef = new ObjRef(newPlaneID);

                    modelcurve.SetUserString(CurveData.CurveOnObj.ToString(), newPlaneID.ToString());
                    modelcurve.SetUserString(CurveData.PlaneOrigin.ToString(), newPlane.Origin.ToString());
                    modelcurve.SetUserString(CurveData.PlaneNormal.ToString(), newPlane.Normal.ToString());
                }
                else if (drawnType == DrawnType.Surface)
                {
                    modelcurve.SetUserString(CurveData.CurveOnObj.ToString(), pointOnObjRef.ObjectId.ToString());
                    modelcurve.SetUserString(CurveData.PlaneOrigin.ToString(), curvePlane.Origin.ToString());
                    modelcurve.SetUserString(CurveData.PlaneNormal.ToString(), curvePlane.Normal.ToString());
                }

                mScene.iCurveList.Add(modelcurve);

                //call next interaction in the chain
                afterCurveCount = mScene.iCurveList.Count;
                mScene.pushInteractionFromChain();
                currentState = State.READY;
            }
        }
Esempio n. 24
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string shpFileLoc = "";

            DA.GetData <string>("Vector Data Location", ref shpFileLoc);

            ///GDAL setup
            ///Some preliminary testing has been done to read SHP, GeoJSON, OSM, KML, MVT, GML and GDB
            ///It can be spotty with KML, MVT and GML and doesn't throw informative errors.  Likely has to do with getting a valid CRS and
            ///TODO: resolve errors with reading KML, MVT, GML.

            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     drv = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");
            OSGeo.OGR.DataSource ds  = OSGeo.OGR.Ogr.Open(shpFileLoc, 0);

            if (ds == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }

            List <OSGeo.OGR.Layer> layerset = new List <OSGeo.OGR.Layer>();
            List <int>             fc       = new List <int>();

            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }
                else
                {
                    layerset.Add(layer);
                }
            }

            ///Declare trees
            GH_Structure <GH_String>    layname = new GH_Structure <GH_String>();
            GH_Structure <GH_Integer>   fcs     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Rectangle> recs    = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    sRefs   = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fnames  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fset    = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>     gset    = new GH_Structure <GH_Point>();


            ///Loop through each layer. Layers usually occur in Geodatabase GDB format. SHP usually has only one layer.
            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }

                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);
                fcs.Append(new GH_Integer(featureCount), new GH_Path(iLayer));

                layname.Append(new GH_String(layer.GetName()), new GH_Path(iLayer));


                ///Get OGR envelope of the data in the layer
                OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
                layer.GetExtent(ext, 1);
                Point3d extMin = new Point3d();
                Point3d extMax = new Point3d();
                extMin.X = ext.MinX;
                extMin.Y = ext.MinY;
                extMax.X = ext.MaxX;
                extMax.Y = ext.MaxY;


                ///Get the spatial reference of the input vector file and set to WGS84 if not known
                OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);
                string sRef = "";

                if (layer.GetSpatialRef() == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.");
                    sr.ImportFromXML(shpFileLoc);
                    string pretty = "";
                    sr.ExportToPrettyWkt(out pretty, 0);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, pretty);
                    sr.SetWellKnownGeogCS("WGS84");
                    sRef = "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.";
                    //sr.ImportFromEPSG(2263);
                }
                else
                {
                    if (layer.GetSpatialRef().Validate() != 0)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is unknown or unsupported.  CRS set automatically set to WGS84.");
                        sr.SetWellKnownGeogCS("WGS84");
                        sRef = "Coordinate Reference System (CRS) is unknown or unsupported.  SRS set automatically set to WGS84.";
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) set from layer" + iLayer + ".");
                        sr = layer.GetSpatialRef();
                        sr.ExportToWkt(out sRef);
                    }
                }

                sRefs.Append(new GH_String(sRef), new GH_Path(iLayer));


                ///Set transform from input spatial reference to Rhino spatial reference
                ///TODO: look into adding a step for transforming to CRS set in SetCRS
                OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
                dst.SetWellKnownGeogCS("WGS84");
                OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
                OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);


                ///Get bounding box of data in layer
                double[] extMinPT = new double[3] {
                    extMin.X, extMin.Y, extMin.Z
                };
                double[] extMaxPT = new double[3] {
                    extMax.X, extMax.Y, extMax.Z
                };
                coordTransform.TransformPoint(extMinPT);
                coordTransform.TransformPoint(extMaxPT);
                Point3d     extPTmin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
                Point3d     extPTmax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);
                Rectangle3d rec      = new Rectangle3d(Plane.WorldXY, Heron.Convert.ToXYZ(extPTmin), Heron.Convert.ToXYZ(extPTmax));
                recs.Append(new GH_Rectangle(rec), new GH_Path(iLayer));


                ///Loop through input boundaries
                for (int i = 0; i < boundary.Count; i++)
                {
                    OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn();

                    ///Get the field names
                    List <string> fieldnames = new List <string>();
                    for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                    {
                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                        fnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(i, iLayer));
                    }

                    ///Check if boundary is contained in extent
                    if (!rec.IsValid || ((rec.Height == 0) && (rec.Width == 0)))
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more vector datasource bounds are not valid.");
                        OSGeo.OGR.Feature feat;
                        int m = 0;

                        while ((feat = layer.GetNextFeature()) != null)
                        {
                            ///Loop through field values
                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                fdef.Dispose();
                            }
                            m++;
                            feat.Dispose();
                        }
                    }

                    else if (boundary[i] == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " not set.");
                    }

                    else if (!boundary[i].IsValid)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + "  is not valid.");
                    }

                    else if (rec.IsValid && Curve.PlanarClosedCurveRelationship(rec.ToNurbsCurve(), boundary[i], Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance) == RegionContainment.Disjoint)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the vector datasource.");
                    }

                    else
                    {
                        ///Create bounding box for clipping geometry
                        Point3d  min   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Min);
                        Point3d  max   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Max);
                        double[] minpT = new double[3];
                        double[] maxpT = new double[3];

                        minpT[0] = min.X;
                        minpT[1] = min.Y;
                        minpT[2] = min.Z;
                        maxpT[0] = max.X;
                        maxpT[1] = max.Y;
                        maxpT[2] = max.Z;
                        revTransform.TransformPoint(minpT);
                        revTransform.TransformPoint(maxpT);

                        ///Convert to OGR geometry
                        ///TODO: add conversion from GH geometry to OGR to Convert class
                        OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                        ///Clip Shapefile
                        ///http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                        ///TODO: allow for polyline/curve as clipper, not just bounding box
                        OSGeo.OGR.Layer clipped_layer = layer;
                        clipped_layer.SetSpatialFilter(ebbox);

                        ///Loop through geometry
                        OSGeo.OGR.Feature feat;
                        def = clipped_layer.GetLayerDefn();

                        int m = 0;
                        while ((feat = clipped_layer.GetNextFeature()) != null)
                        {
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            ///reproject geometry to WGS84
                            ///TODO: look into using the SetCRS global variable here
                            geom.Transform(coordTransform);

                            if (feat.GetGeometryRef() != null)
                            {
                                ///Start get points if open polylines and points
                                for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                                {
                                    ///Loop through geometry points
                                    double[] pT = new double[3];
                                    pT[0] = geom.GetX(gpc);
                                    pT[1] = geom.GetY(gpc);
                                    pT[2] = geom.GetZ(gpc);
                                    if (Double.IsNaN(geom.GetZ(gpc)))
                                    {
                                        pT[2] = 0;
                                    }
                                    //coordTransform.TransformPoint(pT);

                                    Point3d pt3D = new Point3d();
                                    pt3D.X = pT[0];
                                    pt3D.Y = pT[1];
                                    pt3D.Z = pT[2];

                                    gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, iLayer, m));
                                    ///End loop through geometry points

                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                ///End getting points if open polylines or points



                                ///Start getting points if closed polylines and multipolygons
                                for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                                {
                                    sub_geom = geom.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geom;
                                    List <Point3d>     geom_list = new List <Point3d>();

                                    ///trouble getting all points.  this is a troubleshoot
                                    ///gset.Append(new GH_Point(new Point3d(0, 0, sub_geom.GetGeometryCount())), new GH_Path(i, iLayer, m, gi));

                                    if (sub_geom.GetGeometryCount() > 0)
                                    {
                                        for (int n = 0; n < sub_geom.GetGeometryCount(); n++)
                                        {
                                            subsub_geom = sub_geom.GetGeometryRef(n);
                                            for (int ptnum = 0; ptnum < subsub_geom.GetPointCount(); ptnum++)
                                            {
                                                ///Loop through geometry points
                                                double[] pT = new double[3];
                                                pT[0] = subsub_geom.GetX(ptnum);
                                                pT[1] = subsub_geom.GetY(ptnum);
                                                pT[2] = subsub_geom.GetZ(ptnum);

                                                Point3d pt3D = new Point3d();
                                                pt3D.X = pT[0];
                                                pt3D.Y = pT[1];
                                                pt3D.Z = pT[2];

                                                gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi, n));
                                                ///End loop through geometry points
                                            }
                                            subsub_geom.Dispose();
                                        }
                                    }

                                    else
                                    {
                                        for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                                        {
                                            ///Loop through geometry points
                                            double[] pT = new double[3];
                                            pT[0] = sub_geom.GetX(ptnum);
                                            pT[1] = sub_geom.GetY(ptnum);
                                            pT[2] = sub_geom.GetZ(ptnum);

                                            Point3d pt3D = new Point3d();
                                            pt3D.X = pT[0];
                                            pt3D.Y = pT[1];
                                            pt3D.Z = pT[2];

                                            gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi));
                                            ///End loop through geometry points
                                        }
                                    }

                                    sub_geom.Dispose();

                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                //m++;
                            }
                            m++;
                            feat.Dispose();
                        } ///end while loop through features
                    }
                }         //end loop through boundaries

                layer.Dispose();
            }///end loop through layers

            ds.Dispose();

            DA.SetDataTree(0, layname);
            DA.SetDataTree(1, fcs);
            DA.SetDataTree(2, recs);
            DA.SetDataTree(3, sRefs);
            DA.SetDataTree(4, fnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);
        }
Esempio n. 25
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string IMG_file = string.Empty;

            DA.GetData <string>(1, ref IMG_file);

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            Dataset datasource = Gdal.Open(IMG_file, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();


            if (datasource == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }

            ///Get info about image
            string        srcInfo     = string.Empty;
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);
            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }

                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");
            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            Rectangle3d dsbox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));

            double pixelWidth  = dsbox.Width / width;
            double pixelHeight = dsbox.Height / height;

            ///Declare trees
            GH_Structure <GH_Point>   pointcloud = new GH_Structure <GH_Point>();
            GH_Structure <GH_Integer> rCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Integer> cCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Mesh>    tMesh      = new GH_Structure <GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                Curve clippingBoundary = boundary[i];

                if (!clip)
                {
                    clippingBoundary = dsbox.ToNurbsCurve();
                }

                string clippedTopoFile = "/vsimem/topoclipped.tif";

                if (!(dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Min) && (dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Max))) && clip)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the topo dataset.");
                }

                ///Offsets to mesh/boundary based on pixel size
                Point3d clipperMinPreAdd  = clippingBoundary.GetBoundingBox(true).Corner(true, false, true);
                Point3d clipperMinPostAdd = new Point3d(clipperMinPreAdd.X, clipperMinPreAdd.Y, clipperMinPreAdd.Z);
                Point3d clipperMin        = Heron.Convert.XYZToWGS(clipperMinPostAdd);

                Point3d clipperMaxPreAdd = clippingBoundary.GetBoundingBox(true).Corner(false, true, true);
                ///add/subtract pixel width if desired to get closer to boundary
                Point3d clipperMaxPostAdd = new Point3d();
                Point3d clipperMax        = new Point3d();
                if (clip)
                {
                    clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X + pixelWidth, clipperMaxPreAdd.Y - pixelHeight, clipperMaxPreAdd.Z);
                    clipperMax        = Heron.Convert.XYZToWGS(clipperMaxPostAdd);
                }
                else
                {
                    clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X, clipperMaxPreAdd.Y, clipperMaxPreAdd.Z);
                    clipperMax        = Heron.Convert.XYZToWGS(clipperMaxPostAdd);
                }


                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    "-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedTopoFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Band band = clippedDataset.GetRasterBand(1);
                    width  = clippedDataset.RasterXSize;
                    height = clippedDataset.RasterYSize;
                    clippedDataset.GetGeoTransform(adfGeoTransform);
                    Gdal.InvGeoTransform(adfGeoTransform, invTransform);

                    rCount.Append(new GH_Integer(height), path);
                    cCount.Append(new GH_Integer(width), path);
                    Mesh           mesh  = new Mesh();
                    List <Point3d> verts = new List <Point3d>();
                    //var vertsParallel = new System.Collections.Concurrent.ConcurrentDictionary<double[][], Point3d>(Environment.ProcessorCount, ((Urow - 1) * (Lrow - 1)));

                    double[] bits = new double[width * height];
                    band.ReadRaster(0, 0, width, height, bits, width, height, 0, 0);

                    for (int col = 0; col < width; col++)
                    {
                        for (int row = 0; row < height; row++)
                        {
                            // equivalent to bits[col][row] if bits is 2-dimension array
                            double pixel = bits[col + row * width];
                            if (pixel < -10000)
                            {
                                pixel = 0;
                            }

                            double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * row;
                            double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * row;

                            ///convert to WGS84
                            double[] wgsPT = new double[3] {
                                gcol, grow, pixel
                            };
                            coordTransform.TransformPoint(wgsPT);
                            Point3d pt = new Point3d(wgsPT[0], wgsPT[1], wgsPT[2]);

                            verts.Add(Heron.Convert.WGSToXYZ(pt));
                        }

                        /*Parallel.For(Urow, Lrow - 1, rowP =>
                         *  {
                         *      // equivalent to bits[col][row] if bits is 2-dimension array
                         *      double pixel = bits[col + rowP * width];
                         *      if (pixel < -10000)
                         *      {
                         *          pixel = 0;
                         *      }
                         *
                         *      double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * rowP;
                         *      double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * rowP;
                         *
                         *      Point3d pt = new Point3d(gcol, grow, pixel);
                         *      vertsParallel[] = Heron.Convert.ToXYZ(pt);
                         *  });
                         * */
                    }

                    //Create meshes
                    //non Parallel
                    mesh.Vertices.AddVertices(verts);
                    //Parallel
                    //mesh.Vertices.AddVertices(vertsParallel.Values);

                    for (int u = 1; u < cCount[path][0].Value; u++)
                    {
                        for (int v = 1; v < rCount[path][0].Value; v++)
                        {
                            mesh.Faces.AddFace(v - 1 + (u - 1) * (height), v - 1 + u * (height), v - 1 + u * (height) + 1, v - 1 + (u - 1) * (height) + 1);
                            //(k - 1 + (j - 1) * num2, k - 1 + j * num2, k - 1 + j * num2 + 1, k - 1 + (j - 1) * num2 + 1)
                        }
                    }

                    //mesh.Flip(true, true, true);
                    tMesh.Append(new GH_Mesh(mesh), path);

                    band.Dispose();
                }
                Gdal.Unlink("/vsimem/topoclipped.tif");
            }

            datasource.Dispose();

            DA.SetDataTree(0, tMesh);
            DA.SetData(1, dsbox);
            DA.SetData(2, srcInfo);
        }
Esempio n. 26
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare variables
            Rectangle3d rectangle = new Rectangle3d();
            Color       color     = Color.White;
            double      intensity = 1;
            string      name      = "";

            // Reference the inputs
            DA.GetData(0, ref rectangle);
            DA.GetData(1, ref color);
            DA.GetData(2, ref intensity);
            DA.GetData(3, ref name);

            // Get matrix transform between starting plane and rectangle
            Point3d position = rectangle.Center;

            Vector3d vectorX = new Vector3d(-1, 0, 0);
            Vector3d vectorZ = new Vector3d(0, 0, 1);

            Plane zxPlane = new Plane(Point3d.Origin, vectorX, vectorZ);

            var plane     = rectangle.Plane;
            var transform = Transform.PlaneToPlane(zxPlane, plane);

            float[]       matrixArray = transform.ToFloatArray(false);
            List <double> l           = new List <double>();

            foreach (float value in matrixArray)
            {
                decimal dec = new decimal(value);
                double  dub = (double)dec;
                l.Add(Math.Round(dub, 6));
            }

            // Build the light object
            dynamic lightObject = new ExpandoObject();

            lightObject.Uuid = Guid.NewGuid();
            lightObject.Type = "RectAreaLight";
            if (name.Length > 0)
            {
                lightObject.Name = name;
            }
            lightObject.Color     = Convert.ToInt32(color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"), 16);;
            lightObject.Intensity = intensity;
            lightObject.Width     = rectangle.Width;
            lightObject.Height    = rectangle.Height;
            lightObject.Matrix    = new List <double> {
                l[0] * -1, l[2], l[1], l[3], l[8] * -1, l[10], l[9], l[11], l[4] * -1, l[6], l[5], l[7], l[12] * -1, l[14], l[13], l[15]
            };

            // Create a helper to aid in visualizing the light's behavior
            List <Curve> helper = new List <Curve>();

            helper.Add(rectangle.ToNurbsCurve());

            Point3d start         = plane.Origin;
            Point3d end           = start + plane.Normal;
            Line    directionLine = new Line(start, end);

            helper.Add(directionLine.ToNurbsCurve());

            // Create object3d
            Object3d object3d = new Object3d(lightObject);

            // Set outputs
            DA.SetDataList(0, helper);
            DA.SetData(1, object3d);
        }