Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

thirdparty: Update meshoptimizer to 1.2

Arseny Kapoulkine58f5006414ab
diff --git a/modules/meshoptimizer/SCsub b/modules/meshoptimizer/SCsub
index 2ecff8c4d69..bc7324d16e8 100644
--- a/modules/meshoptimizer/SCsub
+++ b/modules/meshoptimizer/SCsub
@@ -24,6 +24,7 @@ thirdparty_sources = [
"simplifier.cpp",
"spatialorder.cpp",
"stripifier.cpp",
+ "tangentspace.cpp",
"vcacheoptimizer.cpp",
"vertexcodec.cpp",
"vertexfilter.cpp",
diff --git a/thirdparty/README.md b/thirdparty/README.md
index 6a0f51153a1..501118154c4 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -720,7 +720,7 @@ Update instructions:
## meshoptimizer
- Upstream: https://github.com/zeux/meshoptimizer
-- Version: 1.1.1 (b22872835dbabc56a6e4a366ea9917f62b7daf1a, 2026)
+- Version: 1.2 (9d9890c73011d75920af614485296d1e03e95448, 2026)
- License: MIT
Files extracted from upstream repository:
diff --git a/thirdparty/meshoptimizer/clusterizer.cpp b/thirdparty/meshoptimizer/clusterizer.cpp
index b5a3cd92168..0b630b2cb01 100644
--- a/thirdparty/meshoptimizer/clusterizer.cpp
+++ b/thirdparty/meshoptimizer/clusterizer.cpp
@@ -246,6 +246,14 @@ static bool appendMeshlet(meshopt_Meshlet& meshlet, unsigned int a, unsigned int
short& bv = used[b];
short& cv = used[c];
+#ifdef MESHOPTIMIZER_CLUSTERIZER_INDEXLIMIT
+ // to ensure that after adding up to 2 new vertices, the existing vertex is within span limit (32), we need to reset vertex indices that are out of range
+ const int span_limit = 32 - 2;
+ av = (av + span_limit < int(meshlet.vertex_count)) ? -1 : av;
+ bv = (bv + span_limit < int(meshlet.vertex_count)) ? -1 : bv;
+ cv = (cv + span_limit < int(meshlet.vertex_count)) ? -1 : cv;
+#endif
+
bool result = false;
int used_extra = (av < 0) + (bv < 0) + (cv < 0);
@@ -694,7 +702,7 @@ static float boxMerge(BVHBoxT& box, const BVHBox& other)
}
float sx = box.max[0] - box.min[0], sy = box.max[1] - box.min[1], sz = box.max[2] - box.min[2];
- return sx * sy + sx * sz + sy * sz;
+ return sx * sy + sy * sz + sz * sx;
}
#endif
@@ -842,7 +850,7 @@ static void bvhPackTail(unsigned char* boundary, const unsigned int* order, size
static bool bvhDivisible(size_t count, size_t min, size_t max)
{
- // count is representable as a sum of values in [min..max] if if it in range of [k*min..k*min+k*(max-min)]
+ // count is representable as a sum of values in [min..max] if it is in range of [k*min..k*min+k*(max-min)]
// equivalent to ceil(count / max) <= floor(count / min), but the form below allows using idiv (see nv_cluster_builder)
// we avoid expensive integer divisions in the common case where min is <= max/2
return min * 2 <= max ? count >= min : count % min <= (count / min) * (max - min);
@@ -1266,6 +1274,8 @@ size_t meshopt_buildMeshletsSpatial(struct meshopt_Meshlet* meshlets, unsigned i
assert(max_vertices >= 3 && max_vertices <= 256);
assert(min_triangles >= 1 && min_triangles <= max_triangles && max_triangles <= 512);
+ assert(fill_weight >= 0);
+
if (index_count == 0)
return 0;
diff --git a/thirdparty/meshoptimizer/indexcodec.cpp b/thirdparty/meshoptimizer/indexcodec.cpp
index 8e6b3a4ae75..2aa1297d0ec 100644
--- a/thirdparty/meshoptimizer/indexcodec.cpp
+++ b/thirdparty/meshoptimizer/indexcodec.cpp
@@ -21,7 +21,7 @@ typedef unsigned int EdgeFifo[16][2];
static const unsigned char kCodeAuxEncodingTable[16] = {
0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98, 0x01, 0x69,
- 0, 0, // last two entries aren't used for encoding
+ 0, 0 // last two entries aren't used for encoding
};
static int rotateTriangle(unsigned int a, unsigned int b, unsigned int c, unsigned int next)
diff --git a/thirdparty/meshoptimizer/indexgenerator.cpp b/thirdparty/meshoptimizer/indexgenerator.cpp
index 5bde1b48dd5..1b707bb1b6e 100644
--- a/thirdparty/meshoptimizer/indexgenerator.cpp
+++ b/thirdparty/meshoptimizer/indexgenerator.cpp
@@ -127,6 +127,30 @@ struct VertexCustomHasher
}
};
+struct TriangleKey
+{
+ unsigned int a, b, c;
+
+ bool operator==(const TriangleKey& other) const
+ {
+ return a == other.a && b == other.b && c == other.c;
+ }
+};
+
+struct TriangleKeyHasher
+{
+ size_t hash(const TriangleKey& k) const
+ {
+ // Optimized Spatial Hashing for Collision Detection of Deformable Objects
+ return (k.a * 73856093) ^ (k.b * 19349663) ^ (k.c * 83492791);
+ }
+
+ bool equal(const TriangleKey& lhs, const TriangleKey& rhs) const
+ {
+ return lhs == rhs;
+ }
+};
+
struct EdgeHasher
{
const unsigned int* remap;
@@ -304,6 +328,63 @@ static void generateShadowBuffer(unsigned int* destination, const unsigned int*
}
}
+static size_t filterIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap, size_t vertex_count, meshopt_Allocator& allocator)
+{
+ (void)vertex_count;
+
+ TriangleKeyHasher hasher = {};
+ TriangleKey empty = {~0u, ~0u, ~0u};
+
+ size_t face_count = index_count / 3;
+ size_t table_size = hashBuckets(face_count);
+ TriangleKey* table = allocator.allocate<TriangleKey>(table_size);
+ memset(table, -1, table_size * sizeof(TriangleKey));
+
+ size_t write = 0;
+
+ for (size_t i = 0; i < face_count; ++i)
+ {
+ unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
+ assert(a < vertex_count && b < vertex_count && c < vertex_count);
+
+ unsigned int ra = remap[a], rb = remap[b], rc = remap[c];
+
+ // degenerate triangle
+ if (ra == rb || ra == rc || rb == rc)
+ continue;
+
+ // canonicalize triangle wrt winding preserving rotation
+ if (rb < ra && rb < rc)
+ {
+ // abc -> bca
+ unsigned int t = ra;
+ ra = rb, rb = rc, rc = t;
+ }
+ else if (rc < ra && rc < rb)
+ {
+ // abc -> cab
+ unsigned int t = rc;
+ rc = rb, rb = ra, ra = t;
+ }
+
+ TriangleKey key = {ra, rb, rc};
+ TriangleKey* entry = hashLookup(table, table_size, hasher, key, empty);
+
+ // duplicate triangle
+ if (entry->a != ~0u)
+ continue;
+
+ *entry = key;
+
+ destination[write + 0] = a;
+ destination[write + 1] = b;
+ destination[write + 2] = c;
+ write += 3;
+ }
+
+ return write;
+}
+
} // namespace meshopt
size_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
@@ -399,11 +480,49 @@ void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* ind
}
}
+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)
+{
+ using namespace meshopt;
+
+ assert(index_count % 3 == 0);
+ assert(vertex_size > 0 && vertex_size <= 256);
+ assert(vertex_size <= vertex_stride);
+
+ meshopt_Allocator allocator;
+ VertexHasher hasher = {static_cast<const unsigned char*>(vertices), vertex_size, vertex_stride};
+
+ unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);
+ generateVertexRemap(remap, indices, index_count, vertex_count, hasher, allocator);
+
+ return filterIndexBuffer(destination, indices, index_count, remap, vertex_count, allocator);
+}
+
+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)
+{
+ using namespace meshopt;
+
+ assert(index_count % 3 == 0);
+ assert(stream_count > 0 && stream_count <= 16);
+
+ for (size_t i = 0; i < stream_count; ++i)
+ {
+ assert(streams[i].size > 0 && streams[i].size <= 256);
+ assert(streams[i].size <= streams[i].stride);
+ }
+
+ meshopt_Allocator allocator;
+ VertexStreamHasher hasher = {streams, stream_count};
+
+ unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);
+ generateVertexRemap(remap, indices, index_count, vertex_count, hasher, allocator);
+
+ return filterIndexBuffer(destination, indices, index_count, remap, vertex_count, allocator);
+}
+
void meshopt_generateShadowIndexBuffer(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)
{
using namespace meshopt;
- assert(indices);
assert(index_count % 3 == 0);
assert(vertex_size > 0 && vertex_size <= 256);
assert(vertex_size <= vertex_stride);
@@ -418,7 +537,6 @@ void meshopt_generateShadowIndexBufferMulti(unsigned int* destination, const uns
{
using namespace meshopt;
- assert(indices);
assert(index_count % 3 == 0);
assert(stream_count > 0 && stream_count <= 16);
diff --git a/thirdparty/meshoptimizer/meshoptimizer.h b/thirdparty/meshoptimizer/meshoptimizer.h
index da6acf06e17..e6aa58eb4d6 100644
--- a/thirdparty/meshoptimizer/meshoptimizer.h
+++ b/thirdparty/meshoptimizer/meshoptimizer.h
@@ -1,5 +1,5 @@
/**
- * meshoptimizer - version 1.1
+ * meshoptimizer - version 1.2
*
* 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 1010 /* 1.1 */
+#define MESHOPTIMIZER_VERSION 1020 /* 1.2 */
/* If no API is defined, assume default */
#ifndef MESHOPTIMIZER_API
@@ -103,6 +103,27 @@ 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
+ * 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);
+
+/**
+ * Experimental: 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.
+ *
+ * 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);
+
/**
* Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary
* All vertices that are binary equivalent (wrt first vertex_size bytes) map to the first vertex in the original vertex buffer.
@@ -252,6 +273,7 @@ MESHOPTIMIZER_API size_t meshopt_encodeIndexBufferBound(size_t index_count, size
/**
* Set index encoder format version (defaults to 1)
+ * This function is not thread safe and must not be called concurrently with meshopt_encodeIndexBuffer/meshopt_encodeIndexSequence.
*
* version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.14+)
*/
@@ -296,7 +318,7 @@ MESHOPTIMIZER_API size_t meshopt_encodeIndexSequenceBound(size_t index_count, si
MESHOPTIMIZER_API int meshopt_decodeIndexSequence(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size);
/**
- * Experimental: Meshlet encoder
+ * Meshlet encoder
* Encodes meshlet data into an array of bytes that is generally smaller and compresses better compared to original.
* Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space
* This function encodes a single meshlet; when encoding multiple meshlets, additional headers may be necessary to store vertex/triangle count and encoded size.
@@ -306,11 +328,11 @@ MESHOPTIMIZER_API int meshopt_decodeIndexSequence(void* destination, size_t inde
* vertices may be NULL, in which case vertex_count must be 0 and only triangle data is encoded
* vertex_count and triangle_count must be <= 256.
*/
-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_encodeMeshlet(unsigned char* buffer, size_t buffer_size, const unsigned int* vertices, size_t vertex_count, const unsigned char* triangles, size_t triangle_count);
-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_encodeMeshletBound(size_t max_vertices, size_t max_triangles);
+MESHOPTIMIZER_API size_t meshopt_encodeMeshlet(unsigned char* buffer, size_t buffer_size, const unsigned int* vertices, size_t vertex_count, const unsigned char* triangles, size_t triangle_count);
+MESHOPTIMIZER_API size_t meshopt_encodeMeshletBound(size_t max_vertices, size_t max_triangles);
/**
- * Experimental: Meshlet decoder
+ * Meshlet decoder
* Decodes meshlet data from an array of bytes generated by meshopt_encodeMeshlet
* Returns 0 if decoding was successful, and an error code otherwise
* The decoder is safe to use for untrusted input, but it may produce garbage data.
@@ -324,8 +346,8 @@ MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_encodeMeshletBound(size_t max_vertices
*
* When using "raw" decoding (meshopt_decodeMeshletRaw), both vertices and triangles should have available space further aligned to 16 bytes for efficient SIMD decoding.
*/
-MESHOPTIMIZER_EXPERIMENTAL int meshopt_decodeMeshlet(void* vertices, size_t vertex_count, size_t vertex_size, void* triangles, size_t triangle_count, size_t triangle_size, const unsigned char* buffer, size_t buffer_size);
-MESHOPTIMIZER_EXPERIMENTAL int meshopt_decodeMeshletRaw(unsigned int* vertices, size_t vertex_count, unsigned int* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size);
+MESHOPTIMIZER_API int meshopt_decodeMeshlet(void* vertices, size_t vertex_count, size_t vertex_size, void* triangles, size_t triangle_count, size_t triangle_size, const unsigned char* buffer, size_t buffer_size);
+MESHOPTIMIZER_API int meshopt_decodeMeshletRaw(unsigned int* vertices, size_t vertex_count, unsigned int* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size);
/**
* Vertex buffer encoder
@@ -356,6 +378,7 @@ MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer,
/**
* Set vertex encoder format version (defaults to 1)
+ * This function is not thread safe and must not be called concurrently with meshopt_encodeVertexBuffer/meshopt_encodeVertexBufferLevel.
*
* version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.23+)
*/
@@ -387,7 +410,7 @@ MESHOPTIMIZER_API int meshopt_decodeVertexVersion(const unsigned char* buffer, s
* Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. W is preserved as is.
*
* meshopt_decodeFilterQuat decodes 3-component quaternion encoding with K-bit component encoding and a 2-bit component index indicating which component to reconstruct.
- * Each component is stored as an 16-bit integer; stride must be equal to 8.
+ * Each component is stored as a 16-bit integer; stride must be equal to 8.
*
* meshopt_decodeFilterExp decodes exponential encoding of floating-point data with 8-bit exponent and 24-bit integer mantissa as 2^E*M.
* Each 32-bit component is decoded in isolation; stride must be divisible by 4.
@@ -405,19 +428,19 @@ MESHOPTIMIZER_API void meshopt_decodeFilterColor(void* buffer, size_t count, siz
* These functions can be used to encode data in a format that meshopt_decodeFilter can decode
*
* meshopt_encodeFilterOct encodes unit vectors with K-bit (2 <= K <= 16) signed X/Y as an output.
- * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. Z will store 1.0f, W is preserved as is.
+ * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 (K <= 8) or 8 (K <= 16). Z will store 1.0f, W is preserved as is.
* Input data must contain 4 floats for every vector (count*4 total).
*
* meshopt_encodeFilterQuat encodes unit quaternions with K-bit (4 <= K <= 16) component encoding.
- * Each component is stored as an 16-bit integer; stride must be equal to 8.
+ * Each component is stored as a 16-bit integer; stride must be equal to 8.
* Input data must contain 4 floats for every quaternion (count*4 total).
*
* meshopt_encodeFilterExp encodes arbitrary (finite) floating-point data with 8-bit exponent and K-bit integer mantissa (1 <= K <= 24).
- * Exponent can be shared between all components of a given vector as defined by stride or all values of a given component; stride must be divisible by 4.
+ * Exponent can be shared between all components of a given vector as defined by stride or all values of a given component; stride must be divisible by 4 (and <= 256).
* Input data must contain stride/4 floats for every vector (count*stride/4 total).
*
* meshopt_encodeFilterColor encodes RGBA color data by converting RGB to YCoCg color space with K-bit (2 <= K <= 16) component encoding; A is stored using K-1 bits.
- * Each component is stored as an 8-bit or 16-bit integer; stride must be equal to 4 or 8.
+ * Each component is stored as an 8-bit or 16-bit integer; stride must be equal to 4 (K <= 8) or 8 (K <= 16).
* Input data must contain 4 floats for every color (count*4 total).
*/
enum meshopt_EncodeExpMode
@@ -454,7 +477,7 @@ enum
meshopt_SimplifyRegularize = 1 << 4,
/* Experimental: Allow collapses across attribute discontinuities, except for vertices that are tagged with meshopt_SimplifyVertex_Protect in vertex_lock. */
meshopt_SimplifyPermissive = 1 << 5,
- /* Experimental: Produce more regular triangle sizes and shapes during simplification, at a small cost to geometric and attribute quality. */
+ /* Produce more regular triangle sizes and shapes during simplification, at a small cost to geometric and attribute quality. */
meshopt_SimplifyRegularizeLight = 1 << 6,
};
@@ -467,7 +490,7 @@ enum
meshopt_SimplifyVertex_Lock = 1 << 0,
/* Protect attribute discontinuity at this vertex; must be used together with meshopt_SimplifyPermissive option. */
meshopt_SimplifyVertex_Protect = 1 << 1,
- /* Experimental: Increase priority for this vertex, making it more likely that it's preserved during simplification. */
+ /* Increase priority for this vertex, making it more likely that it's preserved during simplification. */
meshopt_SimplifyVertex_Priority = 1 << 2,
};
@@ -483,9 +506,9 @@ enum
*
* destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)!
* vertex_positions should have float3 position in the first 12 bytes of each vertex
- * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
+ * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation (unless absolute error option is used)
* options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default
- * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
+ * result_error can be NULL; when it's not NULL, it will contain the resulting (relative/absolute) error after simplification
*/
MESHOPTIMIZER_API size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error);
@@ -507,9 +530,9 @@ MESHOPTIMIZER_API size_t meshopt_simplify(unsigned int* destination, const unsig
* attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position
* attribute_count must be <= 32
* vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex composed of meshopt_SimplifyVertex_* flags
- * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
+ * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation (unless absolute error option is used)
* options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default
- * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
+ * result_error can be NULL; when it's not NULL, it will contain the resulting (relative/absolute) error after simplification
*/
MESHOPTIMIZER_API size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error);
@@ -530,9 +553,9 @@ MESHOPTIMIZER_API size_t meshopt_simplifyWithAttributes(unsigned int* destinatio
* attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position
* attribute_count must be <= 32
* vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex composed of meshopt_SimplifyVertex_* flags
- * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
+ * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation (unless absolute error option is used)
* options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default
- * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
+ * result_error can be NULL; when it's not NULL, it will contain the resulting (relative/absolute) error after simplification
*/
MESHOPTIMIZER_API size_t meshopt_simplifyWithUpdate(unsigned int* indices, size_t index_count, float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error);
@@ -743,13 +766,13 @@ MESHOPTIMIZER_API size_t meshopt_buildMeshletsSpatial(struct meshopt_Meshlet* me
MESHOPTIMIZER_API void meshopt_optimizeMeshlet(unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t triangle_count, size_t vertex_count);
/**
- * Experimental: Meshlet optimizer
+ * Meshlet optimizer
* Reorders meshlet vertices and triangles to maximize locality, with higher levels resulting in smaller compressed size at the cost of optimization time.
* At level 0 the result is equivalent to meshopt_optimizeMeshlet; levels >= 1 may rotate triangle corners to improve compression (which can change provoking vertex and affect OMM data).
*
* level should be in the range [0, 9] with 0 equivalent to meshopt_optimizeMeshlet and 9 being the slowest; the sweet spot for compression ratio is around 3
*/
-MESHOPTIMIZER_EXPERIMENTAL void meshopt_optimizeMeshletLevel(unsigned int* meshlet_vertices, size_t vertex_count, unsigned char* meshlet_triangles, size_t triangle_count, int level);
+MESHOPTIMIZER_API void meshopt_optimizeMeshletLevel(unsigned int* meshlet_vertices, size_t vertex_count, unsigned char* meshlet_triangles, size_t triangle_count, int level);
struct meshopt_Bounds
{
@@ -804,13 +827,15 @@ MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeMeshletBounds(const unsig
MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeSphereBounds(const float* positions, size_t count, size_t positions_stride, const float* radii, size_t radii_stride);
/**
- * Experimental: Extract meshlet-local vertex and triangle indices from absolute cluster indices.
+ * Extract meshlet-local vertex and triangle indices from absolute cluster indices.
* Fills triangles[] and vertices[] such that vertices[triangles[i]] == indices[i], and returns the number of unique vertices.
*
+ * vertices must contain enough space for the resulting references (up to 256 elements)
+ * triangles must contain enough space for local indices (index_count elements)
* indices should have at most 256 unique vertex indices
* index_count/3 must not exceed implementation limits (<= 512)
*/
-MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_extractMeshletIndices(unsigned int* vertices, unsigned char* triangles, const unsigned int* indices, size_t index_count);
+MESHOPTIMIZER_API size_t meshopt_extractMeshletIndices(unsigned int* vertices, unsigned char* triangles, const unsigned int* indices, size_t index_count);
/**
* Cluster partitioner
@@ -898,6 +923,33 @@ MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_opacityMapEntrySize(int level, int sta
*/
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);
+/**
+ * Tangent generation options
+ */
+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. */
+ meshopt_TangentZeroFallback = 1 << 1,
+};
+
+/**
+ * Experimental: 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.
+ *
+ * result must contain enough space for the output tangent data (index_count*4 elements)
+ * indices can be NULL if the input is unindexed
+ * vertex_positions should have float3 position in the first 12 bytes of each vertex
+ * 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);
+
/**
* Quantize a float into half-precision (as defined by IEEE-754 fp16) floating point value
* Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest
@@ -919,11 +971,31 @@ 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
+ * 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).
+ *
+ * To quantize positions, compute:
+ * scale = pow(2, exponent)
+ * iv = int(round(v / scale))
+ * 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
+ * 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);
+
/**
* Set allocation callbacks
* These callbacks will be used instead of the default operator new/operator delete for all temporary allocations in the library.
* Note that all algorithms only allocate memory for temporary use.
* allocate/deallocate are always called in a stack-like order - last pointer to be allocated is deallocated first.
+ * This function is not thread safe and must not be called concurrently with any other meshopt_ function.
+ *
+ * In shared library builds, allocations from templated index wrappers in this header will only be redirected if MESHOPTIMIZER_ALLOC_EXPORT is defined.
*/
MESHOPTIMIZER_API void meshopt_setAllocator(void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t), void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*));
@@ -968,6 +1040,10 @@ inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const
template <typename T>
inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap);
template <typename T>
+inline size_t meshopt_filterIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride);
+template <typename T>
+inline size_t meshopt_filterIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count);
+template <typename T>
inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride);
template <typename T>
inline void meshopt_generateShadowIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count);
@@ -1038,6 +1114,8 @@ template <typename T>
inline size_t meshopt_partitionClusters(unsigned int* destination, const T* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size);
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);
#endif
/* Inline implementation */
@@ -1220,6 +1298,24 @@ inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t in
meshopt_remapIndexBuffer(out.data, indices ? in.data : NULL, index_count, remap);
}
+template <typename T>
+inline size_t meshopt_filterIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride)
+{
+ meshopt_IndexAdapter<T> in(NULL, indices, index_count);
+ meshopt_IndexAdapter<T> out(destination, NULL, index_count);
+
+ return meshopt_filterIndexBuffer(out.data, in.data, index_count, vertices, vertex_count, vertex_size, vertex_stride);
+}
+
+template <typename T>
+inline size_t meshopt_filterIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count)
+{
+ meshopt_IndexAdapter<T> in(NULL, indices, index_count);
+ meshopt_IndexAdapter<T> out(destination, NULL, index_count);
+
+ return meshopt_filterIndexBufferMulti(out.data, in.data, index_count, vertex_count, streams, stream_count);
+}
+
template <typename T>
inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride)
{
@@ -1528,6 +1624,14 @@ inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_
meshopt_spatialSortTriangles(out.data, in.data, index_count, vertex_positions, vertex_count, 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)
+{
+ meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);
+
+ meshopt_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);
+}
#endif
/**
diff --git a/thirdparty/meshoptimizer/partition.cpp b/thirdparty/meshoptimizer/partition.cpp
index 4119a53ed2c..c19cf19f7da 100644
--- a/thirdparty/meshoptimizer/partition.cpp
+++ b/thirdparty/meshoptimizer/partition.cpp
@@ -268,24 +268,6 @@ static GroupOrder heapPop(GroupOrder* heap, size_t size)
return top;
}
-static unsigned int countShared(const ClusterGroup* groups, int group1, int group2, const ClusterAdjacency& adjacency)
-{
- unsigned int total = 0;
-
- for (int i1 = group1; i1 >= 0; i1 = groups[i1].next)
- for (int i2 = group2; i2 >= 0; i2 = groups[i2].next)
- {
- for (unsigned int adj = adjacency.offsets[i1]; adj < adjacency.offsets[i1 + 1]; ++adj)
- if (adjacency.clusters[adj] == unsigned(i2))
- {
- total += adjacency.shared[adj];
- break;
- }
- }
-
- return total;
-}
-
static void mergeBounds(ClusterGroup& target, const ClusterGroup& source)
{
float r1 = target.radius, r2 = source.radius;
@@ -323,7 +305,7 @@ static float boundsScore(const ClusterGroup& target, const ClusterGroup& source)
return mr > 0 ? r1 / mr : 0.f;
}
-static int pickGroupToMerge(const ClusterGroup* groups, int id, const ClusterAdjacency& adjacency, size_t max_partition_size, bool use_bounds)
+static int pickGroupToMerge(const ClusterGroup* groups, int id, const ClusterAdjacency& adjacency, size_t max_partition_size, bool use_bounds, unsigned int* shared_acc, unsigned int& out_shared)
{
assert(groups[id].size > 0);
@@ -331,20 +313,34 @@ static int pickGroupToMerge(const ClusterGroup* groups, int id, const ClusterAdj
int best_group = -1;
float best_score = 0;
+ unsigned int best_shared = 0;
+ // compute shared count based on underlying clusters for every adjacent group
+ // note: we assume shared_acc only contains zeros on input
for (int ci = id; ci >= 0; ci = groups[ci].next)
- {
for (unsigned int adj = adjacency.offsets[ci]; adj != adjacency.offsets[ci + 1]; ++adj)
{
int other = groups[adjacency.clusters[adj]].group;
- if (other < 0)
+ if (other >= 0)
+ shared_acc[other] += adjacency.shared[adj];
+ }
+
+ // score each adjacent group and pick the best one; resets shared_acc in the process
+ for (int ci = id; ci >= 0; ci = groups[ci].next)
+ for (unsigned int adj = adjacency.offsets[ci]; adj != adjacency.offsets[ci + 1]; ++adj)
+ {
+ int other = groups[adjacency.clusters[adj]].group;
+ if (other < 0 || shared_acc[other] == 0)
continue;
+ // note: we reset shared_acc here to make sure the next invocation sees zero inputs; it's important that this is done before any early outs
+ unsigned int shared = shared_acc[other];
+ shared_acc[other] = 0;
+
assert(groups[other].size > 0);
if (groups[id].size + groups[other].size > max_partition_size)
continue;
- unsigned int shared = countShared(groups, id, other, adjacency);
float other_rsqrt = 1.f / sqrtf(float(int(groups[other].vertices)));
// normalize shared count by the expected boundary of each group (+ keeps scoring symmetric)
@@ -358,10 +354,11 @@ static int pickGroupToMerge(const ClusterGroup* groups, int id, const ClusterAdj
{
best_group = other;
best_score = score;
+ best_shared = shared;
}
}
- }
+ out_shared = best_shared;
return best_group;
}
@@ -513,6 +510,9 @@ size_t meshopt_partitionClusters(unsigned int* destination, const unsigned int*
GroupOrder* order = allocator.allocate<GroupOrder>(cluster_count);
size_t pending = 0;
+ unsigned int* shared_acc = allocator.allocate<unsigned int>(cluster_count);
+ memset(shared_acc, 0, cluster_count * sizeof(unsigned int));
+
// create a singleton group for each cluster and order them by priority
for (size_t i = 0; i < cluster_count; ++i)
{
@@ -553,15 +553,13 @@ size_t meshopt_partitionClusters(unsigned int* destination, const unsigned int*
if (groups[top.id].size >= target_partition_size)
continue;
- int best_group = pickGroupToMerge(groups, top.id, adjacency, max_partition_size, /* use_bounds= */ vertex_positions);
+ unsigned int best_shared = 0;
+ int best_group = pickGroupToMerge(groups, top.id, adjacency, max_partition_size, /* use_bounds= */ vertex_positions, shared_acc, best_shared);
// we can't grow the group any more, emit as is
if (best_group == -1)
continue;
- // compute shared vertices to adjust the total vertices estimate after merging
- unsigned int shared = countShared(groups, top.id, best_group, adjacency);
-
// combine groups by linking them together
unsigned int tail = top.id;
while (groups[tail].next >= 0)
@@ -572,7 +570,7 @@ size_t meshopt_partitionClusters(unsigned int* destination, const unsigned int*
// update group sizes; note, the vertex update is a O(1) approximation which avoids recomputing the true size
groups[top.id].size += groups[best_group].size;
groups[top.id].vertices += groups[best_group].vertices;
- groups[top.id].vertices = (groups[top.id].vertices > shared) ? groups[top.id].vertices - shared : 1;
+ groups[top.id].vertices = (groups[top.id].vertices > best_shared) ? groups[top.id].vertices - best_shared : 1;
groups[best_group].size = 0;
groups[best_group].vertices = 0;
diff --git a/thirdparty/meshoptimizer/quantization.cpp b/thirdparty/meshoptimizer/quantization.cpp
index 149835f5013..8571973022a 100644
--- a/thirdparty/meshoptimizer/quantization.cpp
+++ b/thirdparty/meshoptimizer/quantization.cpp
@@ -2,6 +2,8 @@
#include "meshoptimizer.h"
#include <assert.h>
+#include <float.h>
+#include <math.h>
union FloatBits
{
@@ -74,3 +76,52 @@ float meshopt_dequantizeHalf(unsigned short h)
u.ui = s | r;
return u.f;
}
+
+int meshopt_computePositionExponent(const float* minv, const float* maxv, int min_exp, int max_bits)
+{
+ assert(min_exp >= -126);
+ assert(max_bits >= 2 && max_bits <= 24);
+
+ int exp = min_exp;
+
+ // compute max absolute component to ensure that individual endpoints fit on a 24-bit signed grid
+ float maxc = 0.f;
+
+ for (int k = 0; k < 3; ++k)
+ {
+ maxc = maxc < fabsf(minv[k]) ? fabsf(minv[k]) : maxc;
+ maxc = maxc < fabsf(maxv[k]) ? fabsf(maxv[k]) : maxc;
+ }
+
+ int maxc_exp = 0;
+ float maxc_fr = frexpf(maxc, &maxc_exp);
+
+ // maxc is representable as 2^(maxc_exp-24) * 24-bit *unsigned* integer
+ // we have to use a 24-bit *signed* grid, so we have to chop off the last bit
+ // however, rounding in the corner case (mantissa is 1.111...) may increase the exponent by 1 so we need to offset it
+ int maxc_off = 23 - (maxc_fr >= 1.f - FLT_EPSILON / 2);
+
+ exp = exp < maxc_exp - maxc_off ? maxc_exp - maxc_off : exp;
+
+ // compute effective range with conservative rounding, to allow for some ambiguity in the caller's rounding direction
+ float scale = ldexpf(1.f, -exp);
+ float range = 0.f;
+
+ for (int k = 0; k < 3; ++k)
+ {
+ float a = floorf(minv[k] * scale);
+ float v = ceilf(maxv[k] * scale);
+ range = range < v - a ? v - a : range;
+ }
+
+ // range must be representable as max_bits unsigned integer
+ int range_exp = 0;
+ float range_fr = frexpf(range, &range_exp);
+
+ exp += (range_exp > max_bits) ? range_exp - max_bits : 0;
+
+ // correct range if we are at the rounding boundary that would push us to overflow max_bits
+ exp += range_exp > max_bits && range_fr >= 1.f - 1.f / float((1 << max_bits) - 1);
+
+ return exp;
+}
diff --git a/thirdparty/meshoptimizer/simplifier.cpp b/thirdparty/meshoptimizer/simplifier.cpp
index 88d4b15b388..5102b215d44 100644
--- a/thirdparty/meshoptimizer/simplifier.cpp
+++ b/thirdparty/meshoptimizer/simplifier.cpp
@@ -941,7 +941,7 @@ static void quadricFromAttributes(Quadric& Q, QuadricGrad* G, const Vector3& p0,
Q.c += w * (gw * gw);
- // the only remaining sum components are ones that depend on attr; these will be addded during error evaluation, see quadricError
+ // the only remaining sum components are ones that depend on attr; these will be added during error evaluation, see quadricError
G[k].gx = w * gx;
G[k].gy = w * gy;
G[k].gz = w * gz;
@@ -2652,6 +2652,7 @@ size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* ind
assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
assert(vertex_positions_stride % sizeof(float) == 0);
assert(target_index_count <= index_count);
+ assert(target_error >= 0);
// we expect to get ~2 triangles/vertex in the output
size_t target_cell_count = target_index_count / 6;
@@ -2850,7 +2851,7 @@ size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_pos
size_t min_vertices = 0;
size_t max_vertices = vertex_count;
- // instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...
+ // instead of starting in the middle, let's guess as to what the answer might be! surface point count usually grows as a square of grid size...
int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);
for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)
diff --git a/thirdparty/meshoptimizer/tangentspace.cpp b/thirdparty/meshoptimizer/tangentspace.cpp
new file mode 100644
index 00000000000..81cce4d5e43
--- /dev/null
+++ b/thirdparty/meshoptimizer/tangentspace.cpp
@@ -0,0 +1,459 @@
+// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
+#include "meshoptimizer.h"
+
+#include <assert.h>
+#include <math.h>
+#include <string.h>
+
+// This work is based on:
+// Morten Mikkelsen. Simulation of wrinkled surfaces revisited. 2008
+// Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 2003
+// Cecil Hastings Jr. Approximations for digital computers. 1955
+namespace meshopt
+{
+
+struct Tangent
+{
+ float x, y, z, w;
+};
+
+static void computeFaceTangents(Tangent* result, size_t triangle_count, const unsigned int* indices, const float* vertex_positions, size_t vertex_positions_stride, const float* vertex_uvs, size_t vertex_uvs_stride)
+{
+ size_t vertex_position_stride_float = vertex_positions_stride / sizeof(float);
+ size_t vertex_uv_stride_float = vertex_uvs_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];
+
+ const float* ta = &vertex_uvs[a * vertex_uv_stride_float];
+ const float* tb = &vertex_uvs[b * vertex_uv_stride_float];
+ const float* tc = &vertex_uvs[c * vertex_uv_stride_float];
+
+ // compute face tangents using chain rule, see eq. 42
+ 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 dt1x = tb[0] - ta[0], dt1y = tb[1] - ta[1];
+ float dt2x = tc[0] - ta[0], dt2y = tc[1] - ta[1];
+
+ float rx = dt2y * dp1x - dt1y * dp2x;
+ float ry = dt2y * dp1y - dt1y * dp2y;
+ float rz = dt2y * dp1z - dt1y * dp2z;
+
+ // .w stores orientation (+1/-1) or 0 for degenerate triangles, see eq. 48
+ float det = dt1x * dt2y - dt1y * dt2x;
+ float rw = det == 0.f ? 0.f : (det > 0.f ? 1.f : -1.f);
+
+ // treat zero area triangles as degenerate even if their UVs aren't for consistency
+ rw = (pa[0] == pb[0] && pa[1] == pb[1] && pa[2] == pb[2]) ? 0.f : rw;
+ rw = (pa[0] == pc[0] && pa[1] == pc[1] && pa[2] == pc[2]) ? 0.f : rw;
+ rw = (pb[0] == pc[0] && pb[1] == pc[1] && pb[2] == pc[2]) ? 0.f : rw;
+
+ float rl = sqrtf(rx * rx + ry * ry + rz * rz);
+ float rs = rl != 0.f ? rw / rl : 0.f;
+
+ result[i].x = rx * rs;
+ result[i].y = ry * rs;
+ result[i].z = rz * rs;
+ result[i].w = rw;
+ }
+}
+
+struct VertexHasherF
+{
+ const float* vertex_positions;
+ size_t vertex_positions_stride_float;
+ const float* vertex_normals;
+ size_t vertex_normals_stride_float;
+ const float* vertex_uvs;
+ size_t vertex_uvs_stride_float;
+
+ size_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];
+
+ // replace negative zero with zero
+ x = (x == 0x80000000) ? 0 : x;
+ y = (y == 0x80000000) ? 0 : y;
+ z = (z == 0x80000000) ? 0 : z;
+
+ // scramble bits to make sure that integer coordinates have entropy in lower bits
+ x ^= x >> 17;
+ y ^= y >> 17;
+ z ^= z >> 17;
+
+ // mix in normal bits
+ x ^= (n[0] == 0x80000000) ? 0 : n[0] >> 15;
+ y ^= (n[1] == 0x80000000) ? 0 : n[1] >> 15;
+ z ^= (n[2] == 0x80000000) ? 0 : n[2] >> 15;
+
+ // collect texture coordinate bits (simplified -0 handling and scrambling)
+ unsigned int w = (t[0] ^ t[1]) & 0x7fffffff;
+ w ^= w >> 13;
+
+ // Optimized Spatial Hashing for Collision Detection of Deformable Objects
+ return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791) ^ (w * 50331653);
+ }
+
+ bool equal(unsigned int lhs, unsigned int rhs) const
+ {
+ const float* lp = vertex_positions + lhs * vertex_positions_stride_float;
+ 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;
+
+ return lp[0] == rp[0] && lp[1] == rp[1] && lp[2] == rp[2] && ln[0] == rn[0] && ln[1] == rn[1] && ln[2] == rn[2] && lt[0] == rt[0] && lt[1] == rt[1];
+ }
+};
+
+static size_t hashBuckets4(size_t count)
+{
+ size_t buckets = 1;
+ while (buckets < count + count / 4)
+ buckets *= 2;
+
+ return buckets;
+}
+
+template <typename T, typename Hash>
+static T* hashLookup4(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty)
+{
+ assert(buckets > 0);
+ assert((buckets & (buckets - 1)) == 0);
+
+ size_t hashmod = buckets - 1;
+ size_t bucket = hash.hash(key) & hashmod;
+
+ for (size_t probe = 0; probe <= hashmod; ++probe)
+ {
+ T& item = table[bucket];
+
+ if (item == empty)
+ return &item;
+
+ if (hash.equal(item, key))
+ return &item;
+
+ // hash collision, quadratic probing
+ bucket = (bucket + probe + 1) & hashmod;
+ }
+
+ assert(false && "Hash table is full"); // unreachable
+ 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)
+{
+ VertexHasherF 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);
+ memset(vertex_table, -1, vertex_table_size * sizeof(unsigned int));
+
+ for (size_t i = 0; i < vertex_count; ++i)
+ {
+ unsigned int index = unsigned(i);
+ unsigned int* entry = hashLookup4(vertex_table, vertex_table_size, vertex_hasher, index, ~0u);
+
+ if (*entry == ~0u)
+ *entry = index;
+
+ remap[index] = *entry;
+ }
+
+ allocator.deallocate(vertex_table);
+}
+
+struct CornerAdjacency
+{
+ unsigned int* offsets;
+ unsigned int* data;
+};
+
+static void buildCornerAdjacency(CornerAdjacency& adjacency, const unsigned int* indices, size_t index_count, const unsigned int* remap, size_t vertex_count, meshopt_Allocator& allocator)
+{
+ adjacency.offsets = allocator.allocate<unsigned int>(vertex_count + 1);
+ adjacency.data = allocator.allocate<unsigned int>(index_count);
+
+ size_t face_count = index_count / 3;
+ unsigned int* offsets = adjacency.offsets + 1;
+
+ // fill corner counts
+ memset(offsets, 0, vertex_count * sizeof(unsigned int));
+
+ for (size_t i = 0; i < index_count; ++i)
+ {
+ unsigned int v = indices ? remap[indices[i]] : remap[i];
+ assert(v < vertex_count);
+
+ offsets[v]++;
+ }
+
+ // fill offset table
+ unsigned int offset = 0;
+
+ for (size_t i = 0; i < vertex_count; ++i)
+ {
+ unsigned int count = offsets[i];
+ offsets[i] = offset;
+ offset += count;
+ }
+
+ assert(offset == index_count);
+
+ // fill corner data
+ for (size_t i = 0; i < face_count; ++i)
+ {
+ unsigned int a = indices ? remap[indices[i * 3 + 0]] : remap[i * 3 + 0];
+ unsigned int b = indices ? remap[indices[i * 3 + 1]] : remap[i * 3 + 1];
+ unsigned int c = indices ? remap[indices[i * 3 + 2]] : remap[i * 3 + 2];
+
+ // encode corner index in the low 2 bits
+ adjacency.data[offsets[a]++] = unsigned(i << 2) | 0;
+ adjacency.data[offsets[b]++] = unsigned(i << 2) | 1;
+ adjacency.data[offsets[c]++] = unsigned(i << 2) | 2;
+ }
+
+ // finalize offsets
+ adjacency.offsets[0] = 0;
+ assert(adjacency.offsets[vertex_count] == index_count);
+}
+
+static unsigned int follow2(unsigned int* parents, unsigned int index)
+{
+ while (index != parents[index])
+ {
+ unsigned int parent = parents[index];
+ parents[index] = parents[parent];
+ index = parent;
+ }
+
+ return index;
+}
+
+static void mergeTangentGroups(unsigned int* groups, unsigned int* facegroups, unsigned char* facesign, const unsigned int* data, size_t count, const unsigned int* indices, const unsigned int* remap)
+{
+ 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];
+
+ 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];
+
+ // merge tangent groups if triangles are adjacent and orientations agree or either one is degenerate
+ if ((njb == nic || njc == nib) && (facesign[ti] | facesign[tj]) != 3)
+ {
+ // if either triangle is degenerate, it could have been assigned to a concrete orientation; we need to confirm that via facegroups
+ if ((facesign[ti] & facesign[tj]) == 0)
+ {
+ unsigned int gti = follow2(facegroups, ti);
+ unsigned int gtj = follow2(facegroups, tj);
+
+ // skip merge if orientations diverge; otherwise, union the groups with gti as the root
+ if (gti != gtj)
+ {
+ if ((facesign[gti] | facesign[gtj]) == 3)
+ continue;
+
+ facegroups[gtj] = gti;
+ facesign[gti] |= facesign[gtj];
+ }
+ }
+
+ // union tangent groups for individual corners with gi as the root; the orientations must match due to facegroups check above
+ 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
+ float ax = fabsf(x);
+ ax = ax > 1.f ? 1.f : ax;
+ float r = 1.570337f + ax * (-0.2053972f + ax * 0.05147786f);
+ r *= sqrtf(1.0f - ax);
+ 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 const int next[4] = {1, 2, 0, 1};
+
+ size_t vertex_position_stride_float = vertex_positions_stride / sizeof(float);
+ size_t vertex_normal_stride_float = vertex_normals_stride / sizeof(float);
+
+ size_t face_count = index_count / 3;
+
+ for (size_t i = 0; i < face_count; ++i)
+ {
+ const Tangent& t = face_tangents[i];
+
+ if (t.w == 0.f)
+ continue;
+
+ for (int k = 0; k < 3; ++k)
+ {
+ 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]];
+
+ 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;
+
+ const float* n = vertex_normals + a * vertex_normal_stride_float;
+
+ // reproject tangent vector onto vertex normal
+ float sd = t.x * n[0] + t.y * n[1] + t.z * n[2];
+ float sx = t.x - n[0] * sd, sy = t.y - n[1] * sd, sz = t.z - n[2] * sd;
+ float sl = sqrtf(sx * sx + sy * sy + sz * sz);
+
+ // compute incident angle for weighting, in tangent plane
+ // note: this step is absent from the paper, reference implementation computes angle after projecting edges to tangent plane...
+ 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 dp1d = dp1x * n[0] + dp1y * n[1] + dp1z * n[2];
+ float dp2d = dp2x * n[0] + dp2y * n[1] + dp2z * n[2];
+
+ dp1x -= n[0] * dp1d, dp1y -= n[1] * dp1d, dp1z -= n[2] * dp1d;
+ dp2x -= n[0] * dp2d, dp2y -= n[1] * dp2d, dp2z -= n[2] * dp2d;
+
+ 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 renormalized tangent weighted by angle
+ float w = angle * (sl == 0.f ? 0.f : 1.f / sl);
+
+ // weight larger adjacent triangles more to reduce interpolation artifacts from slivers; this deviates from reference implementation for higher quality
+ if ((options & meshopt_TangentCompatible) == 0)
+ w *= dpl;
+
+ r[0] += sx * w;
+ r[1] += sy * w;
+ r[2] += sz * w;
+ }
+ }
+}
+
+} // namespace meshopt
+
+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)
+{
+ 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_normals_stride >= 12 && vertex_normals_stride <= 256);
+ assert(vertex_uvs_stride >= 8 && vertex_uvs_stride <= 256);
+ assert(vertex_positions_stride % sizeof(float) == 0 && vertex_normals_stride % sizeof(float) == 0 && vertex_uvs_stride % sizeof(float) == 0);
+
+ meshopt_Allocator allocator;
+
+ size_t face_count = index_count / 3;
+
+ // compute vertex remap to unique vertex index
+ unsigned 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);
+
+ // build adjacency information
+ CornerAdjacency adjacency = {};
+ buildCornerAdjacency(adjacency, indices, index_count, remap, vertex_count, allocator);
+
+ // compute per-triangle tangents
+ Tangent* face_tangents = allocator.allocate<Tangent>(face_count);
+ computeFaceTangents(face_tangents, face_count, indices, vertex_positions, vertex_positions_stride, vertex_uvs, vertex_uvs_stride);
+
+ // compute per-corner tangent groups: triangles adjacent to the same vertex with the same orientation 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);
+
+ // compute per-face orientation groups: degenerate triangles are merged with adjacent non-degenerate ones and inherit their orientation, stored as a bitmask
+ unsigned int* facegroups = allocator.allocate<unsigned int>(face_count);
+ unsigned char* facesign = allocator.allocate<unsigned char>(face_count);
+
+ for (size_t i = 0; i < face_count; ++i)
+ {
+ facegroups[i] = unsigned(i);
+ facesign[i] = (face_tangents[i].w > 0.f ? 1 : 0) | (face_tangents[i].w < 0.f ? 2 : 0);
+ }
+
+ for (size_t i = 0; i < vertex_count; ++i)
+ if (adjacency.offsets[i + 1] != adjacency.offsets[i])
+ mergeTangentGroups(groups, facegroups, facesign, adjacency.data + adjacency.offsets[i], adjacency.offsets[i + 1] - adjacency.offsets[i], indices, remap);
+
+ for (size_t i = 0; i < index_count; ++i)
+ groups[i] = follow2(groups, unsigned(i));
+
+ // accumulate tangents into their own respective groups
+ memset(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);
+
+ // finalize tangent signs for each face using facegroups
+ for (size_t i = 0; i < face_count; ++i)
+ {
+ unsigned int fg = follow2(facegroups, unsigned(i));
+ float w = (facesign[fg] & 1) ? 1.f : -1.f; // note: if face is degenerate, we canonicalize to -1 for consistency
+
+ result[(i * 3 + 0) * 4 + 3] = result[(i * 3 + 1) * 4 + 3] = result[(i * 3 + 2) * 4 + 3] = w;
+ }
+
+ // finalize tangent vectors by normalizing roots and propagating the rest
+ for (size_t i = 0; i < index_count; ++i)
+ if (groups[i] == i)
+ {
+ float* r = &result[i * 4];
+ 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 ((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 (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
+}
diff --git a/thirdparty/meshoptimizer/vertexcodec.cpp b/thirdparty/meshoptimizer/vertexcodec.cpp
index dabf9854873..c8b9133da00 100644
--- a/thirdparty/meshoptimizer/vertexcodec.cpp
+++ b/thirdparty/meshoptimizer/vertexcodec.cpp
@@ -7,18 +7,18 @@
// The block below auto-detects SIMD ISA that can be used on the target platform
#ifndef MESHOPTIMIZER_NO_SIMD
-// The SIMD implementation requires SSSE3, which can be enabled unconditionally through compiler settings
-#if defined(__AVX__) || defined(__SSSE3__)
+// The SIMD implementation requires SSSE3+POPCNT, which can be enabled unconditionally through compiler settings
+#if defined(__AVX__) || (defined(__SSSE3__) && defined(__POPCNT__))
#define SIMD_SSE
#endif
// An experimental implementation using AVX512 instructions; it's only enabled when AVX512 is enabled through compiler settings
-#if defined(__AVX512VBMI2__) && defined(__AVX512VBMI__) && defined(__AVX512VL__) && defined(__POPCNT__)
+#if defined(__AVX512VBMI2__) && defined(__AVX512VBMI__) && defined(__AVX512VL__)
#undef SIMD_SSE
#define SIMD_AVX
#endif
-// MSVC supports compiling SSSE3 code regardless of compile options; we use a cpuid-based scalar fallback
+// MSVC supports compiling SSSE3+POPCNT code regardless of compile options; we use a cpuid-based scalar fallback
#if !defined(SIMD_SSE) && !defined(SIMD_AVX) && defined(_MSC_VER) && !defined(__clang__) && (defined(_M_IX86) || (defined(_M_X64) && !defined(_M_ARM64EC)))
#define SIMD_SSE
#define SIMD_FALLBACK
@@ -28,7 +28,7 @@
#if !defined(SIMD_SSE) && !defined(SIMD_AVX) && ((defined(__clang__) && __clang_major__ * 100 + __clang_minor__ >= 308) || (defined(__GNUC__) && __GNUC__ * 100 + __GNUC_MINOR__ >= 409)) && (defined(__i386__) || defined(__x86_64__))
#define SIMD_SSE
#define SIMD_FALLBACK
-#define SIMD_TARGET __attribute__((target("ssse3")))
+#define SIMD_TARGET __attribute__((target("ssse3,popcnt")))
#endif
// GCC/clang define these when NEON support is available
@@ -72,7 +72,7 @@
#endif // !MESHOPTIMIZER_NO_SIMD
#ifdef SIMD_SSE
-#include <tmmintrin.h>
+#include <nmmintrin.h>
#endif
#if defined(SIMD_SSE) && defined(SIMD_FALLBACK)
@@ -708,6 +708,14 @@ static const unsigned char* decodeVertexBlock(const unsigned char* data, const u
size_t vertex_count_aligned = (vertex_count + kByteGroupSize - 1) & ~(kByteGroupSize - 1);
assert(vertex_count <= vertex_count_aligned);
+ // we can decode directly into the output buffer
+ // this uses strided writes and also reads the last vertex once, which is bad for performance for write-combined memory so we only enable this if configured
+#ifdef MESHOPTIMIZER_VERTEXCODEC_ZEROCOPY
+ unsigned char* target = vertex_data;
+#else
+ unsigned char* target = transposed;
+#endif
+
size_t control_size = version == 0 ? 0 : vertex_size / 4;
if (size_t(data_end - data) < control_size)
return NULL;
@@ -750,22 +758,23 @@ static const unsigned char* decodeVertexBlock(const unsigned char* data, const u
switch (channel & 3)
{
case 0:
- decodeDeltas1<unsigned char, false>(buffer, transposed + k, vertex_count, vertex_size, last_vertex + k, 0);
+ decodeDeltas1<unsigned char, false>(buffer, target + k, vertex_count, vertex_size, last_vertex + k, 0);
break;
case 1:
- decodeDeltas1<unsigned short, false>(buffer, transposed + k, vertex_count, vertex_size, last_vertex + k, 0);
+ decodeDeltas1<unsigned short, false>(buffer, target + k, vertex_count, vertex_size, last_vertex + k, 0);
break;
case 2:
- decodeDeltas1<unsigned int, true>(buffer, transposed + k, vertex_count, vertex_size, last_vertex + k, (32 - (channel >> 4)) & 31);
+ decodeDeltas1<unsigned int, true>(buffer, target + k, vertex_count, vertex_size, last_vertex + k, (32 - (channel >> 4)) & 31);
break;
default:
return NULL; // invalid channel type
}
}
- memcpy(vertex_data, transposed, vertex_count * vertex_size);
+ if (target == transposed)
+ memcpy(vertex_data, transposed, vertex_count * vertex_size);
- memcpy(last_vertex, &transposed[vertex_size * (vertex_count - 1)], vertex_size);
+ memcpy(last_vertex, &target[vertex_size * (vertex_count - 1)], vertex_size);
return data;
}
@@ -804,210 +813,145 @@ static bool gDecodeBytesGroupInitialized = decodeBytesGroupBuildTables();
#endif
#ifdef SIMD_SSE
-SIMD_TARGET
-inline __m128i decodeShuffleMask(unsigned char mask0, unsigned char mask1)
-{
- __m128i sm0 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&kDecodeBytesGroupShuffle[mask0]));
- __m128i sm1 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&kDecodeBytesGroupShuffle[mask1]));
- __m128i sm1off = _mm_set1_epi8(kDecodeBytesGroupCount[mask0]);
-
- __m128i sm1r = _mm_add_epi8(sm1, sm1off);
-
- return _mm_unpacklo_epi64(sm0, sm1r);
-}
-
-#ifdef __GNUC__
-typedef int __attribute__((aligned(1))) unaligned_int;
-#else
-typedef int unaligned_int;
-#endif
+// sent mask, replicating shuffle, and two multipliers (even/odd) for multishift emulation
+static const unsigned char kDecodeBytesGroupConfig[9][4][16] = {
+ {{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, {0}, {0}},
+ {{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}, {4, 0, 64, 0, 4, 0, 64, 0, 4, 0, 64, 0, 4, 0, 64, 0}, {16, 0, 0, 1, 16, 0, 0, 1, 16, 0, 0, 1, 16, 0, 0, 1}},
+ {{15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}, {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}, {16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0}, {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}},
+ {{0}, {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, {0}, {0}},
+ {{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, {0}, {0}},
+ {{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 64, 0, 16, 0, 4, 0, 0, 1, 64, 0, 16, 0, 4, 0}, {128, 0, 32, 0, 8, 0, 2, 0, 128, 0, 32, 0, 8, 0, 2, 0}},
+ {{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}, {4, 0, 64, 0, 4, 0, 64, 0, 4, 0, 64, 0, 4, 0, 64, 0}, {16, 0, 0, 1, 16, 0, 0, 1, 16, 0, 0, 1, 16, 0, 0, 1}},
+ {{15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}, {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}, {16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0}, {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}},
+ {{0}, {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, {0}, {0}},
+};
SIMD_TARGET
-inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
+static inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
{
- switch (hbits)
- {
- case 0:
- case 4:
- {
- __m128i result = _mm_setzero_si128();
-
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
+ // 0 for 1-bit, 1 for 2-bit, 2 for 4-bit, 3 for 8-bit, and 4 for 0-bit as it makes some of the uses easier
+ static const int hbtn[9] = {4, 1, 2, 3, 4, 0, 1, 2, 3};
- return data;
- }
+ int n = hbtn[hbits];
- case 1:
- case 6:
- {
#ifdef SIMD_LATENCYOPT
- unsigned int data32;
- memcpy(&data32, data, 4);
- data32 &= data32 >> 1;
-
- // arrange bits such that low bits of nibbles of data64 contain all 2-bit elements of data32
- unsigned 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
- int datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60);
+ unsigned long long data64;
+ memcpy(&data64, data, 8);
+ data64 &= data64 >> n;
+ data64 &= data64 >> (n >> 1);
+
+ // mask out one bit per group that is set if all group bits were 1
+ static const unsigned long long lanes[9] = {0, 0x55555555, 0x1111111111111111ull, 0, 0, 0xffff, 0x55555555, 0x1111111111111111ull, 0};
+ int datacnt = int(_mm_popcnt_u64(data64 & lanes[hbits]));
#endif
- __m128i sel2 = _mm_cvtsi32_si128(*reinterpret_cast<const unaligned_int*>(data));
- __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + 4));
-
- __m128i sel22 = _mm_unpacklo_epi8(_mm_srli_epi16(sel2, 4), sel2);
- __m128i sel2222 = _mm_unpacklo_epi8(_mm_srli_epi16(sel22, 2), sel22);
- __m128i sel = _mm_and_si128(sel2222, _mm_set1_epi8(3));
+ // for 8-bit groups, instead of loading the bytes through 'data', we load them through 'skip' as they are easier to preserve
+ // for 0-bit groups, the load results get discarded because mask is always 0; in both cases the shift wraps to zero
+ const unsigned char* skip = data + ((2 << n) & 15);
- __m128i mask = _mm_cmpeq_epi8(sel, _mm_set1_epi8(3));
- int mask16 = _mm_movemask_epi8(mask);
- unsigned char mask0 = (unsigned char)(mask16 & 255);
- unsigned char mask1 = (unsigned char)(mask16 >> 8);
+ __m128i selb = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(data));
+ __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(skip));
- __m128i shuf = decodeShuffleMask(mask0, mask1);
- __m128i result = _mm_or_si128(_mm_shuffle_epi8(rest, shuf), _mm_andnot_si128(mask, sel));
-
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
-
-#ifdef SIMD_LATENCYOPT
- return data + 4 + datacnt;
-#else
- return data + 4 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1];
-#endif
- }
-
- case 2:
- case 7:
- {
-#ifdef SIMD_LATENCYOPT
- unsigned long long data64;
- memcpy(&data64, data, 8);
- data64 &= data64 >> 1;
- data64 &= data64 >> 2;
+ // unpack 1, 2 or 4-bit values: shuffle replicates each source byte into both halves of a 16-bit lane
+ // mulhi extracts even and odd fields into the low byte; the results are interleaved back with shift/or
+ __m128i selw = _mm_shuffle_epi8(selb, _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeBytesGroupConfig[hbits][1])));
+ __m128i sel0 = _mm_mulhi_epu16(selw, _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeBytesGroupConfig[hbits][2])));
+ __m128i sel1 = _mm_mulhi_epu16(selw, _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeBytesGroupConfig[hbits][3])));
+ __m128i seli = _mm_or_si128(sel0, _mm_slli_epi16(sel1, 8));
- // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used mode 3
- int datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60);
-#endif
+ // the interleaved fields are masked by the bit count (special handling: for 0/8-bit values, mul produces 0)
+ __m128i sent = _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeBytesGroupConfig[hbits][0]));
+ __m128i sel = _mm_and_si128(seli, sent);
- __m128i sel4 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(data));
- __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + 8));
+ // compare sel to sentinel; returns 0 for 0-bit (mul produces 0, sent is 1), 1 for 8-bit (mul produces 0, sent is 0)
+ __m128i mask = _mm_cmpeq_epi8(sel, sent);
+ int mask16 = _mm_movemask_epi8(mask);
+ unsigned char mask0 = (unsigned char)(mask16 & 255);
+ unsigned char mask1 = (unsigned char)(mask16 >> 8);
- __m128i sel44 = _mm_unpacklo_epi8(_mm_srli_epi16(sel4, 4), sel4);
- __m128i sel = _mm_and_si128(sel44, _mm_set1_epi8(15));
+ // decode shuffle mask from two halves; second half needs to be shifted by popcount(mask0)
+ __m128i sm0 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&kDecodeBytesGroupShuffle[mask0]));
+ __m128i sm1 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&kDecodeBytesGroupShuffle[mask1]));
- __m128i mask = _mm_cmpeq_epi8(sel, _mm_set1_epi8(15));
- int mask16 = _mm_movemask_epi8(mask);
- unsigned char mask0 = (unsigned char)(mask16 & 255);
- unsigned char mask1 = (unsigned char)(mask16 >> 8);
+ // each lane of mask is 0x00 or 0xff; sad yields 255*popcount(mask0) in low word => low byte is -popcount(mask0)
+ __m128i npops = _mm_sad_epu8(mask, _mm_setzero_si128());
+ __m128i sm1r = _mm_sub_epi8(sm1, _mm_shuffle_epi8(npops, _mm_setzero_si128()));
+ __m128i shuf = _mm_unpacklo_epi64(sm0, sm1r);
- __m128i shuf = decodeShuffleMask(mask0, mask1);
- __m128i result = _mm_or_si128(_mm_shuffle_epi8(rest, shuf), _mm_andnot_si128(mask, sel));
+ // expand rest via shuffle mask and combine with sel; shuffle mask zeroes out bytes that are replaced by sel
+ __m128i result = _mm_or_si128(_mm_shuffle_epi8(rest, shuf), _mm_andnot_si128(mask, sel));
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
#ifdef SIMD_LATENCYOPT
- return data + 8 + datacnt;
+ // datacnt is 0 for 8-bit groups so we can't use skip to advance; 0-bit groups wrap the shift to zero
+ return data + ((2 << n) & 31) + datacnt;
#else
- return data + 8 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1];
+ return skip + _mm_popcnt_u32(mask16);
#endif
- }
-
- case 3:
- case 8:
- {
- __m128i result = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data));
-
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
-
- return data + 16;
- }
-
- case 5:
- {
- __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + 2));
-
- unsigned char mask0 = data[0];
- unsigned char mask1 = data[1];
-
- __m128i shuf = decodeShuffleMask(mask0, mask1);
- __m128i result = _mm_shuffle_epi8(rest, shuf);
-
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
-
- return data + 2 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1];
- }
-
- default:
- SIMD_UNREACHABLE(); // unreachable
- }
}
#endif
#ifdef SIMD_AVX
-static const __m128i kDecodeBytesGroupConfig[8][2] = {
- {_mm_setzero_si128(), _mm_setzero_si128()},
- {_mm_set1_epi8(3), _mm_setr_epi8(6, 4, 2, 0, 14, 12, 10, 8, 22, 20, 18, 16, 30, 28, 26, 24)},
- {_mm_set1_epi8(15), _mm_setr_epi8(4, 0, 12, 8, 20, 16, 28, 24, 36, 32, 44, 40, 52, 48, 60, 56)},
- {_mm_setzero_si128(), _mm_setzero_si128()},
- {_mm_setzero_si128(), _mm_setzero_si128()},
- {_mm_set1_epi8(1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)},
- {_mm_set1_epi8(3), _mm_setr_epi8(6, 4, 2, 0, 14, 12, 10, 8, 22, 20, 18, 16, 30, 28, 26, 24)},
- {_mm_set1_epi8(15), _mm_setr_epi8(4, 0, 12, 8, 20, 16, 28, 24, 36, 32, 44, 40, 52, 48, 60, 56)},
+// sent mask, multishift control
+static const unsigned char kDecodeBytesGroupConfig[9][2][16] = {
+ {{0}, {0}},
+ {{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {6, 4, 2, 0, 14, 12, 10, 8, 22, 20, 18, 16, 30, 28, 26, 24}},
+ {{15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}, {4, 0, 12, 8, 20, 16, 28, 24, 36, 32, 44, 40, 52, 48, 60, 56}},
+ {{0}, {0}},
+ {{0}, {0}},
+ {{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
+ {{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {6, 4, 2, 0, 14, 12, 10, 8, 22, 20, 18, 16, 30, 28, 26, 24}},
+ {{15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}, {4, 0, 12, 8, 20, 16, 28, 24, 36, 32, 44, 40, 52, 48, 60, 56}},
+ {{0}, {0}},
};
SIMD_TARGET
-inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
+static inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
{
- switch (hbits)
- {
- case 0:
- case 4:
- {
- __m128i result = _mm_setzero_si128();
-
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
-
- return data;
- }
+ // 0 for 1-bit, 1 for 2-bit, 2 for 4-bit, 3 for 8-bit, and 4 for 0-bit as it makes some of the uses easier
+ static const int hbtn[9] = {4, 1, 2, 3, 4, 0, 1, 2, 3};
- case 5: // 1-bit
- case 1: // 2-bit
- case 6:
- case 2: // 4-bit
- case 7:
- {
- const unsigned char* skip = data + (2 << (hbits < 3 ? hbits : hbits - 5));
+ int n = hbtn[hbits];
- __m128i selb = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(data));
- __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(skip));
+#ifdef SIMD_LATENCYOPT
+ unsigned long long data64;
+ memcpy(&data64, data, 8);
+ data64 &= data64 >> n;
+ data64 &= data64 >> (n >> 1);
+
+ // mask out one bit per group that is set if all group bits were 1
+ static const unsigned long long lanes[9] = {0, 0x55555555, 0x1111111111111111ull, 0, 0, 0xffff, 0x55555555, 0x1111111111111111ull, 0};
+ int datacnt = int(_mm_popcnt_u64(data64 & lanes[hbits]));
+#endif
- __m128i sent = kDecodeBytesGroupConfig[hbits][0];
- __m128i ctrl = kDecodeBytesGroupConfig[hbits][1];
+ // for 8-bit groups, instead of loading the bytes through 'data', we load them through 'skip' as they are easier to preserve
+ // for 0-bit groups, we use a masked load so that we load zero bytes; in both cases the shift wraps to zero
+ const unsigned char* skip = data + ((2 << n) & 15);
- __m128i selw = _mm_shuffle_epi32(selb, 0x44);
- __m128i sel = _mm_and_si128(sent, _mm_multishift_epi64_epi8(ctrl, selw));
- __mmask16 mask16 = _mm_cmp_epi8_mask(sel, sent, _MM_CMPINT_EQ);
+ __m128i selb = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(data));
+ __m128i rest = _mm_maskz_loadu_epi8(__mmask16((n >> 2) - 1), skip);
- __m128i result = _mm_mask_expand_epi8(sel, mask16, rest);
+ __m128i sent = _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeBytesGroupConfig[hbits][0]));
+ __m128i ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeBytesGroupConfig[hbits][1]));
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
+ // unpack 1, 2 or 4-bit values using multishift and mask the result; for 0/8-bit values, sel is always 0
+ __m128i selw = _mm_shuffle_epi32(selb, 0x44);
+ __m128i sel = _mm_and_si128(sent, _mm_multishift_epi64_epi8(ctrl, selw));
- return skip + _mm_popcnt_u32(mask16);
- }
+ // compare sel to sentinel and combine; mask is 0 for 0/8-bit as sent is 0
+ __mmask16 mask16 = _mm_cmp_epi8_mask(sel, sent, _MM_CMPINT_EQ);
+ __m128i result = _mm_mask_expand_epi8(sel, mask16, rest);
- case 3:
- case 8:
- {
- __m128i result = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data));
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
- _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
-
- return data + 16;
- }
-
- default:
- SIMD_UNREACHABLE(); // unreachable
- }
+#ifdef SIMD_LATENCYOPT
+ // datacnt is 0 for 8-bit groups so we can't use skip to advance; 0-bit groups wrap the shift to zero
+ return data + ((2 << n) & 31) + datacnt;
+#else
+ // mask16 is all 1s for 0-bit groups and we need to use zero instead
+ return skip + _mm_popcnt_u32(n == 4 ? 0 : mask16);
+#endif
}
#endif
@@ -1037,7 +981,7 @@ inline void neonMoveMask(uint8x16_t mask, unsigned char& mask0, unsigned char& m
}
SIMD_TARGET
-inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
+static inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
{
switch (hbits)
{
@@ -1179,7 +1123,7 @@ inline void wasmMoveMask(v128_t mask, unsigned char& mask0, unsigned char& mask1
}
SIMD_TARGET
-inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
+static inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits)
{
switch (hbits)
{
@@ -1443,6 +1387,22 @@ static const unsigned char* decodeBytesSimd(const unsigned char* data, const uns
size_t header_offset = i / kByteGroupSize;
unsigned char header_byte = header[header_offset / 4];
+#if defined(SIMD_SSE) || defined(SIMD_AVX)
+ // very-fast-path: for consecutive 4 groups that are all 0-bit (v0/0, v1/0/0000) or 8-bit (v0/3333, v1/1/3333),
+ // the branchless decoders are slower than branching over the decoding of 4 groups and issuing a few load/store ops
+ if (hshift != 5 && header_byte == 0)
+ {
+ memset(buffer + i, 0, kByteGroupSize * 4);
+ continue;
+ }
+ else if (hshift != 4 && header_byte == 255)
+ {
+ memcpy(buffer + i, data, kByteGroupSize * 4);
+ data += kByteGroupSize * 4;
+ continue;
+ }
+#endif
+
data = decodeBytesGroupSimd(data, buffer + i + kByteGroupSize * 0, hshift + ((header_byte >> 0) & 3));
data = decodeBytesGroupSimd(data, buffer + i + kByteGroupSize * 1, hshift + ((header_byte >> 2) & 3));
data = decodeBytesGroupSimd(data, buffer + i + kByteGroupSize * 2, hshift + ((header_byte >> 4) & 3));
@@ -1560,6 +1520,14 @@ static const unsigned char* decodeVertexBlockSimd(const unsigned char* data, con
size_t vertex_count_aligned = (vertex_count + kByteGroupSize - 1) & ~(kByteGroupSize - 1);
+ // we can decode directly into the output buffer if vertex count is aligned to 16 (delta decode works 16 vertices at a time)
+ // this uses strided writes and also reads the last vertex once, which is bad for performance for write-combined memory so we only enable this if configured
+#ifdef MESHOPTIMIZER_VERTEXCODEC_ZEROCOPY
+ unsigned char* target = vertex_count == vertex_count_aligned ? vertex_data : transposed;
+#else
+ unsigned char* target = transposed;
+#endif
+
size_t control_size = version == 0 ? 0 : vertex_size / 4;
if (size_t(data_end - data) < control_size)
return NULL;
@@ -1605,22 +1573,23 @@ static const unsigned char* decodeVertexBlockSimd(const unsigned char* data, con
switch (channel & 3)
{
case 0:
- decodeDeltas4Simd<0>(buffer, transposed + k, vertex_count_aligned, vertex_size, last_vertex + k, 0);
+ decodeDeltas4Simd<0>(buffer, target + k, vertex_count_aligned, vertex_size, last_vertex + k, 0);
break;
case 1:
- decodeDeltas4Simd<1>(buffer, transposed + k, vertex_count_aligned, vertex_size, last_vertex + k, 0);
+ decodeDeltas4Simd<1>(buffer, target + k, vertex_count_aligned, vertex_size, last_vertex + k, 0);
break;
case 2:
- decodeDeltas4Simd<2>(buffer, transposed + k, vertex_count_aligned, vertex_size, last_vertex + k, (32 - (channel >> 4)) & 31);
+ decodeDeltas4Simd<2>(buffer, target + k, vertex_count_aligned, vertex_size, last_vertex + k, (32 - (channel >> 4)) & 31);
break;
default:
return NULL; // invalid channel type
}
}
- memcpy(vertex_data, transposed, vertex_count * vertex_size);
+ if (target == transposed)
+ memcpy(vertex_data, transposed, vertex_count * vertex_size);
- memcpy(last_vertex, &transposed[vertex_size * (vertex_count - 1)], vertex_size);
+ memcpy(last_vertex, &target[vertex_size * (vertex_count - 1)], vertex_size);
return data;
}
@@ -1837,7 +1806,8 @@ int meshopt_decodeVertexBuffer(void* destination, size_t vertex_count, size_t ve
const unsigned char* (*decode)(const unsigned char*, const unsigned char*, unsigned char*, size_t, size_t, unsigned char[256], const unsigned char*, int) = NULL;
#if defined(SIMD_SSE) && defined(SIMD_FALLBACK)
- decode = (cpuid & (1 << 9)) ? decodeVertexBlockSimd : decodeVertexBlock;
+ const unsigned int cpumask = (1 << 9) | (1 << 23); // SSSE3+POPCNT
+ decode = (cpuid & cpumask) == cpumask ? decodeVertexBlockSimd : decodeVertexBlock;
#elif defined(SIMD_SSE) || defined(SIMD_AVX) || defined(SIMD_NEON) || defined(SIMD_WASM)
decode = decodeVertexBlockSimd;
#else
diff --git a/thirdparty/meshoptimizer/vertexfilter.cpp b/thirdparty/meshoptimizer/vertexfilter.cpp
index 57eecb80c74..de830f1ae0b 100644
--- a/thirdparty/meshoptimizer/vertexfilter.cpp
+++ b/thirdparty/meshoptimizer/vertexfilter.cpp
@@ -894,7 +894,7 @@ static void decodeFilterOctSimd8(signed char* data, size_t count)
v128_t z = wasm_f32x4_sub(wasm_f32x4_convert_i32x4(zf), wasm_f32x4_add(wasm_f32x4_abs(x), wasm_f32x4_abs(y)));
// fixup octahedral coordinates for z<0
- // note: i32x4_min with 0 is equvalent to f32x4_min
+ // note: i32x4_min with 0 is equivalent to f32x4_min
v128_t t = wasm_i32x4_min(z, wasm_i32x4_splat(0));
x = wasm_f32x4_add(x, wasm_v128_xor(t, wasm_v128_and(x, sign)));
@@ -949,7 +949,7 @@ static void decodeFilterOctSimd16(short* data, size_t count)
v128_t z = wasm_f32x4_sub(wasm_f32x4_convert_i32x4(zf), wasm_f32x4_add(wasm_f32x4_abs(x), wasm_f32x4_abs(y)));
// fixup octahedral coordinates for z<0
- // note: i32x4_min with 0 is equvalent to f32x4_min
+ // note: i32x4_min with 0 is equivalent to f32x4_min
v128_t t = wasm_i32x4_min(z, wasm_i32x4_splat(0));
x = wasm_f32x4_add(x, wasm_v128_xor(t, wasm_v128_and(x, sign)));
@@ -1188,8 +1188,9 @@ inline int optlog2(float v)
} u;
u.f = v;
- // +1 accounts for implicit 1. in mantissa; denormalized numbers will end up clamped to min_exp by calling code
- return v == 0 ? 0 : int((u.ui >> 23) & 0xff) - 127 + 1;
+ // +1 accounts for implicit 1. in mantissa; zero and denormalized numbers will end up clamped to min_exp by calling code
+ // this is important for shared exponent modes, as a zero component should not inflate the shared exponent
+ return int((u.ui >> 23) & 0xff) - 127 + 1;
}
// optimized variant of ldexp
@@ -1276,6 +1277,7 @@ void meshopt_encodeFilterOct(void* destination, size_t count, size_t stride, int
{
assert(stride == 4 || stride == 8);
assert(bits >= 2 && bits <= 16);
+ assert(stride == 8 || bits <= 8);
signed char* d8 = static_cast<signed char*>(destination);
short* d16 = static_cast<short*>(destination);
@@ -1366,11 +1368,12 @@ void meshopt_encodeFilterExp(void* destination_, size_t count, size_t stride, in
const int min_exp = -100;
+ // used to track maximum exponent for EncodeExpSharedComponent and zero exponent reuse for EncodeExpSeparate
+ for (size_t j = 0; j < stride_float; ++j)
+ component_exp[j] = (mode == meshopt_EncodeExpSeparate) ? 0 : min_exp;
+
if (mode == meshopt_EncodeExpSharedComponent)
{
- for (size_t j = 0; j < stride_float; ++j)
- component_exp[j] = min_exp;
-
for (size_t i = 0; i < count; ++i)
{
const float* v = &data[i * stride_float];
@@ -1408,7 +1411,9 @@ void meshopt_encodeFilterExp(void* destination_, size_t count, size_t stride, in
{
int e = optlog2(v[j]);
- component_exp[j] = (min_exp < e) ? e : min_exp;
+ // zero values inherit the last encoded exponent to keep the encoded data more compressible
+ if (v[j] != 0)
+ component_exp[j] = (min_exp < e) ? e : min_exp;
}
}
else if (mode == meshopt_EncodeExpClamped)
@@ -1446,6 +1451,7 @@ void meshopt_encodeFilterColor(void* destination, size_t count, size_t stride, i
{
assert(stride == 4 || stride == 8);
assert(bits >= 2 && bits <= 16);
+ assert(stride == 8 || bits <= 8);
unsigned char* d8 = static_cast<unsigned char*>(destination);
unsigned short* d16 = static_cast<unsigned short*>(destination);