Coverage Report

Created: 2025-02-10 06:19

/src/meshoptimizer/src/meshoptimizer.h
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * meshoptimizer - version 0.22
3
 *
4
 * Copyright (C) 2016-2025, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
5
 * Report bugs and download new versions at https://github.com/zeux/meshoptimizer
6
 *
7
 * This library is distributed under the MIT License. See notice at the end of this file.
8
 */
9
#pragma once
10
11
#include <assert.h>
12
#include <stddef.h>
13
14
/* Version macro; major * 1000 + minor * 10 + patch */
15
#define MESHOPTIMIZER_VERSION 220 /* 0.22 */
16
17
/* If no API is defined, assume default */
18
#ifndef MESHOPTIMIZER_API
19
#define MESHOPTIMIZER_API
20
#endif
21
22
/* Set the calling-convention for alloc/dealloc function pointers */
23
#ifndef MESHOPTIMIZER_ALLOC_CALLCONV
24
#ifdef _MSC_VER
25
#define MESHOPTIMIZER_ALLOC_CALLCONV __cdecl
26
#else
27
#define MESHOPTIMIZER_ALLOC_CALLCONV
28
#endif
29
#endif
30
31
/* Experimental APIs have unstable interface and might have implementation that's not fully tested or optimized */
32
#ifndef MESHOPTIMIZER_EXPERIMENTAL
33
#define MESHOPTIMIZER_EXPERIMENTAL MESHOPTIMIZER_API
34
#endif
35
36
/* C interface */
37
#ifdef __cplusplus
38
extern "C"
39
{
40
#endif
41
42
/**
43
 * Vertex attribute stream
44
 * Each element takes size bytes, beginning at data, with stride controlling the spacing between successive elements (stride >= size).
45
 */
46
struct meshopt_Stream
47
{
48
  const void* data;
49
  size_t size;
50
  size_t stride;
51
};
52
53
/**
54
 * Generates a vertex remap table from the vertex buffer and an optional index buffer and returns number of unique vertices
55
 * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence.
56
 * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer.
57
 * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized.
58
 *
59
 * destination must contain enough space for the resulting remap table (vertex_count elements)
60
 * indices can be NULL if the input is unindexed
61
 */
62
MESHOPTIMIZER_API 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);
63
64
/**
65
 * Generates a vertex remap table from multiple vertex streams and an optional index buffer and returns number of unique vertices
66
 * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence.
67
 * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer.
68
 * To remap vertex buffers, you will need to call meshopt_remapVertexBuffer for each vertex stream.
69
 * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized.
70
 *
71
 * destination must contain enough space for the resulting remap table (vertex_count elements)
72
 * indices can be NULL if the input is unindexed
73
 * stream_count must be <= 16
74
 */
75
MESHOPTIMIZER_API size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count);
76
77
/**
78
 * Generates vertex buffer from the source vertex buffer and remap table generated by meshopt_generateVertexRemap
79
 *
80
 * destination must contain enough space for the resulting vertex buffer (unique_vertex_count elements, returned by meshopt_generateVertexRemap)
81
 * vertex_count should be the initial vertex count and not the value returned by meshopt_generateVertexRemap
82
 */
83
MESHOPTIMIZER_API void meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap);
84
85
/**
86
 * Generate index buffer from the source index buffer and remap table generated by meshopt_generateVertexRemap
87
 *
88
 * destination must contain enough space for the resulting index buffer (index_count elements)
89
 * indices can be NULL if the input is unindexed
90
 */
91
MESHOPTIMIZER_API void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap);
92
93
/**
94
 * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary
95
 * All vertices that are binary equivalent (wrt first vertex_size bytes) map to the first vertex in the original vertex buffer.
96
 * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering.
97
 * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized.
98
 *
99
 * destination must contain enough space for the resulting index buffer (index_count elements)
100
 */
101
MESHOPTIMIZER_API 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);
102
103
/**
104
 * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary
105
 * All vertices that are binary equivalent (wrt specified streams) map to the first vertex in the original vertex buffer.
106
 * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering.
107
 * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized.
108
 *
109
 * destination must contain enough space for the resulting index buffer (index_count elements)
110
 * stream_count must be <= 16
111
 */
112
MESHOPTIMIZER_API void meshopt_generateShadowIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count);
113
114
/**
115
 * Generate index buffer that can be used as a geometry shader input with triangle adjacency topology
116
 * Each triangle is converted into a 6-vertex patch with the following layout:
117
 * - 0, 2, 4: original triangle vertices
118
 * - 1, 3, 5: vertices adjacent to edges 02, 24 and 40
119
 * The resulting patch can be rendered with geometry shaders using e.g. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY.
120
 * This can be used to implement algorithms like silhouette detection/expansion and other forms of GS-driven rendering.
121
 *
122
 * destination must contain enough space for the resulting index buffer (index_count*2 elements)
123
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
124
 */
125
MESHOPTIMIZER_API void meshopt_generateAdjacencyIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
126
127
/**
128
 * Generate index buffer that can be used for PN-AEN tessellation with crack-free displacement
129
 * Each triangle is converted into a 12-vertex patch with the following layout:
130
 * - 0, 1, 2: original triangle vertices
131
 * - 3, 4: opposing edge for edge 0, 1
132
 * - 5, 6: opposing edge for edge 1, 2
133
 * - 7, 8: opposing edge for edge 2, 0
134
 * - 9, 10, 11: dominant vertices for corners 0, 1, 2
135
 * The resulting patch can be rendered with hardware tessellation using PN-AEN and displacement mapping.
136
 * See "Tessellation on Any Budget" (John McDonald, GDC 2011) for implementation details.
137
 *
138
 * destination must contain enough space for the resulting index buffer (index_count*4 elements)
139
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
140
 */
141
MESHOPTIMIZER_API void meshopt_generateTessellationIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
142
143
/**
144
 * Experimental: Generate index buffer that can be used for visibility buffer rendering and returns the size of the reorder table
145
 * Each triangle's provoking vertex index is equal to primitive id; this allows passing it to the fragment shader using nointerpolate attribute.
146
 * This is important for performance on hardware where primitive id can't be accessed efficiently in fragment shader.
147
 * The reorder table stores the original vertex id for each vertex in the new index buffer, and should be used in the vertex shader to load vertex data.
148
 * The provoking vertex is assumed to be the first vertex in the triangle; if this is not the case (OpenGL), rotate each triangle (abc -> bca) before rendering.
149
 * For maximum efficiency the input index buffer should be optimized for vertex cache first.
150
 *
151
 * destination must contain enough space for the resulting index buffer (index_count elements)
152
 * reorder must contain enough space for the worst case reorder table (vertex_count + index_count/3 elements)
153
 */
154
MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_generateProvokingIndexBuffer(unsigned int* destination, unsigned int* reorder, const unsigned int* indices, size_t index_count, size_t vertex_count);
155
156
/**
157
 * Vertex transform cache optimizer
158
 * Reorders indices to reduce the number of GPU vertex shader invocations
159
 * If index buffer contains multiple ranges for multiple draw calls, this functions needs to be called on each range individually.
160
 *
161
 * destination must contain enough space for the resulting index buffer (index_count elements)
162
 */
163
MESHOPTIMIZER_API void meshopt_optimizeVertexCache(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count);
164
165
/**
166
 * Vertex transform cache optimizer for strip-like caches
167
 * Produces inferior results to meshopt_optimizeVertexCache from the GPU vertex cache perspective
168
 * However, the resulting index order is more optimal if the goal is to reduce the triangle strip length or improve compression efficiency
169
 *
170
 * destination must contain enough space for the resulting index buffer (index_count elements)
171
 */
172
MESHOPTIMIZER_API void meshopt_optimizeVertexCacheStrip(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count);
173
174
/**
175
 * Vertex transform cache optimizer for FIFO caches
176
 * Reorders indices to reduce the number of GPU vertex shader invocations
177
 * Generally takes ~3x less time to optimize meshes but produces inferior results compared to meshopt_optimizeVertexCache
178
 * If index buffer contains multiple ranges for multiple draw calls, this functions needs to be called on each range individually.
179
 *
180
 * destination must contain enough space for the resulting index buffer (index_count elements)
181
 * cache_size should be less than the actual GPU cache size to avoid cache thrashing
182
 */
183
MESHOPTIMIZER_API void meshopt_optimizeVertexCacheFifo(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size);
184
185
/**
186
 * Overdraw optimizer
187
 * Reorders indices to reduce the number of GPU vertex shader invocations and the pixel overdraw
188
 * If index buffer contains multiple ranges for multiple draw calls, this functions needs to be called on each range individually.
189
 *
190
 * destination must contain enough space for the resulting index buffer (index_count elements)
191
 * indices must contain index data that is the result of meshopt_optimizeVertexCache (*not* the original mesh indices!)
192
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
193
 * threshold indicates how much the overdraw optimizer can degrade vertex cache efficiency (1.05 = up to 5%) to reduce overdraw more efficiently
194
 */
195
MESHOPTIMIZER_API void meshopt_optimizeOverdraw(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold);
196
197
/**
198
 * Vertex fetch cache optimizer
199
 * Reorders vertices and changes indices to reduce the amount of GPU memory fetches during vertex processing
200
 * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused
201
 * This functions works for a single vertex stream; for multiple vertex streams, use meshopt_optimizeVertexFetchRemap + meshopt_remapVertexBuffer for each stream.
202
 *
203
 * destination must contain enough space for the resulting vertex buffer (vertex_count elements)
204
 * indices is used both as an input and as an output index buffer
205
 */
206
MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetch(void* destination, unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
207
208
/**
209
 * Vertex fetch cache optimizer
210
 * Generates vertex remap to reduce the amount of GPU memory fetches during vertex processing
211
 * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused
212
 * The resulting remap table should be used to reorder vertex/index buffers using meshopt_remapVertexBuffer/meshopt_remapIndexBuffer
213
 *
214
 * destination must contain enough space for the resulting remap table (vertex_count elements)
215
 */
216
MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count);
217
218
/**
219
 * Index buffer encoder
220
 * Encodes index data into an array of bytes that is generally much smaller (<1.5 bytes/triangle) and compresses better (<1 bytes/triangle) compared to original.
221
 * Input index buffer must represent a triangle list.
222
 * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space
223
 * For maximum efficiency the index buffer being encoded has to be optimized for vertex cache and vertex fetch first.
224
 *
225
 * buffer must contain enough space for the encoded index buffer (use meshopt_encodeIndexBufferBound to compute worst case size)
226
 */
227
MESHOPTIMIZER_API size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count);
228
MESHOPTIMIZER_API size_t meshopt_encodeIndexBufferBound(size_t index_count, size_t vertex_count);
229
230
/**
231
 * Set index encoder format version
232
 * version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.14+)
233
 */
234
MESHOPTIMIZER_API void meshopt_encodeIndexVersion(int version);
235
236
/**
237
 * Index buffer decoder
238
 * Decodes index data from an array of bytes generated by meshopt_encodeIndexBuffer
239
 * Returns 0 if decoding was successful, and an error code otherwise
240
 * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices).
241
 *
242
 * destination must contain enough space for the resulting index buffer (index_count elements)
243
 */
244
MESHOPTIMIZER_API int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size);
245
246
/**
247
 * Index sequence encoder
248
 * Encodes index sequence into an array of bytes that is generally smaller and compresses better compared to original.
249
 * Input index sequence can represent arbitrary topology; for triangle lists meshopt_encodeIndexBuffer is likely to be better.
250
 * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space
251
 *
252
 * buffer must contain enough space for the encoded index sequence (use meshopt_encodeIndexSequenceBound to compute worst case size)
253
 */
254
MESHOPTIMIZER_API size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count);
255
MESHOPTIMIZER_API size_t meshopt_encodeIndexSequenceBound(size_t index_count, size_t vertex_count);
256
257
/**
258
 * Index sequence decoder
259
 * Decodes index data from an array of bytes generated by meshopt_encodeIndexSequence
260
 * Returns 0 if decoding was successful, and an error code otherwise
261
 * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices).
262
 *
263
 * destination must contain enough space for the resulting index sequence (index_count elements)
264
 */
265
MESHOPTIMIZER_API int meshopt_decodeIndexSequence(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size);
266
267
/**
268
 * Vertex buffer encoder
269
 * Encodes vertex data into an array of bytes that is generally smaller and compresses better compared to original.
270
 * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space
271
 * This function works for a single vertex stream; for multiple vertex streams, call meshopt_encodeVertexBuffer for each stream.
272
 * Note that all vertex_size bytes of each vertex are encoded verbatim, including padding which should be zero-initialized.
273
 * For maximum efficiency the vertex buffer being encoded has to be quantized and optimized for locality of reference (cache/fetch) first.
274
 *
275
 * buffer must contain enough space for the encoded vertex buffer (use meshopt_encodeVertexBufferBound to compute worst case size)
276
 */
277
MESHOPTIMIZER_API size_t meshopt_encodeVertexBuffer(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size);
278
MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size);
279
280
/**
281
 * Experimental: Vertex buffer encoder
282
 * Encodes vertex data just like meshopt_encodeVertexBuffer, but allows to override compression level.
283
 * For compression level to take effect, the vertex encoding version must be set to 1 via meshopt_encodeVertexVersion.
284
 * The default compression level implied by meshopt_encodeVertexBuffer is 2.
285
 *
286
 * level should be in the range [0, 3] with 0 being the fastest and 3 being the slowest and producing the best compression ratio.
287
 */
288
MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level);
289
290
/**
291
 * Set vertex encoder format version
292
 * version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.23+)
293
 */
294
MESHOPTIMIZER_API void meshopt_encodeVertexVersion(int version);
295
296
/**
297
 * Vertex buffer decoder
298
 * Decodes vertex data from an array of bytes generated by meshopt_encodeVertexBuffer
299
 * Returns 0 if decoding was successful, and an error code otherwise
300
 * The decoder is safe to use for untrusted input, but it may produce garbage data.
301
 *
302
 * destination must contain enough space for the resulting vertex buffer (vertex_count * vertex_size bytes)
303
 */
304
MESHOPTIMIZER_API int meshopt_decodeVertexBuffer(void* destination, size_t vertex_count, size_t vertex_size, const unsigned char* buffer, size_t buffer_size);
305
306
/**
307
 * Vertex buffer filters
308
 * These functions can be used to filter output of meshopt_decodeVertexBuffer in-place.
309
 *
310
 * meshopt_decodeFilterOct decodes octahedral encoding of a unit vector with K-bit (K <= 16) signed X/Y as an input; Z must store 1.0f.
311
 * 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.
312
 *
313
 * meshopt_decodeFilterQuat decodes 3-component quaternion encoding with K-bit (4 <= K <= 16) component encoding and a 2-bit component index indicating which component to reconstruct.
314
 * Each component is stored as an 16-bit integer; stride must be equal to 8.
315
 *
316
 * meshopt_decodeFilterExp decodes exponential encoding of floating-point data with 8-bit exponent and 24-bit integer mantissa as 2^E*M.
317
 * Each 32-bit component is decoded in isolation; stride must be divisible by 4.
318
 */
319
MESHOPTIMIZER_API void meshopt_decodeFilterOct(void* buffer, size_t count, size_t stride);
320
MESHOPTIMIZER_API void meshopt_decodeFilterQuat(void* buffer, size_t count, size_t stride);
321
MESHOPTIMIZER_API void meshopt_decodeFilterExp(void* buffer, size_t count, size_t stride);
322
323
/**
324
 * Vertex buffer filter encoders
325
 * These functions can be used to encode data in a format that meshopt_decodeFilter can decode
326
 *
327
 * meshopt_encodeFilterOct encodes unit vectors with K-bit (K <= 16) signed X/Y as an output.
328
 * 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.
329
 * Input data must contain 4 floats for every vector (count*4 total).
330
 *
331
 * meshopt_encodeFilterQuat encodes unit quaternions with K-bit (4 <= K <= 16) component encoding.
332
 * Each component is stored as an 16-bit integer; stride must be equal to 8.
333
 * Input data must contain 4 floats for every quaternion (count*4 total).
334
 *
335
 * meshopt_encodeFilterExp encodes arbitrary (finite) floating-point data with 8-bit exponent and K-bit integer mantissa (1 <= K <= 24).
336
 * 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.
337
 * Input data must contain stride/4 floats for every vector (count*stride/4 total).
338
 */
339
enum meshopt_EncodeExpMode
340
{
341
  /* When encoding exponents, use separate values for each component (maximum quality) */
342
  meshopt_EncodeExpSeparate,
343
  /* When encoding exponents, use shared value for all components of each vector (better compression) */
344
  meshopt_EncodeExpSharedVector,
345
  /* When encoding exponents, use shared value for each component of all vectors (best compression) */
346
  meshopt_EncodeExpSharedComponent,
347
  /* Experimental: When encoding exponents, use separate values for each component, but clamp to 0 (good quality if very small values are not important) */
348
  meshopt_EncodeExpClamped,
349
};
350
351
MESHOPTIMIZER_API void meshopt_encodeFilterOct(void* destination, size_t count, size_t stride, int bits, const float* data);
352
MESHOPTIMIZER_API void meshopt_encodeFilterQuat(void* destination, size_t count, size_t stride, int bits, const float* data);
353
MESHOPTIMIZER_API void meshopt_encodeFilterExp(void* destination, size_t count, size_t stride, int bits, const float* data, enum meshopt_EncodeExpMode mode);
354
355
/**
356
 * Simplification options
357
 */
358
enum
359
{
360
  /* Do not move vertices that are located on the topological border (vertices on triangle edges that don't have a paired triangle). Useful for simplifying portions of the larger mesh. */
361
  meshopt_SimplifyLockBorder = 1 << 0,
362
  /* Improve simplification performance assuming input indices are a sparse subset of the mesh. Note that error becomes relative to subset extents. */
363
  meshopt_SimplifySparse = 1 << 1,
364
  /* Treat error limit and resulting error as absolute instead of relative to mesh extents. */
365
  meshopt_SimplifyErrorAbsolute = 1 << 2,
366
  /* Experimental: remove disconnected parts of the mesh during simplification incrementally, regardless of the topological restrictions inside components. */
367
  meshopt_SimplifyPrune = 1 << 3,
368
};
369
370
/**
371
 * Mesh simplifier
372
 * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible
373
 * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error.
374
 * If not all attributes from the input mesh are required, it's recommended to reindex the mesh without them prior to simplification.
375
 * Returns the number of indices after simplification, with destination containing new index data
376
 * The resulting index buffer references vertices from the original vertex buffer.
377
 * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
378
 *
379
 * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)!
380
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
381
 * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
382
 * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default
383
 * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
384
 */
385
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);
386
387
/**
388
 * Experimental: Mesh simplifier with attribute metric
389
 * The algorithm enhances meshopt_simplify by incorporating attribute values into the error metric used to prioritize simplification order; see meshopt_simplify documentation for details.
390
 * Note that the number of attributes affects memory requirements and running time; this algorithm requires ~1.5x more memory and time compared to meshopt_simplify when using 4 scalar attributes.
391
 *
392
 * vertex_attributes should have attribute_count floats for each vertex
393
 * attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position
394
 * attribute_count must be <= 32
395
 * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex; 1 denotes vertices that can't be moved
396
 */
397
MESHOPTIMIZER_EXPERIMENTAL 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);
398
399
/**
400
 * Experimental: Mesh simplifier (sloppy)
401
 * Reduces the number of triangles in the mesh, sacrificing mesh appearance for simplification performance
402
 * The algorithm doesn't preserve mesh topology but can stop short of the target goal based on target error.
403
 * Returns the number of indices after simplification, with destination containing new index data
404
 * The resulting index buffer references vertices from the original vertex buffer.
405
 * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
406
 *
407
 * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)!
408
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
409
 * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
410
 * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
411
 */
412
MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_simplifySloppy(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, float* result_error);
413
414
/**
415
 * Experimental: Point cloud simplifier
416
 * Reduces the number of points in the cloud to reach the given target
417
 * Returns the number of points after simplification, with destination containing new index data
418
 * The resulting index buffer references vertices from the original vertex buffer.
419
 * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
420
 *
421
 * destination must contain enough space for the target index buffer (target_vertex_count elements)
422
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
423
 * vertex_colors should can be NULL; when it's not NULL, it should have float3 color in the first 12 bytes of each vertex
424
 * color_weight determines relative priority of color wrt position; 1.0 is a safe default
425
 */
426
MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t target_vertex_count);
427
428
/**
429
 * Returns the error scaling factor used by the simplifier to convert between absolute and relative extents
430
 *
431
 * Absolute error must be *divided* by the scaling factor before passing it to meshopt_simplify as target_error
432
 * Relative error returned by meshopt_simplify via result_error must be *multiplied* by the scaling factor to get absolute error.
433
 */
434
MESHOPTIMIZER_API float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
435
436
/**
437
 * Mesh stripifier
438
 * Converts a previously vertex cache optimized triangle list to triangle strip, stitching strips using restart index or degenerate triangles
439
 * Returns the number of indices in the resulting strip, with destination containing new index data
440
 * For maximum efficiency the index buffer being converted has to be optimized for vertex cache first.
441
 * Using restart indices can result in ~10% smaller index buffers, but on some GPUs restart indices may result in decreased performance.
442
 *
443
 * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_stripifyBound
444
 * restart_index should be 0xffff or 0xffffffff depending on index size, or 0 to use degenerate triangles
445
 */
446
MESHOPTIMIZER_API size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int restart_index);
447
MESHOPTIMIZER_API size_t meshopt_stripifyBound(size_t index_count);
448
449
/**
450
 * Mesh unstripifier
451
 * Converts a triangle strip to a triangle list
452
 * Returns the number of indices in the resulting list, with destination containing new index data
453
 *
454
 * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_unstripifyBound
455
 */
456
MESHOPTIMIZER_API size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count, unsigned int restart_index);
457
MESHOPTIMIZER_API size_t meshopt_unstripifyBound(size_t index_count);
458
459
struct meshopt_VertexCacheStatistics
460
{
461
  unsigned int vertices_transformed;
462
  unsigned int warps_executed;
463
  float acmr; /* transformed vertices / triangle count; best case 0.5, worst case 3.0, optimum depends on topology */
464
  float atvr; /* transformed vertices / vertex count; best case 1.0, worst case 6.0, optimum is 1.0 (each vertex is transformed once) */
465
};
466
467
/**
468
 * Vertex transform cache analyzer
469
 * Returns cache hit statistics using a simplified FIFO model
470
 * Results may not match actual GPU performance
471
 */
472
MESHOPTIMIZER_API struct meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size);
473
474
struct meshopt_OverdrawStatistics
475
{
476
  unsigned int pixels_covered;
477
  unsigned int pixels_shaded;
478
  float overdraw; /* shaded pixels / covered pixels; best case 1.0 */
479
};
480
481
/**
482
 * Overdraw analyzer
483
 * Returns overdraw statistics using a software rasterizer
484
 * Results may not match actual GPU performance
485
 *
486
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
487
 */
488
MESHOPTIMIZER_API struct meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
489
490
struct meshopt_VertexFetchStatistics
491
{
492
  unsigned int bytes_fetched;
493
  float overfetch; /* fetched bytes / vertex buffer size; best case 1.0 (each byte is fetched once) */
494
};
495
496
/**
497
 * Vertex fetch cache analyzer
498
 * Returns cache hit statistics using a simplified direct mapped model
499
 * Results may not match actual GPU performance
500
 */
501
MESHOPTIMIZER_API struct meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size);
502
503
/**
504
 * Meshlet is a small mesh cluster (subset) that consists of:
505
 * - triangles, an 8-bit micro triangle (index) buffer, that for each triangle specifies three local vertices to use;
506
 * - vertices, a 32-bit vertex indirection buffer, that for each local vertex specifies which mesh vertex to fetch vertex attributes from.
507
 *
508
 * For efficiency, meshlet triangles and vertices are packed into two large arrays; this structure contains offsets and counts to access the data.
509
 */
510
struct meshopt_Meshlet
511
{
512
  /* offsets within meshlet_vertices and meshlet_triangles arrays with meshlet data */
513
  unsigned int vertex_offset;
514
  unsigned int triangle_offset;
515
516
  /* number of vertices and triangles used in the meshlet; data is stored in consecutive range defined by offset and count */
517
  unsigned int vertex_count;
518
  unsigned int triangle_count;
519
};
520
521
/**
522
 * Meshlet builder
523
 * Splits the mesh into a set of meshlets where each meshlet has a micro index buffer indexing into meshlet vertices that refer to the original vertex buffer
524
 * The resulting data can be used to render meshes using NVidia programmable mesh shading pipeline, or in other cluster-based renderers.
525
 * When targeting mesh shading hardware, for maximum efficiency meshlets should be further optimized using meshopt_optimizeMeshlet.
526
 * When using buildMeshlets, vertex positions need to be provided to minimize the size of the resulting clusters.
527
 * When using buildMeshletsScan, for maximum efficiency the index buffer being converted has to be optimized for vertex cache first.
528
 *
529
 * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound
530
 * meshlet_vertices must contain enough space for all meshlets, worst case size is equal to max_meshlets * max_vertices
531
 * meshlet_triangles must contain enough space for all meshlets, worst case size is equal to max_meshlets * max_triangles * 3
532
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
533
 * max_vertices and max_triangles must not exceed implementation limits (max_vertices <= 255 - not 256!, max_triangles <= 512; max_triangles must be divisible by 4)
534
 * cone_weight should be set to 0 when cone culling is not used, and a value between 0 and 1 otherwise to balance between cluster size and cone culling efficiency
535
 */
536
MESHOPTIMIZER_API size_t meshopt_buildMeshlets(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight);
537
MESHOPTIMIZER_API size_t meshopt_buildMeshletsScan(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles);
538
MESHOPTIMIZER_API size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles);
539
540
/**
541
 * Experimental: Meshlet optimizer
542
 * Reorders meshlet vertices and triangles to maximize locality to improve rasterizer throughput
543
 *
544
 * meshlet_triangles and meshlet_vertices must refer to meshlet triangle and vertex index data; when buildMeshlets* is used, these
545
 * need to be computed from meshlet's vertex_offset and triangle_offset
546
 * triangle_count and vertex_count must not exceed implementation limits (vertex_count <= 255 - not 256!, triangle_count <= 512)
547
 */
548
MESHOPTIMIZER_EXPERIMENTAL void meshopt_optimizeMeshlet(unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t triangle_count, size_t vertex_count);
549
550
struct meshopt_Bounds
551
{
552
  /* bounding sphere, useful for frustum and occlusion culling */
553
  float center[3];
554
  float radius;
555
556
  /* normal cone, useful for backface culling */
557
  float cone_apex[3];
558
  float cone_axis[3];
559
  float cone_cutoff; /* = cos(angle/2) */
560
561
  /* normal cone axis and cutoff, stored in 8-bit SNORM format; decode using x/127.0 */
562
  signed char cone_axis_s8[3];
563
  signed char cone_cutoff_s8;
564
};
565
566
/**
567
 * Cluster bounds generator
568
 * Creates bounding volumes that can be used for frustum, backface and occlusion culling.
569
 *
570
 * For backface culling with orthographic projection, use the following formula to reject backfacing clusters:
571
 *   dot(view, cone_axis) >= cone_cutoff
572
 *
573
 * For perspective projection, you can use the formula that needs cone apex in addition to axis & cutoff:
574
 *   dot(normalize(cone_apex - camera_position), cone_axis) >= cone_cutoff
575
 *
576
 * Alternatively, you can use the formula that doesn't need cone apex and uses bounding sphere instead:
577
 *   dot(normalize(center - camera_position), cone_axis) >= cone_cutoff + radius / length(center - camera_position)
578
 * or an equivalent formula that doesn't have a singularity at center = camera_position:
579
 *   dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius
580
 *
581
 * The formula that uses the apex is slightly more accurate but needs the apex; if you are already using bounding sphere
582
 * to do frustum/occlusion culling, the formula that doesn't use the apex may be preferable (for derivation see
583
 * Real-Time Rendering 4th Edition, section 19.3).
584
 *
585
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
586
 * vertex_count should specify the number of vertices in the entire mesh, not cluster or meshlet
587
 * index_count/3 and triangle_count must not exceed implementation limits (<= 512)
588
 */
589
MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeClusterBounds(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
590
MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeMeshletBounds(const unsigned int* meshlet_vertices, const unsigned char* meshlet_triangles, size_t triangle_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
591
592
/**
593
 * Spatial sorter
594
 * Generates a remap table that can be used to reorder points for spatial locality.
595
 * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer.
596
 *
597
 * destination must contain enough space for the resulting remap table (vertex_count elements)
598
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
599
 */
600
MESHOPTIMIZER_API void meshopt_spatialSortRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
601
602
/**
603
 * Experimental: Spatial sorter
604
 * Reorders triangles for spatial locality, and generates a new index buffer. The resulting index buffer can be used with other functions like optimizeVertexCache.
605
 *
606
 * destination must contain enough space for the resulting index buffer (index_count elements)
607
 * vertex_positions should have float3 position in the first 12 bytes of each vertex
608
 */
609
MESHOPTIMIZER_EXPERIMENTAL void meshopt_spatialSortTriangles(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
610
611
/**
612
 * Quantize a float into half-precision (as defined by IEEE-754 fp16) floating point value
613
 * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest
614
 * Representable magnitude range: [6e-5; 65504]
615
 * Maximum relative reconstruction error: 5e-4
616
 */
617
MESHOPTIMIZER_API unsigned short meshopt_quantizeHalf(float v);
618
619
/**
620
 * Quantize a float into a floating point value with a limited number of significant mantissa bits, preserving the IEEE-754 fp32 binary representation
621
 * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest
622
 * Assumes N is in a valid mantissa precision range, which is 1..23
623
 */
624
MESHOPTIMIZER_API float meshopt_quantizeFloat(float v, int N);
625
626
/**
627
 * Reverse quantization of a half-precision (as defined by IEEE-754 fp16) floating point value
628
 * Preserves Inf/NaN, flushes denormals to zero
629
 */
630
MESHOPTIMIZER_API float meshopt_dequantizeHalf(unsigned short h);
631
632
/**
633
 * Set allocation callbacks
634
 * These callbacks will be used instead of the default operator new/operator delete for all temporary allocations in the library.
635
 * Note that all algorithms only allocate memory for temporary use.
636
 * allocate/deallocate are always called in a stack-like order - last pointer to be allocated is deallocated first.
637
 */
638
MESHOPTIMIZER_API void meshopt_setAllocator(void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t), void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*));
639
640
#ifdef __cplusplus
641
} /* extern "C" */
642
#endif
643
644
/* Quantization into fixed point normalized formats; these are only available as inline C++ functions */
645
#ifdef __cplusplus
646
/**
647
 * Quantize a float in [0..1] range into an N-bit fixed point unorm value
648
 * Assumes reconstruction function (q / (2^N-1)), which is the case for fixed-function normalized fixed point conversion
649
 * Maximum reconstruction error: 1/2^(N+1)
650
 */
651
inline int meshopt_quantizeUnorm(float v, int N);
652
653
/**
654
 * Quantize a float in [-1..1] range into an N-bit fixed point snorm value
655
 * Assumes reconstruction function (q / (2^(N-1)-1)), which is the case for fixed-function normalized fixed point conversion (except early OpenGL versions)
656
 * Maximum reconstruction error: 1/2^N
657
 */
658
inline int meshopt_quantizeSnorm(float v, int N);
659
#endif
660
661
/**
662
 * C++ template interface
663
 *
664
 * These functions mirror the C interface the library provides, providing template-based overloads so that
665
 * the caller can use an arbitrary type for the index data, both for input and output.
666
 * When the supplied type is the same size as that of unsigned int, the wrappers are zero-cost; when it's not,
667
 * the wrappers end up allocating memory and copying index data to convert from one type to another.
668
 */
669
#if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS)
670
template <typename T>
671
inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
672
template <typename T>
673
inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count);
674
template <typename T>
675
inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap);
676
template <typename T>
677
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);
678
template <typename T>
679
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);
680
template <typename T>
681
inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
682
template <typename T>
683
inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
684
template <typename T>
685
inline size_t meshopt_generateProvokingIndexBuffer(T* destination, unsigned int* reorder, const T* indices, size_t index_count, size_t vertex_count);
686
template <typename T>
687
inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count);
688
template <typename T>
689
inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count);
690
template <typename T>
691
inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size);
692
template <typename T>
693
inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold);
694
template <typename T>
695
inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count);
696
template <typename T>
697
inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
698
template <typename T>
699
inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count);
700
template <typename T>
701
inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size);
702
template <typename T>
703
inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count);
704
template <typename T>
705
inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size);
706
template <typename T>
707
inline size_t meshopt_simplify(T* destination, const T* 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 = 0, float* result_error = NULL);
708
template <typename T>
709
inline size_t meshopt_simplifyWithAttributes(T* destination, const T* 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 = 0, float* result_error = NULL);
710
template <typename T>
711
inline size_t meshopt_simplifySloppy(T* destination, const T* 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, float* result_error = NULL);
712
template <typename T>
713
inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index);
714
template <typename T>
715
inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index);
716
template <typename T>
717
inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int buffer_size);
718
template <typename T>
719
inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
720
template <typename T>
721
inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size);
722
template <typename T>
723
inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight);
724
template <typename T>
725
inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles);
726
template <typename T>
727
inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
728
template <typename T>
729
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);
730
#endif
731
732
/* Inline implementation */
733
#ifdef __cplusplus
734
inline int meshopt_quantizeUnorm(float v, int N)
735
0
{
736
0
  const float scale = float((1 << N) - 1);
737
0
738
0
  v = (v >= 0) ? v : 0;
739
0
  v = (v <= 1) ? v : 1;
740
0
741
0
  return int(v * scale + 0.5f);
742
0
}
743
744
inline int meshopt_quantizeSnorm(float v, int N)
745
0
{
746
0
  const float scale = float((1 << (N - 1)) - 1);
747
0
748
0
  float round = (v >= 0 ? 0.5f : -0.5f);
749
0
750
0
  v = (v >= -1) ? v : -1;
751
0
  v = (v <= +1) ? v : +1;
752
0
753
0
  return int(v * scale + round);
754
0
}
755
#endif
756
757
/* Internal implementation helpers */
758
#ifdef __cplusplus
759
class meshopt_Allocator
760
{
761
public:
762
  template <typename T>
763
  struct StorageT
764
  {
765
    static void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t);
766
    static void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*);
767
  };
768
769
  typedef StorageT<void> Storage;
770
771
  meshopt_Allocator()
772
      : blocks()
773
      , count(0)
774
0
  {
775
0
  }
776
777
  ~meshopt_Allocator()
778
0
  {
779
0
    for (size_t i = count; i > 0; --i)
780
0
      Storage::deallocate(blocks[i - 1]);
781
0
  }
782
783
  template <typename T>
784
  T* allocate(size_t size)
785
  {
786
    assert(count < sizeof(blocks) / sizeof(blocks[0]));
787
    T* result = static_cast<T*>(Storage::allocate(size > size_t(-1) / sizeof(T) ? size_t(-1) : size * sizeof(T)));
788
    blocks[count++] = result;
789
    return result;
790
  }
791
792
  void deallocate(void* ptr)
793
0
  {
794
0
    assert(count > 0 && blocks[count - 1] == ptr);
795
0
    Storage::deallocate(ptr);
796
0
    count--;
797
0
  }
798
799
private:
800
  void* blocks[24];
801
  size_t count;
802
};
803
804
// This makes sure that allocate/deallocate are lazily generated in translation units that need them and are deduplicated by the linker
805
template <typename T>
806
void* (MESHOPTIMIZER_ALLOC_CALLCONV* meshopt_Allocator::StorageT<T>::allocate)(size_t) = operator new;
807
template <typename T>
808
void (MESHOPTIMIZER_ALLOC_CALLCONV* meshopt_Allocator::StorageT<T>::deallocate)(void*) = operator delete;
809
#endif
810
811
/* Inline implementation for C++ templated wrappers */
812
#if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS)
813
template <typename T, bool ZeroCopy = sizeof(T) == sizeof(unsigned int)>
814
struct meshopt_IndexAdapter;
815
816
template <typename T>
817
struct meshopt_IndexAdapter<T, false>
818
{
819
  T* result;
820
  unsigned int* data;
821
  size_t count;
822
823
  meshopt_IndexAdapter(T* result_, const T* input, size_t count_)
824
      : result(result_)
825
      , data(NULL)
826
      , count(count_)
827
  {
828
    size_t size = count > size_t(-1) / sizeof(unsigned int) ? size_t(-1) : count * sizeof(unsigned int);
829
830
    data = static_cast<unsigned int*>(meshopt_Allocator::Storage::allocate(size));
831
832
    if (input)
833
    {
834
      for (size_t i = 0; i < count; ++i)
835
        data[i] = input[i];
836
    }
837
  }
838
839
  ~meshopt_IndexAdapter()
840
  {
841
    if (result)
842
    {
843
      for (size_t i = 0; i < count; ++i)
844
        result[i] = T(data[i]);
845
    }
846
847
    meshopt_Allocator::Storage::deallocate(data);
848
  }
849
};
850
851
template <typename T>
852
struct meshopt_IndexAdapter<T, true>
853
{
854
  unsigned int* data;
855
856
  meshopt_IndexAdapter(T* result, const T* input, size_t)
857
      : data(reinterpret_cast<unsigned int*>(result ? result : const_cast<T*>(input)))
858
  {
859
  }
860
};
861
862
template <typename T>
863
inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
864
{
865
  meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);
866
867
  return meshopt_generateVertexRemap(destination, indices ? in.data : NULL, index_count, vertices, vertex_count, vertex_size);
868
}
869
870
template <typename T>
871
inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count)
872
{
873
  meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);
874
875
  return meshopt_generateVertexRemapMulti(destination, indices ? in.data : NULL, index_count, vertex_count, streams, stream_count);
876
}
877
878
template <typename T>
879
inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap)
880
{
881
  meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);
882
  meshopt_IndexAdapter<T> out(destination, 0, index_count);
883
884
  meshopt_remapIndexBuffer(out.data, indices ? in.data : NULL, index_count, remap);
885
}
886
887
template <typename T>
888
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)
889
{
890
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
891
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
892
893
  meshopt_generateShadowIndexBuffer(out.data, in.data, index_count, vertices, vertex_count, vertex_size, vertex_stride);
894
}
895
896
template <typename T>
897
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)
898
{
899
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
900
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
901
902
  meshopt_generateShadowIndexBufferMulti(out.data, in.data, index_count, vertex_count, streams, stream_count);
903
}
904
905
template <typename T>
906
inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
907
{
908
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
909
  meshopt_IndexAdapter<T> out(destination, NULL, index_count * 2);
910
911
  meshopt_generateAdjacencyIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
912
}
913
914
template <typename T>
915
inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
916
{
917
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
918
  meshopt_IndexAdapter<T> out(destination, NULL, index_count * 4);
919
920
  meshopt_generateTessellationIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
921
}
922
923
template <typename T>
924
inline size_t meshopt_generateProvokingIndexBuffer(T* destination, unsigned int* reorder, const T* indices, size_t index_count, size_t vertex_count)
925
{
926
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
927
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
928
929
  size_t bound = vertex_count + (index_count / 3);
930
  assert(size_t(T(bound - 1)) == bound - 1); // bound - 1 must fit in T
931
  (void)bound;
932
933
  return meshopt_generateProvokingIndexBuffer(out.data, reorder, in.data, index_count, vertex_count);
934
}
935
936
template <typename T>
937
inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count)
938
{
939
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
940
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
941
942
  meshopt_optimizeVertexCache(out.data, in.data, index_count, vertex_count);
943
}
944
945
template <typename T>
946
inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count)
947
{
948
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
949
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
950
951
  meshopt_optimizeVertexCacheStrip(out.data, in.data, index_count, vertex_count);
952
}
953
954
template <typename T>
955
inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size)
956
{
957
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
958
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
959
960
  meshopt_optimizeVertexCacheFifo(out.data, in.data, index_count, vertex_count, cache_size);
961
}
962
963
template <typename T>
964
inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold)
965
{
966
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
967
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
968
969
  meshopt_optimizeOverdraw(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, threshold);
970
}
971
972
template <typename T>
973
inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count)
974
{
975
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
976
977
  return meshopt_optimizeVertexFetchRemap(destination, in.data, index_count, vertex_count);
978
}
979
980
template <typename T>
981
inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
982
{
983
  meshopt_IndexAdapter<T> inout(indices, indices, index_count);
984
985
  return meshopt_optimizeVertexFetch(destination, inout.data, index_count, vertices, vertex_count, vertex_size);
986
}
987
988
template <typename T>
989
inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count)
990
{
991
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
992
993
  return meshopt_encodeIndexBuffer(buffer, buffer_size, in.data, index_count);
994
}
995
996
template <typename T>
997
inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size)
998
{
999
  char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1];
1000
  (void)index_size_valid;
1001
1002
  return meshopt_decodeIndexBuffer(destination, index_count, sizeof(T), buffer, buffer_size);
1003
}
1004
1005
template <typename T>
1006
inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count)
1007
{
1008
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1009
1010
  return meshopt_encodeIndexSequence(buffer, buffer_size, in.data, index_count);
1011
}
1012
1013
template <typename T>
1014
inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size)
1015
{
1016
  char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1];
1017
  (void)index_size_valid;
1018
1019
  return meshopt_decodeIndexSequence(destination, index_count, sizeof(T), buffer, buffer_size);
1020
}
1021
1022
template <typename T>
1023
inline size_t meshopt_simplify(T* destination, const T* 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)
1024
{
1025
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1026
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
1027
1028
  return meshopt_simplify(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options, result_error);
1029
}
1030
1031
template <typename T>
1032
inline size_t meshopt_simplifyWithAttributes(T* destination, const T* 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)
1033
{
1034
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1035
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
1036
1037
  return meshopt_simplifyWithAttributes(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, result_error);
1038
}
1039
1040
template <typename T>
1041
inline size_t meshopt_simplifySloppy(T* destination, const T* 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, float* result_error)
1042
{
1043
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1044
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
1045
1046
  return meshopt_simplifySloppy(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, result_error);
1047
}
1048
1049
template <typename T>
1050
inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index)
1051
{
1052
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1053
  meshopt_IndexAdapter<T> out(destination, NULL, (index_count / 3) * 5);
1054
1055
  return meshopt_stripify(out.data, in.data, index_count, vertex_count, unsigned(restart_index));
1056
}
1057
1058
template <typename T>
1059
inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index)
1060
{
1061
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1062
  meshopt_IndexAdapter<T> out(destination, NULL, (index_count - 2) * 3);
1063
1064
  return meshopt_unstripify(out.data, in.data, index_count, unsigned(restart_index));
1065
}
1066
1067
template <typename T>
1068
inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int buffer_size)
1069
{
1070
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1071
1072
  return meshopt_analyzeVertexCache(in.data, index_count, vertex_count, cache_size, warp_size, buffer_size);
1073
}
1074
1075
template <typename T>
1076
inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
1077
{
1078
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1079
1080
  return meshopt_analyzeOverdraw(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
1081
}
1082
1083
template <typename T>
1084
inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size)
1085
{
1086
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1087
1088
  return meshopt_analyzeVertexFetch(in.data, index_count, vertex_count, vertex_size);
1089
}
1090
1091
template <typename T>
1092
inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight)
1093
{
1094
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1095
1096
  return meshopt_buildMeshlets(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, max_triangles, cone_weight);
1097
}
1098
1099
template <typename T>
1100
inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles)
1101
{
1102
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1103
1104
  return meshopt_buildMeshletsScan(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_count, max_vertices, max_triangles);
1105
}
1106
1107
template <typename T>
1108
inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
1109
{
1110
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1111
1112
  return meshopt_computeClusterBounds(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
1113
}
1114
1115
template <typename T>
1116
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)
1117
{
1118
  meshopt_IndexAdapter<T> in(NULL, indices, index_count);
1119
  meshopt_IndexAdapter<T> out(destination, NULL, index_count);
1120
1121
  meshopt_spatialSortTriangles(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
1122
}
1123
#endif
1124
1125
/**
1126
 * Copyright (c) 2016-2025 Arseny Kapoulkine
1127
 *
1128
 * Permission is hereby granted, free of charge, to any person
1129
 * obtaining a copy of this software and associated documentation
1130
 * files (the "Software"), to deal in the Software without
1131
 * restriction, including without limitation the rights to use,
1132
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
1133
 * copies of the Software, and to permit persons to whom the
1134
 * Software is furnished to do so, subject to the following
1135
 * conditions:
1136
 *
1137
 * The above copyright notice and this permission notice shall be
1138
 * included in all copies or substantial portions of the Software.
1139
 *
1140
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1141
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
1142
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1143
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
1144
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
1145
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1146
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1147
 * OTHER DEALINGS IN THE SOFTWARE.
1148
 */