From 455a081ee74fbb09d57857e10f70e651b0862504 Mon Sep 17 00:00:00 2001 From: Google DeepMind Date: Fri, 28 Jul 2023 07:50:15 -0700 Subject: [PATCH] Cache triangles, vertices and normals from the mesh outside of the triangle loop so we don't have to request them inside the loop. This is because each time we call mesh.triangles or similar, the data gets copied from the native memory to a c# structure. PiperOrigin-RevId: 551851115 Change-Id: Ie7820f61639f0d727ecf9716044ce18b3277913b --- unity/Editor/Importer/StlMeshParser.cs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/unity/Editor/Importer/StlMeshParser.cs b/unity/Editor/Importer/StlMeshParser.cs index 24452e1b..207218dc 100644 --- a/unity/Editor/Importer/StlMeshParser.cs +++ b/unity/Editor/Importer/StlMeshParser.cs @@ -101,21 +101,28 @@ public class StlMeshParser { writer.Write(_asciiFileTypeId); writer.Write(new byte[_headerLength - _asciiFileTypeId.Length - 1]); - var numTriangles = mesh.triangles.Length / 3; + // Reading mesh.triangles etc causes a c# array to be instantiated each time to store a copy + // of the data that is owned by the native runtime. For this reason, it's important we do + // this once per mesh, and definitely not per triangle. + var triangles = mesh.triangles; + var normals = mesh.normals; + var vertices = mesh.vertices; + + var numTriangles = triangles.Length / 3; writer.Write((int)numTriangles); - for (var i = 0; i < mesh.triangles.Length; i += _verticesPerTriangle) { + for (var i = 0; i < triangles.Length; i += _verticesPerTriangle) { // STL format uses face normals, while Unity Meshes use vertex normals. We need to convert // one into another by calculating a mean of vertex normals. - var i1 = mesh.triangles[i]; - var i2 = mesh.triangles[i + 1]; - var i3 = mesh.triangles[i + 2]; - var faceNormal = (mesh.normals[i1] + mesh.normals[i2] + mesh.normals[i3]).normalized; + var i1 = triangles[i]; + var i2 = triangles[i + 1]; + var i3 = triangles[i + 2]; + var faceNormal = (normals[i1] + normals[i2] + normals[i3]).normalized; writer.Write(ToXZY(faceNormal)); - writer.Write(ToXZY(mesh.vertices[i1])); - writer.Write(ToXZY(mesh.vertices[i3])); - writer.Write(ToXZY(mesh.vertices[i2])); + writer.Write(ToXZY(vertices[i1])); + writer.Write(ToXZY(vertices[i3])); + writer.Write(ToXZY(vertices[i2])); writer.Write((short)0); }