Ejemplo n.º 1
0
        private static void closeIntersect(Curve innerBounderyCrv, PointCloud startPTsLeft, List <Parkingspace> finalParkingLinesLeft, Point3d crvEnd, out Curve lineOne, out CurveIntersections intersectionsOne)
        {
            int indexOne = startPTsLeft.ClosestPoint(crvEnd);

            lineOne = finalParkingLinesLeft[indexOne].Curves;

            Vector3d vectorone = lineOne.TangentAtEnd;

            vectorone.Rotate(RhinoMath.ToRadians(90), new Vector3d(0, 0, 1));
            Point3d movedPTone = lineOne.PointAtStart + vectorone;

            vectorone.Rotate(RhinoMath.ToRadians(180), new Vector3d(0, 0, 1));
            Point3d    movedPTTwo  = lineOne.PointAtStart + vectorone;
            PointCloud directionPT = new PointCloud();

            directionPT.Add(movedPTone);
            directionPT.Add(movedPTTwo);

            int indexdir = directionPT.ClosestPoint(crvEnd);

            if (indexdir == 0)
            {
                vectorone.Rotate(RhinoMath.ToRadians(180), new Vector3d(0, 0, 1));
            }
            vectorone        = Vector3d.Multiply(vectorone, 10);
            intersectionsOne = Intersection.CurveCurve(innerBounderyCrv, new Line(lineOne.PointAtEnd, vectorone).ToNurbsCurve(), 0.01, 0.01);
        }
Ejemplo n.º 2
0
        public GH_GetterResult LoadFromSelection(out PointCloud pc)
        {
            var go = new GetObject();

            go.GeometryFilter = Rhino.DocObjects.ObjectType.Point | Rhino.DocObjects.ObjectType.PointSet;
            if (go.GetMultiple(1, 0) == Rhino.Input.GetResult.Cancel)
            {
                pc = null;
                return(GH_GetterResult.cancel);
            }
            pc = new PointCloud();

            for (int i = 0; i < go.ObjectCount; i++)
            {
                var obj   = go.Object(i);
                var rhObj = obj.Object();
                if (rhObj.ObjectType == ObjectType.Point)
                {
                    var pt  = obj.Point().Location;
                    var col = rhObj.Attributes.ObjectColor;
                    pc.Add(pt, col);
                }
                else if (rhObj.ObjectType == ObjectType.PointSet)
                {
                    using (PointCloud cloud = obj.PointCloud())
                    {
                        foreach (var item in cloud.AsEnumerable())
                        {
                            pc.Add(item.Location, item.Normal, item.Color);
                        }
                    }
                }
            }
            return(GH_GetterResult.success);
        }
Ejemplo n.º 3
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 <Line> lines = new List <Line>();

            DA.GetDataList(0, lines);

            PointCloud              cloud    = new PointCloud();
            List <IElement>         elements = new List <IElement>();
            List <ITopologicVertex> vertices = new List <ITopologicVertex>();

            foreach (Line ln in lines)
            {
                Point3d p1 = ln.From;
                Point3d p2 = ln.To;

                int idx1 = cloud.ClosestPoint(p1);
                if (idx1 == -1)
                {
                    cloud.Add(p1);
                    idx1 = 1;
                    vertices.Add(new ITopologicVertex(p1.X, p1.Y, p1.Z, idx1));
                }
                else
                {
                    if (p1.DistanceTo(cloud[idx1].Location) > 0.01)
                    {
                        cloud.Add(p1);
                        idx1 = cloud.Count;
                        vertices.Add(new ITopologicVertex(p1.X, p1.Y, p1.Z, idx1));
                    }
                    else
                    {
                        idx1++;
                    }
                }

                int idx2 = cloud.ClosestPoint(p2);
                if (p2.DistanceTo(cloud[idx2].Location) > 0.01)
                {
                    cloud.Add(p2);
                    idx2 = cloud.Count;
                    vertices.Add(new ITopologicVertex(p2.X, p2.Y, p2.Z, idx2));
                }
                else
                {
                    idx2++;
                }

                elements.Add(new IBarElement(idx1, idx2));
            }

            IMesh mesh = new IMesh();

            mesh.AddRangeVertices(vertices);
            mesh.AddRangeElements(elements);
            mesh.BuildTopology();

            DA.SetData(0, mesh);
        }
Ejemplo n.º 4
0
        protected override void SandwormSolveInstance(IGH_DataAccess DA)
        {
            SetupLogging();
            DA.GetData(0, ref _showPixelColor);
            DA.GetData(1, ref _writeOutPoints);
            DA.GetData(2, ref _pixelSize);
            GetSandwormOptions(DA, 5, 3, 4);
            SetupKinect();

            var depthFrameDataInt      = new int[trimmedWidth * trimmedHeight];
            var averagedDepthFrameData = new double[trimmedWidth * trimmedHeight];

            // Initialize outputs
            if (keepFrames <= 1 || _outputPoints == null)
            {
                // Don't replace prior frames (by clearing array) if using keepFrames
                _outputPoints = new List <Point3d>();
            }

            SetupRenderBuffer(depthFrameDataInt, null);
            Core.LogTiming(ref output, timer, "Initial setup"); // Debug Info

            AverageAndBlurPixels(depthFrameDataInt, ref averagedDepthFrameData);

            GeneratePointCloud(averagedDepthFrameData);

            // Assign colors and pixels to the point cloud
            _pointCloud = new PointCloud(); // TODO intelligently manipulate the point cloud
            // TODO: actually color pixels by their RGB values and/or using analytic methods
            if (allPoints.Length > 0)
            {
                for (int i = 0; i < allPoints.Length; i++) // allPoints.Length
                {
                    if (_showPixelColor)
                    {
                        _pointCloud.Add(allPoints[i], Color.Aqua);
                    }
                    else
                    {
                        _pointCloud.Add(allPoints[i]);
                    }
                }
                Core.LogTiming(ref output, timer, "Point cloud construction"); // Debug Info
            }

            //DA.SetDataList(0, ); // TODO: pointcloud output
            if (_writeOutPoints)
            {
                // Cast to GH_Point for performance reasons
                DA.SetDataList(0, allPoints.Select(x => new GH_Point(x)));
            }
            DA.SetDataList(1, output); // For logging/debugging
            ScheduleSolve();
        }
Ejemplo n.º 5
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var hasNotBeenInitialized = _receiveThread == null;

            if (hasNotBeenInitialized)
            {
                StartReceiver();
            }

            if (_receivedData == null)
            {
                return;
            }

            while (!_receivedData.LidarPointCloud.IsEmpty)
            {
                if (_receivedData.LidarPointCloud.TryDequeue(out var item))
                {
                    _pc.Add(item.Item1, item.Item2);
                }
            }

            DA.SetData(0, _pc);
            DA.SetDataList(1, _receivedData.ReceivedPlanes.Values);
            DA.SetDataList(2, _receivedData.ReceivedBodies.Values);
            DA.SetDataList(3, _receivedData.ReceivedMeshes.Values);
        }
Ejemplo n.º 6
0
        public static void ConvertFunc(out HImage image, string currFile)
        {
            if (string.IsNullOrEmpty(currFile))
            {
                image = null;
                return;
            }
            PointCloud thePoints = new PointCloud();
            FileInfo   fileInfo  = new FileInfo(currFile);
            long       fileSize  = fileInfo.Length;

            thePoints.SetCapacity((int)(fileSize / 26));
            int Width, Height;

            using (StreamReader sr = new StreamReader(currFile))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    thePoints.Add(Point3d.ParseFromString(line));
                }
            }
            HalExtention.ConverToCogRangeP(thePoints, 0.0057245f, 0.03f, thePoints.minZ - 0.1f, thePoints.maxZ - 0.1f, out image);
            image.GetImageSize(out Width, out Height);
            int _Height = (int)(Height * 0.03f / 0.0057245f);

            //int _Height = (int)(Height * 0.04f / 0.0055f);
            image = image.ZoomImageSize(Width, _Height, "constant");
        }
        public Line Direction(bool flip, double inflate, List <GH_Curve> curves, double rotateX, double rotateY)
        {
            _pointCloud = new PointCloud();
            _polylines  = new List <Polyline>();

            foreach (var c in curves)
            {
                Polyline polyline;
                c.Value.TryGetPolyline(out polyline);
                _polylines.Add(polyline);
                _pointCloud.Add(c.Value.PointAt(0.0));
            }

            //Get boudingbox and inflate it
            BoundingBox boundingBox = _pointCloud.GetBoundingBox(false);

            boundingBox.Inflate(inflate);

            //Get box center/top points and make line
            Line line = new Line(boundingBox.PointAt(0.5, 0.5, 0), boundingBox.PointAt(0.5, 0.5, 1));

            if (!flip)
            {
                line.Flip();
            }

            //Rotate line around center
            line.Transform(Rhino.Geometry.Transform.Rotation(Rhino.RhinoMath.ToRadians(rotateX), Vector3d.XAxis, line.PointAt(0.5)));
            line.Transform(Rhino.Geometry.Transform.Rotation(Rhino.RhinoMath.ToRadians(rotateY), Vector3d.ZAxis, line.PointAt(0.5)));

            return(line);
        }
Ejemplo n.º 8
0
        private SimpleGraph <Point3d> BuildGraph(List <Polyline> Polylines)
        {
            List <Polyline> .Enumerator enumerator = new List <Polyline> .Enumerator();

            SimpleGraph <Point3d> simpleGraph = new SimpleGraph <Point3d>(null);
            PointCloud            pointCloud  = new PointCloud();

            pointCloud.Add(Polylines[0][0]);
            simpleGraph.AddVertex(Polylines[0][0]);
            int num = 0;

            try {
                enumerator = Polylines.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    Polyline  current  = enumerator.Current;
                    GraphEdge count    = new GraphEdge();
                    int       num1     = pointCloud.ClosestPoint(current[0]);
                    Point3d   location = pointCloud[num1].Location;
                    double    num2     = location.DistanceTo(current[0]);
                    count.From = num1;
                    if (num2 > Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance)
                    {
                        pointCloud.Add(current[0]);
                        simpleGraph.AddVertex(current[0]);
                        count.From = checked (simpleGraph.Count - 1);
                    }
                    num1     = pointCloud.ClosestPoint(current[checked (current.Count - 1)]);
                    count.To = num1;
                    if (pointCloud[num1].Location.DistanceTo(current[checked (current.Count - 1)]) > Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance)
                    {
                        pointCloud.Add(current[checked (current.Count - 1)]);
                        simpleGraph.AddVertex(current[checked (current.Count - 1)]);
                        count.To = checked (simpleGraph.Count - 1);
                    }
                    count.Orient();
                    this.SrtThick[count] = this.Thickness[num];
                    this.SrtFaces[count] = this.FacesCounts[num];
                    simpleGraph.Edges.Add(count);
                    num = checked (num + 1);
                }
            } finally {
                ((IDisposable)enumerator).Dispose();
            }
            return(simpleGraph);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Culls the PFVertex duplicates based on their position in 3d space
        /// MAKE SURE TO REMOVE also the corresponding edges
        /// </summary>
        /// <param name="pottentialDuplicates"></param>
        /// <param name="tollerance"></param>
        /// <returns></returns>
        public static IList <PFVertex> RemoveDuplicates(IList <PFVertex> pottentialDuplicates, double tollerance)
        {
            PointCloud      pc        = new PointCloud();
            List <PFVertex> singulars = new List <PFVertex>();

            pc.Add(pottentialDuplicates[0].Point);
            singulars.Add(pottentialDuplicates[0]);
            for (int p = 1; p < pottentialDuplicates.Count; p++)
            {
                int closeIndex = pc.ClosestPoint(pottentialDuplicates[p].Point);
                if (pottentialDuplicates[p].Point.DistanceTo(pc[closeIndex].Location) > tollerance)
                {
                    pc.Add(pottentialDuplicates[p].Point);
                    singulars.Add(pottentialDuplicates[p]);
                }
            }

            return(singulars);
        }
Ejemplo n.º 10
0
    public void Run(int numPoints, float scale, float[] passes)
    {
        startTime = Time.realtimeSinceStartup;

        mesh = meshFilter.mesh;
        //generate a sphere of points for testing purposes

        cloud = new PointCloud <PointNormal>(mesh.vertexCount);
        //cloud = new PointCloud<PointNormal>(numPoints);
        var vertices = mesh.vertices;
        var normals  = mesh.normals;

        for (int i = 0; i < mesh.vertexCount; i++)
        {
            Vector3 v = vertices[i];
            Vector3 n = normals[i];
            cloud.Add(new PointNormal(v.x, v.y, v.z, n.x, n.y, n.z));
        }

        //for (int i = 0; i < numPoints; i++) {
        //	var normal = new Vector3(UnityEngine.Random.value - 0.5f, UnityEngine.Random.value - 0.5f, UnityEngine.Random.value - 0.5f).normalized;
        //	var point = normal * scale;
        //	cloud.Add(new PointNormal(point.x, point.y, point.z, normal.x, normal.y, normal.z));
        //}

        float initTime = (Time.realtimeSinceStartup - startTime);

        Debug.Log("Point Cloud loaded in: " + initTime + "s");
        startTime = Time.realtimeSinceStartup;

        GetComponent <VoxelRenderer>().SetFromPointCloud(cloud);

        float voxTime = (Time.realtimeSinceStartup - startTime);

        Debug.Log("Renderer initialized in: " + voxTime + "s");
        startTime = Time.realtimeSinceStartup;

        RunBallPivot(passes);
        float triangTime = (Time.realtimeSinceStartup - startTime);

        Debug.Log("Triangulation completed in: " + triangTime + "s");
        Debug.Log("Total Searches: " + pivoter.totalSearches);

        startTime = Time.realtimeSinceStartup;
        MakeMesh();
        float meshTime = Time.realtimeSinceStartup - startTime;

        Debug.Log("Mesh created in: " + meshTime + "s");
        Debug.Log("Tris:" + preMesh.Count);

        text.text = "Point Cloud initialized in: " + initTime + "s\n" +
                    "Triangulation completed in: " + triangTime + "s\n" +
                    "Mesh created in: " + meshTime + "s";
    }
Ejemplo n.º 11
0
        PointCloud PopulatePointCloud(Mesh M)
        {
            PointCloud mP = new PointCloud();

            for (int i = 0; i < M.Vertices.Count; i++)
            {
                mP.Add(M.Vertices[i], M.Normals[i]);
            }

            return(mP);
        }
Ejemplo n.º 12
0
    /// <summary>
    /// This procedure contains the user code. Input parameters are provided as regular arguments,
    /// Output parameters as ref arguments. You don't have to assign output parameters,
    /// they will have a default value.
    /// </summary>
    private void RunScript(List <System.Object> P, List <System.Object> C, int W)
    {
        _cloud = new PointCloud();
        _width = W;

        for (int i = 0; i < P.Count; i++)
        {
            _cloud.Add((Point3d)P[i], (Color)C[i]);
        }

        _clip = _cloud.GetBoundingBox(false);
    }
Ejemplo n.º 13
0
        public Tuple <int, int> ClosestCoords(Point3d point)
        {
            PointCloud pointCloud = new PointCloud();

            for (int y = 0; y < yLen; y++)
            {
                for (int x = 0; x < xLen; x++)
                {
                    pointCloud.Add(Points[x, y]);
                }
            }

            int i = pointCloud.ClosestPoint(point);

            return(Tuple.Create(i % xLen, i / xLen));
        }
Ejemplo n.º 14
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            if (RFContext.Clip)
            {
                int    N        = RFContext.Cloud.Count;
                bool[] included = new bool[N];

                for (int i = 0; i < N; ++i)
                {
                    if (RFContext.ClippingBox.Contains(RFContext.Cloud[i].Location))
                    {
                        included[i] = true;
                    }
                }


                PointCloud pc = new PointCloud();

                for (int i = 0; i < N; ++i)
                {
                    if (included[i])
                    {
                        pc.Add(
                            RFContext.Cloud[i].Location,
                            RFContext.Cloud[i].Normal,
                            RFContext.Cloud[i].Color);
                    }
                }

                doc.Objects.AddPointCloud(pc);
            }
            else
            {
                doc.Objects.AddPointCloud(RFContext.Cloud);
            }

            Polyline poly = new Polyline(new Point3d[] {
                new Point3d(0, 0, 0), new Point3d(120, 0, 0),
                new Point3d(0, 100, 0), new Point3d(0, 0, 0)
            });

            poly.Transform(RFContext.Xform);
            doc.Objects.AddPolyline(poly);

            RFContext.ClearCloud();
            return(Result.Success);
        }
Ejemplo n.º 15
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.GetData("Enabled", ref m_display_enabled);

            if (m_display_enabled)
            {
                int         N = 0;
                List <Mesh> m_input_meshes = new List <Mesh>();
                DA.GetDataList("Mesh", m_input_meshes);

                Mesh m_mesh = new Mesh();
                for (int i = 0; i < m_input_meshes.Count; ++i)
                {
                    m_mesh.Append(m_input_meshes[i]);
                }

                DA.GetData("Samples", ref N);

                BoundingBox bb      = m_mesh.GetBoundingBox(true);
                Plane       m_plane = Plane.WorldXY;
                m_plane.Origin = new Point3d(bb.Min.X, bb.Min.Y, bb.Max.Z + 10.0);
                Rectangle3d rec = new Rectangle3d(m_plane, bb.Max.X - bb.Min.X, bb.Max.Y - bb.Min.Y);

                Random rnd      = new Random();
                double hrecW    = rec.Width / 2;
                double hrecH    = rec.Height / 2;
                double hit_dist = 0;

                m_cloud = new PointCloud();

                for (int i = 0; i < N; ++i)
                {
                    Ray3d ray = new Ray3d(new Point3d(
                                              rec.Center.X - hrecW + rnd.NextDouble() * rec.Width,
                                              rec.Center.Y - hrecH + rnd.NextDouble() * rec.Height,
                                              rec.Center.Z),
                                          -Vector3d.ZAxis);

                    hit_dist = Rhino.Geometry.Intersect.Intersection.MeshRay(m_mesh, ray);
                    if (hit_dist > 0)
                    {
                        m_cloud.Add(ray.Position + ray.Direction * hit_dist);
                    }
                }
            }
        }
Ejemplo n.º 16
0
            private PointCloud <PointXYZRGB> ReadData(byte[] byteArray)
            {
                PointCloud <PointXYZRGB> cloud = new PointCloud <PointXYZRGB> ();

                for (int i = 0; i < _width * _height; i++)
                {
                    float x   = System.BitConverter.ToSingle(_data, i * (int)_point_step + 0);
                    float y   = System.BitConverter.ToSingle(_data, i * (int)_point_step + 4);
                    float z   = System.BitConverter.ToSingle(_data, i * (int)_point_step + 8);
                    float rgb = System.BitConverter.ToSingle(_data, i * (int)_point_step + 16);
                    if (!float.IsNaN(x + y + z))
                    {
                        PointXYZRGB p = new PointXYZRGB(x, y, z, rgb);
                        cloud.Add(p);
                    }
                }
                return(cloud);
            }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            Random r     = new Random(13);
            var    plcnt = 1000000;
            var    edge  = 10;

            GetNumber gn = new GetNumber();

            gn.SetCommandPrompt("How many pointsies");
            gn.SetDefaultInteger(plcnt);
            gn.SetUpperLimit(500000001, true);
            gn.SetLowerLimit(1, true);
            gn.AcceptNothing(true);

            var gnrc = gn.Get();

            if (gnrc == GetResult.Nothing || gnrc == GetResult.Number)
            {
                var nr = (int)gn.Number();
                if (nr > 500000000)
                {
                    RhinoApp.WriteLine("More than 500.000.000 points");
                    return(Result.Cancel);
                }
                pc = new PointCloud();
                for (int i = 0; i < nr; i++)
                {
                    var d = (double)i;
                    pc.Add(
                        new Point3d(r.NextDouble() * edge, r.NextDouble() * edge, r.NextDouble() * edge),
                        System.Drawing.Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255))
                        );
                }
                cnd.ThePc   = pc;
                cnd.Enabled = true;
            }

            doc.Views.Redraw();


            return(Result.Success);
        }
Ejemplo n.º 18
0
            public static int[] CreateUnderlyingLinesFromCurve(Curve crv, double size, bool synchronize = false)
            {
                Polyline poly;

                crv.TryGetPolyline(out poly);

                List <int> ptsTags  = new List <int>();
                PointCloud ptsCloud = new PointCloud();
                int        tag;
                Point3d    p;

                int[] tempTags = new int[poly.Count];
                int   idx;

                for (int i = 0; i < poly.Count; i++)
                {
                    p   = poly[i];
                    idx = EvaluatePoint(ptsCloud, p, 0.001);

                    if (idx == -1)
                    {
                        tag = IBuilder.AddPoint(p.X, p.Y, p.Z, size);
                        ptsTags.Add(tag);
                        ptsCloud.Add(p);
                        idx = ptsCloud.Count - 1;
                    }

                    tempTags[i] = idx;
                }

                int[] dimTags = new int[poly.SegmentCount];
                for (int i = 0; i < poly.SegmentCount; i++)
                {
                    dimTags[i] = IBuilder.AddLine(ptsTags[tempTags[i]], ptsTags[tempTags[i + 1]]);
                }

                if (synchronize)
                {
                    IBuilder.Synchronize();
                }
                return(dimTags);
            }
Ejemplo n.º 19
0
        public List <Tuple <int, double, double, double, byte, byte, byte> > VoxelizeMesh(Mesh M, Color MC, int M_ID, Vector3d Vsize, int CO, ref PointCloud VPC)
        {
            //{ID,X,Y,Z,R,G,B}
            BoundingBox RBBox = M.GetBoundingBox(false);
            //bounding box in R3 (real numbers)
            BoundingBox ZBBox = RBBox_to_ZBBox(RBBox, Vsize);
            //boudning box in Z3 (integer numbers) (note that they are again embedded in R3 for visualization)

            List <Point3d> gridpoints = BBoxToVoxels(ZBBox, Vsize);

            List <Point3d> Mesh_NearPoints = NearPoints(gridpoints, M, Vsize.Length / 2);
            //A = Mesh_NearPoints
            List <Tuple <int, double, double, double, byte, byte, byte> > Voxels = new List <Tuple <int, double, double, double, byte, byte, byte> >();

            //{ID,X,Y,Z,R,G,B}

            Line[] Intarget = null;
            //int[] Facets = null;
            // for each potential voxel check if it has to be included in the raster
            foreach (Point3d gp in Mesh_NearPoints)
            {
                if (CO == 26)
                {
                    Intarget = MeshTarget26_Connected(gp, Vsize);
                }
                else if (CO == 6)
                {
                    Intarget = MeshTarget06_Connected(gp, Vsize);
                }
                else
                {
                    RhinoApp.WriteLine("connectivity target undefined!");
                }
                //Line[] Intersections = Array.FindAll(Intarget, lambda => MeshLineIntersect(M, lambda));
                if (Array.Exists(Intarget, lambda => MeshLineIntersect(M, lambda)))
                {
                    Voxels.Add(Tuple.Create(M_ID, gp.X, gp.Y, gp.Z, MC.R, MC.G, MC.B));
                    VPC.Add(gp, MC);
                }
            }
            return(Voxels);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Blend colors in a point cloud with a list of colors same amount as amount of points) or one color.
        /// </summary>
        /// <param name="cloud"></param>
        /// <param name="color"></param>
        /// <param name="pct"></param>
        /// <returns></returns>
        public static PointCloud BlendColors(PointCloud cloud, List <Color> color, Double pct)
        {
            PointCloud newCloud = new PointCloud(cloud);


            //Create Partitions for multithreading.
            var rangePartitioner = System.Collections.Concurrent.Partitioner.Create(0, newCloud.Count, (int)Math.Ceiling(newCloud.Count / (double)Environment.ProcessorCount));

            List <PointCloud> subclouds = new List <PointCloud>();

            //Run MultiThreaded Loop.
            System.Threading.Tasks.Parallel.ForEach(rangePartitioner, (rng, loopState) =>
            {
                PointCloud subCloud = new PointCloud();
                for (int j = rng.Item1; j < rng.Item2; j++)
                {
                    Color Ptcolor  = newCloud[j].Color;
                    Color newColor = new Color();
                    if (color.Count == 1)
                    {
                        newColor = Blend(Ptcolor, color[0], pct);
                    }
                    else
                    {
                        newColor = Blend(Ptcolor, color[j], pct);
                    }

                    subCloud.Add(newCloud[j].Location, newColor);
                }
                subclouds.Add(subCloud);
            }

                                                    );

            PointCloud mergeCloud = new PointCloud();

            for (int i = 0; i < subclouds.Count; i++)
            {
                mergeCloud.Merge(subclouds[i]);
            }
            return(mergeCloud);
        }
Ejemplo n.º 21
0
    private PointCloud <PointXYZRGBAIntensity> ReadDataRGBAIntensity(byte[] byteArray)
    {
        PointCloud <PointXYZRGBAIntensity> cloud = new PointCloud <PointXYZRGBAIntensity> ();

        //int temp = byteArray.Length / (int)_point_step;
        for (int i = 0; i < _width * _height; i++)
        {
            float x         = System.BitConverter.ToSingle(_data, i * (int)_point_step + 0);
            float y         = System.BitConverter.ToSingle(_data, i * (int)_point_step + 4);
            float z         = System.BitConverter.ToSingle(_data, i * (int)_point_step + 8);
            uint  rgba      = System.BitConverter.ToUInt32(_data, i * (int)_point_step + 12);
            float intensity = System.BitConverter.ToSingle(_data, i * (int)_point_step + 12);
            if (!(float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z)))
            {
                PointXYZRGBAIntensity p = new PointXYZRGBAIntensity(x, y, z, rgba, intensity);
                cloud.Add(p);
            }
        }
        return(cloud);
    }
Ejemplo n.º 22
0
    public void RunInUpdate(bool fromShape, PointMeshType shape, int pivotsPerUpdate, int pivotAnimationSteps, int numPoints, float scale, float radius)
    {
        this.pivotsPerUpdate     = pivotsPerUpdate;
        this.pivotAnimationSteps = pivotAnimationSteps;
        running    = true;
        ballRadius = radius;
        mesh       = meshFilter.mesh;
        ball.transform.localScale = new Vector3(radius * 2, radius * 2, radius * 2);
        //generate a sphere of points for testing purposes

        if (fromShape)
        {
            cloud = new PointCloud <PointNormal>(numPoints);

            if (shape == PointMeshType.Sphere)
            {
                for (int i = 0; i < numPoints; i++)
                {
                    var normal = new Vector3(UnityEngine.Random.value - 0.5f, UnityEngine.Random.value - 0.5f, UnityEngine.Random.value - 0.5f).normalized;
                    var point  = normal * scale;
                    cloud.Add(new PointNormal(point.x, point.y, point.z, normal.x, normal.y, normal.z));
                }
            }
        }
        else
        {
            cloud = new PointCloud <PointNormal>(mesh.vertexCount);
            var vertices = mesh.vertices;
            var normals  = mesh.normals;
            for (int i = 0; i < mesh.vertexCount; i++)
            {
                Vector3 v = vertices[i];
                Vector3 n = normals[i];
                cloud.Add(new PointNormal(v.x, v.y, v.z, n.x, n.y, n.z));
            }
        }

        GetComponent <VoxelRenderer>().SetFromPointCloud(cloud);
        pivoter = new Pivoter(cloud, ballRadius);
        f       = new Front();
    }
Ejemplo n.º 23
0
        void AddXYBPointToCloud(ref PointCloud pc, ref System.IO.BinaryReader reader)
        {
            double x, y, z;

            x = reader.ReadDouble() * this.scale;
            y = reader.ReadDouble() * this.scale;
            z = reader.ReadDouble() * this.scale;
            ushort i = reader.ReadUInt16();

            pc.Add(new Point3d(x, y, z));
            System.Drawing.Color col = System.Drawing.Color.FromArgb(UInt16toColor(i));

            pc[pc.Count - 1].Color = col;

            for (int j = 0; j < resolution - 1; ++j)
            {
                x = reader.ReadDouble() * this.scale;
                y = reader.ReadDouble() * this.scale;
                z = reader.ReadDouble() * this.scale;
                i = reader.ReadUInt16();
            }
        }
Ejemplo n.º 24
0
        public static Polyline GetAxis(IEnumerable <Polyline> regions, Polyline boundary)
        {
            var lines = regions.SelectMany(e => e.GetSegments());
            var pc    = new PointCloud(boundary.GetSegments().Select(l => l.PointAt(0.5)));

            var edges         = lines.Select(l => (Line: l, Center: l.PointAt(0.5)));
            var interiorEdges = edges.Where(e => !Exists(e.Center, pc));
            var interiorLines = new List <Line>();

            foreach (var edge in interiorEdges)
            {
                if (Exists(edge.Center, pc))
                {
                    continue;
                }

                pc.Add(edge.Center);
                interiorLines.Add(edge.Line);
            }

            return(GetAxis(interiorLines));
        }
    private PointCloud <PointXYZIntensity> ReadData(byte[] byteArray)
    {
        PointCloud <PointXYZIntensity> cloud = new PointCloud <PointXYZIntensity> ();
        int temp = byteArray.Length / (int)_point_step;

        for (int i = 0; i < _width * _height; i++)
        {
            float x         = System.BitConverter.ToSingle(_data, i * (int)_point_step + 0);
            float y         = System.BitConverter.ToSingle(_data, i * (int)_point_step + 4);
            float z         = System.BitConverter.ToSingle(_data, i * (int)_point_step + 8);
            float intensity = System.BitConverter.ToSingle(_data, i * (int)_point_step + 12);
            if (!(float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z) || float.IsNaN(intensity)))
            {
                PointXYZIntensity p = new PointXYZIntensity(x, y, z, intensity);
                //Debug.Log(x + ", " + y + ", " + z);
                cloud.Add(p);
            }
            //Debug.Log(i + "/" + _width * _height + ", " + temp);
        }
        //Debug.Log("Done1");
        return(cloud);
    }
Ejemplo n.º 26
0
            public static int[] CreateUnderlyingLinesFromPolyline(Polyline poly, double size, ref List <int> ptsTags, ref PointCloud ptsCloud, double t = 0.001, bool synchronize = false)
            {
                Point3d p;
                int     tag;

                int[] crvTags = new int[poly.SegmentCount];

                int[] tempTags = new int[poly.Count];
                int   idx;

                for (int j = 0; j < poly.Count; j++)
                {
                    p   = poly[j];
                    idx = EvaluatePoint(ptsCloud, p, t);

                    if (idx == -1)
                    {
                        tag = IBuilder.AddPoint(p.X, p.Y, p.Z, size);
                        ptsTags.Add(tag);
                        ptsCloud.Add(p);
                        idx = ptsCloud.Count - 1;
                    }

                    tempTags[j] = idx;
                }

                for (int j = 0; j < poly.SegmentCount; j++)
                {
                    crvTags[j] = IBuilder.AddLine(ptsTags[tempTags[j]], ptsTags[tempTags[j + 1]]);
                }

                if (synchronize)
                {
                    IBuilder.Synchronize();
                }

                return(crvTags);
            }
Ejemplo n.º 27
0
            public static int[] CreateUnderlyingSplinesFromCurve(Curve crv, double size, bool synchronize = false)
            {
                // Covert curve into polycurve
                PolyCurve pc = crv.ToArcsAndLines(Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, Rhino.RhinoDoc.ActiveDoc.ModelAngleToleranceRadians, 0, 1);

                // Divide points into 4 groups and create splines
                int remain = pc.SegmentCount % 4;
                int count  = (pc.SegmentCount - remain) / 4;

                int[] dimTags = new int[4];

                int        sIdx = 0, pIdx, tag;
                PointCloud ptsCloud = new PointCloud();
                List <int> allTags  = new List <int>();
                Point3d    p;

                for (int i = 0; i < 4; i++)
                {
                    if (i == 3)
                    {
                        count += remain;
                    }
                    int[] ptTags = new int[count + 1];

                    for (int j = 0; j < count; j++)
                    {
                        p    = pc.SegmentCurve(sIdx).PointAtStart;
                        pIdx = EvaluatePoint(ptsCloud, p, 0.0001);

                        if (pIdx == -1)
                        {
                            tag = IBuilder.AddPoint(p.X, p.Y, p.Z, size);
                            ptsCloud.Add(p);
                            allTags.Add(tag);
                        }
                        else
                        {
                            tag = allTags[pIdx];
                        }

                        ptTags[j] = tag;

                        if (j == count - 1)
                        {
                            p    = pc.SegmentCurve(sIdx).PointAtEnd;
                            pIdx = EvaluatePoint(ptsCloud, p, 0.001);

                            if (pIdx == -1)
                            {
                                tag = IBuilder.AddPoint(p.X, p.Y, p.Z, size);
                                ptsCloud.Add(p);
                                allTags.Add(tag);
                            }
                            else
                            {
                                tag = allTags[pIdx];
                            }

                            ptTags[j + 1] = tag;
                        }
                        sIdx++;
                    }

                    dimTags[i] = IBuilder.AddSpline(ptTags);
                }

                if (synchronize)
                {
                    IBuilder.Synchronize();
                }

                return(dimTags);
            }
Ejemplo n.º 28
0
        public static Polyline GetAxis(IEnumerable <Line> lines)
        {
            var allPoints = lines.SelectMany(l => new Point3d[] { l.From, l.To });
            var pc        = new PointCloud();

            foreach (var point in allPoints)
            {
                if (Exists(point, pc))
                {
                    continue;
                }
                pc.Add(point);
            }

            var nodes = new List <List <Edge> >(Enumerable.Repeat(new List <Edge>(), pc.Count));

            var edges = lines.Select(l =>
            {
                var edge = new Edge()
                {
                    Start = pc.ClosestPoint(l.From), End = pc.ClosestPoint(l.To), Line = l, Enabled = true
                };
                nodes[edge.Start].Add(edge);
                nodes[edge.End].Add(edge);
                return(edge);
            }).ToList();

            while (true)
            {
                var toDisable = new List <Edge>();

                for (int i = 0; i < nodes.Count; i++)
                {
                    var node    = nodes[i];
                    int valence = node.Count(e => e.Enabled);

                    if (valence == 1)
                    {
                        var edge = node.First(e => e.Enabled);
                        var j    = edge.Start == i ? edge.End : edge.Start;

                        int otherValence = nodes[j].Count(e => e.Enabled);
                        if (otherValence >= 3)
                        {
                            toDisable.Add(edge);
                        }
                    }
                }

                if (toDisable.Count == 0)
                {
                    break;
                }

                foreach (var edge in toDisable)
                {
                    edge.Enabled = false;
                }
            }

            var axes = edges
                       .Where(e => e.Enabled)
                       .Select(e => e.Line.ToNurbsCurve());

            var      curve = Curve.JoinCurves(axes);
            Polyline pl    = new Polyline();

            if (curve.Length > 0)
            {
                curve[0].TryGetPolyline(out pl);
            }
            else
            {
                Line   maxLine   = Line.Unset;
                double maxLength = 0;

                foreach (var line in lines)
                {
                    double length = line.Direction.SquareLength;
                    if (length > maxLength)
                    {
                        maxLength = length;
                        maxLine   = line;
                    }
                }

                pl = new Polyline(new Point3d[] { maxLine.From, maxLine.To });
            }

            return(pl);
        }
Ejemplo n.º 29
0
        private static NGonsCore.Graphs.UndirectedGraph LinesToUndirectedGrap(List <Line> lines)
        {
            List <Point3d> pts = new List <Point3d>();

            foreach (Line l in lines)
            {
                pts.Add(l.From);
                pts.Add(l.To);
            }

            //Sorting
            var edges = new List <int>();

            var allPoints = new List <Point3d>(pts); //naked points

            int i = 0;

            while (allPoints.Count != 0)
            {
                Point3d pt = allPoints[0];
                allPoints.RemoveAt(0);


                for (int d = 0; d < pts.Count; d++)
                {
                    if (pt.Equals(pts[d]))
                    {
                        edges.Add(d);
                        break;
                    }
                }

                i++;
            }

            var uniqueVertices = new HashSet <int>(edges).ToList();

            //Creating typological points
            var topologyPoints = new PointCloud();

            foreach (int k in uniqueVertices)
            {
                topologyPoints.Add(pts[k]);
            }

            //var vertices = Enumerable.Range(0, uniqueVertices.Count);

            for (int k = 0; k < uniqueVertices.Count; k++)
            {
                if (uniqueVertices.ElementAt(k) != k)
                {
                    for (int l = 0; l < edges.Count; l++)
                    {
                        if (edges[l] == uniqueVertices[k])
                        {
                            edges[l] = k;
                        }
                    }
                }
            }

            //Create graph
            NGonsCore.Graphs.UndirectedGraph g = new NGonsCore.Graphs.UndirectedGraph(uniqueVertices.Count);

            for (int k = 0; k < uniqueVertices.Count; k++)
            {
                g.InsertVertex(k.ToString());
            }


            for (int k = 0; k < edges.Count; k += 2)
            {
                g.InsertEdge(edges[k].ToString(), edges[k + 1].ToString());
            }

            g.SetAttribute((object)topologyPoints);


            return(g);
        }
Ejemplo n.º 30
0
        public static IMesh DualMesh(IMesh mesh)
        {
            IMesh nM = new IMesh();

            // Face center points
            foreach (IElement e in mesh.Elements)
            {
                nM.AddVertex(e.Key, new ITopologicVertex(ISubdividor.ComputeAveragePosition(e.Vertices, mesh)));
            }

            int[]      data1, data2;
            PointCloud cloud  = new PointCloud();
            List <int> global = new List <int>();

            int vertexKey = nM.FindNextVertexKey();

            foreach (ITopologicVertex v in mesh.Vertices)
            {
                data1 = mesh.Topology.GetVertexIncidentElementsSorted(v.Key);
                if (!mesh.Topology.IsNakedVertex(v.Key))
                {
                    nM.AddElement(new ISurfaceElement(data1));
                }
                else
                {
                    List <int> local = new List <int>();

                    data2 = mesh.Topology.GetVertexAdjacentVerticesSorted(v.Key);
                    bool flag = false;

                    foreach (int vv in data2)
                    {
                        if (mesh.Topology.IsNakedEdge(vv, v.Key))
                        {
                            Point3d p   = ISubdividor.ComputeAveragePoint(new[] { vv, v.Key }, mesh);
                            int     idx = cloud.ClosestPoint(p);

                            if (idx == -1)
                            {
                                flag = true;
                            }
                            else
                            {
                                if (p.DistanceTo(cloud[idx].Location) > 0.01)
                                {
                                    flag = true;
                                }
                                else
                                {
                                    flag = false;
                                }
                            }

                            if (flag)
                            {
                                cloud.Add(p);
                                nM.AddVertex(vertexKey, new ITopologicVertex(p));
                                global.Add(vertexKey);
                                local.Add(vertexKey);
                                vertexKey++;
                            }
                            else
                            {
                                local.Add(global[idx]);
                            }
                        }
                    }

                    nM.AddVertex(vertexKey, new ITopologicVertex(v));
                    local.Insert(1, vertexKey);
                    local.AddRange(data1.Reverse());
                    vertexKey++;

                    nM.AddElement(new ISurfaceElement(local.ToArray()));
                }
            }

            nM.BuildTopology(true);

            return(nM);
        }