C# fastest way to add a list of vertices to a mesh

Thanks Giulio, you were right about the vertices being too close to each other. I always worked with a “Large objects - Meters” template, which has a precision of only 2 decimal points. Apparently this was too little for Point3f to work. Switching to “Small objects - Meters” with 0.001 unit tolerance fixed it for me.

Results are really satisfying:

For everyone who is interested here is the final code:

public static Mesh CreateQuadMesh(Mesh mesh, Point3f[] vertices, Color[] colors, int xStride, int yStride)
        {
            int xd = xStride;       // The x-dimension of the data
            int yd = yStride;       // They y-dimension of the data

            // If the mesh is empty or mesh dimensions changed - reset everything 
            if (mesh.Faces.Count != (xStride - 2) * (yStride - 2))
            {
                mesh = new Mesh();
                mesh.Vertices.Capacity = vertices.Length;      // Don't resize array
                mesh.Vertices.UseDoublePrecisionVertices = false;
                mesh.Vertices.AddVertices(vertices);       

                for (int y = 1; y < yd - 1; y++)       // Iterate over y dimension
                {
                    for (int x = 1; x < xd - 1; x++)       // Iterate over x dimension
                    {
                        int i = y * xd + x;
                        int j = (y - 1) * xd + x;

                        mesh.Faces.AddFace(j - 1, j, i, i - 1);
                    }
                }
            }
            else // don't redraw mesh, just replace the Z coordinate of each vertex
            {
                mesh.Vertices.UseDoublePrecisionVertices = false; 

                unsafe
                {
                    using (var meshAccess = mesh.GetUnsafeLock(true))
                    {
                        int arrayLength;
                        Point3f* points = meshAccess.VertexPoint3fArray(out arrayLength);
                        for (int i = 0; i < arrayLength; i++)
                        {
                            points->Z = vertices[i].Z;
                            points++;
                        }
                        mesh.ReleaseUnsafeLock(meshAccess);
                    }  
                }
            }

            if (colors.Length > 0) // Colors only provided if the mesh style permits
            {
                mesh.VertexColors.SetColors(colors);
            }

            return mesh;
        }
6 Likes

I don’t know if you’ll see any improvement, but you could even set the z values in a parallel for loop.

Actually, this might even be faster

1 Like