wo80 / Triangle.NET

C# / .NET version of Jonathan Shewchuk's Triangle mesh generator.
442 stars 81 forks source link

Deep copy a mesh surface #45

Closed AllenTaiTW closed 2 months ago

AllenTaiTW commented 2 months ago

How to deep copy a mesh surface because adjustments to the z-coordinate are needed. Currently, I'm reconstructing a new mesh using the point set of the mesh, but if the former has undergone operations such as flipping, the reconstruction won't be optimal.

wo80 commented 2 months ago

Cloning isn't supported out of the box. You can try the following code, it should be fairly efficient. Let me know if that works. If it doesn't, you're welcome to do a pull request adding the features you need.

using System.Linq;
using TriangleNet;
using TriangleNet.Geometry;
using TriangleNet.Meshing;
using TriangleNet.Topology;

public static Mesh Clone(IMesh mesh)
{
    mesh.Renumber();

    var p = new Polygon(mesh.Vertices.Count);

    // Make sure to use the correct type here (point including z-coordinate) and to copy the id.
    p.Points.AddRange(mesh.Vertices.Select(p => new Vertex(p.X, p.Y, p.Z, p.Label) { ID = p.ID }));
    p.Segments.AddRange(mesh.Segments);
    p.Holes.AddRange(mesh.Holes);

    // The mesh will use the vertex instances of the polygon p but create new segment and
    // triangle instances.
    return Converter.Instance.ToMesh(p, mesh.Triangles.ToList());
}

EDIT: updated the code (no need to create new segments)

AllenTaiTW commented 2 months ago

Thank you for your response! The Clone() method works very well. It would be better if we could also deep copy the mesh.Segments.

wo80 commented 2 months ago

Ok, I missed that the converter will reference the original vertices of the segments. Please replace

p.Segments.AddRange(mesh.Segments);

with

// Make sure the segments reference the new points (this works because the mesh vertices are numbered linearly).
p.Segments.AddRange(mesh.Segments.Select(s => new Segment(p.Points[s.P0], p.Points[s.P1], s.Label)));

If you think we are done here, please close the issue.