meshoptimizer.h 58 KB

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