// public List<point> DeriveGeometry2D(IIfcProduct ifcElement)
        // {
        //     var resultList = new List<point>();
        //
        //     // var allTriangles = new List<Triangles>();
        //     // foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded))
        //     foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement))
        //     {
        //         XbimShapeGeometry geometry = context.ShapeGeometry(instance);
        //
        //         var data = ((IXbimShapeGeometryData)geometry).ShapeData;
        //         using (var stream = new MemoryStream(data))
        //         {
        //             using (var reader = new BinaryReader(stream))
        //             {
        //                 XbimShapeTriangulation mesh = reader.ReadShapeTriangulation();
        //                 mesh = mesh.Transform(instance.Transformation);
        //
        //                 // find the minimal z coordinate
        //                 double minZ = 10000;
        //                 foreach (var vertex in mesh.Vertices)
        //                 {
        //                     if (vertex.Z <= minZ)
        //                         minZ = vertex.Z;
        //                 }
        //                 List<IVertex> points = new List<IVertex>();
        //
        //                 foreach (var vertex in mesh.Vertices)
        //                 {
        //                     if (vertex.Z != minZ)
        //                         continue;
        //
        //                     points.Add(new DefaultVertex { Position = new[] { vertex.X, vertex.Y } });
        //
        //                     if (vertex.X >= MaxX)
        //                         MaxX = vertex.X;
        //                     if (vertex.Y >= MaxY)
        //                         MaxY= vertex.Y;
        //
        //                     if (vertex.X <= MinX)
        //                         MinX = vertex.X;
        //                     if (vertex.Y <= MinY)
        //                         MinY = vertex.Y;
        //                 }
        //
        //                 if (points.Count <= 2)
        //                     return null;
        //
        //                 // Compute ConvexHull
        //                 var cH = ConvexHull.Create(points);
        //
        //                 foreach (var item in cH.Points)
        //                 {
        //                     var point = new point() { x = item.Position[0], y = item.Position[1] };
        //                     bool duplicate = false;
        //                     foreach (var result in resultList)
        //                     {
        //                         if (result == point)
        //                         {
        //                             duplicate = true;
        //                             break;
        //                         }
        //                     }
        //                     if(!duplicate)
        //                         resultList.Add(point);
        //                 }
        //
        //             }
        //         }
        //     }
        //     return resultList;
        // }

        /// <summary>
        /// Create a Convex Hull for a list of 2D-points
        /// </summary>
        /// <param name="points"></param>
        /// <returns></returns>
        public List <point> CreateConvexHull(List <point> inputPoints)
        {
            List <IVertex> points = new List <IVertex>();

            foreach (var point in inputPoints)
            {
                points.Add(new DefaultVertex {
                    Position = new[] { point.x, point.y }
                });
            }

            if (points.Count <= 2)
            {
                return(null);
            }

            // Compute ConvexHull
            var cH = ConvexHull.Create(points);

            var result = new List <point>();

            foreach (var item in cH.Points)
            {
                result.Add(new point {
                    x = item.Position[0], y = item.Position[1]
                });
            }
            return(result);
        }
예제 #2
0
        private static void Main(string[] args)
        {
            var    dir       = new DirectoryInfo("../../../../TestFiles");
            var    fileNames = dir.GetFiles();
            string filename  = "";

            for (var i = 0; i < fileNames.Count(); i++)
            {
                try
                {
                    filename = fileNames[i].FullName;
                    Console.WriteLine("Attempting: " + filename);
                    List <DefaultVertex> vertices;
                    var v3D        = MakeModelVisual3D(filename, out vertices);
                    var now        = DateTime.Now;
                    var convexHull = ConvexHull.Create(vertices);
                    var interval   = DateTime.Now - now;
                    Window3DPlot.ShowWithConvexHull(v3D, convexHull);
                    Console.WriteLine("time = " + interval);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed on " + filename + ": " + e.Message);
                }
            }
            Console.ReadLine();
        }
예제 #3
0
        public static List <Point[]> FacesAsThreePoints(List <Point> points)
        {
            List <Vertex> vertices = new List <Vertex>();

            foreach (Point p in points)
            {
                vertices.Add(new Vertex(p.X, p.Y, p.Z));
            }

            var         convexHull = ConvexHull.Create <Vertex, Face>(vertices);
            List <Face> faces      = convexHull.Result.Faces.ToList();

            List <Point[]> outPoints = new List <Point[]>();

            foreach (Face f in faces)
            {
                Vertex[] verts      = f.Vertices;
                Point[]  facePoints = new Point[3];
                for (int i = 0; i < verts.Length; i++)
                {
                    double x         = f.Vertices[i].Position[0];
                    double y         = f.Vertices[i].Position[1];
                    double z         = f.Vertices[i].Position[2];
                    Point  facePoint = Point.ByCoordinates(x, y, z);
                    facePoints[i] = facePoint;
                }
                outPoints.Add(facePoints);
            }

            return(outPoints);
        }
예제 #4
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="TVGLConvexHull" /> class.
        /// </summary>
        /// <param name="ts">The tessellated solid that the convex hull is made from.</param>
        public TVGLConvexHull(IList <Vertex> vertices, double tolerance)
        {
            var convexHull = ConvexHull.Create(vertices, tolerance);

            if (convexHull.Result == null)
            {
                return;
            }
            Vertices = convexHull.Result.Points.ToArray();
            var convexHullFaceList  = new List <PolygonalFace>();
            var checkSumMultipliers = new long[3];

            for (var i = 0; i < 3; i++)
            {
                checkSumMultipliers[i] = (long)Math.Pow(Constants.CubeRootOfLongMaxValue, i);
            }
            var alreadyCreatedFaces = new HashSet <long>();

            foreach (var cvxFace in convexHull.Result.Faces)
            {
                var faceVertices   = cvxFace.Vertices;
                var orderedIndices = faceVertices.Select(v => v.IndexInList).ToList();
                orderedIndices.Sort();
                var checksum = orderedIndices.Select((t, j) => t * checkSumMultipliers[j]).Sum();
                if (alreadyCreatedFaces.Contains(checksum))
                {
                    continue;
                }
                alreadyCreatedFaces.Add(checksum);
                convexHullFaceList.Add(new PolygonalFace(faceVertices, new Vector3(cvxFace.Normal), false));
            }
            Faces = convexHullFaceList.ToArray();
            Edges = MakeEdges(Faces, Vertices);
            TessellatedSolid.CalculateVolumeAndCenter(Faces, tolerance, out Volume, out Center);
        }
예제 #5
0
    // Use this for initialization
    void Start()
    {
        CreateLineMaterial();

        mesh = new Mesh();
        Vertex2[] vertices  = new Vertex2[NumberOfVertices];
        Vector3[] meshVerts = new Vector3[NumberOfVertices];
        int[]     indices   = new int[NumberOfVertices];

        Random.seed = 0;
        for (var i = 0; i < NumberOfVertices; i++)
        {
            vertices[i]  = new Vertex2(size * Random.Range(-1.0f, 1.0f), size * Random.Range(-1.0f, 1.0f));
            meshVerts[i] = vertices[i].ToVector3();
            indices[i]   = i;
        }

        mesh.vertices = meshVerts;
        mesh.SetIndices(indices, MeshTopology.Points, 0);
        //mesh.bounds = new Bounds(Vector3.zero, new Vector3((float)size,(float)size,(float)size));

        float now = Time.realtimeSinceStartup;
        ConvexHull <Vertex2, Face2> convexHull = ConvexHull.Create <Vertex2, Face2>(vertices);
        float interval = Time.realtimeSinceStartup - now;

        convexHullVertices = new List <Vertex2>(convexHull.Points);
        convexHullFaces    = new List <Face2>(convexHull.Faces);

        Debug.Log("Out of the " + NumberOfVertices + " vertices, there are " + convexHullVertices.Count + " verts on the convex hull.");
        Debug.Log("time = " + interval * 1000.0f + " ms");
    }
예제 #6
0
    protected override int[] FindTriangles()
    {
        var triangles = new List <int> ();
        //Convert vertices to MIVertices
        var miVertices = new List <MIVertex> ();

        for (int i = 0; i < _vertices.Length; ++i)
        {
            var miVertex = new MIVertex();
            var vertex   = _vertices [i];
            miVertex.Index    = i;
            miVertex.Position = new double[3] {
                vertex.x, vertex.y, vertex.z
            };
            miVertices.Add(miVertex);
        }
        //Generate convex hull + extract triangles
        var hull = ConvexHull.Create(miVertices);

        foreach (var face in hull.Faces)
        {
            foreach (var vertex in face.Vertices)
            {
                triangles.Add(vertex.Index);
            }
        }
        return(triangles.ToArray());
    }
예제 #7
0
        ConvexHull <Vertex, Face> CreateHull(List <Vertex> input, bool enableSimplify)
        {
            if (input.Count < 3)
            {
                return(null);
            }

            try
            {
                return(ConvexHull.Create <Vertex, Face>(
                           input, kToleranceMeters_PS * App.METERS_TO_UNITS * POINTER_TO_LOCAL));
            }
            catch (ArgumentOutOfRangeException)
            {
                // Too much degeneracy to create a hull (this is the exception we actually get)
                // The docs say Create() throws ArgumentException in this case, but instead it
                // reads off the end of a List<>, causing this range exception.
                return(null);
            }
            catch (ArgumentException)
            {
                // Too much degeneracy to create a hull
                return(null);
            }
        }
        public static designGraph tagconvexhullpoints(designGraph host)
        {
            //putting this here for now
            //tags the points on a convex hull with the label hullpt
            //why even make this into a rule
            Dictionary <Tuple <double, double, double>, int>
            lookup = new Dictionary <Tuple <double, double, double>, int>();
            List <double[]> points = new List <double[]>();

            for (int i = 0; i < host.nodes.Count; i++)
            {
                node n = host.nodes[i];
                n.localLabels.RemoveAll(s => s == "hullpt");
                double[] pos = new double[] { n.X, n.Y, n.Z };

                points.Add(pos);
                lookup.Add(Tuple.Create(n.X, n.Y, n.Z), i);
            }

            var chull = ConvexHull.Create(points);

            foreach (var pt in chull.Points)
            {
                var pttple = Tuple.Create(pt.Position[0], pt.Position[1], pt.Position[2]);
                if (lookup.ContainsKey(pttple))
                {
                    int n = lookup[pttple];
                    host.nodes[n].localLabels.Add("hullpt");
                }
            }
            return(host);
        }
예제 #9
0
        static void Main()
        {
            const int    NumberOfVertices = 100000;
            const double size             = 1000;

            var r = new Random();

            Console.WriteLine("Ready? Push Return/Enter to start.");
            Console.ReadLine();

            Console.WriteLine("Making " + NumberOfVertices + " random vertices.");

            var vertices = new Vertex[NumberOfVertices];

            for (var i = 0; i < NumberOfVertices; i++)
            {
                vertices[i] = new Vertex(size * r.NextDouble(), size * r.NextDouble());
            }

            Console.WriteLine("Running...");
            var now        = DateTime.Now;
            var convexHull = ConvexHull.Create(vertices).Result.Points;
            var interval   = DateTime.Now - now;

            Console.WriteLine("Out of the {0} 2D vertices, there are {1} on the convex hull.", NumberOfVertices, convexHull.Count());
            Console.WriteLine("time = " + interval);

            Console.ReadLine();
        }
예제 #10
0
    /// <summary>
    /// Generates a rock from a given set of points.
    /// </summary>
    public static Mesh MeshFromPoints(IEnumerable <Vector3> points)
    {
        Mesh m = new Mesh();

        m.name = "Mesh";

        List <int> triangles = new List <int>();

        var vertices = points.Select(x => new Vertex(x)).ToList();

        var result = ConvexHull.Create(vertices);

        m.vertices = result.Points.Select(x => x.ToVec()).ToArray();

        var resultPoints = result.Points.ToList();

        foreach (var face in result.Faces)
        {
            triangles.Add(resultPoints.IndexOf(face.Vertices[0]));
            triangles.Add(resultPoints.IndexOf(face.Vertices[1]));
            triangles.Add(resultPoints.IndexOf(face.Vertices[2]));
        }

        m.triangles = triangles.ToArray();
        m.RecalculateNormals();

        //m = LowPolyConverter.Convert(m); //Converts the generated mesh to low poly

        return(m);
    }
예제 #11
0
        ConvexHull <Vertex, Face> CreateHull(List <Vertex> input, bool enableSimplify)
        {
            if (input.Count < 3)
            {
                return(null);
            }

            try {
                if (m_Simplification_PS > 0 && enableSimplify)
                {
                    // Abuse the "tolerance" parameter of the convex hull generator. This generates
                    // simpler geometry that is sometimes nonmanifold, especially as you crank up the
                    // tolerance. Thus, this pass is used solely to strip points.
                    var simpleHull = ConvexHull.Create <Vertex, Face>(
                        input, m_Simplification_PS * App.METERS_TO_UNITS * POINTER_TO_LOCAL);
                    input = simpleHull.Points.ToList();
                }
                return(ConvexHull.Create <Vertex, Face>(
                           input, kToleranceMeters_PS * App.METERS_TO_UNITS * POINTER_TO_LOCAL));
            } catch (ArgumentOutOfRangeException) {
                // Too much degeneracy to create a hull (this is the exception we actually get)
                // The docs say Create() throws ArgumentException in this case, but instead it
                // reads off the end of a List<>, causing this range exception.
                return(null);
            } catch (ArgumentException) {
                // Too much degeneracy to create a hull
                return(null);
            }
        }
예제 #12
0
    /// <summary>
    /// Assign cell corners, neighbors, edge connections, and corner connections
    /// </summary>
    /// <returns></returns>
    private IEnumerator ConnectCells()
    {
        ConvexHull <VoronoiCell, DefaultConvexFace <VoronoiCell> > hull =
            ConvexHull.Create <VoronoiCell, DefaultConvexFace <VoronoiCell> > (_cells);

        foreach (DefaultConvexFace <VoronoiCell> face in hull.Faces)
        {
            VoronoiCell c0 = face.Vertices[0];
            VoronoiCell c1 = face.Vertices[1];
            VoronoiCell c2 = face.Vertices[2];

            Vector3 centroid = ((c0.transform.position +
                                 c1.transform.position +
                                 c2.transform.position) / 3f).normalized * Radius;

            c0.Corners.Add(centroid - c0.transform.position);
            c1.Corners.Add(centroid - c1.transform.position);
            c2.Corners.Add(centroid - c2.transform.position);

            c0.SetNeighbor(c1);
            c0.SetNeighbor(c2);
            c1.SetNeighbor(c2);
        }
        yield return(null);
    }
예제 #13
0
        /// <summary>
        /// Creates a convex hull given the original vertices of a mesh.
        /// </summary>
        /// <param name="original">The original vertices of a mesh</param>
        /// <param name="convexMesh">The output mesh data of the convex hull</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance</param>
        /// <returns>The outcome of the process (successfull or unsuccessful)</returns>
        public static ConvexHullCreationResultOutcome GenerateConvexHull(Vector3[] original, out MeshData convexMesh, double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
        {
            convexMesh = new MeshData();

            List <MIVertex> vertices = original.Select(point => new MIVertex(point)).ToList();
            var             creation = ConvexHull.Create(vertices, PlaneDistanceTolerance);
            var             result   = creation.Result;

            List <int>      triangles      = new List <int>();
            List <MIVertex> resultVertices = result.Points.ToList();

            foreach (var face in result.Faces)
            {
                triangles.Add(resultVertices.IndexOf(face.Vertices[0]));
                triangles.Add(resultVertices.IndexOf(face.Vertices[1]));
                triangles.Add(resultVertices.IndexOf(face.Vertices[2]));
            }

            convexMesh.vertices  = result.Points.Select(point => point.ToVec()).ToArray();
            convexMesh.triangles = triangles.ToArray();
            //convexMesh.RecalculateNormals();
            //convexMesh.RecalculateBounds();

            return(creation.Outcome);
        }
예제 #14
0
    public static List <BXDAMesh.BXDASubMesh> GetHull(BXDAMesh bMesh)
    {
        List <BXDAMesh.BXDASubMesh> meshes = new List <BXDAMesh.BXDASubMesh>();

        foreach (BXDAMesh.BXDASubMesh mesh in bMesh.meshes)
        {
            List <HullVertex> RawVertices = new List <HullVertex>();
            for (int i = 0; i < mesh.verts.Length; i += 3)
            {
                RawVertices.Add(new HullVertex(mesh.verts[i], mesh.verts[i + 1], mesh.verts[i + 2]));
            }
            var Hull         = ConvexHull.Create(RawVertices);
            var HullVertices = new List <HullVertex>();
            HullVertices.AddRange(Hull.Points);

            List <uint> indices = new List <uint>();
            foreach (var face in Hull.Faces)
            {
                indices.Add((uint)HullVertices.IndexOf(face.Vertices[0]));
                indices.Add((uint)HullVertices.IndexOf(face.Vertices[1]));
                indices.Add((uint)HullVertices.IndexOf(face.Vertices[2]));
            }
            float[] verts = Array.ConvertAll(GetRawVerts(HullVertices.ToArray()), item => (float)item);

            meshes.Add(ExportMeshInternal(verts, (uint)verts.Length / 3, indices.ToArray(), ((uint)indices.Count / 3)));
        }
        return(meshes);
    }
예제 #15
0
    //===================================================================

    Mesh CreateConvexMesh(System.Collections.Generic.IEnumerable <Vector3> stars)
    {
        Mesh m = new Mesh();

        m.name = "ScriptedMesh";
        System.Collections.Generic.List <int> triangles = new System.Collections.Generic.List <int>();

        var vertices = stars.Select(x => new Vertex(x)).ToList();

        var result = ConvexHull.Create(vertices);

        m.vertices = result.Points.Select(x => x.ToVec()).ToArray();
        var xxx = result.Points.ToList();

        foreach (var face in result.Faces)
        {
            triangles.Add(xxx.IndexOf(face.Vertices[0]));
            triangles.Add(xxx.IndexOf(face.Vertices[1]));
            triangles.Add(xxx.IndexOf(face.Vertices[2]));
        }

        m.triangles = triangles.ToArray();
        m.RecalculateNormals();
        return(m);
    }
예제 #16
0
        public static CompactnessMeasurerResult Measure(ApproximatePeptide peptide)
        {
            var vertices        = ToVertices(peptide.AminoAcids);
            var convexHull      = ConvexHull.Create(vertices);
            var volume          = CalculateVolume(convexHull.Result);
            var convexHullGraph = ToGraph(convexHull.Result);

            return(new CompactnessMeasurerResult(volume, convexHullGraph));
        }
예제 #17
0
        public static Mesh CreateConvexMesh(Vector3[] vertices)
        {
            ConvexHull <IVertex, DefaultConvexFace <IVertex> > convexHull = ConvexHull.Create <IVertex>(ConvertToMIConvexHullVertices(vertices), null);

            return(new Mesh {
                vertices = ConvertToUnityVertices(convexHull),
                triangles = ConvertToUnityTriangles(convexHull)
            });
        }
예제 #18
0
    private void UpdateMesh(List <Vector3> input, Mesh mesh, MaterialID matid, UVMapper uvMapper)
    {
        Vertex3[] inputVtx3 = new Vertex3[input.Count];
        CastToVertex3(input, inputVtx3);

        ConvexHull <Vertex3, Face3> hull = ConvexHull.Create <Vertex3, Face3>(inputVtx3, 0.0001);

//        List<Vertex3> hullVtx3 = new List<Vertex3>(hull.Points);
        List <Vertex3> hullVtx3 = new List <Vertex3>();
        List <Face3>   faces    = new List <Face3>(hull.Faces);

        int[] indices = new int[faces.Count * 3];

        int n = 0;

        for (int i = 0; i < faces.Count; ++i)
        {
            // Sometime in the future, I'd like each side of the log
            // to share vertices, and only separate them along the
            // cardinal edges.

            // This is how we do it when we want to separate each
            // triangle. We create a vertex for each point of each
            // triangle.
            hullVtx3.Add(faces[i].Vertices[0]);
            indices[n++] = hullVtx3.Count - 1;
            hullVtx3.Add(faces[i].Vertices[1]);
            indices[n++] = hullVtx3.Count - 1;
            hullVtx3.Add(faces[i].Vertices[2]);
            indices[n++] = hullVtx3.Count - 1;

            // This is the way to do it when you want to share
            // vertices between triangles. That's not going to
            // work with texture atlassing.
//            indices[n++] = hullVtx3.IndexOf(faces[i].Vertices[0]);
//            indices[n++] = hullVtx3.IndexOf(faces[i].Vertices[1]);
//            indices[n++] = hullVtx3.IndexOf(faces[i].Vertices[2]);
        }

        Vector3[] vertices = new Vector3[hullVtx3.Count];
        CastToVector3(hullVtx3, vertices);

        mesh.Clear();
        mesh.vertices = vertices;
        mesh.SetIndices(indices, MeshTopology.Triangles, 0);

        MaterialData md    = MaterialIndex.GetMaterialData(matIndex, matid);
        UVMapFn      mapFn = UVMapper.GetMapFunction(uvMapper, md.mapFnID);

        UVMapper.SetUV(md, mesh, mapFn);

        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
    }
예제 #19
0
파일: Program.cs 프로젝트: hipigod/Dynamo
        static TimeSpan TestNDConvexHull(int dim, int numVert, double size)
        {
            var vertices = CreateRandomVertices(dim, numVert, size);

            return(RunComputation(() =>
            {
                var h = ConvexHull.Create(vertices);
                // Console.WriteLine(h.Points.Count());
                return h;
            }));
        }
예제 #20
0
        private static Mesh CreateHullMesh(Mesh mesh, VertexCollecton sourceVertices)
        {
            // Get the convex hull for the mesh
            var cHVertexList = new List <CHVertex>();

            foreach (var vertex in sourceVertices)
            {
                cHVertexList.Add(new CHVertex(vertex.Position));
            }
            var convexHull = ConvexHull <CHVertex, CHFace> .Create(cHVertexList, .01);

            if (convexHull != null)
            {
                // create the mesh from the hull data
                Mesh hullMesh = new Mesh();
                foreach (var face in convexHull.Faces)
                {
                    List <IVertex> vertices = new List <IVertex>();
                    foreach (var vertex in face.Vertices)
                    {
                        var meshVertex = hullMesh.CreateVertex(new Vector3(vertex.Position[0], vertex.Position[1], vertex.Position[2]));
                        vertices.Add(meshVertex);
                    }
                    hullMesh.CreateFace(vertices.ToArray());
                }

                try
                {
                    // make sure there is not currently a convex hull on this object
                    if (mesh.PropertyBag.ContainsKey(ConvexHullMesh))
                    {
                        mesh.PropertyBag.Remove(ConvexHullMesh);
                    }

                    // add the new hull
                    mesh.PropertyBag.Add(ConvexHullMesh, hullMesh);
                    // make sure we remove this hull if the mesh changes
                    mesh.Changed += MeshChanged_RemoveConvexHull;

                    // remove the marker that says we are building the hull
                    if (mesh.PropertyBag.ContainsKey(CreatingConvexHullMesh))
                    {
                        mesh.PropertyBag.Remove(CreatingConvexHullMesh);
                    }
                    return(hullMesh);
                }
                catch
                {
                }
            }

            return(null);
        }
예제 #21
0
        public static Mesh ConvexHull3D(List <Vector3> points)
        {
            List <DefaultVertex> vertices = points.ConvertAll(new System.Converter <Vector3, DefaultVertex>(VertOfVector3));

            ConvexHull <DefaultVertex, DefaultConvexFace <DefaultVertex> > hull;

            hull = ConvexHull.Create <DefaultVertex, DefaultConvexFace <DefaultVertex> >(vertices);

            List <Vector3> hullVerts = new List <Vector3>();
            List <int>     hullFaces = new List <int>();

            int ptIndex = 0;
            Dictionary <DefaultVertex, int> pointDict = new Dictionary <DefaultVertex, int>();

            // Extract list of vertices
            foreach (DefaultVertex v in hull.Points)
            {
                Vector3 vec = Vector3OfVert(v);
                hullVerts.Add(vec);
                pointDict.Add(v, ptIndex);
                ptIndex++;
            }

            List <Vector3> separateVerts = new List <Vector3>();
            int            vertCount     = 0;

            // Extract list of faces
            foreach (var f in hull.Faces)
            {
                int v1 = vertCount++;
                int v2 = vertCount++;
                int v3 = vertCount++;

                hullFaces.Add(v1);
                hullFaces.Add(v2);
                hullFaces.Add(v3);

                separateVerts.Add(Vector3OfVert(f.Vertices[0]));
                separateVerts.Add(Vector3OfVert(f.Vertices[1]));
                separateVerts.Add(Vector3OfVert(f.Vertices[2]));
                //int index = pointDict[f.Vertices[i]];
                //hullFaces.Add(index);
            }

            Mesh m = new Mesh();

            m.vertices  = separateVerts.ToArray();
            m.triangles = hullFaces.ToArray();
            m.RecalculateNormals();

            return(m);
        }
예제 #22
0
        private void btnRun_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("Running...");
            var now        = DateTime.Now;
            var convexHull = ConvexHull.Create <Vertex, Face>(vertices);

            convexHullVertices = convexHull.Result.Points.ToList();
            faces = convexHull.Result.Faces.ToList();
            var interval = DateTime.Now - now;

            txtBlkTimer.Text = interval.Hours + ":" + interval.Minutes
                               + ":" + interval.Seconds + "." + interval.TotalMilliseconds;

            Display();
        }
예제 #23
0
        static void TestHypercube(int dim)
        {
            var hypercube = new double[1 << dim][];

            for (int i = 0; i < 1 << dim; i++)
            {
                hypercube[i] = Enumerable.Range(0, dim).Select(j => ((i >> j) & 1) == 1 ? 10.0 : 0.0).ToArray();
            }
            var hull = ConvexHull.Create(hypercube);

            foreach (var n in hull.Faces.Select(f => f.Normal).OrderBy(v => v, new VectorComparer()))
            {
                Console.WriteLine(string.Join(" ", n.Select(x => x.ToString("0.0"))));
            }
        }
예제 #24
0
        public void FindConvexHull()
        {
            var vertices = new MIVertex2D[points.Count];

            for (var i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new MIVertex2D(points[i].x, points[i].y);
            }

            MIVertex2D[] convexHull = (MIVertex2D[])ConvexHull.Create(vertices).Points;

            for (int i = 0; i < convexHull.Length; i++)
            {
                image.SetPixel((int)convexHull[i].Position[0], (int)convexHull[i].Position[1], Color.Red);
            }
        }
예제 #25
0
        public static Dictionary <string, List <object> > FacesAsPointsAndIndices(List <Point> points)
        {
            List <Vertex> vertices = new List <Vertex>();

            foreach (Point p in points)
            {
                vertices.Add(new Vertex(p.X, p.Y, p.Z));
            }
            var         convexHull = ConvexHull.Create <Vertex, Face>(vertices);
            List <Face> faces      = convexHull.Result.Faces.ToList();

            List <Point> flattenedList = new List <Point>();

            foreach (Face f in faces)
            {
                Vertex[] verts      = f.Vertices;
                Point[]  facePoints = new Point[3];
                for (int i = 0; i < verts.Length; i++)
                {
                    double x         = f.Vertices[i].Position[0];
                    double y         = f.Vertices[i].Position[1];
                    double z         = f.Vertices[i].Position[2];
                    Point  facePoint = Point.ByCoordinates(x, y, z);
                    facePoints[i] = facePoint;
                    flattenedList.Add(facePoint);
                }
            }

            // Cull duplicate points from the set
            var uniquePointsHashSet = new HashSet <Point>(flattenedList);

            // Convert back to a list
            var uniquePoints = new List <object>(uniquePointsHashSet);

            List <object> indices = new List <object>();

            foreach (Point pt in flattenedList)
            {
                indices.Add(uniquePoints.IndexOf(pt));
            }

            return(new Dictionary <string, List <object> >()
            {
                { "Points", uniquePoints },
                { "Indices", indices }
            });
        }
예제 #26
0
        private List <MIVector> GetVerticesForSideOfRectangle(MIVector from, MIVector to, bool leftSide)
        {
            List <MIVector> vertices = new List <MIVector>
            {
                from,
                to
            };

            foreach (MIVector bound in _bounds)
            {
                if ((leftSide ? 1 : -1) * IsLeft(from, to, bound) > 0)
                {
                    vertices.Add(bound);
                }
            }

            return(ConvexHull.Create(vertices).Points.ToList());
        }
예제 #27
0
 private void MIConvexHullMenuItem_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         var now  = DateTime.Now;
         var hull = ConvexHull.Create(vertices);
         CVXvertices = hull.Points.ToList();
         CVXfaces    = hull.Faces.ToList();
         var interval = DateTime.Now - now;
         UpdateTimer(interval);
         btnDisplay.IsEnabled = btnDisplay.IsDefault = true;
         Voro_edges           = null; Voro_nodes = null; Del_tetras = null;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Information);
     }
 }
예제 #28
0
        public static Mesh GenerateConvexHull(Mesh[] meshes)
        {
            Mesh CV = new Mesh();

            List <MIVertex> vertices = new List <MIVertex>();

            for (int i = 0; i < meshes.Length; i++)
            {
                //Console.WriteLine(meshes[i].vertexCount());
                for (int j = 0; j < meshes[i].vertexCount(); j++)
                {
                    vertices.Add(new MIVertex(
                                     meshes[i].vertices[j].v.x,
                                     meshes[i].vertices[j].v.y,
                                     meshes[i].vertices[j].v.z
                                     ));
                }
            }

            ConvexHull <MIVertex, MIFace> convexHull = ConvexHull.Create <MIVertex, MIFace>(vertices);

            List <MIVertex> convexHullVertices = convexHull.Points.ToList();
            List <MIFace>   faces = convexHull.Faces.ToList();

            for (int i = 0; i < faces.Count; i++)
            {
                CV.AddVertex(new Vector(faces[i].Vertices[0].Position[0],
                                        faces[i].Vertices[0].Position[1],
                                        faces[i].Vertices[0].Position[2]
                                        ));
                CV.AddVertex(new Vector(faces[i].Vertices[1].Position[0],
                                        faces[i].Vertices[1].Position[1],
                                        faces[i].Vertices[1].Position[2]
                                        ));
                CV.AddVertex(new Vector(faces[i].Vertices[2].Position[0],
                                        faces[i].Vertices[2].Position[1],
                                        faces[i].Vertices[2].Position[2]
                                        ));
                CV.AddTriangle(3 * i, 3 * i + 1, 3 * i + 2);
            }

            return(CV);
        }
        /// <summary>
        /// Создание 3Д модели
        /// </summary>
        /// <param name="points3D">Набор точек в трехмерном пространстве</param>
        /// <param name="writeToFile">Флаг записи в файл</param>
        /// <returns>3D модель</returns>
        public static void Create3DModel(List <Point3D> points3D, string modelName = "standartModel", string path = "")
        {
            Tracer.Info("\nПостроение 3D модели:");
            Stopwatch timer = Stopwatch.StartNew(); // Старт секундомера для диагностики работы алгоритма

            Tracer.Info("\nСоздание вершин, на основе точек в трехмерном пространстве...");
            List <Vertex> vertices = new List <Vertex>();

            foreach (var point3D in points3D)
            {
                vertices.Add(new Vertex(point3D.X, point3D.Y, point3D.Z));
            }
            Tracer.Info("Построение оболочки 3D модели...");
            ConvexHull <Vertex, Face> convexHull = ConvexHull.Create <Vertex, Face>(vertices);

            WriteModelToFile(convexHull.Faces.ToList(), modelName, path);

            timer.Stop(); // Остановка секундомера
            Tracer.Info($"\nПостроение 3D модели завершено. Это заняло {timer.ElapsedMilliseconds} мс.\n");
        }
예제 #30
0
        static void Main()
        {
            const int    NumberOfVertices = 30000;
            const double size             = 1000;
            const int    dimension        = 3;

            var r = new Random();

            Console.WriteLine("Ready? Push Return/Enter to start.");
            Console.ReadLine();

            Console.WriteLine("Making " + NumberOfVertices + " random vertices.");
            /* our inputs are simply in the form of an array of double arrays */
            var vertices = new double[NumberOfVertices][];

            for (var i = 0; i < NumberOfVertices; i++)
            {
                var location = new double[dimension];
                for (var j = 0; j < dimension; j++)
                {
                    location[j] = size * r.NextDouble();
                }
                vertices[i] = location;
            }
            Console.WriteLine("Running...");
            var now = DateTime.Now;

            var convexHull = ConvexHull.Create(vertices);

            double[][] hullPoints = convexHull.Points.Select(p => p.Position).ToArray();

            var interval = DateTime.Now - now;

            Console.WriteLine("Out of the {0} 2D vertices, there are {1} on the convex hull.", NumberOfVertices, hullPoints.Length);
            Console.WriteLine("time = " + interval);

            Console.WriteLine();
            Console.WriteLine("Push Return/Enter to test 5D hypercube hull and print its normals.");
            Console.ReadLine();
            TestHypercube(5);
        }