public _OdDb.ObjectIdCollection BakeGhGeometry(IGH_GeometricGoo gg)
        {
            var tmpFile = new Rhino.FileIO.File3dm();

            AddGeometry(tmpFile, gg);
            return(BakeGhGeometry(tmpFile));
        }
예제 #2
0
        public Guid Transform(Guid objectId, Transform xform, bool deleteOriginal)
        {
            if (!_storage.ContainsKey(objectId))
            {
                return(Guid.Empty);
            }

            var obj = _storage[objectId];

            if (obj == null)
            {
                return(Guid.Empty);
            }

            IGH_GeometricGoo newObj = deleteOriginal
                                  ? obj.GhGeometry.Transform(xform)
                                  : obj.GhGeometry.DuplicateGeometry().Transform(xform);

            if (newObj == null)
            {
                return(Guid.Empty);
            }

            if (deleteOriginal)
            {
                obj.GhGeometry     = newObj;
                _storage[objectId] = obj; // AttributedGeometry is a ValueType
                return(objectId);
            }
            var newId     = Guid.NewGuid();
            var attrClone = object.ReferenceEquals(obj.Attributes, null) ? null : obj.Attributes.Duplicate();

            _storage.Add(newId, new AttributedGeometry(newObj, attrClone));
            return(newId);
        }
예제 #3
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            IGH_GeometricGoo geoGoo = null;

            if (!DA.GetData("Geometry", ref geoGoo))
            {
                return;
            }

            if (!geoGoo.IsReferencedGeometry)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This geometry is not referenced from Rhino.");
                return;
            }

            var rhinoObj = Rhino.RhinoDoc.ActiveDoc.Objects.Find(geoGoo.ReferenceID);
            var name     = rhinoObj.Attributes.Name;

            if (!name.Contains("["))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This geometry does not have element ID embedded in its name.");
                return;
            }

            var id = name.Split(new[] { '[', ']' }).LastOrDefault(s => !String.IsNullOrEmpty(s));

            DA.SetData("Element ID", id);
        }
예제 #4
0
        //Box映射
        public static IGH_GeometricGoo BoxMapping(Box box1, Box box2, IGH_GeometricGoo geo)
        {
            if (!box1.IsValid || !box2.IsValid)
            {
                return(null);
            }
            Plane plane1 = box1.Plane;
            Plane plane2 = box2.Plane;

            plane1.Origin = box1.Center;
            plane2.Origin = box2.Center;
            double       xscale       = box2.X.Length / box1.X.Length;
            double       yscale       = box2.Y.Length / box1.Y.Length;
            double       zscale       = box2.Z.Length / box1.Z.Length;
            ITransform   item         = new Scale(plane1, xscale, yscale, zscale);
            ITransform   item2        = new Orientation(plane1, plane2);
            GH_Transform gh_Transform = new GH_Transform();

            gh_Transform.CompoundTransforms.Add(item);
            gh_Transform.CompoundTransforms.Add(item2);
            gh_Transform.ClearCaches();

            IGH_GeometricGoo geo2 = geo.DuplicateGeometry();

            geo2 = geo2.Transform(gh_Transform.Value);
            return(geo2);
        }
예제 #5
0
        /// <summary>
        /// Parses all geometries and adds to the linked lists. This does not clear the lists.
        /// </summary>
        /// <param name="geometricGoos"></param>
        /// <param name="breps"></param>
        /// <param name="meshes"></param>
        /// <param name="curves"></param>
        public static void ParseAll(IList <IGH_GeometricGoo> geometricGoos, List <Brep> breps = null, List <Mesh> meshes = null, List <Curve> curves = null)
        {
            for (int i = 0; i < geometricGoos.Count; i++)
            {
                IGH_GeometricGoo shape = geometricGoos[i];

                if (shape is Mesh || shape is GH_Mesh)
                {
                    if (meshes != null)
                    {
                        meshes.Add(GH_Convert.ToGeometryBase(shape) as Mesh);
                    }
                }
                if (shape is Brep || shape is GH_Brep)
                {
                    if (breps != null)
                    {
                        breps.Add(GH_Convert.ToGeometryBase(shape) as Brep);
                    }
                }
                if (shape is Curve || shape is GH_Curve)
                {
                    if (curves != null)
                    {
                        curves.Add(GH_Convert.ToGeometryBase(shape) as Curve);
                    }
                }
            }
        }
예제 #6
0
        protected override void SolveInstance(IGH_DataAccess da)
        {
            List <IGH_GeometricGoo> a_list       = da.GetDataList <IGH_GeometricGoo>(0);
            List <int>      groups               = da.GetDataList <int>(1);
            List <double>   axial_stiffness      = da.GetDataList <double>(2);
            List <double>   rotational_stiffness = da.GetDataList <double>(3);
            List <Vector3d> direction            = da.GetDataList <Vector3d>(4);

            List <GH_Spring> out_list = new List <GH_Spring>();

            for (int i = 0; i < a_list.Count; i++)
            {
                IGH_GeometricGoo a_goo = a_list[i];

                GH_Spring spr = new GH_Spring();
                spr.Value                = new GH_CouplingStruc();
                spr.GroupId              = groups.GetItemOrLast(i);
                spr.Axial_stiffness      = axial_stiffness.GetItemOrLast(i);
                spr.Rotational_stiffness = rotational_stiffness.GetItemOrLast(i);
                spr.Direction            = direction.GetItemOrLast(i);

                Enum state = spr.Value.SetInput(a_goo, true);
                if (state.Equals(GH_CouplingStruc.State.OK))
                {
                    out_list.Add(spr);
                }
                else
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input param: only (structural)points/lines allowed");
                }
            }

            da.SetDataList(0, out_list);
        }
예제 #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)
        {
            IGH_GeometricGoo shape = null;

            if (!DA.GetData <IGH_GeometricGoo>(0, ref shape))
            {
                return;
            }

            GeometryBase geo = null;

            if (shape is Mesh || shape is GH_Mesh ||
                shape is Brep || shape is GH_Brep ||
                shape is Surface || shape is GH_Surface ||
                shape is Curve || shape is GH_Curve ||
                shape is GH_Box || shape is GH_Line)
            {
                geo = GH_Convert.ToGeometryBase(shape);
            }
            else
            {
                return;
            }

            var bbox = geo.GetBoundingBox(true);

            DA.SetData(0, bbox.Center);
        }
예제 #8
0
 public BuildingPart(PolylineCurve pL, IGH_GeometricGoo partGoo, List <GH_String> partFieldNames, List <GH_String> partFieldValues, OsmGeo osmGeo)
 {
     this.PartFootprint   = pL;
     this.PartGoo         = partGoo;
     this.PartFieldNames  = partFieldNames;
     this.PartFieldValues = partFieldValues;
     this.PartOsmGeo      = osmGeo;
 }
예제 #9
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <IGH_GeometricGoo> geometry = new List <IGH_GeometricGoo>();
            Curve curve = null;

            if (!DA.GetDataList(0, geometry) || !DA.GetData(1, ref curve))
            {
                return;
            }
            ////////////////将于指定曲线线有关系的物件选出(Brep,Curve,Mesh)strict 选出完全重合,some 局部重合 ,all 相关联所有
            List <IGH_GeometricGoo> collect = new List <IGH_GeometricGoo>();
            List <int> indexes = new List <int>();

            for (int i = 0; i < geometry.Count; i++)
            {
                IGH_GeometricGoo obj = geometry[i];
                if (obj is GH_Curve)
                {
                    GH_Curve ghcurve = (GH_Curve)obj;
                    if (CurveAndCurve(ghcurve.Value, curve, strict, some, all))
                    {
                        indexes.Add(i);
                        collect.Add(obj);
                    }
                }
                else if (obj is GH_Brep)
                {
                    GH_Brep ghbrep = (GH_Brep)obj;
                    if (CurveAndBrep(ghbrep.Value, curve, strict, some, all))
                    {
                        indexes.Add(i);
                        collect.Add(obj);
                    }
                }
                else if (obj is GH_Surface)
                {
                    GH_Surface ghsurface = (GH_Surface)obj;
                    if (CurveAndBrep(ghsurface.Value, curve, strict, some, all))
                    {
                        indexes.Add(i);
                        collect.Add(obj);
                    }
                }
                else if (obj is GH_Mesh)
                {
                    GH_Mesh ghmesh = (GH_Mesh)obj;
                    if (CurveAndMesh(ghmesh.Value, curve, strict, some, all))
                    {
                        indexes.Add(i);
                        collect.Add(obj);
                    }
                }
            }
            DA.SetDataList(0, collect);
            DA.SetDataList(1, indexes);
        }
예제 #10
0
        /*******************************************/

        public static bool CastToGoo(object value, ref IGH_GeometricGoo target)
        {
            try
            {
                target = GH_Convert.ToGeometricGoo(value);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #11
0
        public Enum SetInput(IGH_GeometricGoo gg, bool a)
        {
            Enum res               = State.OK;
            bool isPoint           = false;
            GS_StructuralPoint spt = null;
            GS_StructuralLine  sln = null;

            if (gg is GH_Point)
            {
                spt       = new GS_StructuralPoint();
                spt.Value = new Point((gg as GH_Point).Value);
                isPoint   = true;
            }
            else if (gg is GS_StructuralPoint)
            {
                spt     = gg as GS_StructuralPoint;
                isPoint = true;
            }
            else if (gg is GH_Curve)
            {
                sln       = new GS_StructuralLine();
                sln.Value = (gg as GH_Curve).Value;
            }
            else if (gg is GH_Line)
            {
                sln       = new GS_StructuralLine();
                sln.Value = new LineCurve((gg as GH_Line).Value);
            }
            else if (gg is GH_Arc)
            {
                sln       = new GS_StructuralLine();
                sln.Value = new ArcCurve((gg as GH_Arc).Value);
            }
            else if (gg is GS_StructuralLine)
            {
                sln = gg as GS_StructuralLine;
            }
            //else
            //throw new InvalidCastException("Input param: only (structural)points/lines allowed");

            if ((spt is null) && (sln is null))
            {
                if (a)
                {
                    res = State.InvalidA;
                }
                else
                {
                    res = State.InvalidB;
                }
            }
예제 #12
0
        protected override void SolveInstance(IGH_DataAccess da)
        {
            List <IGH_GeometricGoo> a_list        = da.GetDataList <IGH_GeometricGoo>(0);
            List <IGH_GeometricGoo> b_list        = da.GetDataList <IGH_GeometricGoo>(1);
            List <int>      groups                = da.GetDataList <int>(2);
            List <double>   axial_stiffness       = da.GetDataList <double>(3);
            List <double>   rotational_stiffness  = da.GetDataList <double>(4);
            List <double>   transversal_stiffness = da.GetDataList <double>(5);
            List <Vector3d> direction             = da.GetDataList <Vector3d>(6);

            List <GH_Elastic_Coupling> out_list = new List <GH_Elastic_Coupling>();

            int count = Math.Max(a_list.Count, b_list.Count);

            for (int i = 0; i < count; i++)
            {
                IGH_GeometricGoo a_goo = a_list.GetItemOrLast(i);
                IGH_GeometricGoo b_goo = b_list.GetItemOrLast(i);

                GH_Elastic_Coupling spr = new GH_Elastic_Coupling();
                spr.Value                 = new GH_CouplingStruc();
                spr.GroupId               = groups.GetItemOrLast(i);
                spr.Axial_stiffness       = axial_stiffness.GetItemOrLast(i);
                spr.Rotational_stiffness  = rotational_stiffness.GetItemOrLast(i);
                spr.Transversal_stiffness = transversal_stiffness.GetItemOrLast(i);
                spr.Direction             = direction.GetItemOrLast(i);

                Enum state = spr.Value.SetInputs(a_goo, b_goo);
                if (state.Equals(GH_CouplingStruc.State.OK))
                {
                    out_list.Add(spr);
                }
                else if (state.Equals(GH_CouplingStruc.State.InvalidA))
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input param A: only (structural)points/lines allowed");
                }
                else if (state.Equals(GH_CouplingStruc.State.InvalidB))
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input param B: only (structural)points/lines allowed");
                }
                else if (state.Equals(GH_CouplingStruc.State.Modified))
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input parameters swapped, only Elastic Couplings from Lines to Points are supported");
                    out_list.Add(spr);
                }
            }

            da.SetDataList(0, out_list);
        }
예제 #13
0
    //this is for morphing - dont even know what it is, but I dont have to
    public GeomObject Morph(SpaceMorph morph)
    {
        GeomObject mObj = Duplicate();

        foreach (string key in mObj.MemberDict.Keys)
        {
            List <IGH_Goo> newData = new List <IGH_Goo>();
            for (int i = 0; i < mObj.MemberDict[key].Count; i++)
            {
                if (typeof(IGH_GeometricGoo).IsAssignableFrom(mObj.MemberDict[key][i].GetType()))
                {
                    IGH_GeometricGoo geom = (IGH_GeometricGoo)mObj.MemberDict[key][i];
                    mObj.MemberDict[key][i] = geom.Morph(morph);
                }
            }
        }

        return(mObj);
    }
예제 #14
0
    //this is for transform
    public GeomObject Transform(Transform xform)
    {
        GeomObject xObj = Duplicate();

        foreach (string key in xObj.MemberDict.Keys)
        {
            List <IGH_Goo> newData = new List <IGH_Goo>();
            for (int i = 0; i < xObj.MemberDict[key].Count; i++)
            {
                if (typeof(IGH_GeometricGoo).IsAssignableFrom(xObj.MemberDict[key][i].GetType()))
                {
                    IGH_GeometricGoo geom = (IGH_GeometricGoo)xObj.MemberDict[key][i];
                    xObj.MemberDict[key][i] = geom.Transform(xform);
                }
            }
        }

        return(xObj);
    }
예제 #15
0
    protected override void SolveInstance(IGH_DataAccess DA)
    {
        IGH_GeometricGoo geometry = null;
        DisplayMaterial  material = null;
        string           layer    = "";

        if (!DA.GetData(0, ref geometry))
        {
            return;
        }
        DA.GetData(1, ref material);
        DA.GetData(2, ref layer);

        var target = GH_Convert.ToGeometryBase(geometry);

        var displayStyle = new DisplayGeometry(target, material, layer);

        DA.SetData(0, new GH_DisplayGeometry(displayStyle));
    }
예제 #16
0
        public static double EstimateRefinementCells(IGH_GeometricGoo geo, double baseCellSize)
        {
            var regionName        = Geometry.getUserString(geo, "ComputeName");
            var refinementDetails = Geometry.getUserString(geo, "ComputeRefinementRegion");

            if (string.IsNullOrEmpty(regionName) || string.IsNullOrEmpty(refinementDetails))
            {
                return(0.0);
            }

            var details = new RefinementDetails().FromJson(refinementDetails);

            details.CellSize = baseCellSize;
            var cellSize = baseCellSize / Math.Pow(2, int.Parse(details.Levels.Split(' ')[1]));
            var mesh     = new Mesh();

            geo.CastTo(out mesh);

            return(mesh.Volume() / Math.Pow(cellSize, 3));
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            IGH_GeometricGoo geo = null;

            if (!DA.GetData("Geometry", ref geo))
            {
                return;
            }
            var bbox = geo.Boundingbox;

            if (!bbox.IsValid)
            {
                bbox = geo.GetBoundingBox(Transform.Identity);
            }
            var transVec = Point3d.Origin - bbox.Center;

            var newGeo = geo.DuplicateGeometry().Transform(Transform.Translation(transVec));

            DA.SetData("Recentered Geometry", newGeo);
            DA.SetData("Translation Vector", transVec);
        }
예제 #18
0
        public static double EstimateSurfaceAreaCells(IGH_GeometricGoo geo, double baseCellSize)
        {
            var surfaceName = Geometry.getUserString(geo, "ComputeName");
            var levels      = Geometry.getUserString(geo, "ComputeMeshLevels");

            if (string.IsNullOrEmpty(surfaceName) || string.IsNullOrEmpty(levels))
            {
                return(0.0);
            }

            var meshLevel = new MeshLevelDetails().FromJson(levels);

            meshLevel.CellSize = baseCellSize;
            var cellSize = baseCellSize / Math.Pow(2, meshLevel.Level.Min);
            var mesh     = new Mesh();

            geo.CastTo(out mesh);
            var area = AreaMassProperties.Compute(mesh).Area;

            return((area / Math.Pow(cellSize, 2)) * 4);
        }
예제 #19
0
        private static IGH_GeometricGoo DeReferenceWithReflection(IGH_GeometricGoo geom)
        {
            var geomType = geom.GetType();
            var geomInfo = geomType.GetRuntimeProperty("Value");

            if (geomInfo != null)
            {
                var geomVal = geomInfo.GetValue(geom);
                if (geomVal is GeometryBase rhinoGeom)
                {
                    IGH_GeometricGoo newGoo;
                    try
                    {
                        newGoo = (IGH_GeometricGoo)Activator.CreateInstance(geomType, rhinoGeom);
                    }
                    catch { newGoo = geom; }
                    geom = newGoo;
                }
            }
            return(geom.DuplicateGeometry());
        }
예제 #20
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)
        {
            // code for accessing GUID by Fraser Greenroyd
            // https://frasergreenroyd.com/how-to-access-geometry-guids-in-grasshopper-components/
            IGH_GeometricGoo geom = null;

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

            Guid id = geom.ReferenceID;

            Rhino.DocObjects.ObjectAttributes objAtt = Rhino.RhinoDoc.ActiveDoc.Objects.Find(id).Attributes;

            int layerIndex = objAtt.LayerIndex;

            string layer = Rhino.RhinoDoc.ActiveDoc.Layers[layerIndex].Name;

            DA.SetData(0, layer);
        }
예제 #21
0
        public static IGH_GeometricGoo BoxTrans(Box box1, Box box2, IGH_GeometricGoo geo)
        {
            if (!box1.IsValid || !box2.IsValid)
            {
                return(null);
            }
            Plane plane1 = box1.Plane;
            Plane plane2 = box2.Plane;

            plane1.Origin = box1.Center;
            plane2.Origin = box2.Center;
            ITransform   item         = new Orientation(plane1, plane2);
            GH_Transform gh_Transform = new GH_Transform();

            gh_Transform.CompoundTransforms.Add(item);
            gh_Transform.ClearCaches();

            IGH_GeometricGoo geo2 = geo.DuplicateGeometry();

            geo2 = geo2.Transform(gh_Transform.Value);
            return(geo2);
        }
예제 #22
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            IGH_GeometricGoo g = null;

            DA.GetData <IGH_GeometricGoo>(0, ref g);

            string geoType = g.TypeName;

            string name = null;

            DA.GetData(1, ref name);

            bool activate = false;

            DA.GetData(2, ref activate);

            Rhino.DocObjects.ObjectAttributes atts = new Rhino.DocObjects.ObjectAttributes();
            string newID = null;

            atts.Name = name;

            if (activate)
            {
                GH_Point p = g as GH_Point;
                if (p != null)
                {
                    GeometryBase geo = GH_Convert.ToGeometryBase(p);
                    newID = RhinoDoc.ActiveDoc.Objects.Add(geo, atts).ToString();
                }
                GH_Curve c = g as GH_Curve;
                if (c != null)
                {
                    GeometryBase geo = GH_Convert.ToGeometryBase(c);
                    newID = RhinoDoc.ActiveDoc.Objects.Add(geo, atts).ToString();
                }
            }

            DA.SetData(0, newID);
        }
예제 #23
0
        static Rhino.Geometry.GeometryBase AsGeometryBase(IGH_GeometricGoo obj)
        {
            var scriptVariable = obj?.ScriptVariable();

            switch (scriptVariable)
            {
            case Rhino.Geometry.Point3d point: return(new Rhino.Geometry.Point(point));

            case Rhino.Geometry.Line line: return(new Rhino.Geometry.LineCurve(line));

            case Rhino.Geometry.Rectangle3d rect: return(rect.ToNurbsCurve());

            case Rhino.Geometry.Arc arc: return(new Rhino.Geometry.ArcCurve(arc));

            case Rhino.Geometry.Circle circle: return(new Rhino.Geometry.ArcCurve(circle));

            case Rhino.Geometry.Ellipse ellipse: return(ellipse.ToNurbsCurve());

            case Rhino.Geometry.Box box: return(box.ToBrep());
            }

            return((scriptVariable as Rhino.Geometry.GeometryBase)?.DuplicateShallow());
        }
예제 #24
0
        internal static IGH_GeometricGoo DeReferenceWhereRequired(IGH_GeometricGoo geom)
        {
            if (geom.IsReferencedGeometry)
            {
                geom.LoadGeometry();

                //Really want c# 9 switch expressions
                if (geom is GH_Brep brep)
                {
                    return(new GH_Brep((Brep)brep.Value.Duplicate()));
                }
                if (geom is GH_Curve curve)
                {
                    return(new GH_Curve((Curve)curve.Value.Duplicate()));
                }
                if (geom is GH_Mesh mesh)
                {
                    return(new GH_Mesh((Mesh)mesh.Value.Duplicate()));
                }
                if (geom is GH_Point point)
                {
                    return(new GH_Point(point.Value));
                }
                if (geom is GH_Surface surface)
                {
                    return(new GH_Surface((Brep)surface.Value.Duplicate()));
                }
                //if (geom is GH_SubD subd) { return new GH_SubD((SubD)subd.Value.Duplicate()); }

                //If none of the hard coded cases fit use reflection to copy the object
                return(DeReferenceWithReflection(geom));
            }
            else
            {
                return(geom);
            }
        }
예제 #25
0
        /// <summary>
        /// input a List/IGH_GeometricGoo/
        /// List/IGH_GeometricGoo/ shapes = new List/IGH_GeometricGoo/();
        /// DA.GetDataList/IGH_GeometricGoo/(2, shapes);
        /// </summary>
        /// <param name="geometricGoos">List IGH_GeometricGoo  shapes, can be Brep and Mesh</param>
        /// <returns>joinedMesh</returns>
        ///
        public static Mesh ParseToJoinedMesh(List <IGH_GeometricGoo> geometricGoos, out BoundingBox boundingBox, bool parallel = true)
        {
            boundingBox = new BoundingBox();

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

            Mesh[] meshes = new Mesh[geometricGoos.Count];

            Mesh joinedMesh = new Mesh();

            if (parallel)
            {
                Parallel.For(0, geometricGoos.Count, delegate(int i)
                {
                    IGH_GeometricGoo shape = geometricGoos[i];

                    if (shape is Mesh || shape is GH_Mesh)
                    {
                        var geobase = GH_Convert.ToGeometryBase(shape);
                        meshes[i]   = geobase as Mesh;
                    }
                    else if (shape is Brep || shape is GH_Brep)
                    {
                        var geobase          = GH_Convert.ToGeometryBase(shape);
                        Brep brep            = geobase as Brep;
                        MeshingParameters mp = MeshingParameters.Default;

                        Mesh[] meshParts = Mesh.CreateFromBrep(brep, mp);

                        meshes[i] = meshParts[0];

                        for (int j = 1; j < meshParts.Length; j++)
                        {
                            meshes[i].Append(meshParts[j]);
                        }
                    }
                });
            }
            else
            {
                for (int i = 0; i < geometricGoos.Count; i++)
                {
                    IGH_GeometricGoo shape = geometricGoos[i];

                    if (shape is Mesh || shape is GH_Mesh)
                    {
                        var geobase = GH_Convert.ToGeometryBase(shape);
                        meshes[i] = geobase as Mesh;
                    }
                    else if (shape is Brep || shape is GH_Brep)
                    {
                        var  geobase         = GH_Convert.ToGeometryBase(shape);
                        Brep brep            = geobase as Brep;
                        MeshingParameters mp = MeshingParameters.Default;

                        Mesh[] meshParts = Mesh.CreateFromBrep(brep, mp);

                        meshes[i] = meshParts[0];

                        for (int j = 1; j < meshParts.Length; j++)
                        {
                            meshes[i].Append(meshParts[j]);
                        }
                    }
                }
            }

            foreach (var mesh in meshes)
            {
                if (mesh != null)
                {
                    joinedMesh.Append(mesh);
                }
            }


            CleanMesh(joinedMesh);
            boundingBox = joinedMesh.GetBoundingBox(true);

            return(joinedMesh);
        }
예제 #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)
        {
            ///Gather GHA inputs
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            string osmFilePath = string.Empty;

            DA.GetData <string>("OSM Data Location", ref osmFilePath);

            //string userSRStext = "WGS84";
            //DA.GetData<string>(2, ref userSRStext);

            List <string> filterWords = new List <string>();

            DA.GetDataList <string>(2, filterWords);

            List <string> filterKeyValue = new List <string>();

            DA.GetDataList <string>(3, filterKeyValue);

            Transform xformToMetric   = new Transform(Rhino.RhinoMath.UnitScale(RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters));
            Transform xformFromMetric = new Transform(Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Meters, RhinoDoc.ActiveDoc.ModelUnitSystem));

            ///Declare trees
            Rectangle3d recs = new Rectangle3d();
            GH_Structure <GH_String>        fieldNames  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        fieldValues = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> geometryGoo = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <IGH_GeometricGoo> buildingGoo = new GH_Structure <IGH_GeometricGoo>();


            Point3d max = new Point3d();
            Point3d min = new Point3d();

            if (boundary != null)
            {
                Point3d maxM = boundary.GetBoundingBox(true).Corner(true, false, true);
                max = Heron.Convert.XYZToWGS(maxM);

                Point3d minM = boundary.GetBoundingBox(true).Corner(false, true, true);
                min = Heron.Convert.XYZToWGS(minM);
            }

            /// get extents (why is this not part of OsmSharp?)
            System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load(osmFilePath);
            if (xdoc.Root.Element("bounds") != null)
            {
                double  minlat    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("minlat").Value);
                double  minlon    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("minlon").Value);
                double  maxlat    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("maxlat").Value);
                double  maxlon    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("maxlon").Value);
                Point3d boundsMin = Heron.Convert.WGSToXYZ(new Point3d(minlon, minlat, 0));
                Point3d boundsMax = Heron.Convert.WGSToXYZ(new Point3d(maxlon, maxlat, 0));

                recs = new Rectangle3d(Plane.WorldXY, boundsMin, boundsMax);
            }
            else
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Cannot determine the extents of the OSM file. A 'bounds' element may not be present in the file.");
            }


            using (var fileStreamSource = File.OpenRead(osmFilePath))
            {
                /// create a source.
                OsmSharp.Streams.XmlOsmStreamSource source = new OsmSharp.Streams.XmlOsmStreamSource(fileStreamSource);

                /// filter by bounding box
                OsmSharp.Streams.OsmStreamSource sourceClipped = source;
                if (clipped)
                {
                    sourceClipped = source.FilterBox((float)max.X, (float)max.Y, (float)min.X, (float)min.Y, true);
                }

                /// create a dictionary of elements
                OsmSharp.Db.Impl.MemorySnapshotDb sourceMem = new OsmSharp.Db.Impl.MemorySnapshotDb(sourceClipped);

                /// filter the source
                var filtered = from osmGeos in sourceClipped
                               where osmGeos.Tags != null
                               select osmGeos;

                if (filterWords.Any())
                {
                    filtered = from osmGeos in filtered
                               where osmGeos.Tags.ContainsAnyKey(filterWords)
                               select osmGeos;
                }

                if (filterKeyValue.Any())
                {
                    List <Tag> tags = new List <Tag>();
                    foreach (string term in filterKeyValue)
                    {
                        string[] kv  = term.Split(',');
                        Tag      tag = new Tag(kv[0], kv[1]);
                        tags.Add(tag);
                    }
                    filtered = from osmGeos in filtered
                               where osmGeos.Tags.Intersect(tags).Any()
                               select osmGeos;
                }

                source.Dispose();

                /// loop over all objects and count them.
                int nodes = 0, ways = 0, relations = 0;

                foreach (OsmSharp.OsmGeo osmGeo in filtered)
                {
                    //NODES
                    if (osmGeo.Type == OsmGeoType.Node)
                    {
                        OsmSharp.Node n         = (OsmSharp.Node)osmGeo;
                        GH_Path       nodesPath = new GH_Path(0, nodes);

                        //populate Fields and Values for each node
                        fieldNames.AppendRange(GetKeys(osmGeo), nodesPath);
                        fieldValues.AppendRange(GetValues(osmGeo), nodesPath);

                        //get geometry for node
                        Point3d nPoint = Heron.Convert.WGSToXYZ(new Point3d((double)n.Longitude, (double)n.Latitude, 0));
                        geometryGoo.Append(new GH_Point(nPoint), nodesPath);

                        //increment nodes
                        nodes++;
                    }

                    ////////////////////////////////////////////////////////////
                    //WAYS
                    if (osmGeo.Type == OsmGeoType.Way)
                    {
                        OsmSharp.Way w        = (OsmSharp.Way)osmGeo;
                        GH_Path      waysPath = new GH_Path(1, ways);

                        //populate Fields and Values for each way
                        fieldNames.AppendRange(GetKeys(osmGeo), waysPath);
                        fieldValues.AppendRange(GetValues(osmGeo), waysPath);

                        //get polyline geometry for way
                        List <Point3d> wayNodes = new List <Point3d>();
                        foreach (long j in w.Nodes)
                        {
                            OsmSharp.Node n = (OsmSharp.Node)sourceMem.Get(OsmGeoType.Node, j);
                            wayNodes.Add(Heron.Convert.WGSToXYZ(new Point3d((double)n.Longitude, (double)n.Latitude, 0)));
                        }

                        PolylineCurve pL = new PolylineCurve(wayNodes);
                        if (pL.IsClosed)
                        {
                            //create base surface
                            Brep[] breps = Brep.CreatePlanarBreps(pL, DocumentTolerance());
                            geometryGoo.Append(new GH_Brep(breps[0]), waysPath);
                        }
                        else
                        {
                            geometryGoo.Append(new GH_Curve(pL), waysPath);
                        }

                        //building massing
                        if (w.Tags.ContainsKey("building") || w.Tags.ContainsKey("building:part"))
                        {
                            if (pL.IsClosed)
                            {
                                CurveOrientation orient = pL.ClosedCurveOrientation(Plane.WorldXY);
                                if (orient != CurveOrientation.CounterClockwise)
                                {
                                    pL.Reverse();
                                }

                                Vector3d hVec = new Vector3d(0, 0, GetBldgHeight(osmGeo));
                                hVec.Transform(xformFromMetric);

                                Extrusion        ex      = Extrusion.Create(pL, hVec.Z, true);
                                IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(ex);
                                buildingGoo.Append(bldgGoo, waysPath);
                            }
                        }

                        //increment ways
                        ways++;
                    }
                    ///////////////////////////////////////////////////////////

                    //RELATIONS
                    if (osmGeo.Type == OsmGeoType.Relation)
                    {
                        OsmSharp.Relation r            = (OsmSharp.Relation)osmGeo;
                        GH_Path           relationPath = new GH_Path(2, relations);

                        //populate Fields and Values for each relation
                        fieldNames.AppendRange(GetKeys(osmGeo), relationPath);
                        fieldValues.AppendRange(GetValues(osmGeo), relationPath);

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

                        // start members loop
                        for (int mem = 0; mem < r.Members.Length; mem++)
                        {
                            GH_Path memberPath = new GH_Path(2, relations, mem);

                            OsmSharp.RelationMember rMem    = r.Members[mem];
                            OsmSharp.OsmGeo         rMemGeo = sourceMem.Get(rMem.Type, rMem.Id);

                            if (rMemGeo != null)
                            {
                                //get geometry for node
                                if (rMemGeo.Type == OsmGeoType.Node)
                                {
                                    long          memNodeId = rMem.Id;
                                    OsmSharp.Node memN      = (OsmSharp.Node)sourceMem.Get(rMem.Type, rMem.Id);
                                    Point3d       memPoint  = Heron.Convert.WGSToXYZ(new Point3d((double)memN.Longitude, (double)memN.Latitude, 0));
                                    geometryGoo.Append(new GH_Point(memPoint), memberPath);
                                }

                                //get geometry for way
                                if (rMem.Type == OsmGeoType.Way)
                                {
                                    long memWayId = rMem.Id;

                                    OsmSharp.Way memWay = (OsmSharp.Way)rMemGeo;

                                    //get polyline geometry for way
                                    List <Point3d> memNodes = new List <Point3d>();
                                    foreach (long memNodeId in memWay.Nodes)
                                    {
                                        OsmSharp.Node memNode = (OsmSharp.Node)sourceMem.Get(OsmGeoType.Node, memNodeId);
                                        memNodes.Add(Heron.Convert.WGSToXYZ(new Point3d((double)memNode.Longitude, (double)memNode.Latitude, 0)));
                                    }

                                    PolylineCurve memPolyline = new PolylineCurve(memNodes);

                                    geometryGoo.Append(new GH_Curve(memPolyline.ToNurbsCurve()), memberPath);

                                    CurveOrientation orient = memPolyline.ClosedCurveOrientation(Plane.WorldXY);
                                    if (orient != CurveOrientation.CounterClockwise)
                                    {
                                        memPolyline.Reverse();
                                    }

                                    pLines.Add(memPolyline.ToNurbsCurve());
                                }

                                //get nested relations
                                if (rMem.Type == OsmGeoType.Relation)
                                {
                                    ///not sure if this is needed
                                }
                            }
                        }
                        //end members loop

                        bool allClosed = true;
                        foreach (Curve pc in pLines)
                        {
                            if (!pc.IsClosed)
                            {
                                allClosed = false;
                            }
                        }

                        if (pLines.Count > 0 && allClosed)
                        {
                            //create base surface
                            Brep[] breps = Brep.CreatePlanarBreps(pLines, DocumentTolerance());
                            geometryGoo.RemovePath(relationPath);

                            foreach (Brep b in breps)
                            {
                                geometryGoo.Append(new GH_Brep(b), relationPath);

                                //building massing
                                if (r.Tags.ContainsKey("building") || r.Tags.ContainsKey("building:part"))
                                {
                                    Vector3d hVec = new Vector3d(0, 0, GetBldgHeight(osmGeo));
                                    hVec.Transform(xformFromMetric);

                                    //create extrusion from base surface
                                    buildingGoo.Append(new GH_Brep(Brep.CreateFromOffsetFace(b.Faces[0], hVec.Z, DocumentTolerance(), false, true)), relationPath);
                                }
                            }
                        }

                        //increment relations
                        relations++;
                    } ///end relation loop
                }     ///end filtered loop
            }         ///end osm source loop

            if (recs.IsValid)
            {
                DA.SetData(0, recs);
            }
            DA.SetDataTree(1, fieldNames);
            DA.SetDataTree(2, fieldValues);
            DA.SetDataTree(3, geometryGoo);
            DA.SetDataTree(4, buildingGoo);
        } ///end SolveInstance
예제 #27
0
        /// <summary>
        /// 計算部分
        /// </summary>
        /// <param name="DA">インプットパラメータからデータを取得し、出力用のデータを保持するオブジェクト</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            int              nFL = 0;
            double           FH = 0, Angle = 0, R = 0;
            IGH_GeometricGoo FL    = null;
            Brep             Floor = null;

            // 入力設定============================
            if (!DA.GetData(0, ref nFL))
            {
                return;
            }
            if (!DA.GetData(1, ref FH))
            {
                return;
            }
            if (!DA.GetData(2, ref Angle))
            {
                return;
            }
            if (!DA.GetData(3, ref R))
            {
                return;
            }
            if (!DA.GetData(4, ref FL))
            {
                return;
            }
            if (!DA.GetData(4, ref Floor))
            {
                return;
            }

            // 床の作成
            List <IGH_GeometricGoo> list = new List <IGH_GeometricGoo>(nFL);
            Vector3d DirectionVector     = new Vector3d(0, 0, FH);
            Point3d  Center = new Point3d(0, 0, 0);

            for (int i = 0; i < nFL; i++)
            {
                ITransform transform  = new Translation(DirectionVector * (double)i);
                ITransform transform2 = new Rotation(Center, DirectionVector, Angle * (double)i);
                if (FL != null)
                {
                    IGH_GeometricGoo FL2 = FL.DuplicateGeometry();
                    FL2 = FL2.Transform(transform.ToMatrix());
                    FL2 = FL2.Transform(transform2.ToMatrix());
                    list.Add(FL2);
                }
                else
                {
                    list.Add(null);
                }
            }

            // 柱の作成
            List <Brep> collist = new List <Brep>(nFL);

            Point3d[] CornerPoints = Floor.DuplicateVertices();
            // 内柱
            Point3d Point1in = new Point3d(CornerPoints[0].X / 2.0, CornerPoints[0].Y / 2.0, CornerPoints[0].Z / 2.0);
            Point3d Point2in = new Point3d(CornerPoints[1].X / 2.0, CornerPoints[1].Y / 2.0, CornerPoints[1].Z / 2.0);
            Point3d Point3in = new Point3d(CornerPoints[2].X / 2.0, CornerPoints[2].Y / 2.0, CornerPoints[2].Z / 2.0);
            Point3d Point4in = new Point3d(CornerPoints[3].X / 2.0, CornerPoints[3].Y / 2.0, CornerPoints[3].Z / 2.0);
            // 外柱
            Point3d Point1outS = new Point3d(CornerPoints[0].X, CornerPoints[0].Y, CornerPoints[0].Z);
            Point3d Point2outS = new Point3d(CornerPoints[1].X, CornerPoints[1].Y, CornerPoints[1].Z);
            Point3d Point3outS = new Point3d(CornerPoints[2].X, CornerPoints[2].Y, CornerPoints[2].Z);
            Point3d Point4outS = new Point3d(CornerPoints[3].X, CornerPoints[3].Y, CornerPoints[3].Z);
            Point3d Point1outE = Point1outS;
            Point3d Point2outE = Point2outS;
            Point3d Point3outE = Point3outS;
            Point3d Point4outE = Point4outS;

            double num1 = GH_Component.DocumentTolerance();
            double num2 = GH_Component.DocumentAngleTolerance();

            for (int i = 0; i < nFL - 1; i++)
            {
                if (FL != null)
                {
                    if (i != 0)
                    {
                        // 内柱
                        Point1in = new Point3d(Point1in.X, Point1in.Y, Point1in.Z + FH);
                        Point2in = new Point3d(Point2in.X, Point2in.Y, Point2in.Z + FH);
                        Point3in = new Point3d(Point3in.X, Point3in.Y, Point3in.Z + FH);
                        Point4in = new Point3d(Point4in.X, Point4in.Y, Point4in.Z + FH);
                        // 外柱
                        Point1outS = new Point3d(Point1outE.X, Point1outE.Y, Point1outE.Z);
                        Point2outS = new Point3d(Point2outE.X, Point2outE.Y, Point2outE.Z);
                        Point3outS = new Point3d(Point3outE.X, Point3outE.Y, Point3outE.Z);
                        Point4outS = new Point3d(Point4outE.X, Point4outE.Y, Point4outE.Z);
                    }

                    // 外柱 終点
                    Point1outE = new Point3d(
                        Point1outS.X * Math.Cos(Angle) - Point1outS.Y * Math.Sin(Angle),
                        Point1outS.X * Math.Sin(Angle) + Point1outS.Y * Math.Cos(Angle),
                        Point1outS.Z + FH);
                    Point2outE = new Point3d(
                        Point2outS.X * Math.Cos(Angle) - Point2outS.Y * Math.Sin(Angle),
                        Point2outS.X * Math.Sin(Angle) + Point2outS.Y * Math.Cos(Angle),
                        Point2outS.Z + FH);
                    Point3outE = new Point3d(
                        Point3outS.X * Math.Cos(Angle) - Point3outS.Y * Math.Sin(Angle),
                        Point3outS.X * Math.Sin(Angle) + Point3outS.Y * Math.Cos(Angle),
                        Point3outS.Z + FH);
                    Point4outE = new Point3d(
                        Point4outS.X * Math.Cos(Angle) - Point4outS.Y * Math.Sin(Angle),
                        Point4outS.X * Math.Sin(Angle) + Point4outS.Y * Math.Cos(Angle),
                        Point4outS.Z + FH);

                    LineCurve LineCurve1in = new LineCurve(new Line(Point1in, DirectionVector));
                    LineCurve LineCurve2in = new LineCurve(new Line(Point2in, DirectionVector));
                    LineCurve LineCurve3in = new LineCurve(new Line(Point3in, DirectionVector));
                    LineCurve LineCurve4in = new LineCurve(new Line(Point4in, DirectionVector));
                    //
                    LineCurve LineCurve1out = new LineCurve(new Line(Point1outS, Point1outE));
                    LineCurve LineCurve2out = new LineCurve(new Line(Point2outS, Point2outE));
                    LineCurve LineCurve3out = new LineCurve(new Line(Point3outS, Point3outE));
                    LineCurve LineCurve4out = new LineCurve(new Line(Point4outS, Point4outE));

                    Brep[] col1in = Brep.CreatePipe(LineCurve1in, R, true, 0, false, num1, num2);
                    Brep[] col2in = Brep.CreatePipe(LineCurve2in, R, true, 0, false, num1, num2);
                    Brep[] col3in = Brep.CreatePipe(LineCurve3in, R, true, 0, false, num1, num2);
                    Brep[] col4in = Brep.CreatePipe(LineCurve4in, R, true, 0, false, num1, num2);
                    //
                    Brep[] col1out = Brep.CreatePipe(LineCurve1out, R, true, 0, false, num1, num2);
                    Brep[] col2out = Brep.CreatePipe(LineCurve2out, R, true, 0, false, num1, num2);
                    Brep[] col3out = Brep.CreatePipe(LineCurve3out, R, true, 0, false, num1, num2);
                    Brep[] col4out = Brep.CreatePipe(LineCurve4out, R, true, 0, false, num1, num2);

                    collist.AddRange(col1in);
                    collist.AddRange(col2in);
                    collist.AddRange(col3in);
                    collist.AddRange(col4in);
                    collist.AddRange(col1out);
                    collist.AddRange(col2out);
                    collist.AddRange(col3out);
                    collist.AddRange(col4out);
                }
            }
            // 出力設定============================
            DA.SetDataList(0, list);
            DA.SetDataList(1, collist);
        }
예제 #28
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var gridSize   = Units.ConvertFromMeter(DA.Fetch <double>("GridSize [m]"));
            var edgeOffset = Units.ConvertFromMeter(DA.Fetch <double>("Edge Offset [m]"));

            var offset     = Units.ConvertFromMeter(DA.Fetch <double>("Vertical Offset [m]"));
            var useCenters = DA.Fetch <bool>("IsoCurves");
            var geometries = DA.FetchList <IGH_GeometricGoo>("Geometry");
            var goLarge    = DA.Fetch <bool>("GoLarge");

            DataTree <Point3d> centers = new DataTree <Point3d>();
            List <Grid>        myGrids = new List <Grid>();
            List <Mesh>        meshes  = new List <Mesh>();

            //List<Mesh> inMeshes = new List<Mesh>();
            List <Brep>  inBreps = new List <Brep>();
            List <Curve> inCrvs  = new List <Curve>();

            //string msg = "";
            useCenters = !useCenters;

            for (int i = 0; i < geometries.Count; i++)
            {
                if (geometries[i] == null)
                {
                    continue;
                }

                IGH_GeometricGoo shape = geometries[i].DuplicateGeometry();

                shape.Transform(Transform.Translation(0, 0, offset));

                if (shape is Mesh || shape is GH_Mesh)
                {
                    //inMeshes.Add(GH_Convert.ToGeometryBase(shape) as Mesh);
                    myGrids.Add(new Grid(GH_Convert.ToGeometryBase(shape) as Mesh, useCenters: useCenters));
                }
                else if (shape is Brep || shape is GH_Brep)
                {
                    //myGrids.Add(new Grid(GH_Convert.ToGeometryBase(shape) as Brep, gridSize, useCenters: useCenters));
                    inBreps.Add(GH_Convert.ToGeometryBase(shape) as Brep);
                }
                else if (shape is Curve || shape is GH_Curve)
                {
                    //myGrids.Add(new Grid(GH_Convert.ToGeometryBase(shape) as Curve, gridSize, useCenters: useCenters));
                    inCrvs.Add(GH_Convert.ToGeometryBase(shape) as Curve);
                }
                else
                {
                    myGrids.Add(null);
                    meshes.Add(null);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "error on an input grid");
                }
            }

            List <Brep> breps = InputGeometries.CurvesToOffsetBreps(inCrvs, edgeOffset) ?? new List <Brep>();

            breps.AddRange(InputGeometries.BrepsToOffsetBreps(inBreps, edgeOffset));


            for (int i = 0; i < breps.Count; i++)
            {
                myGrids.Add(new Grid(breps[i], gridSize, useCenters: useCenters, goLarge));
            }

            for (int i = 0; i < myGrids.Count; i++)
            {
                meshes.Add(myGrids[i].SimMesh);
                GH_Path p = new GH_Path(i);
                centers.AddRange(myGrids[i].SimPoints, p);
            }


            DA.SetDataList(0, myGrids);
            DA.SetDataList(1, meshes);
            DA.SetDataTree(2, centers);
            //DA.SetData(3, msg);
        }
        /// <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_GeometricGoo shape    = null;
            int            num        = -1;
            int            ite        = -1;
            List <Point3d> attractors = new List <Point3d>();
            List <double>  radiuses   = new List <double>();
            List <double>  weights    = new List <double>();

            if (!DA.GetData <IGH_GeometricGoo>(0, ref shape))
            {
                return;
            }
            if (!DA.GetData(1, ref num))
            {
                return;
            }
            if (!DA.GetData(2, ref ite))
            {
                return;
            }
            DA.GetDataList(3, attractors);
            DA.GetDataList(4, radiuses);
            DA.GetDataList(5, weights);

            GeometryBase geo = GH_Convert.ToGeometryBase(shape);

            var points   = new Point3dList();
            var attracts = new Point3dList(attractors);
            var rnd      = new Random();

            var bbox = geo.GetBoundingBox(true);

            for (int i = 0; i < num; i++)
            {
                if (points.Count == 0)
                {
                    var rndpt = CreateRandomPoint(rnd, geo, bbox);
                    points.Add(rndpt);
                }
                else
                {
                    double  fdist = -1;
                    Point3d fpos  = new Point3d();
                    for (int t = 0; t < Math.Max(Math.Min(ite, i), 10); t++)
                    {
                        var nrndpt = CreateRandomPoint(rnd, geo, bbox);

                        double nattractdist = 1;
                        for (int n = 0; n < attracts.Count; n++)
                        {
                            var nattract = attracts[n];
                            var rad      = radiuses[Math.Min(n, radiuses.Count - 1)];
                            var pow      = weights[Math.Min(n, radiuses.Count - 1)];

                            var ntdist = Math.Pow(JellyUtility.Remap(Math.Min(nattract.DistanceTo(nrndpt), rad), 0, rad, 0, 1.0), pow);
                            nattractdist *= ntdist;
                        }

                        var nindex = points.ClosestIndex(nrndpt);
                        var npos   = points[nindex];

                        var ndist = npos.DistanceTo(nrndpt) * nattractdist;

                        if (fdist < ndist)
                        {
                            fdist = ndist;
                            fpos  = nrndpt;
                        }
                    }
                    points.Add(fpos);
                }
            }


            DA.SetDataList(0, points);
        }
예제 #30
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 boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            int zoom = -1;

            DA.GetData <int>(1, ref zoom);

            string filePath = string.Empty;

            DA.GetData <string>(2, ref filePath);
            if (!filePath.EndsWith(@"\"))
            {
                filePath = filePath + @"\";
            }

            string prefix = string.Empty;

            DA.GetData <string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;

            string mbToken = string.Empty;

            DA.GetData <string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;

            DA.GetData <bool>("Run", ref run);


            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.OGR.Ogr.RegisterAll();
            RESTful.GdalConfiguration.ConfigureGdal();


            GH_Curve  imgFrame;
            GH_String tCount;
            GH_Structure <GH_String>        fnames        = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        fvalues       = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGoo          = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <GH_String>        gtype         = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGooBuildings = new GH_Structure <IGH_GeometricGoo>();



            int tileTotalCount      = 0;
            int tileDownloadedCount = 0;

            ///Get image frame for given boundary
            if (!boundary.GetBoundingBox(true).IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                return;
            }
            BoundingBox boundaryBox = boundary.GetBoundingBox(true);

            //create cache folder for vector tiles
            string        cacheLoc       = filePath + @"HeronCache\";
            List <string> cachefilePaths = new List <string>();

            if (!Directory.Exists(cacheLoc))
            {
                Directory.CreateDirectory(cacheLoc);
            }

            //tile bounding box array
            List <Point3d> boxPtList = new List <Point3d>();


            //get the tile coordinates for all tiles within boundary
            var ranges  = Convert.GetTileRange(boundaryBox, zoom);
            var x_range = ranges.XRange;
            var y_range = ranges.YRange;

            if (x_range.Length > 100 || y_range.Length > 100)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                return;
            }

            ///cycle through tiles to get bounding box
            List <Polyline> tileExtents = new List <Polyline>();
            List <double>   tileHeight  = new List <double>();
            List <double>   tileWidth   = new List <double>();

            for (int y = (int)y_range.Min; y <= y_range.Max; y++)
            {
                for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                {
                    //add bounding box of tile to list for translation
                    Polyline tileExtent = Heron.Convert.GetTileAsPolygon(zoom, y, x);
                    tileExtents.Add(tileExtent);
                    tileWidth.Add(tileExtent[0].DistanceTo(tileExtent[1]));
                    tileHeight.Add(tileExtent[1].DistanceTo(tileExtent[2]));

                    boxPtList.AddRange(tileExtent.ToList());
                    cachefilePaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".mvt");
                    tileTotalCount = tileTotalCount + 1;
                }
            }

            tCount = new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)");

            ///bounding box of tile boundaries
            BoundingBox bboxPts = new BoundingBox(boxPtList);

            ///convert bounding box to polyline
            List <Point3d> imageCorners = bboxPts.GetCorners().ToList();

            imageCorners.Add(imageCorners[0]);
            imgFrame = new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve());

            ///tile range as string for (de)serialization of TileCacheMeta
            string tileRangeString = "Tile range for zoom " + zoom.ToString() + ": "
                                     + x_range[0].ToString() + "-"
                                     + y_range[0].ToString() + " to "
                                     + x_range[1].ToString() + "-"
                                     + y_range[1].ToString();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, tileRangeString);

            ///Query Mapbox URL
            ///download all tiles within boundary

            ///API to query
            string mbURLauth = mbURL + mbToken;

            if (run == true)
            {
                for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                    {
                        //create tileCache name
                        string tileCache    = mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".mvt";
                        string tileCacheLoc = cacheLoc + tileCache;

                        //check cache folder to see if tile image exists locally
                        if (File.Exists(tileCacheLoc))
                        {
                        }

                        else
                        {
                            string urlAuth = Heron.Convert.GetZoomURL(x, y, zoom, mbURLauth);
                            System.Net.WebClient client = new System.Net.WebClient();
                            client.DownloadFile(urlAuth, tileCacheLoc);
                            client.Dispose();

                            ///https://gdal.org/development/rfc/rfc59.1_utilities_as_a_library.html
                            ///http://osgeo-org.1560.x6.nabble.com/gdal-dev-How-to-convert-shapefile-to-geojson-using-c-bindings-td5390953.html#a5391028
                            ///ogr2ogr is slow
                            //OSGeo.GDAL.Dataset httpDS = OSGeo.GDAL.Gdal.OpenEx("MVT:"+urlAuth,4,null,null,null);
                            //var transOptions = new OSGeo.GDAL.GDALVectorTranslateOptions(new[] { "-s_srs","EPSG:3857", "-t_srs", "EPSG:4326","-skipfailures" });
                            //var transDS = OSGeo.GDAL.Gdal.wrapper_GDALVectorTranslateDestName(mvtLoc + zoom + "-" + x + "-" + y , httpDS, transOptions, null, null);
                            //httpDS.Dispose();
                            //transDS.Dispose();

                            tileDownloadedCount = tileDownloadedCount + 1;
                        }
                    }
                }
            }

            //add to tile count total
            tCount = new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, tCount.ToString());


            ///Build a VRT file
            ///https://stackoverflow.com/questions/55386597/gdal-c-sharp-wrapper-for-vrt-doesnt-write-a-vrt-file

            //string vrtFile = cacheLoc + "mapboxvector.vrt";
            //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, vrtFile);
            //var vrtOptions = new OSGeo.GDAL.GDALBuildVRTOptions(new[] { "-overwrite" });
            //var vrtDataset = OSGeo.GDAL.Gdal.wrapper_GDALBuildVRT_names(vrtFile, cachefilePaths.ToArray(), vrtOptions, null, null);
            //vrtDataset.Dispose();


            ///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);
            userSRS.SetFromUserInput("WGS84");


            OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.SetFromUserInput("EPSG:3857");

            ///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);

            //OSGeo.GDAL.Driver gdalOGR = OSGeo.GDAL.Gdal.GetDriverByName("VRT");
            //var ds = OSGeo.GDAL.Gdal.OpenEx(vrtFile, 4, ["VRT","MVT"], null, null);


            int t = 0;

            foreach (string mvtTile in cachefilePaths)// cachefilePaths)
            {
                OSGeo.OGR.Driver     drv        = OSGeo.OGR.Ogr.GetDriverByName("MVT");
                OSGeo.OGR.DataSource ds         = OSGeo.OGR.Ogr.Open("MVT:" + mvtTile, 0);
                string[]             mvtOptions = new[] { "CLIP", "NO" };
                //OSGeo.OGR.DataSource ds = drv.Open(mvtTile, 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;
                }

                ///Morph raw mapbox tile points to geolocated tile
                Vector3d  moveDir   = tileExtents[t].ElementAt(0) - new Point3d(0, 0, 0);
                Transform move      = Transform.Translation(moveDir);
                Transform scale     = Transform.Scale(Plane.WorldXY, tileWidth[t] / 4096, tileHeight[t] / 4096, 1);
                Transform scaleMove = Transform.Multiply(move, scale);

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

                    long count        = layer.GetFeatureCount(1);
                    int  featureCount = System.Convert.ToInt32(count);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Layer #" + iLayer + " " + layer.GetName() + " has " + featureCount + " features");

                    //if (layer.GetName() == "admin" || layer.GetName() == "building")
                    //{

                    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(iLayer, t));
                    }

                    ///Loop through geometry
                    OSGeo.OGR.Feature feat;

                    int m = 0;
                    ///error "Self-intersection at or near point..." when zoom gets below 12 for water
                    ///this is an issue with the way mvt simplifies geometries at lower zoom levels and is a known problem
                    ///TODO: look into how to fix invalid geom and return to the typical while loop iterating method
                    //while ((feat = layer.GetNextFeature()) != null)

                    while (true)
                    {
                        try
                        {
                            feat = layer.GetNextFeature();
                        }
                        catch
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some features had invalid geometry and were skipped.");
                            continue;
                        }

                        if (feat == null)
                        {
                            break;
                        }


                        OSGeo.OGR.Geometry geom = feat.GetGeometryRef();

                        ///reproject geometry to WGS84 and userSRS
                        ///TODO: look into using the SetCRS global variable here

                        gtype.Append(new GH_String(geom.GetGeometryName()), new GH_Path(iLayer, t, m));
                        Transform tr = scaleMove; // new Transform(1);

                        if (feat.GetGeometryRef() != null)
                        {
                            ///Convert GDAL geometries to IGH_GeometricGoo
                            foreach (IGH_GeometricGoo gMorphed in Heron.Convert.OgrGeomToGHGoo(geom, tr))
                            {
                                //gMorphed.Morph(morph);
                                gGoo.Append(gMorphed, new GH_Path(iLayer, t, m));
                            }

                            if (layer.GetName() == "building")
                            {
                                if (feat.GetFieldAsString(def.GetFieldIndex("extrude")) == "true")
                                {
                                    double unitsConversion = Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters);
                                    double height          = System.Convert.ToDouble(feat.GetFieldAsString(def.GetFieldIndex("height"))) / unitsConversion;
                                    double min_height      = System.Convert.ToDouble(feat.GetFieldAsString(def.GetFieldIndex("min_height"))) / unitsConversion;
                                    bool   underground     = System.Convert.ToBoolean(feat.GetFieldAsString(def.GetFieldIndex("underground")));

                                    if (geom.GetGeometryType() == wkbGeometryType.wkbPolygon)
                                    {
                                        Extrusion        bldg    = Heron.Convert.OgrPolygonToExtrusion(geom, tr, height, min_height, underground);
                                        IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(bldg);
                                        gGooBuildings.Append(bldgGoo, new GH_Path(iLayer, t, m));
                                    }

                                    if (geom.GetGeometryType() == wkbGeometryType.wkbMultiPolygon)
                                    {
                                        List <Extrusion> bldgs = Heron.Convert.OgrMultiPolyToExtrusions(geom, tr, height, min_height, underground);
                                        foreach (Extrusion bldg in bldgs)
                                        {
                                            IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(bldg);
                                            gGooBuildings.Append(bldgGoo, new GH_Path(iLayer, t, m));
                                        }
                                    }
                                }
                            }

                            /// Get Feature Values
                            if (fvalues.PathExists(new GH_Path(iLayer, t, m)))
                            {
                                //fvalues.get_Branch(new GH_Path(iLayer, t, m)).Clear();
                            }

                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                if (feat.IsFieldSet(iField))
                                {
                                    fvalues.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(iLayer, t, m));
                                }
                                else
                                {
                                    fvalues.Append(new GH_String("null"), new GH_Path(iLayer, t, m));
                                }
                            }
                        }
                        m++;
                        geom.Dispose();
                        feat.Dispose();
                    }///end while loop through features

                    //}///end layer by name

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

                ds.Dispose();
                t++;
            }///end loop through mvt tiles

            //write out new tile range metadata for serialization
            TileCacheMeta = tileRangeString;



            DA.SetData(0, imgFrame);
            DA.SetDataTree(1, fnames);
            DA.SetDataTree(2, fvalues);
            DA.SetDataTree(3, gGoo);
            DA.SetDataList(4, "copyright Mapbox");
            DA.SetDataTree(5, gtype);
            DA.SetDataTree(6, gGooBuildings);
            DA.SetDataList(7, tileExtents);
        }