Godot Engine – Multi-platform 2D and 3D game engine
thirdparty: Update meshoptimizer to v1.3
Arseny Kapoulkine3560e41ffd22
diff --git a/modules/meshoptimizer/SCsub b/modules/meshoptimizer/SCsubindex bc7324d16e8..db4940c6142 100644--- a/modules/meshoptimizer/SCsub+++ b/modules/meshoptimizer/SCsub@@ -17,10 +17,14 @@ thirdparty_sources = ["indexanalyzer.cpp","indexcodec.cpp","indexgenerator.cpp",+ "meshletcodec.cpp",+ "meshletutils.cpp",+ "opacitymap.cpp","overdrawoptimizer.cpp","partition.cpp","quantization.cpp","rasterizer.cpp",+ "remesher.cpp","simplifier.cpp","spatialorder.cpp","stripifier.cpp",diff --git a/scene/resources/surface_tool.h b/scene/resources/surface_tool.hindex 4083045d699..a3f2d6523fa 100644--- a/scene/resources/surface_tool.h+++ b/scene/resources/surface_tool.h@@ -93,6 +93,12 @@ public:SIMPLIFY_REGULARIZE = 1 << 4, // From meshopt_SimplifyRegularize/* Allow collapses across attribute discontinuities, except for vertices that are tagged with 0x02 in vertex_lock. */SIMPLIFY_PERMISSIVE = 1 << 5, // From meshopt_SimplifyPermissive+ /* Produce more regular triangle sizes and shapes during simplification, at a small cost to geometric and attribute quality. */+ SIMPLIFY_REGULARIZE_LIGHT = 1 << 6, // From meshopt_SimplifyRegularizeLight+ /* Try to preserve fold lines between opposite-facing triangles, at a small performance cost. */+ SIMPLIFY_PRESERVE_FOLDS = 1 << 7, // From meshopt_SimplifyPreserveFolds+ /* Clamp attribute error to match position error scale and avoid extreme error values in areas with high attribute variance. */+ SIMPLIFY_ERROR_CLAMPED = 1 << 8, // From meshopt_SimplifyErrorClamped/* Produce tangents compatible with MikkTSpace (same weighting and fallbacks) at the cost of reduced quality. Not recommended unless normal maps are baked. */TANGENT_COMPATIBLE = 1 << 0, // From meshopt_TangentCompatible};diff --git a/thirdparty/README.md b/thirdparty/README.mdindex d597fbd7000..5161ba6c789 100644--- a/thirdparty/README.md+++ b/thirdparty/README.md@@ -722,7 +722,7 @@ Patches:## meshoptimizer- Upstream: https://github.com/zeux/meshoptimizer-- Version: 1.2 (9d9890c73011d75920af614485296d1e03e95448, 2026)+- Version: 1.3 (9e1f07b159d3cb777f1c67ed31fc11fd117986f4, 2026)- License: MITFiles extracted from upstream repository:diff --git a/thirdparty/meshoptimizer/clusterizer.cpp b/thirdparty/meshoptimizer/clusterizer.cppindex 0b630b2cb01..8e884e0632c 100644--- a/thirdparty/meshoptimizer/clusterizer.cpp+++ b/thirdparty/meshoptimizer/clusterizer.cpp@@ -863,6 +863,15 @@ static void bvhComputeArea(float* areas, const BVHBox* boxes, const unsigned intfor (size_t i = 0; i < count; ++i){+#ifdef SIMD_SSE+ // prefetch boxes ahead to reduce the stalls from cache misses; the loop is not load-limited so these do not hurt even on smaller inputs+ if (i + 16 < count)+ {+ _mm_prefetch(reinterpret_cast<const char*>(&boxes[order[i + 16]]), _MM_HINT_T0);+ _mm_prefetch(reinterpret_cast<const char*>(&boxes[order[count - 1 - i - 16]]), _MM_HINT_T0);+ }+#endif+float larea = boxMerge(accuml, boxes[order[i]]);float rarea = boxMerge(accumr, boxes[order[count - 1 - i]]);diff --git a/thirdparty/meshoptimizer/indexcodec.cpp b/thirdparty/meshoptimizer/indexcodec.cppindex 2aa1297d0ec..8dead634328 100644--- a/thirdparty/meshoptimizer/indexcodec.cpp+++ b/thirdparty/meshoptimizer/indexcodec.cpp@@ -138,19 +138,25 @@ static int getCodeAuxIndex(unsigned char v, const unsigned char* table)return -1;}-static void writeTriangle(void* destination, size_t offset, size_t index_size, unsigned int a, unsigned int b, unsigned int c)+static void* writeTriangle(void* destination, size_t index_size, unsigned int a, unsigned int b, unsigned int c){if (index_size == 2){- static_cast<unsigned short*>(destination)[offset + 0] = (unsigned short)(a);- static_cast<unsigned short*>(destination)[offset + 1] = (unsigned short)(b);- static_cast<unsigned short*>(destination)[offset + 2] = (unsigned short)(c);+ unsigned short* tri = static_cast<unsigned short*>(destination);+ tri[0] = (unsigned short)(a);+ tri[1] = (unsigned short)(b);+ tri[2] = (unsigned short)(c);++ return tri + 3;}else{- static_cast<unsigned int*>(destination)[offset + 0] = a;- static_cast<unsigned int*>(destination)[offset + 1] = b;- static_cast<unsigned int*>(destination)[offset + 2] = c;+ unsigned int* tri = static_cast<unsigned int*>(destination);+ tri[0] = a;+ tri[1] = b;+ tri[2] = c;++ return tri + 3;}}@@ -409,19 +415,16 @@ int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t inde// since we store 16-byte codeaux table at the end, triangle data has to begin before data_safe_endconst unsigned char* code = buffer + 1;- const unsigned char* data = code + index_count / 3;+ const unsigned char* code_end = code + index_count / 3;+ const unsigned char* data = code_end;++ // each triangle reads at most 16 bytes of data: 1b for codeaux and 5b for each free indexconst unsigned char* data_safe_end = buffer + buffer_size - 16;const unsigned char* codeaux_table = data_safe_end;- for (size_t i = 0; i < index_count; i += 3)+ while (code < code_end){- // make sure we have enough data to read for a triangle- // each triangle reads at most 16 bytes of data: 1b for codeaux and 5b for each free index- // after this we can be sure we can read without extra bounds checks- if (data > data_safe_end)- return -2;-unsigned char codetri = *code++;if (codetri < 0xf0)@@ -441,6 +444,14 @@ int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t inde{// fifo reads are wrapped around 16 entry bufferunsigned int cf = vertexfifo[(vertexfifooffset - 1 - fec) & 15];++#if (defined(__GNUC__) || defined(__clang__)) && (defined(__x86_64__) || defined(__aarch64__))+ // on clang, x86-cmov-conversion pass emits a branch since cf is a load from memory; asm barrier defeats this+ // this can be fixed with __builtin_unpredictable, but gcc doesn't support it and has a similar problem due to if-conversion+ // additionally, gcc can fuse a/b into one 64-bit load but use 32-bit edgefifo[] stores, which breaks load store forwarding+ __asm__("" : "+r"(a) : "r"(cf));+#endif+c = (fec == 0) ? next : cf;int fec0 = fec == 0;@@ -451,9 +462,13 @@ int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t inde}else{- // fec - (fec ^ 3) decodes 13, 14 into -1, 1+ // make sure we have enough data to read for a triangle; this check covers worst case advance+ if (data > data_safe_end)+ return -2;++ // fec * 2 - 27 decodes 13, 14 into -1, 1// note that we need to update the last index since free indices are delta-encoded- last = c = (fec != 15) ? last + (fec - (fec ^ 3)) : decodeIndex(data, last);+ last = c = (fec != 15) ? last + (fec * 2 - 27) : decodeIndex(data, last);// push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctlypushVertexFifo(vertexfifo, c, vertexfifooffset);@@ -464,7 +479,7 @@ int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t indepushEdgeFifo(edgefifo, a, c, edgefifooffset);// output triangle- writeTriangle(destination, i, index_size, a, b, c);+ destination = writeTriangle(destination, index_size, a, b, c);}else{@@ -494,7 +509,7 @@ int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t indenext += fec0;// output triangle- writeTriangle(destination, i, index_size, a, b, c);+ destination = writeTriangle(destination, index_size, a, b, c);// push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctlypushVertexFifo(vertexfifo, a, vertexfifooffset);@@ -507,6 +522,10 @@ int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t inde}else{+ // make sure we have enough data to read for a triangle; this check covers worst case advance+ if (data > data_safe_end)+ return -2;+// slow path: read a full byte for codeaux instead of using a table lookupunsigned char codeaux = *data++;@@ -535,7 +554,7 @@ int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t indelast = c = decodeIndex(data, last);// output triangle- writeTriangle(destination, i, index_size, a, b, c);+ destination = writeTriangle(destination, index_size, a, b, c);// push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctlypushVertexFifo(vertexfifo, a, vertexfifooffset);diff --git a/thirdparty/meshoptimizer/indexgenerator.cpp b/thirdparty/meshoptimizer/indexgenerator.cppindex 1b707bb1b6e..0f29614000f 100644--- a/thirdparty/meshoptimizer/indexgenerator.cpp+++ b/thirdparty/meshoptimizer/indexgenerator.cpp@@ -11,7 +11,7 @@namespace meshopt{-static unsigned int hashUpdate4(unsigned int h, const unsigned char* key, size_t len)+static unsigned int hashUpdate(unsigned int h, const unsigned char* key, size_t len){// MurmurHash2const unsigned int m = 0x5bd1e995;@@ -19,7 +19,8 @@ static unsigned int hashUpdate4(unsigned int h, const unsigned char* key, size_twhile (len >= 4){- unsigned int k = *reinterpret_cast<const unsigned int*>(key);+ unsigned int k;+ memcpy(&k, key, sizeof(k));k *= m;k ^= k >> r;@@ -32,6 +33,13 @@ static unsigned int hashUpdate4(unsigned int h, const unsigned char* key, size_tlen -= 4;}+ if (len > 0)+ {+ h ^= key[0] | (key[len / 2] << 8) | (key[len - 1] << 16);+ h *= m;+ h ^= h >> r;+ }+return h;}@@ -43,7 +51,7 @@ struct VertexHashersize_t hash(unsigned int index) const{- return hashUpdate4(0, vertices + index * vertex_stride, vertex_size);+ return hashUpdate(0, vertices + index * vertex_stride, vertex_size);}bool equal(unsigned int lhs, unsigned int rhs) const@@ -66,7 +74,7 @@ struct VertexStreamHasherconst meshopt_Stream& s = streams[i];const unsigned char* data = static_cast<const unsigned char*>(s.data);- h = hashUpdate4(h, data + index * s.stride, s.size);+ h = hashUpdate(h, data + index * s.stride, s.size);}return h;diff --git a/thirdparty/meshoptimizer/meshoptimizer.h b/thirdparty/meshoptimizer/meshoptimizer.hindex e6aa58eb4d6..ff69785b52c 100644--- a/thirdparty/meshoptimizer/meshoptimizer.h+++ b/thirdparty/meshoptimizer/meshoptimizer.h@@ -1,5 +1,5 @@/**- * meshoptimizer - version 1.2+ * meshoptimizer - version 1.3** Copyright (C) 2016-2026, by Arseny Kapoulkine ([email protected])* Report bugs and download new versions at https://github.com/zeux/meshoptimizer@@ -12,7 +12,7 @@#include <stddef.h>/* Version macro; major * 1000 + minor * 10 + patch */-#define MESHOPTIMIZER_VERSION 1020 /* 1.2 */+#define MESHOPTIMIZER_VERSION 1030 /* 1.3 *//* If no API is defined, assume default */#ifndef MESHOPTIMIZER_API@@ -104,17 +104,17 @@ MESHOPTIMIZER_API void meshopt_remapVertexBuffer(void* destination, const void*MESHOPTIMIZER_API void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap);/**- * Experimental: Filter out redundant triangles from the index buffer and return the number of remaining indices+ * Filter out redundant triangles from the index buffer and return the number of remaining indices* Triangles are considered redundant if they are degenerate (two vertices have the same vertex key) or duplicate (matching triangle was present earlier).* First vertex_size bytes of every vertex are compared for equality; typically vertex_size should be set to the size of the position attribute.* Note that duplicate triangles with opposite windings are preserved, as they may be needed for double-sided rendering.** destination must contain enough space for the resulting index buffer (index_count elements)*/-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_filterIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride);+MESHOPTIMIZER_API size_t meshopt_filterIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride);/**- * Experimental: Filter out redundant triangles from the index buffer and return the number of remaining indices+ * Filter out redundant triangles from the index buffer and return the number of remaining indices* Triangles are considered redundant if they are degenerate (two vertices have the same vertex key) or duplicate (matching triangle was present earlier).* All bytes in specified streams are compared for equality; streams should include attributes relevant for position transform (e.g. bone influences).* Note that duplicate triangles with opposite windings are preserved, as they may be needed for double-sided rendering.@@ -122,7 +122,7 @@ MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_filterIndexBuffer(unsigned int* destin* destination must contain enough space for the resulting index buffer (index_count elements)* stream_count must be <= 16*/-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_filterIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count);+MESHOPTIMIZER_API size_t meshopt_filterIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count);/*** Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary@@ -475,10 +475,14 @@ enummeshopt_SimplifyPrune = 1 << 3,/* Produce more regular triangle sizes and shapes during simplification, at some cost to geometric and attribute quality. */meshopt_SimplifyRegularize = 1 << 4,- /* Experimental: Allow collapses across attribute discontinuities, except for vertices that are tagged with meshopt_SimplifyVertex_Protect in vertex_lock. */+ /* Allow collapses across attribute discontinuities, except for vertices that are tagged with meshopt_SimplifyVertex_Protect in vertex_lock. */meshopt_SimplifyPermissive = 1 << 5,/* Produce more regular triangle sizes and shapes during simplification, at a small cost to geometric and attribute quality. */meshopt_SimplifyRegularizeLight = 1 << 6,+ /* Experimental: Try to preserve fold lines between opposite-facing triangles, at a small performance cost. */+ meshopt_SimplifyPreserveFolds = 1 << 7,+ /* Experimental: Clamp attribute error to match position error scale and avoid extreme error values in areas with high attribute variance. */+ meshopt_SimplifyErrorClamped = 1 << 8,};/**@@ -881,7 +885,7 @@ MESHOPTIMIZER_API void meshopt_spatialSortTriangles(unsigned int* destination, cMESHOPTIMIZER_API void meshopt_spatialClusterPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t cluster_size);/**- * Experimental: Opacity micromap generator (measure)+ * Opacity micromap generator (measure)* Computes a subdivision level for each input triangle, as well as deduplicating the triangles that reference the same UVs to reduce rasterization requests.* Returns the number of OMM entries.*@@ -892,10 +896,10 @@ MESHOPTIMIZER_API void meshopt_spatialClusterPoints(unsigned int* destination, c* max_level specifies the maximum subdivision level (0..12)* target_edge can be 0; when >0, triangle subdivision is adaptive and targets target_edge^2 texel area*/-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_opacityMapMeasure(unsigned char* levels, unsigned int* sources, int* omm_indices, const unsigned int* indices, size_t index_count, const float* vertex_uvs, size_t vertex_count, size_t vertex_uvs_stride, unsigned int texture_width, unsigned int texture_height, int max_level, float target_edge);+MESHOPTIMIZER_API size_t meshopt_opacityMapMeasure(unsigned char* levels, unsigned int* sources, int* omm_indices, const unsigned int* indices, size_t index_count, const float* vertex_uvs, size_t vertex_count, size_t vertex_uvs_stride, unsigned int texture_width, unsigned int texture_height, int max_level, float target_edge);/**- * Experimental: Opacity micromap generator (rasterize)+ * Opacity micromap generator (rasterize)* Rasterizes opacity state for a single triangle entry by sampling the alpha texture, using bilinear filtering and 0.5 alpha cutoff.** result should contain enough space for the output opacity data (which can be computed using meshopt_opacityMapEntrySize)@@ -906,11 +910,11 @@ MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_opacityMapMeasure(unsigned char* level* texture_stride specifies the distance in bytes between consecutive pixels, e.g. 4 for RGBA input* texture_pitch specifies the distance in bytes between consecutive rows, e.g. 4*texture_width for tightly packed RGBA input*/-MESHOPTIMIZER_EXPERIMENTAL void meshopt_opacityMapRasterize(unsigned char* result, int level, int states, const float* uv0, const float* uv1, const float* uv2, const unsigned char* texture_data, size_t texture_stride, size_t texture_pitch, unsigned int texture_width, unsigned int texture_height);-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_opacityMapEntrySize(int level, int states);+MESHOPTIMIZER_API void meshopt_opacityMapRasterize(unsigned char* result, int level, int states, const float* uv0, const float* uv1, const float* uv2, const unsigned char* texture_data, size_t texture_stride, size_t texture_pitch, unsigned int texture_width, unsigned int texture_height);+MESHOPTIMIZER_API size_t meshopt_opacityMapEntrySize(int level, int states);/**- * Experimental: Opacity micromap generator (compact)+ * Opacity micromap generator (compact)* Compacts and deduplicates opacity data, merging identical micromap entries and replacing micromap states with special indices (-4..-1) when possible.* Returns the number of OMM entries after compaction; the data array should be trimmed using the last offset/size.*@@ -921,7 +925,7 @@ MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_opacityMapEntrySize(int level, int sta* omm_indices should contain indices into the original OMM data, and will be updated with a new index or a special index (-4..-1) when possible* states should be 2 for 2-state format (opaque/transparent) and 4 for 4-state format (opaque/transparent/unknown)*/-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_opacityMapCompact(unsigned char* data, size_t data_size, unsigned char* levels, unsigned int* offsets, size_t omm_count, int* omm_indices, size_t triangle_count, int states);+MESHOPTIMIZER_API size_t meshopt_opacityMapCompact(unsigned char* data, size_t data_size, unsigned char* levels, unsigned int* offsets, size_t omm_count, int* omm_indices, size_t triangle_count, int states);/*** Tangent generation options@@ -930,17 +934,17 @@ enum{/* Produce tangents compatible with MikkTSpace (same weighting and fallbacks) at the cost of reduced quality. Not recommended unless normal maps are baked. */meshopt_TangentCompatible = 1 << 0,- /* Experimental: For vertices only connected to degenerate triangles, output zero tangents instead of an arbitrary fallback. */+ /* For vertices only connected to degenerate triangles, output zero tangents instead of an arbitrary fallback. */meshopt_TangentZeroFallback = 1 << 1,};/**- * Experimental: Tangent space generator+ * Tangent space generator* Computes per-corner tangent vectors; for each corner, computes normalized tangent vector (xyz) and orientation (w, +/-1).* Bitangent can be reconstructed via cross(normal, tangent.xyz) * tangent.w.* To apply tangents to the mesh, either deindex and reindex it with the tangent stream, or copy tangents to existing vertex data while duplicating* vertices with different tangent vectors (e.g. on UV mirror seams).- * Input can be indexed or unindexed (indices=NULL); this does not affect the resulting tangents, but indexed inputs are ~30% faster to process.+ * Input can be indexed or unindexed (indices=NULL); this does not affect the resulting tangents, but indexed inputs are faster to process.** result must contain enough space for the output tangent data (index_count*4 elements)* indices can be NULL if the input is unindexed@@ -948,7 +952,47 @@ enum* vertex_normals should have unit float3 normal in the first 12 bytes of each vertex* vertex_uvs should have float2 texture coordinate in the first 8 bytes of each vertex*/-MESHOPTIMIZER_EXPERIMENTAL void meshopt_generateTangents(float* result, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, unsigned int options);+MESHOPTIMIZER_API void meshopt_generateTangents(float* result, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, unsigned int options);++/**+ * Experimental: Normal generator+ * Computes per-corner normal vectors; normals are averaged across soft edges, using crease angle to determine which edges are hard.+ * To apply normals to the mesh, either deindex and reindex it with the normal stream, or copy normals to existing vertex data while duplicating+ * vertices with different normal vectors (on normal seams).+ * Input can be indexed or unindexed (indices=NULL); this does not affect the resulting normals, but indexed inputs are faster to process.+ *+ * result must contain enough space for the output normal data (index_count*3 elements)+ * indices can be NULL if the input is unindexed+ * vertex_positions should have float3 position in the first 12 bytes of each vertex+ * crease_angle specifies the angle in radians below which normals are averaged across edges+ * smoothing specifies the amount of smoothing to apply to resulting normals as a post-process; larger smoothing values take longer, with the recommended range being [0..5].+ */+MESHOPTIMIZER_EXPERIMENTAL void meshopt_generateNormals(float* result, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float crease_angle, float smoothing);++/**+ * Experimental: Remeshing flags+ */+enum+{+ /* Produce a two-sided shell that wraps around surfaces of the original mesh, instead of a solid mesh. */+ meshopt_RemeshShell = 1 << 0,+ /* Compute optimal output positions that approximate the original surface as closely as possible. */+ meshopt_RemeshSolve = 1 << 1,+};++/**+ * Experimental: Voxel remesher+ * Generates a new mesh that approximates or refines the original mesh, attempting to preserve mesh appearance at a given voxel resolution.+ * The original topology is not preserved; features that are closer than the voxel size may be merged, and small gaps in the original mesh may be closed.+ * Returns the number of triangles in the new mesh, with destination containing a vertex position for each triangle corner.+ *+ * destination can be NULL; when it's not NULL, it must contain enough space for the resulting triangle buffer (max_triangle_count * 3 vertices, 3 floats per vertex)+ * max_triangle_count is the number of triangles that can be written; when destination is NULL or insufficiently large, the returned value is an upper bound on the number of triangles+ * vertex_positions should have float3 position in the first 12 bytes of each vertex+ * resolution is the dimension of the internal voxel grid and should be in the range [4, 256]+ * options must be a bitmask composed of meshopt_RemeshX options; 0 is a safe default+ */+MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_remesh(float* destination, size_t max_triangle_count, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, unsigned int options);/*** Quantize a float into half-precision (as defined by IEEE-754 fp16) floating point value@@ -972,7 +1016,7 @@ MESHOPTIMIZER_API float meshopt_quantizeFloat(float v, int N);MESHOPTIMIZER_API float meshopt_dequantizeHalf(unsigned short h);/**- * Experimental: Compute shared exponent suitable for mesh/cluster position quantization+ * Compute shared exponent suitable for mesh/cluster position quantization* Given mesh or cluster bounds, compute a shared exponent that can be used to quantize any position inside the bounds to a 24-bit integer grid.* The resulting output can be stored as a compact bit-stream to be decoded directly in shaders, or to be used as an input to RT BVH builders,* for example via D3D12_VERTEX_FORMAT_COMPRESSED1 in DXR2 (max_bits=16).@@ -983,10 +1027,10 @@ MESHOPTIMIZER_API float meshopt_dequantizeHalf(unsigned short h);* The resulting integer can be stored as signed 24-bit, or as an unsigned offset from a signed 24-bit anchor value, shared between all positions.** minv/maxv specify the axis-aligned bounding box of the mesh or cluster; each should refer to a float3 value- * min_exp specifies the minimum value for the returned exponent, limiting precision to reduce size; e.g. min_exp = -10 will produce minimum error of 1mm given metric units+ * min_exp specifies the minimum value for the returned exponent, limiting precision to reduce size; e.g. min_exp = -10 limits precision to 1mm given metric units* max_bits specifies the maximum allowed number of bits for the quantized integer range (offset from anchor is an unsigned integer up to 2^max_bits-1)*/-MESHOPTIMIZER_EXPERIMENTAL int meshopt_computePositionExponent(const float* minv, const float* maxv, int min_exp, int max_bits);+MESHOPTIMIZER_API int meshopt_computePositionExponent(const float* minv, const float* maxv, int min_exp, int max_bits);/*** Set allocation callbacks@@ -1116,6 +1160,10 @@ template <typename T>inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);template <typename T>inline void meshopt_generateTangents(float* result, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, unsigned int options = 0);+template <typename T>+inline void meshopt_generateNormals(float* result, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float crease_angle, float smoothing = 0.f);+template <typename T>+inline size_t meshopt_remesh(float* destination, size_t max_triangle_count, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, unsigned int options = 0);#endif/* Inline implementation */@@ -1632,6 +1680,22 @@ inline void meshopt_generateTangents(float* result, const T* indices, size_t indmeshopt_generateTangents(result, indices ? in.data : NULL, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_normals, vertex_normals_stride, vertex_uvs, vertex_uvs_stride, options);}++template <typename T>+inline void meshopt_generateNormals(float* result, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float crease_angle, float smoothing)+{+ meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);++ meshopt_generateNormals(result, indices ? in.data : NULL, index_count, vertex_positions, vertex_count, vertex_positions_stride, crease_angle, smoothing);+}++template <typename T>+inline size_t meshopt_remesh(float* destination, size_t max_triangle_count, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, unsigned int options)+{+ meshopt_IndexAdapter<T> in(NULL, indices, index_count);++ return meshopt_remesh(destination, max_triangle_count, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, resolution, options);+}#endif/**diff --git a/thirdparty/meshoptimizer/partition.cpp b/thirdparty/meshoptimizer/partition.cppindex c19cf19f7da..5f0426da696 100644--- a/thirdparty/meshoptimizer/partition.cpp+++ b/thirdparty/meshoptimizer/partition.cpp@@ -151,6 +151,9 @@ static void buildClusterAdjacency(ClusterAdjacency& adjacency, const unsigned inmemmove(ref_offsets + 1, ref_offsets, vertex_count * sizeof(unsigned int));ref_offsets[0] = 0;+ unsigned int* slots = allocator.allocate<unsigned int>(cluster_count);+ memset(slots, -1, cluster_count * sizeof(unsigned int));+// fill cluster adjacency for each cluster...adjacency.offsets[0] = 0;@@ -174,18 +177,13 @@ static void buildClusterAdjacency(ClusterAdjacency& adjacency, const unsigned incontinue;// if the cluster is already in the list, increment the shared count- bool found = false;- for (size_t l = 0; l < count; ++l)- if (adj[l] == c)- {- found = true;- shd[l]++;- break;- }-- // .. or append a new cluster- if (!found)+ // we do not need to clear slots across clusters due to adj[slot] confirmation check+ unsigned int slot = slots[c];+ if (slot < count && adj[slot] == c)+ shd[slot]++;+ else{+ slots[c] = unsigned(count);adj[count] = c;shd[count] = 1;count++;@@ -200,6 +198,7 @@ static void buildClusterAdjacency(ClusterAdjacency& adjacency, const unsigned inassert(adjacency.offsets[cluster_count] <= total_adjacency);// ref_offsets can't be deallocated as it was allocated before adjacency+ allocator.deallocate(slots);allocator.deallocate(ref_data);}diff --git a/thirdparty/meshoptimizer/remesher.cpp b/thirdparty/meshoptimizer/remesher.cppnew file mode 100644index 00000000000..9279cc3a8de--- /dev/null+++ b/thirdparty/meshoptimizer/remesher.cpp@@ -0,0 +1,782 @@+// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details+#include "meshoptimizer.h"++#include <assert.h>+#include <float.h>+#include <math.h>+#include <string.h>++#ifndef TRACE+#define TRACE 0+#endif++#if TRACE+#include <stdio.h>+#endif++// Note: this is only exposed for development purposes; do *not* use+enum+{+ meshopt_RemeshInternalDebug = 1 << 30+};++// This work is based on:+// William Lorensen, Harvey Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. 1987+// Michael Garland and Paul S. Heckbert. Surface simplification using quadric error metrics. 1997+namespace meshopt+{++// triangles are encoded as three vertex codes in three nibbles+// vertex codes match the bit order XYZ (e.g. 3 maps to X=1 Y=1 Z=0)+struct Case+{+ unsigned char code;+ unsigned char altmode;+ unsigned short triangles[5]; // up to 4 triangles and a null terminator+ unsigned short alternate[5]; // alternate triangulation, restricted to have <= triangles vs primary+};++// the base cases establish a canonical triangulation; unlike classical Marching Cubes, we connect cube *corners* instead of edges+// each case may have an alternate triangulation, used based on deciders; crucially, open boundary edges must stay consistent as decider varies per cell+static const Case kBaseCases[] = {+ {0x00, 0, {}, {}},+ {0x01, 0, {}, {}},+ {0x03, 0, {}, {}},+ {0x06, 0, {}, {}},+ {0x07, 0, {0x120}, {}},+ {0x0f, 2, {0x130, 0x032}, {0x321, 0x120}},+ {0x16, 1, {0x124, 0x142}, {}},+ {0x17, 0, {0x124}, {}},+ {0x18, 0, {}, {}},+ {0x19, 1, {0x043, 0x403}, {}},+ {0x1b, 1, {0x134, 0x430}, {0x410, 0x013}},+ {0x1d, 1, {0x243, 0x340}, {0x320, 0x024}},+ {0x1e, 1, {0x142, 0x432, 0x341}, {0x132}},+ {0x1f, 2, {0x412, 0x213}, {0x134, 0x432}},+ {0x3c, 1, {0x345, 0x324, 0x543, 0x423}, {}},+ {0x3d, 1, {0x253, 0x524, 0x350}, {0x240, 0x504, 0x320}},+ {0x3f, 2, {0x325, 0x524}, {0x243, 0x345}},+ {0x69, 1, {0x035, 0x560, 0x306, 0x536}, {}},+ {0x6b, 1, {0x063, 0x605, 0x365}, {0x305}},+ {0x6f, 1, {0x365, 0x560}, {0x530, 0x036}},+ {0x7e, 0, {0x142, 0x536}, {}},+ {0x7f, 0, {0x365}, {}},+ {0xf0, 2, {0x547, 0x746}, {0x465, 0x567}},+ {0xff, 0, {}, {}},+};++// for each cube case, a triangulation is derived from the base cases via 90 degree rotations+static unsigned short kTriangleTable[256][2][5];+static unsigned char kTriangleCount[256];+static unsigned char kTriangleAlt[256];++static bool buildRemeshTables()+{+ // corner remap for 90 degree rotations around X and Y+ static const unsigned char rotations[2][8] = {{2, 3, 6, 7, 0, 1, 4, 5}, {4, 0, 6, 2, 5, 1, 7, 3}};++ unsigned char filled[256] = {};++ // copy base cases as is; we will generate the rest via rotations+ for (size_t i = 0; i < sizeof(kBaseCases) / sizeof(kBaseCases[0]); ++i)+ {+ const Case& c = kBaseCases[i];+ memcpy(kTriangleTable[c.code][0], c.triangles, sizeof(c.triangles));+ memcpy(kTriangleTable[c.code][1], c.altmode ? c.alternate : c.triangles, sizeof(c.triangles));+ kTriangleAlt[c.code] = c.altmode;+ filled[kBaseCases[i].code] = 1;+ }++ // propagate base cases iteratively to fill all cube cases via rotations+ // note: the worst case is 5 passes but in practice we only need 3 to fill all cases+ for (int pass = 0; pass < 3; ++pass)+ for (int code = 0; code < 256; ++code)+ {+ if (filled[code] != 1)+ continue;++ for (int r = 0; r < 2; ++r)+ {+ unsigned char rotated = 0;+ for (int i = 0; i < 8; ++i)+ rotated |= ((code >> i) & 1) << rotations[r][i];++ if (filled[rotated])+ continue;++ for (int k = 0; k < 2; ++k)+ for (int i = 0; kTriangleTable[code][k][i]; ++i)+ {+ unsigned short tri = kTriangleTable[code][k][i];+ kTriangleTable[rotated][k][i] = (rotations[r][(tri >> 8) & 0xf] << 8) | (rotations[r][(tri >> 4) & 0xf] << 4) | rotations[r][tri & 0xf];+ }++ kTriangleAlt[rotated] = kTriangleAlt[code];+ filled[rotated] = 1; // mark as pending+ }++ filled[code] = 2; // mark as processed+ }++ // finalize auxiliary tables+ for (int code = 0; code < 256; ++code)+ {+ assert(filled[code]);++ int count = 0;+ while (kTriangleTable[code][0][count])+ count++;++ kTriangleCount[code] = (unsigned char)count;++ // counting pass does not use alternate triangulations, so they need to stay at or below primary triangle count+ assert(kTriangleTable[code][1][count] == 0);++ // quadric decider expects a canonical quad encoding (0xabc 0xcbd)+ if (kTriangleAlt[code] == 2)+ assert(count == 2 && (kTriangleTable[code][0][0] & 0xf0) == (kTriangleTable[code][0][1] & 0xf0) && (kTriangleTable[code][0][0] & 0xf) == (kTriangleTable[code][0][1] >> 8));+ }++ return true;+}++static bool gRemeshTablesInitialized = buildRemeshTables();++struct Voxel+{+ unsigned int coord;+ unsigned char octants;++ float px, py, pz;+ float w;++ // a00*x^2 + a11*y^2 + a22*z^2 + 2*a10*xy + 2*a20*xz + 2*a21*yz + 2*b0*x + 2*b1*y + 2*b2*z + c+ float a00, a11, a22;+ float a10, a20, a21;+ float b0, b1, b2, c;+};++static void voxelAccumulate(Voxel& vox, float px, float py, float pz, float w)+{+ vox.px += px * w;+ vox.py += py * w;+ vox.pz += pz * w;+ vox.w += w;+}++static void voxelAccumulateQ(Voxel& vox, float a, float b, float c, float d, float w)+{+ float aw = a * w;+ float bw = b * w;+ float cw = c * w;+ float dw = d * w;++ vox.a00 += a * aw;+ vox.a11 += b * bw;+ vox.a22 += c * cw;+ vox.a10 += a * bw;+ vox.a20 += a * cw;+ vox.a21 += b * cw;+ vox.b0 += a * dw;+ vox.b1 += b * dw;+ vox.b2 += c * dw;+ vox.c += d * dw;+}++static float voxelError(const Voxel& vox, float x, float y, float z)+{+ float rx = (vox.b0 + vox.a10 * y) * 2.f + vox.a00 * x;+ float ry = (vox.b1 + vox.a21 * z) * 2.f + vox.a11 * y;+ float rz = (vox.b2 + vox.a20 * x) * 2.f + vox.a22 * z;++ return fabsf(vox.c + rx * x + ry * y + rz * z);+}++static bool voxelSolve(float& rx, float& ry, float& rz, const Voxel& vox, float lambda)+{+ // solve A*p = -b where A is the quadric matrix and b is the linear term+ float rw = lambda * vox.w;+ float a00 = rw + vox.a00, a11 = rw + vox.a11, a22 = rw + vox.a22;+ float a10 = vox.a10, a20 = vox.a20, a21 = vox.a21;+ float x0 = lambda * vox.px - vox.b0, x1 = lambda * vox.py - vox.b1, x2 = lambda * vox.pz - vox.b2;++ float eps = 1e-6f * vox.w;++ // LDL decomposition: A = LDL^T+ float d0 = a00;+ float l10 = a10 / d0;+ float l20 = a20 / d0;++ float d1 = a11 - a10 * l10;+ float dl21 = a21 - a20 * l10;+ float l21 = dl21 / d1;++ float d2 = a22 - a20 * l20 - dl21 * l21;++ // solve L*y = x+ float y0 = x0;+ float y1 = x1 - l10 * y0;+ float y2 = x2 - l20 * y0 - l21 * y1;++ // solve D*z = y+ float z0 = y0 / d0;+ float z1 = y1 / d1;+ float z2 = y2 / d2;++ // substitute L^T*p = z+ rz = z2;+ ry = z1 - l21 * rz;+ rx = z0 - l10 * ry - l20 * rz;++ return fabsf(d0) > eps && fabsf(d1) > eps && fabsf(d2) > eps;+}++static float measureGrid(const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, int resolution, float* out_offset)+{+ size_t vertex_stride_float = vertex_positions_stride / sizeof(float);++ float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};+ float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};++ for (size_t i = 0; i < vertex_count; ++i)+ {+ const float* v = vertex_positions_data + i * vertex_stride_float;++ for (int j = 0; j < 3; ++j)+ {+ float vj = v[j];++ minv[j] = minv[j] > vj ? vj : minv[j];+ maxv[j] = maxv[j] < vj ? vj : maxv[j];+ }+ }++ float extent = 0.f;++ extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]);+ extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]);+ extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]);++ // small subvoxel padding keeps vertices inside the last valid voxel to avoid clamping correctness issues+ extent *= (resolution + 1e-2f) / float(resolution);++ // rescale extents to [0..resolution - 2], because the first and last voxels are used as empty padding+ float scale = extent == 0 ? 0.f : (resolution - 2) / extent;++ // center mesh in the grid; this improves voxelization for symmetric inputs+ for (int j = 0; j < 3; ++j)+ out_offset[j] = minv[j] - (extent - (maxv[j] - minv[j])) * 0.5f;++ return scale;+}++static void voxelize(unsigned char* grid, const unsigned int* rowmap, Voxel* voxels, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, float scale, const float offset[3], unsigned int options)+{+ (void)vertex_count;++ size_t vertex_stride_float = vertex_positions_stride / sizeof(float);++ for (size_t i = 0; i < index_count; i += 3)+ {+ unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];+ assert(a < vertex_count && b < vertex_count && c < vertex_count);++ const float* va = vertex_positions + a * vertex_stride_float;+ const float* vb = vertex_positions + b * vertex_stride_float;+ const float* vc = vertex_positions + c * vertex_stride_float;++ float ex = vb[0] - va[0], ey = vb[1] - va[1], ez = vb[2] - va[2];+ float fx = vc[0] - va[0], fy = vc[1] - va[1], fz = vc[2] - va[2];+ float gx = vc[0] - vb[0], gy = vc[1] - vb[1], gz = vc[2] - vb[2];++ // use maximum edge length to establish sampling rate+ float el2 = ex * ex + ey * ey + ez * ez;+ float fl2 = fx * fx + fy * fy + fz * fz;+ float gl2 = gx * gx + gy * gy + gz * gz;++ float max_edge = el2 > fl2 ? el2 : fl2;+ max_edge = max_edge > gl2 ? max_edge : gl2;+ max_edge = sqrtf(max_edge);++ // we target 2 samples per voxel edge which should be enough to hit all voxels at any rotation+ int samples = int(max_edge * scale * 2.f);+ samples = samples > 1 ? samples : 1;+ samples = samples < resolution * 2 ? samples : resolution * 2;++ // normal is used to compute area for weighting as well as for the quadric+ float nx = ey * fz - ez * fy, ny = ez * fx - ex * fz, nz = ex * fy - ey * fx;+ float area = sqrtf(nx * nx + ny * ny + nz * nz);++ // skip degenerate triangles; they don't contribute to voxelization and may result in NaN when computing voxel centroid+ if (area == 0.f)+ continue;++ float ns = 1.f / area;+ nx *= ns, ny *= ns, nz *= ns;++ float sx = va[0] - offset[0], sy = va[1] - offset[1], sz = va[2] - offset[2];+ float sr = 1.f;+ float weight = area / float((samples + 1) * (samples + 2));++ // this division is on a critical path, and for dense input meshes the branch is almost never taken so it's worth skipping it+ if (samples > 1)+ sr = 1.f / float(samples);++ for (int u = 0; u <= samples; ++u)+ for (int v = 0; v <= samples - u; ++v)+ {+ float su = float(u) * sr, sv = float(v) * sr;+ float px = sx + su * ex + sv * fx;+ float py = sy + su * ey + sv * fy;+ float pz = sz + su * ez + sv * fz;++ // compute coordinates with an extra bit to use in octant mask+ int hx = int(px * (scale * 2));+ int hy = int(py * (scale * 2));+ int hz = int(pz * (scale * 2));+ int x = hx >> 1, y = hy >> 1, z = hz >> 1;++ // safety: rounding errors and non-finite inputs may produce out of bounds coordinates, so we clamp them+ int cutoff = resolution - 3;+ x = unsigned(x) < unsigned(cutoff) ? x : cutoff;+ y = unsigned(y) < unsigned(cutoff) ? y : cutoff;+ z = unsigned(z) < unsigned(cutoff) ? z : cutoff;++ size_t row = (y + 1) + size_t(resolution) * (z + 1);+ size_t idx = (x + 1) + size_t(resolution) * row;++ if (voxels)+ {+ assert(grid[idx] != 0 && grid[idx] != 0xff);+ Voxel& vox = voxels[rowmap[row] + (grid[idx] - 1)];++ vox.coord = (unsigned(x) << 20) | (unsigned(y) << 10) | unsigned(z);+ vox.octants |= 1 << ((hx & 1) | ((hy & 1) << 1) | ((hz & 1) << 2));++ voxelAccumulate(vox, px, py, pz, weight);++ if (options & meshopt_RemeshSolve)+ {+ float distance = nx * px + ny * py + nz * pz;+ voxelAccumulateQ(vox, nx, ny, nz, -distance, weight);+ }+ }+ else+ {+ grid[idx] = 1;+ }+ }+ }+}++static size_t rowpack(unsigned char* grid, unsigned int* rowmap, int resolution)+{+ size_t result = 0;+ size_t slice = size_t(resolution) * size_t(resolution);++ unsigned char zero[256];+ memset(zero, 0, resolution);++ for (size_t i = 0; i < slice; ++i)+ {+ unsigned char* data = grid + i * size_t(resolution);++ if (memcmp(data, zero, resolution) == 0)+ {+ // mark empty rows with a sentinel to accelerate further processing+ rowmap[i] = ~0u;+ continue;+ }++ int count = 0;++ for (int x = 0; x < resolution; ++x)+ {+ assert(data[x] <= 1); // voxelize only produces 0/1 values++ count += data[x];+ data[x] = (data[x] != 0) ? (unsigned char)count : 0;+ }++ assert(count < 255); // we store offsets in a single byte, with 0 reserved for empty voxels and 0xff reserved for interior voxels++ rowmap[i] = unsigned(result);+ result += count;+ }++ return result;+}++static void solidifyQueue(unsigned int row, unsigned int* worklist, unsigned char* queued, size_t& pending)+{+ if (queued[row])+ return;++ queued[row] = 1;+ worklist[pending++] = row;+}++static void solidify(unsigned char* grid, const unsigned int* rowmap, unsigned int* worklist, unsigned char* queued, int resolution)+{+ size_t pending = 0;+ memset(queued, 0, size_t(resolution) * size_t(resolution));++ // mark the interior empty voxels as 'inside'; we will propagate 'empty' state from the boundary+ for (int z = 1; z < resolution - 1; ++z)+ for (int y = 1; y < resolution - 1; ++y)+ {+ // rows without occupied voxels shortcircuit the interior propagation and are kept as 'empty'+ if (rowmap[y + size_t(resolution) * z] == ~0u)+ continue;++ unsigned char* data = grid + size_t(resolution) * (y + size_t(resolution) * z);++ for (int x = 1; x < resolution - 1; ++x)+ data[x] = (data[x] == 0) ? 0xff : data[x];+ }++ // queue all rows for processing; note that boundary rows are always empty but we need them to propagate into neighboring rows+ for (int z = 0; z < resolution; ++z)+ for (int y = 0; y < resolution; ++y)+ solidifyQueue(y + size_t(resolution) * z, worklist, queued, pending);++ while (pending)+ {+ unsigned int row = worklist[--pending];+ assert(queued[row]);+ queued[row] = 0;++ unsigned char* data = grid + size_t(resolution) * row;++ // propagate outside state to the interior within row; rows without occupied voxels have no 'inside' voxels+ if (rowmap[row] != ~0u)+ {+ for (int x = 1; x < resolution - 1; ++x)+ data[x] = (data[x] == 0xff && data[x - 1] == 0) ? 0 : data[x];++ for (int x = resolution - 2; x >= 1; --x)+ data[x] = (data[x] == 0xff && data[x + 1] == 0) ? 0 : data[x];+ }++ // propagate outside state to the interior into neighboring rows+ int y = row % resolution, z = row / resolution;++ for (int k = 0; k < 4; ++k)+ {+ int yn = y + (k == 0 ? -1 : (k == 1 ? 1 : 0));+ int zn = z + (k == 2 ? -1 : (k == 3 ? 1 : 0));++ if (yn < 1 || yn >= resolution - 1 || zn < 1 || zn >= resolution - 1)+ continue;++ // neighboring rows without occupied voxels have no 'inside' voxels and can be skipped+ if (rowmap[yn + size_t(resolution) * zn] == ~0u)+ continue;++ unsigned char* datan = grid + size_t(resolution) * (yn + size_t(resolution) * zn);+ unsigned char changed = 0;++ for (int x = 1; x < resolution - 1; ++x)+ {+ unsigned char rep = ((data[x] == 0) & (datan[x] == 0xff)) ? 0 : datan[x];+ changed |= rep ^ datan[x];+ datan[x] = rep;+ }++ if (changed)+ solidifyQueue(yn + size_t(resolution) * zn, worklist, queued, pending);+ }+ }+}++static void solve(Voxel* voxels, size_t voxel_count, float scale, unsigned int options)+{+ // regularization factor is a tradeoff between solve stability/uniformity and adherence to the original surface+ float factor = 3e-2f;++ // cutoff is a squared distance in model space; sqrt(3)/scale is the voxel diagonal+ float cutoff = 3.f / (scale * scale);+ float rscale = 1.f / scale;++ size_t solved = 0;++ for (size_t i = 0; i < voxel_count; ++i)+ {+ Voxel& vox = voxels[i];+ float px = vox.px / vox.w, py = vox.py / vox.w, pz = vox.pz / vox.w;++ // voxel corner, used for clamping and debug visualization+ float cx = int((vox.coord >> 20) & 1023) * rscale;+ float cy = int((vox.coord >> 10) & 1023) * rscale;+ float cz = int((vox.coord >> 0) & 1023) * rscale;++ if (options & meshopt_RemeshSolve)+ {+ // compute minimizing point; this includes regularization to stabilize the solve+ float sx, sy, sz;+ if (voxelSolve(sx, sy, sz, vox, factor))+ {+ float d = (sx - px) * (sx - px) + (sy - py) * (sy - py) + (sz - pz) * (sz - pz);++ // reject solutions that move the vertex too far from voxel centroid; this is a safety net in case regularization is insufficient+ if (d < cutoff)+ {+ // use a clamped solution to reduce intersections+ px = sx > cx ? sx : cx;+ px = px < cx + rscale ? px : cx + rscale;+ py = sy > cy ? sy : cy;+ py = py < cy + rscale ? py : cy + rscale;+ pz = sz > cz ? sz : cz;+ pz = pz < cz + rscale ? pz : cz + rscale;++ solved++;+ }+ }+ }++ if (options & meshopt_RemeshInternalDebug)+ {+ px = cx + 0.5f * rscale;+ py = cy + 0.5f * rscale;+ pz = cz + 0.5f * rscale;+ }++ vox.px = px;+ vox.py = py;+ vox.pz = pz;+ }++ (void)solved;++#if TRACE+ if (options & meshopt_RemeshSolve)+ printf("remesher: solved %zu/%zu voxels\n", solved, voxel_count);+#endif+}++static void emitVertex(float* result, int x, int y, int z, int corner, const unsigned char* grid, const unsigned int* rowmap, const Voxel* voxels, int resolution, const float offset[3])+{+ int ox = corner & 1, oy = (corner >> 1) & 1, oz = (corner >> 2) & 1;++ size_t row = (y + oy) + size_t(resolution) * (z + oz);+ size_t idx = (x + ox) + size_t(resolution) * row;++ assert(grid[idx] != 0 && grid[idx] != 0xff);+ const Voxel& vox = voxels[rowmap[row] + (grid[idx] - 1)];++ result[0] = vox.px + offset[0];+ result[1] = vox.py + offset[1];+ result[2] = vox.pz + offset[2];+}++static bool octantDecider(int x, int y, int z, int cube, const unsigned char* grid, const unsigned int* rowmap, const Voxel* voxels, int resolution)+{+ for (int c = 0; c < 8; ++c)+ if (cube & (1 << c))+ {+ int ox = c & 1, oy = (c >> 1) & 1, oz = (c >> 2) & 1;++ size_t row = (y + oy) + size_t(resolution) * (z + oz);+ size_t idx = (x + ox) + size_t(resolution) * row;++ assert(grid[idx] != 0);++ // note: unlike vertex emission, which never consults interior occupied corners, here we need to skip corners without an occupied voxel+ if (grid[idx] == 0xff)+ continue;++ const Voxel& vox = voxels[rowmap[row] + (grid[idx] - 1)];++ // test octant contained within the cell (opposite of the corner index)+ if (vox.octants & (1 << (7 - c)))+ return false;+ }++ // select alternate configuration if *all* octants are empty+ return true;+}++static bool quadricDecider(int x, int y, int z, int cube, const unsigned char* grid, const unsigned int* rowmap, const Voxel* voxels, int resolution, float rscale)+{+ // quads are encoded implicitly as 0xabc 0xcbd+ unsigned int quad = (kTriangleTable[cube][0][0] << 4) | (kTriangleTable[cube][0][1] & 0xf);++ const Voxel* corner[4];++ for (int i = 0; i < 4; ++i)+ {+ int c = (quad >> (12 - i * 4)) & 0xf;+ size_t row = (y + ((c >> 1) & 1)) + size_t(resolution) * (z + ((c >> 2) & 1));+ size_t idx = (x + (c & 1)) + size_t(resolution) * row;++ assert(grid[idx] != 0 && grid[idx] != 0xff);+ corner[i] = &voxels[rowmap[row] + (grid[idx] - 1)];+ }++ // accumulate the quadrics of all four corners; we sum (a+d)+(b+c) to get the same results on both sides of thin sheets+ const Voxel *va = corner[0], *vb = corner[1], *vc = corner[2], *vd = corner[3];++ Voxel sum = {};+ sum.a00 = (va->a00 + vd->a00) + (vb->a00 + vc->a00), sum.a11 = (va->a11 + vd->a11) + (vb->a11 + vc->a11), sum.a22 = (va->a22 + vd->a22) + (vb->a22 + vc->a22);+ sum.a10 = (va->a10 + vd->a10) + (vb->a10 + vc->a10), sum.a20 = (va->a20 + vd->a20) + (vb->a20 + vc->a20), sum.a21 = (va->a21 + vd->a21) + (vb->a21 + vc->a21);+ sum.b0 = (va->b0 + vd->b0) + (vb->b0 + vc->b0), sum.b1 = (va->b1 + vd->b1) + (vb->b1 + vc->b1), sum.b2 = (va->b2 + vd->b2) + (vb->b2 + vc->b2);+ sum.c = (va->c + vd->c) + (vb->c + vc->c), sum.w = (va->w + vd->w) + (vb->w + vc->w);++ // evaluate error for midpoints of primary (bc) and alternate (ad) diagonal+ float error0 = voxelError(sum, (vb->px + vc->px) * 0.5f, (vb->py + vc->py) * 0.5f, (vb->pz + vc->pz) * 0.5f);+ float error1 = voxelError(sum, (va->px + vd->px) * 0.5f, (va->py + vd->py) * 0.5f, (va->pz + vd->pz) * 0.5f);++ // select alternate configuration if it is clearly better and if the primary error is not too small, to avoid excessive flips+ return error0 > sum.w * (0.1f * 0.1f * rscale * rscale) && error1 < error0 * (0.85f * 0.85f);+}++static size_t polygonize(float* destination, size_t max_triangle_count, const unsigned char* grid, const unsigned int* rowmap, const Voxel* voxels, int resolution, float scale, const float offset[3], unsigned int options)+{+ size_t result = 0;+ size_t slice = size_t(resolution) * size_t(resolution);+ float rscale = 1.f / scale;++ assert(gRemeshTablesInitialized);++ for (int z = 0; z < resolution - 1; ++z)+ for (int y = 0; y < resolution - 1; ++y)+ {+ size_t row = y + size_t(resolution) * z;++ // skip processing if all four rows are entirely empty as that guarantees empty output (even three out of four would be enough but that's more expensive to check)+ if ((rowmap[row] & rowmap[row + 1] & rowmap[row + resolution] & rowmap[row + resolution + 1]) == ~0u)+ continue;++ const unsigned char* data = grid + size_t(resolution) * row;++ // we track each slice as a 8-bit code (matching cube indexing) as we iterate through the row to avoid extra lookups+ int last = (data[0] != 0) | ((data[resolution] != 0) << 2) | ((data[slice] != 0) << 4) | ((data[slice + resolution] != 0) << 6);++ for (int x = 0; x < resolution - 1; ++x)+ {+ int next = (data[x + 1] != 0) | ((data[x + 1 + resolution] != 0) << 2) | ((data[x + 1 + slice] != 0) << 4) | ((data[x + 1 + slice + resolution] != 0) << 6);++ // next slice bits are in position for the next iteration so we need to shift them to retrieve current cube code+ int cube = last | (next << 1);+ last = next;++ if (cube == 0 || cube == 0xff)+ continue;++ if (!destination)+ {+ // fast path: we can statically determine the upper bound on triangles the loop below will output based on cube configuration+ result += kTriangleCount[cube];+ continue;+ }++ // deciders are only evaluated for cells with an alternate configuration to reduce overhead+ int alt = 0;++ if (kTriangleAlt[cube] == 1)+ alt = octantDecider(x, y, z, cube, grid, rowmap, voxels, resolution);+ else if (kTriangleAlt[cube] == 2 && (options & meshopt_RemeshSolve))+ alt = quadricDecider(x, y, z, cube, grid, rowmap, voxels, resolution, rscale);++ const unsigned short* tris = kTriangleTable[cube][alt];++ for (int i = 0; tris[i]; ++i)+ {+ // note: we only emit the triangle if we have space for it, but we count it regardless for consistent capacity estimation+ if (result < max_triangle_count)+ {+ unsigned short tri = tris[i];++ emitVertex(&destination[result * 9 + 0], x, y, z, (tri >> 8) & 0xf, grid, rowmap, voxels, resolution, offset);+ emitVertex(&destination[result * 9 + 3], x, y, z, (tri >> 4) & 0xf, grid, rowmap, voxels, resolution, offset);+ emitVertex(&destination[result * 9 + 6], x, y, z, (tri >> 0) & 0xf, grid, rowmap, voxels, resolution, offset);+ }++ result++;+ }+ }+ }++ return result;+}++} // namespace meshopt++size_t meshopt_remesh(float* destination, size_t max_triangle_count, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, unsigned int options)+{+ using namespace meshopt;++ assert(destination || max_triangle_count == 0);+ assert(index_count % 3 == 0);+ assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);+ assert(vertex_positions_stride % sizeof(float) == 0);+ assert(resolution >= 4 && resolution <= 256);++ meshopt_Allocator allocator;++ // measure voxel grid to compute position => voxel mapping+ float offset[3] = {};+ float scale = measureGrid(vertex_positions, vertex_count, vertex_positions_stride, resolution, offset);++ // rasterize triangles into the voxel grid: in the first pass, this simply tags occupied voxels+ unsigned char* grid = allocator.allocate<unsigned char>(size_t(resolution) * size_t(resolution) * size_t(resolution));+ memset(grid, 0, size_t(resolution) * size_t(resolution) * size_t(resolution));++ voxelize(grid, NULL, NULL, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, resolution, scale, offset, options);++ // compute row offsets for occupied voxels; also stores ~0u for empty rows to accelerate further processing+ unsigned int* rowmap = allocator.allocate<unsigned int>(size_t(resolution) * size_t(resolution));+ size_t voxel_count = rowpack(grid, rowmap, resolution);++#if TRACE+ printf("remesher: %zu voxels occupied\n", voxel_count);+#endif++ // allocate additional voxel data for each occupied voxel; this can be filled in the second pass to compute positions+ // note that we only do this if we need to compute output triangles; counting runs skip it for performance+ Voxel* voxels = NULL;++ if (destination)+ {+ voxels = allocator.allocate<Voxel>(voxel_count);+ memset(voxels, 0, voxel_count * sizeof(Voxel));+ }++ // fill in empty voxels that are not reachable from the grid boundary; the inside empty voxels are marked with 0xff+ // note that these voxels do *not* have the associated Voxel data as they were never voxelized+ if ((options & meshopt_RemeshShell) == 0)+ {+ unsigned int* worklist = allocator.allocate<unsigned int>(size_t(resolution) * size_t(resolution));+ unsigned char* queued = allocator.allocate<unsigned char>(size_t(resolution) * size_t(resolution));++ solidify(grid, rowmap, worklist, queued, resolution);++#if TRACE+ size_t inside_count = 0, occupied_count = 0;+ for (size_t i = 0; i < size_t(resolution) * size_t(resolution) * size_t(resolution); ++i)+ {+ inside_count += (grid[i] == 0xff);+ occupied_count += (grid[i] != 0 && grid[i] != 0xff);+ }++ printf("remesher: %zu voxels occupied, %zu voxels inside\n", occupied_count, inside_count);+#endif+ }++ // accumulate voxel positions: in the second pass, this computes enough data in each voxel to calculate positions+ if (voxels)+ voxelize(grid, rowmap, voxels, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, resolution, scale, offset, options);++ // compute final voxel positions; each voxel has a single resulting position that will be emitted during polygonization+ if (voxels)+ solve(voxels, voxel_count, scale, options);++ // output triangles from the voxel grid; if destination is NULL, this still counts the number of triangles that would be generated+ size_t result = polygonize(destination, max_triangle_count, grid, rowmap, voxels, resolution, scale, offset, options);++#if TRACE+ printf("remesher: %zu triangles (%zu capacity)\n", result, max_triangle_count);+#endif++ return result;+}diff --git a/thirdparty/meshoptimizer/simplifier.cpp b/thirdparty/meshoptimizer/simplifier.cppindex 5102b215d44..85c502524f4 100644--- a/thirdparty/meshoptimizer/simplifier.cpp+++ b/thirdparty/meshoptimizer/simplifier.cpp@@ -299,6 +299,7 @@ enum VertexKindKind_Border, // not on an attribute seam, has exactly two open edgesKind_Seam, // on an attribute seam with exactly two attribute seam edgesKind_Complex, // none of the above; these vertices can move as long as all wedges move to the target vertex+ Kind_Fringe, // complex vertex on a geometric border; can only move to another fringe vertexKind_Locked, // none of the above; these vertices can't moveKind_Count@@ -307,14 +308,16 @@ enum VertexKind// manifold vertices can collapse onto anything// border/seam vertices can collapse onto border/seam respectively, or locked// complex vertices can collapse onto complex/locked+// fringe vertices can only collapse onto fringe vertices; border, manifold and complex vertices can collapse onto them// a rule of thumb is that collapsing kind A into kind B preserves the kind B in the target vertex// for example, while we could collapse Complex into Manifold, this would mean the target vertex isn't Manifold anymoreconst unsigned char kCanCollapse[Kind_Count][Kind_Count] = {- {1, 1, 1, 1, 1},- {0, 1, 0, 0, 1},- {0, 0, 1, 0, 1},- {0, 0, 0, 1, 1},- {0, 0, 0, 0, 0},+ {1, 1, 1, 1, 1, 1},+ {0, 1, 0, 0, 1, 1},+ {0, 0, 1, 0, 0, 1},+ {0, 0, 0, 1, 1, 1},+ {0, 0, 0, 0, 1, 0},+ {0, 0, 0, 0, 0, 0},};// if a vertex is manifold or seam, adjoining edges are guaranteed to have an opposite edge@@ -323,11 +326,12 @@ const unsigned char kCanCollapse[Kind_Count][Kind_Count] = {// while many complex collapses have the opposite edge, since complex vertices collapse to the// same wedge, keeping opposite edges separate improves the quality by considering both targetsconst unsigned char kHasOpposite[Kind_Count][Kind_Count] = {- {1, 1, 1, 1, 1},- {1, 0, 1, 0, 0},- {1, 1, 1, 0, 1},- {1, 0, 0, 0, 0},- {1, 0, 1, 0, 0},+ {1, 1, 1, 1, 1, 1},+ {1, 0, 1, 0, 0, 0},+ {1, 1, 1, 0, 0, 1},+ {1, 0, 0, 0, 0, 0},+ {1, 0, 0, 0, 0, 0},+ {1, 0, 1, 0, 0, 0},};static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b)@@ -399,10 +403,6 @@ static void classifyVertices(unsigned char* result, unsigned int* loop, unsigned}}-#if TRACE- size_t stats[4] = {};-#endif-for (size_t i = 0; i < vertex_count; ++i){if (remap[i] == i)@@ -433,7 +433,6 @@ static void classifyVertices(unsigned char* result, unsigned int* loop, unsignedelse{result[i] = Kind_Locked;- TRACESTATS(0);}}else if (wedge[wedge[i]] == i)@@ -445,29 +444,21 @@ static void classifyVertices(unsigned char* result, unsigned int* loop, unsigned// seam should have one open half-edge for each vertex, and the edges need to "connect" - point to the same vertex post-remapif (openiv != ~0u && openiv != i && openov != ~0u && openov != i &&- openiw != ~0u && openiw != w && openow != ~0u && openow != w)+ openiw != ~0u && openiw != w && openow != ~0u && openow != w &&+ remap[openiv] == remap[openow] && remap[openov] == remap[openiw] && remap[openiv] != remap[openov]){- if (remap[openiv] == remap[openow] && remap[openov] == remap[openiw] && remap[openiv] != remap[openov])- {- result[i] = Kind_Seam;- }- else- {- result[i] = Kind_Locked;- TRACESTATS(1);- }+ result[i] = Kind_Seam;}else{+ // mismatched seam endpoints or disconnected seam; we don't have classification availableresult[i] = Kind_Locked;- TRACESTATS(2);}}else{// more than one vertex maps to this one; we don't have classification availableresult[i] = Kind_Locked;- TRACESTATS(3);}}else@@ -489,10 +480,10 @@ static void classifyVertices(unsigned char* result, unsigned int* loop, unsignedcontinue;}- bool protect = false;+ unsigned int v = unsigned(i);// vertex_lock may protect any wedge, not just the primary vertex, so we switch to complex only if no wedges are protected- unsigned int v = unsigned(i);+ bool protect = false;do{unsigned int rv = sparse_remap ? sparse_remap[v] : v;@@ -500,18 +491,20 @@ static void classifyVertices(unsigned char* result, unsigned int* loop, unsignedv = wedge[v];} while (v != i);- // protect if any adjoining edge doesn't have an opposite edge (indicating vertex is on the border)+ // check if any adjoining edge doesn't have an opposite edge (indicating vertex is on the border)+ bool border = false;do{const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[v]];size_t count = adjacency.offsets[v + 1] - adjacency.offsets[v];for (size_t j = 0; j < count; ++j)- protect |= !hasEdge(adjacency, edges[j].next, v, remap, wedge);+ border |= !hasEdge(adjacency, edges[j].next, v, remap, wedge);v = wedge[v];} while (v != i);- result[i] = protect ? result[i] : int(Kind_Complex);+ // border vertices with attribute discontinuities can only collapse along the border, so they need a separate tagging+ result[i] = protect ? result[i] : (unsigned char)(border ? Kind_Fringe : Kind_Complex);}if (vertex_lock)@@ -532,13 +525,8 @@ static void classifyVertices(unsigned char* result, unsigned int* loop, unsignedif (options & meshopt_SimplifyLockBorder)for (size_t i = 0; i < vertex_count; ++i)- if (result[i] == Kind_Border)+ if (result[i] == Kind_Border || result[i] == Kind_Fringe)result[i] = Kind_Locked;--#if TRACE- printf("locked: many open edges %d, disconnected seam %d, many seam edges %d, many wedges %d\n",- int(stats[0]), int(stats[1]), int(stats[2]), int(stats[3]));-#endif}struct Vector3@@ -749,28 +737,15 @@ static void quadricAdd(QuadricGrad* G, const QuadricGrad* R, size_t attribute_costatic float quadricEval(const Quadric& Q, const Vector3& v){- float rx = Q.b0;- float ry = Q.b1;- float rz = Q.b2;-- rx += Q.a10 * v.y;- ry += Q.a21 * v.z;- rz += Q.a20 * v.x;-- rx *= 2;- ry *= 2;- rz *= 2;+ float rx = (Q.b0 + Q.a10 * v.y) * 2.f;+ float ry = (Q.b1 + Q.a21 * v.z) * 2.f;+ float rz = (Q.b2 + Q.a20 * v.x) * 2.f;rx += Q.a00 * v.x;ry += Q.a11 * v.y;rz += Q.a22 * v.z;- float r = Q.c;- r += rx * v.x;- r += ry * v.y;- r += rz * v.z;-- return r;+ return Q.c + rx * v.x + ry * v.y + rz * v.z;}static float quadricError(const Quadric& Q, const Vector3& v)@@ -781,7 +756,7 @@ static float quadricError(const Quadric& Q, const Vector3& v)return fabsf(r) * s;}-static float quadricError(const Quadric& Q, const QuadricGrad* G, size_t attribute_count, const Vector3& v, const float* va)+static float quadricError(const Quadric& Q, const QuadricGrad* G, size_t attribute_count, const Vector3& v, const float* va, bool clamped){float r = quadricEval(Q, v);@@ -795,7 +770,9 @@ static float quadricError(const Quadric& Q, const QuadricGrad* G, size_t attribu}// note: unlike position error, we do not normalize by Q.w to retain edge scaling as described in quadricFromAttributes- return fabsf(r);+ // we do support clamping, with the error limited to the cumulative weight (= area), which makes perceptual error map to position error more closely+ float e = fabsf(r);+ return clamped ? (e < Q.w ? e : Q.w) : e;}static void quadricFromPlane(Quadric& Q, float a, float b, float c, float d, float w)@@ -1119,26 +1096,36 @@ static void fillEdgeQuadrics(Quadric* vertex_quadrics, const unsigned int* indicunsigned char k0 = vertex_kind[i0];unsigned char k1 = vertex_kind[i1];- // check that either i0 or i1 are border/seam and are on the same edge loop- // note that we need to add the error even for edged that connect e.g. border & locked- // if we don't do that, the adjacent border->border edge won't have correct errors for corners- if (k0 != Kind_Border && k0 != Kind_Seam && k1 != Kind_Border && k1 != Kind_Seam)+ // early out: manifold vertices never lie on a border+ if (k0 == Kind_Manifold || k1 == Kind_Manifold)+ continue;++ // one of the vertices must be border/seam/fringe; additional checks help validate the border+ if (k0 != Kind_Border && k0 != Kind_Seam && k0 != Kind_Fringe && k1 != Kind_Border && k1 != Kind_Seam && k1 != Kind_Fringe)continue;+ // if i0/i1 are border/seam we check if they are on the same edge loop+ // note that we need to add the error even for edges that connect e.g. border & locked+ // if we don't do that, the adjacent border->border edge won't have correct errors for cornersif ((k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)continue;if ((k1 == Kind_Border || k1 == Kind_Seam) && loopback[i1] != i0)continue;+ // fringe vertices don't have proper edge loops, so we need to add edge quadrics to fringe-fringe or fringe-locked edges+ // note that border-fringe edges are still processed, guarded by the loop check above+ if ((k0 == Kind_Fringe || k1 == Kind_Fringe) && (k0 == Kind_Complex || k1 == Kind_Complex))+ continue;+unsigned int i2 = indices[i + next[e + 1]];// we try hard to maintain border edge geometry; seam edges can move more freely- // due to topological restrictions on collapses, seam quadrics slightly improves collapse structure but aren't critical+ // due to topological restrictions on collapses, seam quadrics slightly improve collapse structure but aren't criticalconst float kEdgeWeightSeam = 0.5f; // applied twice due to opposite edgesconst float kEdgeWeightBorder = 10.f;- float edgeWeight = (k0 == Kind_Border || k1 == Kind_Border) ? kEdgeWeightBorder : kEdgeWeightSeam;+ float edgeWeight = (k0 == Kind_Seam || k1 == Kind_Seam) ? kEdgeWeightSeam : kEdgeWeightBorder;Quadric Q;quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight);@@ -1156,6 +1143,68 @@ static void fillEdgeQuadrics(Quadric* vertex_quadrics, const unsigned int* indic}}+static unsigned int oppositeVertex(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b, const unsigned int* remap, const unsigned int* wedge)+{+ unsigned int v = a;+ unsigned int r = ~0u;++ do+ {+ unsigned int count = adjacency.offsets[v + 1] - adjacency.offsets[v];+ const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[v];++ for (size_t i = 0; i < count; ++i)+ if (remap[edges[i].next] == remap[b])+ r = (r == ~0u) ? edges[i].prev : a;++ v = wedge[v];+ } while (v != a);++ // we only return the opposite vertex if it's unique+ return r == a ? ~0u : r;+}++static void fillFoldQuadrics(Quadric* vertex_quadrics, const EdgeAdjacency& adjacency, const Vector3* vertex_positions, size_t vertex_count, const unsigned int* remap, const unsigned int* wedge)+{+ for (size_t i0 = 0; i0 < vertex_count; ++i0)+ for (unsigned int i = adjacency.offsets[i0]; i < adjacency.offsets[i0 + 1]; ++i)+ {+ unsigned int i1 = adjacency.data[i].next;+ unsigned int i2 = adjacency.data[i].prev;++ // since we only process paired edges each edge should occur twice; skip redundant edges+ if (remap[i1] > remap[i0])+ continue;++ unsigned int i3 = oppositeVertex(adjacency, i1, unsigned(i0), remap, wedge);++ if (i3 == ~0u)+ continue;++ Vector3 p10 = {vertex_positions[i1].x - vertex_positions[i0].x, vertex_positions[i1].y - vertex_positions[i0].y, vertex_positions[i1].z - vertex_positions[i0].z};+ Vector3 p20 = {vertex_positions[i2].x - vertex_positions[i0].x, vertex_positions[i2].y - vertex_positions[i0].y, vertex_positions[i2].z - vertex_positions[i0].z};+ Vector3 p30 = {vertex_positions[i3].x - vertex_positions[i0].x, vertex_positions[i3].y - vertex_positions[i0].y, vertex_positions[i3].z - vertex_positions[i0].z};++ Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};+ Vector3 opposite = {p30.y * p10.z - p30.z * p10.y, p30.z * p10.x - p30.x * p10.z, p30.x * p10.y - p30.y * p10.x};+ float nl = sqrtf(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z);+ float ol = sqrtf(opposite.x * opposite.x + opposite.y * opposite.y + opposite.z * opposite.z);++ // identify folds by checking dihedral angle against a somewhat arbitrary ~30 degree cutoff+ if (normal.x * opposite.x + normal.y * opposite.y + normal.z * opposite.z >= -0.85f * nl * ol)+ continue;++ // use both triangles for symmetry since we won't visit this edge again+ Quadric Q, QO;+ quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], 1.f);+ quadricFromTriangleEdge(QO, vertex_positions[i0], vertex_positions[i1], vertex_positions[i3], 1.f);+ quadricAdd(Q, QO);++ quadricAdd(vertex_quadrics[remap[i0]], Q);+ quadricAdd(vertex_quadrics[remap[i1]], Q);+ }+}+static void fillAttributeQuadrics(Quadric* attribute_quadrics, QuadricGrad* attribute_gradients, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const float* vertex_attributes, size_t attribute_count){for (size_t i = 0; i < index_count; i += 3)@@ -1219,13 +1268,7 @@ static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vert// early-out when at least one triangle flips due to a collapseif (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1))- {-#if TRACE >= 2- printf("edge block %d -> %d: flip welded %d %d %d\n", i0, i1, a, i0, b);-#endif-return true;- }}return false;@@ -1371,7 +1414,7 @@ static size_t pickEdgeCollapses(Collapse* collapses, size_t collapse_capacity, creturn collapse_count;}-static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const float* vertex_attributes, const Quadric* vertex_quadrics, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)+static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const float* vertex_attributes, const Quadric* vertex_quadrics, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback, bool clamped){for (size_t i = 0; i < collapse_count; ++i){@@ -1384,14 +1427,10 @@ static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, constfloat ei = quadricError(vertex_quadrics[remap[i0]], vertex_positions[i1]);float ej = bidi ? quadricError(vertex_quadrics[remap[i1]], vertex_positions[i0]) : FLT_MAX;-#if TRACE >= 3- float di = ei, dj = ej;-#endif-if (attribute_count){- ei += quadricError(attribute_quadrics[i0], &attribute_gradients[i0 * attribute_count], attribute_count, vertex_positions[i1], &vertex_attributes[i1 * attribute_count]);- ej += bidi ? quadricError(attribute_quadrics[i1], &attribute_gradients[i1 * attribute_count], attribute_count, vertex_positions[i0], &vertex_attributes[i0 * attribute_count]) : 0;+ ei += quadricError(attribute_quadrics[i0], &attribute_gradients[i0 * attribute_count], attribute_count, vertex_positions[i1], &vertex_attributes[i1 * attribute_count], clamped);+ ej += bidi ? quadricError(attribute_quadrics[i1], &attribute_gradients[i1 * attribute_count], attribute_count, vertex_positions[i0], &vertex_attributes[i0 * attribute_count], clamped) : 0;// seam edges need to aggregate attribute errors between primary and secondary edges, as attribute quadrics are separateif (vertex_kind[i0] == Kind_Seam)@@ -1406,26 +1445,26 @@ static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const// note: this should never happen due to the assertion above, but when disabled if we ever hit this case we'll get a memory safety issue; for now play it safes1 = (s1 != ~0u) ? s1 : wedge[i1];- ei += quadricError(attribute_quadrics[s0], &attribute_gradients[s0 * attribute_count], attribute_count, vertex_positions[s1], &vertex_attributes[s1 * attribute_count]);- ej += bidi ? quadricError(attribute_quadrics[s1], &attribute_gradients[s1 * attribute_count], attribute_count, vertex_positions[s0], &vertex_attributes[s0 * attribute_count]) : 0;+ ei += quadricError(attribute_quadrics[s0], &attribute_gradients[s0 * attribute_count], attribute_count, vertex_positions[s1], &vertex_attributes[s1 * attribute_count], clamped);+ ej += bidi ? quadricError(attribute_quadrics[s1], &attribute_gradients[s1 * attribute_count], attribute_count, vertex_positions[s0], &vertex_attributes[s0 * attribute_count], clamped) : 0;}else{// complex edges can have multiple wedges, so we need to aggregate errors for all wedges based on the selected target- if (vertex_kind[i0] == Kind_Complex)+ if (vertex_kind[i0] == Kind_Complex || vertex_kind[i0] == Kind_Fringe)for (unsigned int v = wedge[i0]; v != i0; v = wedge[v]){unsigned int t = getComplexTarget(v, i1, remap, loop, loopback);- ei += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count]);+ ei += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count], clamped);}- if (vertex_kind[i1] == Kind_Complex && bidi)+ if ((vertex_kind[i1] == Kind_Complex || vertex_kind[i1] == Kind_Fringe) && bidi)for (unsigned int v = wedge[i1]; v != i1; v = wedge[v]){unsigned int t = getComplexTarget(v, i0, remap, loop, loopback);- ej += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count]);+ ej += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count], clamped);}}}@@ -1436,16 +1475,6 @@ static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, constc.v0 = rev ? i1 : i0;c.v1 = rev ? i0 : i1;c.error = ej < ei ? ej : ei;--#if TRACE >= 3- if (bidi)- printf("edge eval %d -> %d: error %f (pos %f, attr %f); reverse %f (pos %f, attr %f)\n",- rev ? i1 : i0, rev ? i0 : i1,- sqrtf(rev ? ej : ei), sqrtf(rev ? dj : di), sqrtf(rev ? ej - dj : ei - di),- sqrtf(rev ? ei : ej), sqrtf(rev ? di : dj), sqrtf(rev ? ei - di : ej - dj));- else- printf("edge eval %d -> %d: error %f (pos %f, attr %f)\n", i0, i1, sqrtf(c.error), sqrtf(di), sqrtf(ei - di));-#endif}}@@ -1527,7 +1556,7 @@ static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char*}// we limit the error in each pass based on the error of optimal last collapse; since many collapses will be locked- // as they will share vertices with other successfull collapses, we need to increase the acceptable error by some factor+ // as they will share vertices with other successful collapses, we need to increase the acceptable error by some factorfloat error_goal = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX;// on average, each collapse is expected to lock 6 other collapses; to avoid degenerate passes on meshes with odd@@ -1564,25 +1593,16 @@ static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char*continue;}-#if TRACE >= 2- printf("edge commit %d -> %d: kind %d->%d, error %f\n", i0, i1, vertex_kind[i0], vertex_kind[i1], sqrtf(c.error));-#endif-assert(collapse_remap[r0] == r0);assert(collapse_remap[r1] == r1);- if (kind == Kind_Complex)+ if (kind == Kind_Complex || kind == Kind_Fringe){- // remap all vertices in the complex to the target vertex- unsigned int v = i0;-- do- {- unsigned int t = getComplexTarget(v, i1, remap, loop, loopback);+ collapse_remap[i0] = i1;- collapse_remap[v] = t;- v = wedge[v];- } while (v != i0);+ // remap all vertices in the complex to the target vertex, using the same ranking that we used to evaluate the collapses+ for (unsigned int v = wedge[i0]; v != i0; v = wedge[v])+ collapse_remap[v] = getComplexTarget(v, i1, remap, loop, loopback);}else if (kind == Kind_Seam){@@ -1616,6 +1636,7 @@ static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char*collapse_locked[r1] = 1;// border edges collapse 1 triangle, other edges collapse 2 or more+ // fringe edges often collapse 1 but may also collapse 2 because they don't respect loops, so we conservatively assume 2triangle_collapses += (kind == Kind_Border) ? 1 : 2;edge_collapses++;@@ -1685,7 +1706,7 @@ static void solvePositions(Vector3* vertex_positions, size_t vertex_count, const// moving vertices on an attribute discontinuity may result in extrapolating UV outside of the chart bounds// moving vertices on a border requires a stronger edge quadric to preserve the border geometry- if (vertex_kind[i] == Kind_Locked || vertex_kind[i] == Kind_Seam || vertex_kind[i] == Kind_Border)+ if (vertex_kind[i] != Kind_Manifold && vertex_kind[i] != Kind_Complex)continue;if (remap[i] != i)@@ -1777,7 +1798,7 @@ static void solveAttributes(Vector3* vertex_positions, float* vertex_attributes,unsigned int shared = ~0u;// for complex vertices, preserve attribute continuity and use highest weight wedge if values were shared- if (vertex_kind[i] == Kind_Complex)+ if (vertex_kind[i] == Kind_Complex || vertex_kind[i] == Kind_Fringe){shared = unsigned(i);@@ -1975,15 +1996,9 @@ static void measureComponents(float* component_errors, size_t component_count, c}// we've used the output buffer as scratch space, so we need to move the results to proper indices+ // note: we keep the squared error to make it match quadric error metricfor (size_t i = 0; i < component_count; ++i)- {-#if TRACE >= 2- printf("component %d: center %f %f %f, error %e\n", int(i),- component_errors[i * 4 + 0], component_errors[i * 4 + 1], component_errors[i * 4 + 2], sqrtf(component_errors[i * 4 + 3]));-#endif- // note: we keep the squared error to make it match quadric error metriccomponent_errors[i] = component_errors[i * 4 + 3];- }}static size_t pruneComponents(unsigned int* indices, size_t index_count, const unsigned int* components, const float* component_errors, size_t component_count, float error_cutoff, float& nexterror)@@ -2029,7 +2044,7 @@ struct CellHashersize_t hash(unsigned int i) const{- unsigned int h = vertex_ids[i];+ unsigned int h = vertex_ids ? vertex_ids[i] : unsigned(i);// MurmurHash2 finalizerh ^= h >> 13;@@ -2040,26 +2055,7 @@ struct CellHasherbool equal(unsigned int lhs, unsigned int rhs) const{- return vertex_ids[lhs] == vertex_ids[rhs];- }-};--struct IdHasher-{- size_t hash(unsigned int id) const- {- unsigned int h = id;-- // MurmurHash2 finalizer- h ^= h >> 13;- h *= 0x5bd1e995;- h ^= h >> 15;- return h;- }-- bool equal(unsigned int lhs, unsigned int rhs) const- {- return lhs == rhs;+ return vertex_ids ? vertex_ids[lhs] == vertex_ids[rhs] : lhs == rhs;}};@@ -2148,7 +2144,7 @@ static size_t fillVertexCells(unsigned int* table, size_t table_size, unsigned istatic size_t countVertexCells(unsigned int* table, size_t table_size, const unsigned int* vertex_ids, size_t vertex_count){- IdHasher hasher;+ CellHasher hasher = {NULL};memset(table, -1, table_size * sizeof(unsigned int));@@ -2396,8 +2392,8 @@ size_t meshopt_simplifyEdge(unsigned int* destination, const unsigned int* indicfor (size_t i = 0; i < vertex_count; ++i)kinds[vertex_kind[i]] += remap[i] == i;- printf("kinds: manifold %d, border %d, seam %d, complex %d, locked %d\n",- int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Locked]));+ printf("kinds: manifold %d, border %d, seam %d, complex %d, fringe %d, locked %d\n",+ int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Fringe]), int(kinds[Kind_Locked]));#endifVector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);@@ -2446,6 +2442,9 @@ size_t meshopt_simplifyEdge(unsigned int* destination, const unsigned int* indicfillVertexQuadrics(vertex_quadrics, vertex_positions, vertex_count, remap, vertex_lock, sparse_remap, options);fillEdgeQuadrics(vertex_quadrics, result, index_count, vertex_positions, remap, vertex_kind, loop, loopback);+ if (options & meshopt_SimplifyPreserveFolds)+ fillFoldQuadrics(vertex_quadrics, adjacency, vertex_positions, vertex_count, remap, wedge);+if (attribute_count)fillAttributeQuadrics(attribute_quadrics, attribute_gradients, result, index_count, vertex_positions, vertex_attributes, attribute_count);@@ -2503,10 +2502,10 @@ size_t meshopt_simplifyEdge(unsigned int* destination, const unsigned int* indicbreak;#if TRACE- printf("pass %d:%c", int(pass_count++), TRACE >= 2 ? '\n' : ' ');+ printf("pass %d: ", int(pass_count++));#endif- rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_attributes, vertex_quadrics, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, vertex_kind, loop, loopback);+ rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_attributes, vertex_quadrics, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, vertex_kind, loop, loopback, (options & meshopt_SimplifyErrorClamped) != 0);sortEdgeCollapses(collapse_order, edge_collapses, edge_collapse_count);diff --git a/thirdparty/meshoptimizer/tangentspace.cpp b/thirdparty/meshoptimizer/tangentspace.cppindex 81cce4d5e43..f9a60e97a53 100644--- a/thirdparty/meshoptimizer/tangentspace.cpp+++ b/thirdparty/meshoptimizer/tangentspace.cpp@@ -65,6 +65,44 @@ static void computeFaceTangents(Tangent* result, size_t triangle_count, const un}}+struct Normal+{+ float x, y, z;+ int id;+};++static void computeFaceNormals(Normal* result, size_t triangle_count, const unsigned int* indices, const float* vertex_positions, size_t vertex_positions_stride)+{+ size_t vertex_position_stride_float = vertex_positions_stride / sizeof(float);++ for (size_t i = 0; i < triangle_count; ++i)+ {+ unsigned int a = indices ? indices[i * 3 + 0] : unsigned(i * 3 + 0);+ unsigned int b = indices ? indices[i * 3 + 1] : unsigned(i * 3 + 1);+ unsigned int c = indices ? indices[i * 3 + 2] : unsigned(i * 3 + 2);++ const float* pa = &vertex_positions[a * vertex_position_stride_float];+ const float* pb = &vertex_positions[b * vertex_position_stride_float];+ const float* pc = &vertex_positions[c * vertex_position_stride_float];++ float dp1x = pb[0] - pa[0], dp1y = pb[1] - pa[1], dp1z = pb[2] - pa[2];+ float dp2x = pc[0] - pa[0], dp2y = pc[1] - pa[1], dp2z = pc[2] - pa[2];++ float nx = dp1y * dp2z - dp1z * dp2y;+ float ny = dp1z * dp2x - dp1x * dp2z;+ float nz = dp1x * dp2y - dp1y * dp2x;++ float nl = sqrtf(nx * nx + ny * ny + nz * nz);+ float ns = nl != 0.f ? 1.f / nl : 0.f;++ result[i].x = nx * ns;+ result[i].y = ny * ns;+ result[i].z = nz * ns;+ result[i].id = nl != 0.f;+ }+}++template <bool PositionOnly>struct VertexHasherF{const float* vertex_positions;@@ -77,8 +115,6 @@ struct VertexHasherFsize_t hash(unsigned int index) const{const unsigned int* p = reinterpret_cast<const unsigned int*>(vertex_positions + index * vertex_positions_stride_float);- const unsigned int* n = reinterpret_cast<const unsigned int*>(vertex_normals + index * vertex_normals_stride_float);- const unsigned int* t = reinterpret_cast<const unsigned int*>(vertex_uvs + index * vertex_uvs_stride_float);unsigned int x = p[0], y = p[1], z = p[2];@@ -92,6 +128,12 @@ struct VertexHasherFy ^= y >> 17;z ^= z >> 17;+ if (PositionOnly)+ return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791);++ const unsigned int* n = reinterpret_cast<const unsigned int*>(vertex_normals + index * vertex_normals_stride_float);+ const unsigned int* t = reinterpret_cast<const unsigned int*>(vertex_uvs + index * vertex_uvs_stride_float);+// mix in normal bitsx ^= (n[0] == 0x80000000) ? 0 : n[0] >> 15;y ^= (n[1] == 0x80000000) ? 0 : n[1] >> 15;@@ -108,9 +150,13 @@ struct VertexHasherFbool equal(unsigned int lhs, unsigned int rhs) const{const float* lp = vertex_positions + lhs * vertex_positions_stride_float;+ const float* rp = vertex_positions + rhs * vertex_positions_stride_float;++ if (PositionOnly)+ return lp[0] == rp[0] && lp[1] == rp[1] && lp[2] == rp[2];+const float* ln = vertex_normals + lhs * vertex_normals_stride_float;const float* lt = vertex_uvs + lhs * vertex_uvs_stride_float;- const float* rp = vertex_positions + rhs * vertex_positions_stride_float;const float* rn = vertex_normals + rhs * vertex_normals_stride_float;const float* rt = vertex_uvs + rhs * vertex_uvs_stride_float;@@ -154,9 +200,10 @@ static T* hashLookup4(T* table, size_t buckets, const Hash& hash, const T& key,return NULL;}-static void buildVertexRemap(unsigned int* remap, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, meshopt_Allocator& allocator)+template <bool PositionOnly>+static void buildVertexRemap(unsigned int* remap, size_t vertex_count, const float* vertex_positions, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, meshopt_Allocator& allocator){- VertexHasherF vertex_hasher = {vertex_positions, vertex_positions_stride / sizeof(float), vertex_normals, vertex_normals_stride / sizeof(float), vertex_uvs, vertex_uvs_stride / sizeof(float)};+ VertexHasherF<PositionOnly> vertex_hasher = {vertex_positions, vertex_positions_stride / sizeof(float), vertex_normals, vertex_normals_stride / sizeof(float), vertex_uvs, vertex_uvs_stride / sizeof(float)};size_t vertex_table_size = hashBuckets4(vertex_count);unsigned int* vertex_table = allocator.allocate<unsigned int>(vertex_table_size);@@ -296,6 +343,46 @@ static void mergeTangentGroups(unsigned int* groups, unsigned int* facegroups, u}}+static void mergeNormalGroups(unsigned int* groups, const unsigned int* data, size_t count, const unsigned int* indices, const unsigned int* remap, const Normal* face_normals, float crease_cutoff)+{+ static const int next[4] = {1, 2, 0, 1};++ for (size_t i = 0; i < count; ++i)+ {+ unsigned int ti = data[i] >> 2;+ unsigned int cib = ti * 3 + next[(data[i] & 3) + 0];+ unsigned int cic = ti * 3 + next[(data[i] & 3) + 1];++ unsigned int nib = indices ? remap[indices[cib]] : remap[cib];+ unsigned int nic = indices ? remap[indices[cic]] : remap[cic];++ const Normal& fi = face_normals[ti];++ for (size_t j = i + 1; j < count; ++j)+ {+ unsigned int tj = data[j] >> 2;+ unsigned int cjb = tj * 3 + next[(data[j] & 3) + 0];+ unsigned int cjc = tj * 3 + next[(data[j] & 3) + 1];++ unsigned int njb = indices ? remap[indices[cjb]] : remap[cjb];+ unsigned int njc = indices ? remap[indices[cjc]] : remap[cjc];++ const Normal& fj = face_normals[tj];++ // merge normal groups if triangles are adjacent and normal angle is below crease threshold+ if ((njb == nic || njc == nib) && fi.x * fj.x + fi.y * fj.y + fi.z * fj.z > crease_cutoff && fi.id == fj.id)+ {+ // union normal groups for individual corners with gi as the root+ unsigned int gi = follow2(groups, ti * 3 + (data[i] & 3));+ unsigned int gj = follow2(groups, tj * 3 + (data[j] & 3));++ if (gi != gj)+ groups[gj] = gi;+ }+ }+ }+}+inline float optacos(float x){// approximation for acos(x) = sqrt(1 - abs(x)) * 2-degree polynomial, max error ~5e-4@@ -306,7 +393,7 @@ inline float optacos(float x)return x < 0.f ? 3.1415926f - r : r;}-static void accumulateTangentGroups(float* result, const unsigned int* groups, const unsigned int* indices, size_t index_count, const unsigned int* remap, const Tangent* face_tangents, const float* vertex_positions, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, unsigned int options)+static void accumulateTangents(float* result, const unsigned int* groups, const unsigned int* indices, size_t index_count, const Tangent* face_tangents, const float* vertex_positions, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, unsigned int options){static const int next[4] = {1, 2, 0, 1};@@ -326,9 +413,9 @@ static void accumulateTangentGroups(float* result, const unsigned int* groups, c{float* r = &result[size_t(groups[i * 3 + k]) * 4];- unsigned int a = indices ? remap[indices[i * 3 + k]] : remap[i * 3 + k];- unsigned int b = indices ? remap[indices[i * 3 + next[k]]] : remap[i * 3 + next[k]];- unsigned int c = indices ? remap[indices[i * 3 + next[k + 1]]] : remap[i * 3 + next[k + 1]];+ unsigned int a = indices ? indices[i * 3 + k] : unsigned(i * 3 + k);+ unsigned int b = indices ? indices[i * 3 + next[k]] : unsigned(i * 3 + next[k]);+ unsigned int c = indices ? indices[i * 3 + next[k + 1]] : unsigned(i * 3 + next[k + 1]);const float* pa = vertex_positions + a * vertex_position_stride_float;const float* pb = vertex_positions + b * vertex_position_stride_float;@@ -373,6 +460,111 @@ static void accumulateTangentGroups(float* result, const unsigned int* groups, c}}+static void accumulateNormals(float* result, const unsigned int* groups, const unsigned int* indices, size_t index_count, const Normal* face_normals, const float* vertex_positions, size_t vertex_positions_stride)+{+ static const int next[4] = {1, 2, 0, 1};++ size_t vertex_position_stride_float = vertex_positions_stride / sizeof(float);++ size_t face_count = index_count / 3;++ for (size_t i = 0; i < face_count; ++i)+ {+ const Normal& n = face_normals[i];++ for (int k = 0; k < 3; ++k)+ {+ float* r = &result[size_t(groups[i * 3 + k]) * 3];++ unsigned int a = indices ? indices[i * 3 + k] : unsigned(i * 3 + k);+ unsigned int b = indices ? indices[i * 3 + next[k]] : unsigned(i * 3 + next[k]);+ unsigned int c = indices ? indices[i * 3 + next[k + 1]] : unsigned(i * 3 + next[k + 1]);++ const float* pa = vertex_positions + a * vertex_position_stride_float;+ const float* pb = vertex_positions + b * vertex_position_stride_float;+ const float* pc = vertex_positions + c * vertex_position_stride_float;++ // compute incident angle for weighting+ float dp1x = pb[0] - pa[0], dp1y = pb[1] - pa[1], dp1z = pb[2] - pa[2];+ float dp2x = pc[0] - pa[0], dp2y = pc[1] - pa[1], dp2z = pc[2] - pa[2];++ float dp1l = dp1x * dp1x + dp1y * dp1y + dp1z * dp1z;+ float dp2l = dp2x * dp2x + dp2y * dp2y + dp2z * dp2z;+ float dpl = sqrtf(dp1l * dp2l);++ float cosa = (dp1x * dp2x + dp1y * dp2y + dp1z * dp2z) * (dpl == 0.f ? 0.f : 1.f / dpl);+ float angle = optacos(cosa); // optacos handles clamping to [-1..1]++ // accumulate normal weighted by angle and edge length product; this weighting scheme matches the default scheme used for tangents+ float w = angle * dpl;++ r[0] += n.x * w;+ r[1] += n.y * w;+ r[2] += n.z * w;+ }+ }+}++static void smoothNormals(float* result, float* scratch, const unsigned int* groups, size_t index_count, float alpha)+{+ static const int next[4] = {1, 2, 0, 1};++ size_t face_count = index_count / 3;++ memset(scratch, 0, index_count * 4 * sizeof(float));++ // for each triangle, accumulate normal deltas alongside each edge in both directions+ for (size_t i = 0; i < face_count; ++i)+ {+ for (int k = 0; k < 3; ++k)+ {+ unsigned int ga = groups[i * 3 + k];+ unsigned int gb = groups[i * 3 + next[k]];++ const float* na = &result[ga * 3];+ const float* nb = &result[gb * 3];++ // normal alignment is symmetric; we compute it once per edge and use dp^2 for stronger alignment+ float dp = na[0] * nb[0] + na[1] * nb[1] + na[2] * nb[2];+ float w = (dp > 0.f ? dp * dp : 0.f);++ float nx = (nb[0] - na[0]) * w, ny = (nb[1] - na[1]) * w, nz = (nb[2] - na[2]) * w;++ // accumulate deltas; the last component is used to compute delta averages below+ float* sa = &scratch[ga * 4];+ float* sb = &scratch[gb * 4];++ sa[0] += nx;+ sa[1] += ny;+ sa[2] += nz;+ sa[3] += 1.f;++ sb[0] -= nx;+ sb[1] -= ny;+ sb[2] -= nz;+ sb[3] += 1.f;+ }+ }++ // apply average delta to group roots and renormalize the results+ for (size_t i = 0; i < index_count; ++i)+ if (groups[i] == i && scratch[i * 4 + 3] > 0.f)+ {+ float* r = &result[i * 3];+ const float* s = &scratch[i * 4];++ float sw = alpha / s[3];+ float rx = r[0] + s[0] * sw, ry = r[1] + s[1] * sw, rz = r[2] + s[2] * sw;++ float rl = sqrtf(rx * rx + ry * ry + rz * rz);+ float rs = rl == 0.f ? 0.f : 1.f / rl;++ r[0] = rx * rs;+ r[1] = ry * rs;+ r[2] = rz * rs;+ }+}+} // namespace meshoptvoid meshopt_generateTangents(float* result, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, unsigned int options)@@ -392,7 +584,7 @@ void meshopt_generateTangents(float* result, const unsigned int* indices, size_t// compute vertex remap to unique vertex indexunsigned int* remap = allocator.allocate<unsigned int>(vertex_count);- buildVertexRemap(remap, vertex_positions, vertex_count, vertex_positions_stride, vertex_normals, vertex_normals_stride, vertex_uvs, vertex_uvs_stride, allocator);+ buildVertexRemap<false>(remap, vertex_count, vertex_positions, vertex_positions_stride, vertex_normals, vertex_normals_stride, vertex_uvs, vertex_uvs_stride, allocator);// build adjacency informationCornerAdjacency adjacency = {};@@ -426,7 +618,7 @@ void meshopt_generateTangents(float* result, const unsigned int* indices, size_t// accumulate tangents into their own respective groupsmemset(result, 0, index_count * sizeof(float) * 4);- accumulateTangentGroups(result, groups, indices, index_count, remap, face_tangents, vertex_positions, vertex_positions_stride, vertex_normals, vertex_normals_stride, options);+ accumulateTangents(result, groups, indices, index_count, face_tangents, vertex_positions, vertex_positions_stride, vertex_normals, vertex_normals_stride, options);// finalize tangent signs for each face using facegroupsfor (size_t i = 0; i < face_count; ++i)@@ -449,11 +641,90 @@ void meshopt_generateTangents(float* result, const unsigned int* indices, size_tr[1] *= s;r[2] *= s;- if ((options & meshopt_TangentZeroFallback) == 0)- r[0] = s == 0.f ? 1.f : r[0]; // for isolated degenerate triangles, use (1, 0, 0) tangent for consistency+ // for isolated degenerate triangles, use (1, 0, 0) tangent for consistency+ r[0] = (l == 0.f && (options & meshopt_TangentZeroFallback) == 0) ? 1.f : r[0];}for (size_t i = 0; i < index_count; ++i)if (groups[i] != i)memcpy(&result[i * 4], &result[size_t(groups[i]) * 4], sizeof(float) * 3); // .w was set per face earlier}++void meshopt_generateNormals(float* result, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float crease_angle, float smoothing)+{+ using namespace meshopt;++ assert(indices || index_count == vertex_count);+ assert(index_count % 3 == 0);+ assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);+ assert(vertex_positions_stride % sizeof(float) == 0);+ assert(crease_angle >= 0 && crease_angle <= 3.1415927f);+ assert(smoothing >= 0);++ meshopt_Allocator allocator;++ size_t face_count = index_count / 3;+ float crease_cutoff = cosf(crease_angle);++ // compute vertex remap to unique vertex index+ unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);+ buildVertexRemap<true>(remap, vertex_count, vertex_positions, vertex_positions_stride, NULL, 0, NULL, 0, allocator);++ // build adjacency information+ CornerAdjacency adjacency = {};+ buildCornerAdjacency(adjacency, indices, index_count, remap, vertex_count, allocator);++ // compute per-triangle normals+ Normal* face_normals = allocator.allocate<Normal>(face_count);+ computeFaceNormals(face_normals, face_count, indices, vertex_positions, vertex_positions_stride);++ // compute per-corner normal groups: triangles adjacent to the same vertex with similar normals are merged in strips+ unsigned int* groups = allocator.allocate<unsigned int>(index_count);+ for (size_t i = 0; i < index_count; ++i)+ groups[i] = unsigned(i);++ for (size_t i = 0; i < vertex_count; ++i)+ if (adjacency.offsets[i + 1] != adjacency.offsets[i])+ mergeNormalGroups(groups, adjacency.data + adjacency.offsets[i], adjacency.offsets[i + 1] - adjacency.offsets[i], indices, remap, face_normals, crease_cutoff);++ for (size_t i = 0; i < index_count; ++i)+ groups[i] = follow2(groups, unsigned(i));++ // accumulate normals into their own respective groups+ memset(result, 0, index_count * sizeof(float) * 3);+ accumulateNormals(result, groups, indices, index_count, face_normals, vertex_positions, vertex_positions_stride);++ // normalize accumulated normals; we need to do this before smoothing as smoothing expects normalized inputs+ for (size_t i = 0; i < index_count; ++i)+ if (groups[i] == i)+ {+ float* r = &result[i * 3];+ float l = sqrtf(r[0] * r[0] + r[1] * r[1] + r[2] * r[2]);+ float s = l == 0.f ? 0.f : 1.f / l;++ r[0] *= s;+ r[1] *= s;+ r[2] *= s;+ }++ if (smoothing > 0.f)+ {+ int passes = int(ceilf(smoothing));+ passes = passes < 10 ? passes : 10; // clamp to avoid pathological cases++ float* scratch = allocator.allocate<float>(index_count * 4);++ for (int pass = 0; pass < passes; ++pass)+ {+ float rem = smoothing - float(pass);+ float alpha = 0.5f * (rem < 1.f ? rem : 1.f);++ smoothNormals(result, scratch, groups, index_count, alpha);+ }+ }++ // finalize normal vectors by propagating the rest+ for (size_t i = 0; i < index_count; ++i)+ if (groups[i] != i)+ memcpy(&result[i * 3], &result[size_t(groups[i]) * 3], sizeof(float) * 3);+}diff --git a/thirdparty/meshoptimizer/vertexcodec.cpp b/thirdparty/meshoptimizer/vertexcodec.cppindex c8b9133da00..e6ccef02bf6 100644--- a/thirdparty/meshoptimizer/vertexcodec.cpp+++ b/thirdparty/meshoptimizer/vertexcodec.cpp@@ -1006,7 +1006,7 @@ static inline const unsigned char* decodeBytesGroupSimd(const unsigned char* dat// arrange bits such that low bits of nibbles of data64 contain all 2-bit elements of data32unsigned long long data64 = ((unsigned long long)data32 << 30) | data32;- // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used mode 3+ // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used a cheaper modeint datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60);#endif@@ -1042,7 +1042,7 @@ static inline const unsigned char* decodeBytesGroupSimd(const unsigned char* datdata64 &= data64 >> 1;data64 &= data64 >> 2;- // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used mode 3+ // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used a cheaper modeint datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60);#endif@@ -1651,7 +1651,7 @@ size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_sizefor (size_t k = 0; k < vertex_size; k += 4){int rot = level >= 3 ? estimateRotate(vertex_data, vertex_count, vertex_size, k, /* group_size= */ 16) : 0;- int channel = estimateChannel(vertex_data, vertex_count, vertex_size, k, vertex_block_size, /* block_skip= */ 3, /* max_channels= */ level >= 3 ? 3 : 2, rot);+ int channel = estimateChannel(vertex_data, vertex_count, vertex_size, k, vertex_block_size, /* block_skip= */ 3, /* max_channel= */ level >= 3 ? 3 : 2, rot);assert(unsigned(channel) < 2 || ((channel & 3) == 2 && unsigned(channel >> 4) < 8));channels[k / 4] = (unsigned char)channel;@@ -1761,15 +1761,15 @@ size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size)size_t vertex_block_count = (vertex_count + vertex_block_size - 1) / vertex_block_size;size_t vertex_block_control_size = vertex_size / 4;- size_t vertex_block_header_size = (vertex_block_size / kByteGroupSize + 3) / 4;- size_t vertex_block_data_size = vertex_block_size;+ size_t vertex_byte_header_size = (vertex_block_size / kByteGroupSize + 3) / 4;+ size_t vertex_byte_data_size = vertex_block_size;size_t tail_size = vertex_size + (vertex_size / 4);size_t tail_size_min = kTailMinSizeV0 > kTailMinSizeV1 ? kTailMinSizeV0 : kTailMinSizeV1;size_t tail_size_pad = tail_size < tail_size_min ? tail_size_min : tail_size;assert(tail_size_pad >= kByteGroupDecodeLimit);- return 1 + vertex_block_count * vertex_size * (vertex_block_control_size + vertex_block_header_size + vertex_block_data_size) + tail_size_pad;+ return 1 + vertex_block_count * (vertex_block_control_size + vertex_size * (vertex_byte_header_size + vertex_byte_data_size)) + tail_size_pad;}void meshopt_encodeVertexVersion(int version)diff --git a/thirdparty/meshoptimizer/vertexfilter.cpp b/thirdparty/meshoptimizer/vertexfilter.cppindex de830f1ae0b..a8d89d1aa14 100644--- a/thirdparty/meshoptimizer/vertexfilter.cpp+++ b/thirdparty/meshoptimizer/vertexfilter.cpp@@ -113,7 +113,7 @@ static void decodeFilterQuat(short* data, size_t count)for (size_t i = 0; i < count; ++i){- // recover scale from the high byte of the component+ // recover scale from the high byte/word of the componentint sf = data[i * 4 + 3] | 3;float s = float(sf);@@ -1439,9 +1439,14 @@ void meshopt_encodeFilterExp(void* destination_, size_t count, size_t stride, inexp -= (bits - 1);// compute renormalized rounded mantissa for each component- int mmask = (1 << 24) - 1;+ const int mmask = (1 << 24) - 1;+ const int mmax = mmask >> 1;+int m = int(v[j] * optexp2(-exp) + (v[j] >= 0 ? 0.5f : -0.5f));+ // clamp mantissa so that rounding away from zero doesn't overflow+ m = m > mmax ? mmax : m;+d[j] = (m & mmask) | (unsigned(exp) << 24);}}