예제 #1
0
        public static DMesh3 ReadMeshFromMM(RemoteControl rc, int nObjectId, bool bWantColors = false)
        {
            Debug.Assert(bWantColors == false); // haven't implemented yet

            DMesh3 mesh = new DMesh3(MeshComponents.FaceGroups);

            int NV           = rc.GetVertexCount(nObjectId);
            int nBatchSize   = 750;
            int nFullBatches = NV / nBatchSize;

            for (int i = 0; i < nFullBatches; ++i)
            {
                Vector3f[] vPositions = rc.GetVertexPositionInRange(nObjectId, i * nBatchSize, nBatchSize);
                for (int j = 0; j < vPositions.Length; ++j)
                {
                    int vid = mesh.AppendVertex((Vector3d)vPositions[j]);
                    Debug.Assert(vid == i * nBatchSize + j);
                }
            }
            int nLeft = NV - nFullBatches * nBatchSize;

            if (nLeft > 0)
            {
                Vector3f[] vPositions = rc.GetVertexPositionInRange(nObjectId, nFullBatches * nBatchSize, nLeft);
                for (int j = 0; j < nLeft; ++j)
                {
                    int vid = mesh.AppendVertex((Vector3d)vPositions[j]);
                }
            }

            int NT = rc.GetTriangleCount(nObjectId);

            nBatchSize   = 750;
            nFullBatches = NT / nBatchSize;
            for (int i = 0; i < nFullBatches; ++i)
            {
                Index3i[] vTriangles = rc.GetTrianglesInRange(nObjectId, i * nBatchSize, nBatchSize);
                int[]     vGroups    = rc.GetFaceGroupsInRange(nObjectId, i * nBatchSize, nBatchSize);
                for (int j = 0; j < vTriangles.Length; ++j)
                {
                    int vid = mesh.AppendTriangle(vTriangles[j], vGroups[j]);
                    Debug.Assert(vid == i * nBatchSize + j);
                }
            }
            nLeft = NT - nFullBatches * nBatchSize;
            if (nLeft > 0)
            {
                Index3i[] vTriangles = rc.GetTrianglesInRange(nObjectId, nFullBatches * nBatchSize, nLeft);
                int[]     vGroups    = rc.GetFaceGroupsInRange(nObjectId, nFullBatches * nBatchSize, nLeft);
                for (int j = 0; j < nLeft; ++j)
                {
                    int vid = mesh.AppendTriangle(vTriangles[j], vGroups[j]);
                }
            }

            return(mesh);
        }
예제 #2
0
        DMesh3 BuildPlanarMesh(bool bPreservePolygon)
        {
            DMesh3 planarMesh = new DMesh3();

            Vector2d center    = CurveUtils2.CentroidVtx(Loop.Vertices);
            int      center_id = planarMesh.AppendVertex(new Vector3d(center.x, center.y, 0));

            int prev_id  = -1;
            int first_id = -1;

            foreach (Vector2d v in Loop.Vertices)
            {
                int next_id = planarMesh.AppendVertex(new Vector3d(v.x, v.y, Thickness));
                if (prev_id > 0)
                {
                    planarMesh.AppendTriangle(center_id, prev_id, next_id);
                    prev_id = next_id;
                }
                else
                {
                    first_id = next_id;
                    prev_id  = next_id;
                }
            }
            planarMesh.AppendTriangle(center_id, prev_id, first_id);

            if (ReverseOrientation)
            {
                planarMesh.ReverseOrientation();
            }

            Debug.Assert(planarMesh.CheckValidity());


            double   edge_len = (TargetEdgeLength == 0) ? Loop.AverageEdgeLength : TargetEdgeLength;
            Remesher r        = new Remesher(planarMesh);

            r.SetTargetEdgeLength(edge_len);
            r.SmoothSpeedT = 1.0f;
            if (bPreservePolygon)
            {
                MeshConstraintUtil.FixAllBoundaryEdges(r);
            }
            else
            {
                MeshConstraintUtil.PreserveBoundaryLoops(r);
            }

            for (int k = 0; k < 20; ++k)
            {
                r.BasicRemeshPass();
            }

            return(planarMesh);
        }
예제 #3
0
        static DMesh3 GenCol_CreateMesh(List <DefaultConvexFace <VertexVector3> > triangles)
        {
            DMesh3 mesh = new DMesh3();

            var g3Vertices  = new List <Vector3d>();
            var g3Triangles = new List <Vector3d[]>();

            for (int i = 0; i < triangles.Count; i++)
            {
                var t1 = new Vector3d(triangles[i].Vertices[0].Position[0], triangles[i].Vertices[0].Position[1], triangles[i].Vertices[0].Position[2]);
                var t2 = new Vector3d(triangles[i].Vertices[1].Position[0], triangles[i].Vertices[1].Position[1], triangles[i].Vertices[1].Position[2]);
                var t3 = new Vector3d(triangles[i].Vertices[2].Position[0], triangles[i].Vertices[2].Position[1], triangles[i].Vertices[2].Position[2]);

                var v1 = g3Vertices.FindIndex(e => e.x == t1.x && e.y == t1.y && e.z == t1.z);
                var v2 = g3Vertices.FindIndex(e => e.x == t2.x && e.y == t2.y && e.z == t2.z);
                var v3 = g3Vertices.FindIndex(e => e.x == t3.x && e.y == t3.y && e.z == t3.z);

                if (v1 == -1)
                {
                    g3Vertices.Add(t1);
                    mesh.AppendVertex(t1);
                }

                if (v2 == -1)
                {
                    g3Vertices.Add(t2);
                    mesh.AppendVertex(t2);
                }

                if (v3 == -1)
                {
                    g3Vertices.Add(t3);
                    mesh.AppendVertex(t3);
                }

                g3Triangles.Add(new Vector3d[] { t1, t2, t3 });
            }

            for (int i = 0; i < g3Triangles.Count; i++)
            {
                var idx = new Index3i(
                    g3Vertices.IndexOf(g3Triangles[i][0]),
                    g3Vertices.IndexOf(g3Triangles[i][1]),
                    g3Vertices.IndexOf(g3Triangles[i][2])
                    );

                mesh.AppendTriangle(idx);
            }

            return(mesh);
        }
예제 #4
0
        public static Tuple <int[], int[]> AddTriangleStripBetweenPolygons(DMesh3 mesh, int[] baseVertices, IList <Vector3d> newPolygon)
        {
            if (mesh == null || baseVertices == null || newPolygon == null || baseVertices.Length != newPolygon.Count)
            {
                return(null);
            }
            int[] newVertices  = new int[newPolygon.Count];
            int[] newTriangles = new int[newPolygon.Count * 2];
            int   v;

            for (v = 0; v < newPolygon.Count; ++v)
            {
                newVertices[v] = mesh.AppendVertex(newPolygon[v]);
            }
            int currTriangle = 0;

            for (v = 0; v < newPolygon.Count - 1; ++v)
            {
                newTriangles[currTriangle]     = mesh.AppendTriangle(baseVertices[v + 1], baseVertices[v], newVertices[v]);
                newTriangles[currTriangle + 1] = mesh.AppendTriangle(baseVertices[v + 1], newVertices[v], newVertices[v + 1]);
                currTriangle += 2;
            }
            newTriangles[currTriangle]     = mesh.AppendTriangle(baseVertices[0], baseVertices[v], newVertices[v]);
            newTriangles[currTriangle + 1] = mesh.AppendTriangle(baseVertices[0], newVertices[v], newVertices[0]);
            return(Tuple.Create(newVertices, newTriangles));
        }
예제 #5
0
        public static DMesh3 ToDMesh3(this Mesh mesh)
        {
            var dMesh3 = new DMesh3();

            for (int i = 0; i < mesh.Vertices.Count; i++)
            {
                var vertex = mesh.Vertices[i];
                var normal = mesh.Normals[i];

                NewVertexInfo ni = new NewVertexInfo()
                {
                    v = new g3.Vector3d(vertex.X, vertex.Z, vertex.Y),
                    n = new g3.Vector3f(normal.X, normal.Z, normal.Y)
                };

                dMesh3.AppendVertex(ni);
            }

            foreach (var face in mesh.Faces)
            {
                dMesh3.AppendTriangle(face.A, face.B, face.C);
            }

            return(dMesh3);
        }
예제 #6
0
        public static DMesh3 ToG3Sharp(this IGeometry self)
        {
            var r = new DMesh3();

            foreach (var v in self.Vertices.ToEnumerable())
            {
                r.AppendVertex(v.ToVector3D());
            }
            var indices = self.ToTriMesh().Indices;

            for (var i = 0; i < indices.Count; i += 3)
            {
                var result = r.AppendTriangle(indices[i], indices[i + 1], indices[i + 2]);
                if (result < 0)
                {
                    if (result == DMesh3.NonManifoldID)
                    {
                        throw new Exception("Can't create non-manifold mesh");
                    }
                    if (result == DMesh3.InvalidID)
                    {
                        throw new Exception("Invalid vertex ID");
                    }
                    throw new Exception("Unknown error creating mesh");
                }
            }
            return(r);
        }
예제 #7
0
        static DMesh3 GenCol_CleanVertices(DMesh3 mesh)
        {
            var newMesh      = new DMesh3(mesh, true);
            var tmpVertices  = newMesh.Vertices().ToList();
            var tmpTriangles = newMesh.Triangles().ToList();

            var finalVertices = new List <Vector3d>();
            var usedVertices  = new List <int>();

            for (int i = 0; i < tmpTriangles.Count; i++)
            {
                var triangle = tmpTriangles[i];

                if (usedVertices.IndexOf(triangle.a) == -1)
                {
                    usedVertices.Add(triangle.a);
                }

                if (usedVertices.IndexOf(triangle.b) == -1)
                {
                    usedVertices.Add(triangle.b);
                }

                if (usedVertices.IndexOf(triangle.c) == -1)
                {
                    usedVertices.Add(triangle.c);
                }
            }

            usedVertices.Sort();

            var finalMesh = new DMesh3();

            for (int i = 0; i < usedVertices.Count; i++)
            {
                finalVertices.Add(tmpVertices[usedVertices[i]]);
                finalMesh.AppendVertex(tmpVertices[usedVertices[i]]);
            }

            for (int i = 0; i < tmpTriangles.Count; i++)
            {
                var triangle = tmpTriangles[i];

                triangle.a = finalVertices.IndexOf(tmpVertices[triangle.a]);
                triangle.b = finalVertices.IndexOf(tmpVertices[triangle.b]);
                triangle.c = finalVertices.IndexOf(tmpVertices[triangle.c]);

                if (triangle.a == -1 || triangle.b == -1 || triangle.c == -1)
                {
                    continue;
                }

                finalMesh.AppendTriangle(triangle);
            }

            return(finalMesh);
        }
예제 #8
0
        public static DMesh3 ToDMesh(this Mesh uMesh,
                                     bool bNorm = true,
                                     bool bUV   = false,
                                     bool bCol  = false)
        {
            int nV = uMesh.vertices.Length;

            bNorm &= (uMesh.normals != null && uMesh.normals.Length == nV);
            bUV   &= (uMesh.uv != null && uMesh.uv.Length == nV);
            bCol  &= (uMesh.colors != null && uMesh.colors.Length == nV);

            DMesh3 dMesh = new DMesh3(bNorm, bCol, bUV);

            for (int i = 0; i < nV; i++)
            {
                NewVertexInfo vi = new NewVertexInfo()
                {
                    v = uMesh.vertices[i]
                };
                if (bNorm)
                {
                    vi.bHaveN = true;
                    vi.n      = uMesh.normals[i];
                }
                if (bUV)
                {
                    vi.bHaveUV = true;
                    vi.uv      = uMesh.uv[i];
                }
                if (bUV)
                {
                    vi.bHaveC = true;
                    vi.c      = new Vector3f(uMesh.colors[i].r,
                                             uMesh.colors[i].g,
                                             uMesh.colors[i].b);
                }
                int vID = dMesh.AppendVertex(vi);
                Util.gDevAssert(vID == i);
            }

            int nT = uMesh.triangles.Length;

            for (int i = 0; i < nT; i += 3)
            {
                dMesh.AppendTriangle(uMesh.triangles[i],
                                     uMesh.triangles[i + 1],
                                     uMesh.triangles[i + 2]);
            }
            return(dMesh);
        }
예제 #9
0
        virtual public void PreRender()
        {
            if (in_shutdown())
            {
                return;
            }

            if (parameters_dirty)
            {
                PolyLine2d spiral = PolyLine2d.MakeBoxSpiral(Vector2d.Zero, length, PathWidth + spacing);

                DMesh3 mesh = new DMesh3();

                List <int> bottom_verts = new List <int>();
                List <int> top_verts    = new List <int>();
                for (int i = 0; i < spiral.VertexCount; ++i)
                {
                    Vector2d x  = spiral[i];
                    Vector3d vb = new Vector3d(x.x, 0, x.y);
                    bottom_verts.Add(mesh.AppendVertex(vb));
                    top_verts.Add(mesh.AppendVertex(vb + Height * Vector3d.AxisY));
                }

                MeshEditor editor = new MeshEditor(mesh);
                editor.StitchSpan(bottom_verts, top_verts);

                PreviewSO.ReplaceMesh(mesh, true);

                Vector3d translate = scene_bounds.Point(1, -1, 1);
                translate.x += spiral.Bounds.Width + PathWidth;
                Frame3f sceneF = Frame3f.Identity.Translated((Vector3f)translate);
                PreviewSO.SetLocalFrame(sceneF, CoordSpace.SceneCoords);

                parameters_dirty = false;
            }
        }
예제 #10
0
        public static DMesh3 ToDMesh3(this Mesh inMesh)
        {
            var outMesh = new DMesh3();

            foreach (var vertex in inMesh.Vertices)
            {
                outMesh.AppendVertex(new Vector3d(vertex.X, vertex.Y, vertex.Z));
            }

            foreach (var face in inMesh.Faces)
            {
                outMesh.AppendTriangle(face.v0, face.v1, face.v2);
            }

            return(outMesh);
        }
예제 #11
0
        public static DMesh3 ToDMesh3(this MeshGeometry3D mesh)
        {
            var dMesh     = new DMesh3();
            var positions = mesh.Positions;
            var indexes   = mesh.TriangleIndices;

            foreach (var p in positions)
            {
                dMesh.AppendVertex(p.ToVector3d());
            }

            for (int i = 0; i < indexes.Count; i += 3)
            {
                dMesh.AppendTriangle(indexes[i], indexes[i + 1], indexes[i + 2]);
            }

            return(dMesh);
        }
예제 #12
0
        /// <summary>
        /// add vertex to mesh, with locking if we are computing in parallel
        /// </summary>
        int append_vertex(Vector3d v)
        {
            bool lock_taken = false;

            if (parallel_mesh_access)
            {
                mesh_lock.Enter(ref lock_taken);
            }

            int vid = Mesh.AppendVertex(v);

            if (lock_taken)
            {
                mesh_lock.Exit();
            }

            return(vid);
        }
예제 #13
0
    public static DMesh3 ToDMesh3(this Mesh mesh)
    {
        DMesh3 result = new DMesh3();

        var indices = mesh.GetIndices(0);
        var verts   = mesh.vertices;

        for (int i = 0; i < verts.Length; i++)
        {
            result.AppendVertex(verts[i]);
        }

        for (int i = 0; i < indices.Length / 3; i++)
        {
            result.AppendTriangle(
                indices[i * 3 + 0],
                indices[i * 3 + 1],
                indices[i * 3 + 2]
                );
        }
        return(result);
    }
예제 #14
0
        private void ExportMesh(ToolpathPreviewMesh mesh, string filePath)
        {
            var dmesh3 = new DMesh3();

            foreach (var vertex in mesh.Vertices)
            {
                dmesh3.AppendVertex(vertex.Point);
            }

            for (int i = 0; i < mesh.Triangles.Count; i += 3)
            {
                dmesh3.AppendTriangle(mesh.Triangles[i], mesh.Triangles[i + 1], mesh.Triangles[i + 2]);
            }

            var writeMesh = new WriteMesh(dmesh3, "Name");
            var stlWriter = new STLWriter();

            using var writer = File.CreateText(filePath);
            stlWriter.Write(writer, new List <WriteMesh>()
            {
                writeMesh
            }, WriteOptions.Defaults);
        }
예제 #15
0
        /// <summary>
        /// Cut a "partial" hole, ie we cut the mesh with the polygon once, and then
        /// extrude downwards to a planar version of the cut boundary.
        ///
        /// Currently only supports extruding downwards from topmost intersection.
        ///
        /// </summary>
        protected bool CutPartialHole(DMesh3 mesh, HoleInfo hi, Vector3d translate, bool bUpwards)
        {
            if (hi.IsVertical == false)
            {
                throw new Exception("unsupported!");
            }

            Vector3d basePoint = CombinedBounds.Center - CombinedBounds.Extents.y * Vector3d.AxisY + translate;

            // do we need to compute spatial DS for each hole? not super efficient...
            DMeshAABBTree3 spatial = new DMeshAABBTree3(mesh, true);

            Vector3d direction = (bUpwards) ? Vector3d.AxisY : -Vector3d.AxisY;
            Vector3d center    = basePoint + new Vector3d(hi.XZOffset.x, 0, hi.XZOffset.y) - 10000 * direction;


            Ray3d ray     = new Ray3d(center, direction);
            int   hit_tid = spatial.FindNearestHitTriangle(ray);

            if (hit_tid == DMesh3.InvalidID)
            {
                return(false);
            }

            IntrRay3Triangle3 intersection = MeshQueries.TriangleIntersection(mesh, hit_tid, ray);
            Vector3d          inter_pos    = ray.PointAt(intersection.RayParameter);

            Frame3f projectFrame = new Frame3f(ray.Origin, ray.Direction);

            int nVerts = 32;

            if (hi.Vertices != 0)
            {
                nVerts = hi.Vertices;
            }
            double    angleShiftRad = hi.AxisAngleD * MathUtil.Deg2Rad;
            Polygon2d circle        = Polygon2d.MakeCircle(hi.Radius, nVerts, angleShiftRad);

            try {
                EdgeLoop loop = null;

                MeshInsertProjectedPolygon insert = new MeshInsertProjectedPolygon(mesh, circle, projectFrame, hit_tid)
                {
                    SimplifyInsertion = false
                };
                if (insert.Insert())
                {
                    loop = insert.InsertedLoop;

                    // [RMS] do we need to simplify for this one?
                    //if (loop.VertexCount > circle.VertexCount)
                    //    loop = simplify_loop(mesh, loop, circle.VertexCount);

                    MeshEditor editor = new MeshEditor(mesh);

                    Vector3d base_pos = inter_pos;
                    base_pos.y = basePoint.y + hi.PartialHoleBaseHeight;

                    int   N       = loop.VertexCount;
                    int[] newLoop = new int[N];
                    for (int k = 0; k < N; ++k)
                    {
                        newLoop[k] = mesh.AppendVertex(mesh, loop.Vertices[k]);
                        Vector3d cur_v = mesh.GetVertex(newLoop[k]);
                        cur_v.y = base_pos.y;
                        mesh.SetVertex(newLoop[k], cur_v);
                    }
                    int   base_vid = mesh.AppendVertex(base_pos);
                    int[] fan_tris = editor.AddTriangleFan_OrderedVertexLoop(base_vid, newLoop);
                    FaceGroupUtil.SetGroupID(mesh, fan_tris, hi.PartialHoleGroupID);
                    int[] stitch_tris = editor.StitchLoop(loop.Vertices, newLoop);

                    // need to remesh fan region because otherwise we get pathological cases
                    RegionRemesher remesh = new RegionRemesher(mesh, fan_tris);
                    remesh.SetTargetEdgeLength(2.0);
                    remesh.SmoothSpeedT       = 1.0;
                    remesh.PreventNormalFlips = true;
                    for (int k = 0; k < 25; ++k)
                    {
                        remesh.BasicRemeshPass();
                    }
                    //remesh.EnableCollapses = remesh.EnableFlips = remesh.EnableSplits = false;
                    //for (int k = 0; k < 20; ++k)
                    //    remesh.BasicRemeshPass();
                    remesh.BackPropropagate();

                    return(true);
                }
                else
                {
                    return(false);
                }
            } catch (Exception e) {
                f3.DebugUtil.Log("partial hole {0} failed!! {1}", hi.nHole, e.Message);
                return(false);
            }
        }
예제 #16
0
        public static DMesh3 UnityMeshToDMesh(Mesh mesh, bool bSwapLeftright)
        {
            Vector3[] vertices = mesh.vertices;
            Vector3[] normals  = mesh.normals;
            Color32[] colors32 = mesh.colors32;
            Color[]   colors   = mesh.colors;
            Vector2[] uv       = mesh.uv;

            bool bNormals    = (normals.Length == mesh.vertexCount);
            bool bColors     = (colors.Length == mesh.vertexCount || colors32.Length == mesh.vertexCount);
            bool bByteColors = (colors32.Length == mesh.vertexCount);
            bool bUVs        = (uv.Length == mesh.vertexCount);

            DMesh3 dmesh = new DMesh3(bNormals, bColors, bUVs, false);

            for (int i = 0; i < mesh.vertexCount; ++i)
            {
                Vector3d v = vertices[i];
                if (bSwapLeftright)
                {
                    v.x = -v.x;
                    v.z = -v.z;
                }
                NewVertexInfo vInfo = new NewVertexInfo(v);
                if (bNormals)
                {
                    vInfo.bHaveN = true;
                    vInfo.n      = normals[i];
                    if (bSwapLeftright)
                    {
                        vInfo.n.x = -vInfo.n.x;
                        vInfo.n.z = -vInfo.n.z;
                    }
                }
                if (bColors)
                {
                    vInfo.bHaveC = true;
                    if (bByteColors)
                    {
                        vInfo.c = new Colorf(colors32[i].r, colors32[i].g, colors32[i].b, 255);
                    }
                    else
                    {
                        vInfo.c = colors[i];
                    }
                }
                if (bUVs)
                {
                    vInfo.bHaveUV = true;
                    vInfo.uv      = uv[i];
                }

                int vid = dmesh.AppendVertex(vInfo);
                if (vid != i)
                {
                    throw new InvalidOperationException("UnityUtil.UnityMeshToDMesh: indices weirdness...");
                }
            }

            int[] triangles = mesh.triangles;
            for (int i = 0; i < triangles.Length / 3; ++i)
            {
                dmesh.AppendTriangle(triangles[3 * i], triangles[3 * i + 1], triangles[3 * i + 2]);
            }

            return(dmesh);
        }
예제 #17
0
        // Ctor
        public TerrainChunk(int _arrX, int _arrY, int terrainSize)
        {
            //this can be done here because it wont ever need to be modified.
            List <int> inds = new List <int>();

            #region Init
            xPos   = _arrX * (numXVerts - 1);
            yPos   = _arrY * (numXVerts - 1);
            arrayX = _arrX;
            arrayY = _arrY;

            dMesh = new DMesh3(MeshComponents.VertexNormals | MeshComponents.VertexColors);

            int indexTracker = 0;
            for (int i = 0; i < numXVerts; i++)
            {
                for (int j = 0; j < numXVerts; j++)
                {
                    Vector3d v = new Vector3d((float)i + xPos, 0, (float)j + yPos);
                    //vertices.Add(new BasicVertex(Convert.ToV3(v), new Vector3(0, 0, 0), new Vector3(0, 1, 0)));
                    dMesh.AppendVertex(new NewVertexInfo(v, new Vector3f(0, 1, 0)));

                    //fancy uv stuff.
                    float uvu, uvv;
                    uvu = ((1f / (numXVerts - 1)) * i);
                    uvv = 1 - ((1f / (numXVerts - 1)) * j);


                    Vertex vert = new Vertex()
                    {
                        x     = (float)v.x,
                        y     = (float)v.y,
                        z     = (float)v.z,
                        u     = uvu,
                        v     = uvv,
                        n1    = 0.0f,
                        n2    = 1.0f,
                        n3    = 0.0f,
                        index = indexTracker
                    };
                    vertices.Add(vert);
                    vertNeedsCollisionUpdate.Add(false);

                    indexTracker++;
                }
            }
            for (int j = 0; j < numXVerts - 1; j++)
            {
                for (int i = 0; i < numXVerts - 1; i++)
                {
                    int i1, i2, i3, i4, i5, i6;

                    int row1 = i * numXVerts;
                    int row2 = (i + 1) * numXVerts;

                    i1 = row1 + j;
                    i2 = row1 + j + 1;
                    i3 = row2 + j;

                    i4 = row2 + j + 1;
                    i5 = row2 + j;
                    i6 = row1 + j + 1;

                    if (i == numXVerts - 1 && j == numXVerts - 1)
                    {
                        Console.Write(i4 + " " + i5 + " " + i6);
                    }

                    dMesh.AppendTriangle(i1, i2, i3);
                    dMesh.AppendTriangle(i4, i5, i6);
                    inds.Add(i1);
                    inds.Add(i2);
                    inds.Add(i3);
                    inds.Add(i4);
                    inds.Add(i5);
                    inds.Add(i6);
                }
            }
            dMesh.EnableVertexNormals(new Vector3f(0, 1, 0));

            dMeshAABB = new DMeshAABBTree3(dMesh);
            dMeshAABB.Build();
            #endregion
            //
            //
            InitRendering(inds);
        }
예제 #18
0
        protected override async Task _init()
        {
            RecordSet layer = _layer as RecordSet;
            string    ex    = Path.GetExtension(layer.Source).ToLower();

            if (ex != ".dxf")
            {
                DMesh3Builder meshes = await loadObj(layer.Source);

                features = meshes.Meshes;
                foreach (DMesh3 mesh in features)
                {
                    foreach (int idx in mesh.VertexIndices())
                    {
                        Vector3d vtx = mesh.GetVertex(idx);
                        mesh.SetVertex(idx, new Vector3d(vtx.x, vtx.z, vtx.y));
                    }
                }
                symbology = layer.Properties.Units;
            }
            if (ex == ".dxf")
            {
                List <Vector3d> vertexes = new List <Vector3d>();
                List <Index3i>  tris     = new List <Index3i>();

                try {
                    //
                    // Try opening with netDxf - this will only open files in autoCAD version 2000 or later
                    //
                    if (layer.Crs != null && layer.Crs != "")
                    {
                        SetCrs(Convert.TextToSR(layer.Crs));
                    }
                    DXF.DxfDocument doc;
                    using (Stream stream = File.Open(layer.Source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                        doc = DXF.DxfDocument.Load(stream);
                        stream.Close();
                    }
                    string layout = doc.ActiveLayout;
                    IEnumerable <Face3d>     faces     = doc.Faces3d;
                    List <DCurve3>           curves    = new List <DCurve3>();
                    CoordinateTransformation transform = new CoordinateTransformation(GetCrs(), AppState.instance.mapProj);
                    foreach (Face3d face in faces)
                    {
                        List <Vector3d> tri = new List <Vector3d>();
                        tri.Add(face.FirstVertex.ToVector3d(transform));
                        tri.Add(face.SecondVertex.ToVector3d(transform));
                        tri.Add(face.ThirdVertex.ToVector3d(transform));
                        if (face.FourthVertex != face.ThirdVertex)
                        {
                            Debug.Log(" Not a Tringle");
                        }
                        curves.Add(new DCurve3(tri, false, true));
                    }
                    //
                    // for each face, check to make sure that vertices are in the vertex list and add the tri to the tri list
                    //
                    foreach (DCurve3 curve in curves)
                    {
                        List <int> tri = new List <int>();
                        for (int i = 0; i < 3; i++)
                        {
                            Vector3d v     = curve.GetVertex(i);
                            int      index = vertexes.IndexOf(v);
                            if (index == -1)
                            {
                                vertexes.Add(v);
                                index = vertexes.IndexOf(v);
                            }
                            tri.Add(index);
                        }
                        tris.Add(new Index3i(tri.ToArray()));
                    }
                } catch {
                    //
                    // if netDXF fails - try opening in GDAL that can open AutoCAD 2 file
                    //
                    using (OgrReader ogrReader = new OgrReader()) {
                        await ogrReader.Load(layer.Source, layer.Properties.ReadOnly? 0 : 1, layer.Properties.SourceType);

                        entities = ogrReader.GetLayers()[0];
                        SetCrs(OgrReader.getSR(entities, layer));
                        RecordSet metadata = GetMetadata();
                        if (metadata.Properties.BBox != null)
                        {
                            entities.SetSpatialFilterRect(metadata.Properties.BBox[0], metadata.Properties.BBox[1], metadata.Properties.BBox[2], metadata.Properties.BBox[3]);
                        }
                        await ogrReader.GetFeaturesAsync(entities);

                        foreach (Feature feature in ogrReader.features)
                        {
                            Geometry geom = feature.GetGeometryRef();
                            if (geom == null)
                            {
                                continue;
                            }
                            wkbGeometryType ftype = geom.GetGeometryType();
                            OgrReader.Flatten(ref ftype);
                            //
                            // Get the faces
                            //
                            if (ftype == wkbGeometryType.wkbPolygon)
                            {
                                List <Geometry> LinearRings = new List <Geometry>();
                                List <DCurve3>  curves      = new List <DCurve3>();
                                for (int i = 0; i < geom.GetGeometryCount(); i++)
                                {
                                    LinearRings.Add(geom.GetGeometryRef(i));
                                }
                                //
                                // Load the faces as a list of DCurve3
                                //
                                foreach (Geometry LinearRing in LinearRings)
                                {
                                    wkbGeometryType type = LinearRing.GetGeometryType();
                                    if (type == wkbGeometryType.wkbLinearRing || type == wkbGeometryType.wkbLineString25D || type == wkbGeometryType.wkbLineString)
                                    {
                                        LinearRing.CloseRings();
                                        DCurve3 curve = new DCurve3();
                                        curve.FromGeometry(LinearRing, GetCrs());
                                        if (curve.VertexCount != 4)
                                        {
                                            Debug.LogError("incorrect face size");
                                        }
                                        else
                                        {
                                            curves.Add(curve);
                                        }
                                    }
                                }
                                //
                                // for each tri, check to make sure that vertcie are in the vertex list and add the tri to the tri list
                                //
                                foreach (DCurve3 curve in curves)
                                {
                                    List <int> tri = new List <int>();
                                    for (int i = 0; i < 3; i++)
                                    {
                                        Vector3d v     = curve.GetVertex(i);
                                        int      index = vertexes.IndexOf(v);
                                        if (index == -1)
                                        {
                                            vertexes.Add(v);
                                            index = vertexes.IndexOf(v);
                                        }
                                        tri.Add(index);
                                    }
                                    tris.Add(new Index3i(tri.ToArray()));
                                }
                            }
                        }
                    }
                }
                //
                // vertexes and tris should now describe a mesh
                //
                DMesh3 dmesh = new DMesh3(false, false, false, false);
                vertexes.ForEach(v => dmesh.AppendVertex(v));
                tris.ForEach(t => dmesh.AppendTriangle(t));
                features = new List <DMesh3>();
                features.Add(dmesh.Compactify());
                symbology = layer.Properties.Units;
                return;
            }
        }
예제 #19
0
        public virtual DMesh3 RestoreDMesh(TypedAttribSet attributes)
        {
            bool           is_compressed = false;
            TypedAttribSet meshAttr      = find_struct(attributes, IOStrings.BinaryDMeshStruct);

            if (meshAttr == null)
            {
                meshAttr      = find_struct(attributes, IOStrings.CompressedDMeshStruct);
                is_compressed = true;
            }
            if (meshAttr == null)
            {
                throw new Exception("SOFactory.RestoreDMesh: DMesh binary or compressed struct not found!");
            }

            VectorArray3d v = null;
            VectorArray3f n = null, c = null;
            VectorArray2f uv = null;

            VectorArray3i t = null;

            int[] g = null;

            IndexArray4i e = null;

            short[] e_ref = null;

            var storageMode = IOStrings.MeshStorageMode.EdgeRefCounts;

            if (meshAttr.ContainsKey(IOStrings.AMeshStorageMode))
            {
                storageMode = (IOStrings.MeshStorageMode)(int) meshAttr[IOStrings.AMeshStorageMode];
            }

            if (is_compressed)
            {
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshVertices3Compressed))
                {
                    v = meshAttr[IOStrings.AMeshVertices3Compressed] as VectorArray3d;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshNormals3Compressed))
                {
                    n = meshAttr[IOStrings.AMeshNormals3Compressed] as VectorArray3f;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshColors3Compressed))
                {
                    c = meshAttr[IOStrings.AMeshColors3Compressed] as VectorArray3f;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshUVs2Compressed))
                {
                    uv = meshAttr[IOStrings.AMeshUVs2Compressed] as VectorArray2f;
                }

                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshTrianglesCompressed))
                {
                    t = meshAttr[IOStrings.AMeshTrianglesCompressed] as VectorArray3i;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshTriangleGroupsCompressed))
                {
                    g = meshAttr[IOStrings.AMeshTriangleGroupsCompressed] as int[];
                }

                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshEdgesCompressed))
                {
                    e = meshAttr[IOStrings.AMeshEdgesCompressed] as IndexArray4i;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshEdgeRefCountsCompressed))
                {
                    e_ref = meshAttr[IOStrings.AMeshEdgeRefCountsCompressed] as short[];
                }
            }
            else
            {
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshVertices3Binary))
                {
                    v = meshAttr[IOStrings.AMeshVertices3Binary] as VectorArray3d;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshNormals3Binary))
                {
                    n = meshAttr[IOStrings.AMeshNormals3Binary] as VectorArray3f;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshColors3Binary))
                {
                    c = meshAttr[IOStrings.AMeshColors3Binary] as VectorArray3f;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshUVs2Binary))
                {
                    uv = meshAttr[IOStrings.AMeshUVs2Binary] as VectorArray2f;
                }

                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshTrianglesBinary))
                {
                    t = meshAttr[IOStrings.AMeshTrianglesBinary] as VectorArray3i;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshTriangleGroupsBinary))
                {
                    g = meshAttr[IOStrings.AMeshTriangleGroupsBinary] as int[];
                }

                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshEdgesBinary))
                {
                    e = meshAttr[IOStrings.AMeshEdgesBinary] as IndexArray4i;
                }
                if (check_key_or_debug_print(meshAttr, IOStrings.AMeshEdgeRefCountsBinary))
                {
                    e_ref = meshAttr[IOStrings.AMeshEdgeRefCountsBinary] as short[];
                }
            }

            DMesh3 m = new DMesh3();

            if (n != null)
            {
                m.EnableVertexNormals(Vector3f.Zero);
            }
            if (c != null)
            {
                m.EnableVertexColors(Vector3f.Zero);
            }
            if (uv != null)
            {
                m.EnableVertexUVs(Vector2f.Zero);
            }
            if (g != null)
            {
                m.EnableTriangleGroups(0);
            }

            if (storageMode == IOStrings.MeshStorageMode.EdgeRefCounts)
            {
                if (v == null || t == null || e == null || e_ref == null)
                {
                    return(null);
                }

                m.VerticesBuffer = new DVector <double>(v);
                if (n != null)
                {
                    m.NormalsBuffer = new DVector <float>(n);
                }
                if (c != null)
                {
                    m.ColorsBuffer = new DVector <float>(c);
                }
                if (uv != null)
                {
                    m.UVBuffer = new DVector <float>(uv);
                }
                m.TrianglesBuffer = new DVector <int>(t);
                if (g != null)
                {
                    m.GroupsBuffer = new DVector <int>(g);
                }

                m.EdgesBuffer    = new DVector <int>(e);
                m.EdgesRefCounts = new RefCountVector(e_ref);
                m.RebuildFromEdgeRefcounts();
            }
            else if (storageMode == IOStrings.MeshStorageMode.Minimal)
            {
                if (v == null || t == null)
                {
                    return(null);
                }

                int           NV    = v.Count;
                NewVertexInfo vinfo = new NewVertexInfo();
                for (int k = 0; k < NV; ++k)
                {
                    vinfo.v = v[k];
                    if (n != null)
                    {
                        vinfo.n = n[k];
                    }
                    if (c != null)
                    {
                        vinfo.c = c[k];
                    }
                    if (uv != null)
                    {
                        vinfo.uv = uv[k];
                    }
                    m.AppendVertex(ref vinfo);
                }

                int NT = t.Count;
                for (int k = 0; k < NT; ++k)
                {
                    Vector3i tri  = t[k];
                    int      setg = (g == null) ? -1 : g[k];
                    m.AppendTriangle(tri, setg);
                }
            }
            else
            {
                throw new Exception("SOFactory.RestoreDMesh: unsupported mesh storage mode");
            }

            return(m);
        }