meshoptimizer.h 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. /**
  2. * meshoptimizer - version 0.18
  3. *
  4. * Copyright (C) 2016-2022, 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 180 /* 0.18 */
  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. * Mantissa is shared between all components of a given vector as defined by stride; stride must be divisible by 4.
  277. * Input data must contain stride/4 floats for every vector (count*stride/4 total).
  278. * When individual (scalar) encoding is desired, simply pass stride=4 and adjust count accordingly.
  279. */
  280. MESHOPTIMIZER_EXPERIMENTAL void meshopt_encodeFilterOct(void* destination, size_t count, size_t stride, int bits, const float* data);
  281. MESHOPTIMIZER_EXPERIMENTAL void meshopt_encodeFilterQuat(void* destination, size_t count, size_t stride, int bits, const float* data);
  282. MESHOPTIMIZER_EXPERIMENTAL void meshopt_encodeFilterExp(void* destination, size_t count, size_t stride, int bits, const float* data);
  283. /**
  284. * Simplification options
  285. */
  286. enum
  287. {
  288. /* 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. */
  289. meshopt_SimplifyLockBorder = 1 << 0,
  290. };
  291. /**
  292. * Experimental: Mesh simplifier with attribute metric; attributes follow xyz position data atm (vertex data must contain 3 + attribute_count floats per vertex)
  293. */
  294. MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_data, size_t vertex_count, size_t vertex_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error, const float* attributes, const float* attribute_weights, size_t attribute_count);
  295. /**
  296. * Mesh simplifier
  297. * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible
  298. * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error.
  299. * If not all attributes from the input mesh are required, it's recommended to reindex the mesh using meshopt_generateShadowIndexBuffer prior to simplification.
  300. * Returns the number of indices after simplification, with destination containing new index data
  301. * The resulting index buffer references vertices from the original vertex buffer.
  302. * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
  303. *
  304. * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)!
  305. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  306. * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
  307. * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default
  308. * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
  309. */
  310. 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);
  311. /**
  312. * Experimental: Mesh simplifier (sloppy)
  313. * Reduces the number of triangles in the mesh, sacrificing mesh appearance for simplification performance
  314. * The algorithm doesn't preserve mesh topology but can stop short of the target goal based on target error.
  315. * Returns the number of indices after simplification, with destination containing new index data
  316. * The resulting index buffer references vertices from the original vertex buffer.
  317. * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
  318. *
  319. * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)!
  320. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  321. * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
  322. * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
  323. */
  324. 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);
  325. /**
  326. * Experimental: Point cloud simplifier
  327. * Reduces the number of points in the cloud to reach the given target
  328. * Returns the number of points after simplification, with destination containing new index data
  329. * The resulting index buffer references vertices from the original vertex buffer.
  330. * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
  331. *
  332. * destination must contain enough space for the target index buffer (target_vertex_count elements)
  333. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  334. */
  335. MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_vertex_count);
  336. /**
  337. * Returns the error scaling factor used by the simplifier to convert between absolute and relative extents
  338. *
  339. * Absolute error must be *divided* by the scaling factor before passing it to meshopt_simplify as target_error
  340. * Relative error returned by meshopt_simplify via result_error must be *multiplied* by the scaling factor to get absolute error.
  341. */
  342. MESHOPTIMIZER_API float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  343. /**
  344. * Mesh stripifier
  345. * Converts a previously vertex cache optimized triangle list to triangle strip, stitching strips using restart index or degenerate triangles
  346. * Returns the number of indices in the resulting strip, with destination containing new index data
  347. * For maximum efficiency the index buffer being converted has to be optimized for vertex cache first.
  348. * Using restart indices can result in ~10% smaller index buffers, but on some GPUs restart indices may result in decreased performance.
  349. *
  350. * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_stripifyBound
  351. * restart_index should be 0xffff or 0xffffffff depending on index size, or 0 to use degenerate triangles
  352. */
  353. 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);
  354. MESHOPTIMIZER_API size_t meshopt_stripifyBound(size_t index_count);
  355. /**
  356. * Mesh unstripifier
  357. * Converts a triangle strip to a triangle list
  358. * Returns the number of indices in the resulting list, with destination containing new index data
  359. *
  360. * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_unstripifyBound
  361. */
  362. MESHOPTIMIZER_API size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count, unsigned int restart_index);
  363. MESHOPTIMIZER_API size_t meshopt_unstripifyBound(size_t index_count);
  364. struct meshopt_VertexCacheStatistics
  365. {
  366. unsigned int vertices_transformed;
  367. unsigned int warps_executed;
  368. float acmr; /* transformed vertices / triangle count; best case 0.5, worst case 3.0, optimum depends on topology */
  369. float atvr; /* transformed vertices / vertex count; best case 1.0, worst case 6.0, optimum is 1.0 (each vertex is transformed once) */
  370. };
  371. /**
  372. * Vertex transform cache analyzer
  373. * Returns cache hit statistics using a simplified FIFO model
  374. * Results may not match actual GPU performance
  375. */
  376. 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);
  377. struct meshopt_OverdrawStatistics
  378. {
  379. unsigned int pixels_covered;
  380. unsigned int pixels_shaded;
  381. float overdraw; /* shaded pixels / covered pixels; best case 1.0 */
  382. };
  383. /**
  384. * Overdraw analyzer
  385. * Returns overdraw statistics using a software rasterizer
  386. * Results may not match actual GPU performance
  387. *
  388. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  389. */
  390. 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);
  391. struct meshopt_VertexFetchStatistics
  392. {
  393. unsigned int bytes_fetched;
  394. float overfetch; /* fetched bytes / vertex buffer size; best case 1.0 (each byte is fetched once) */
  395. };
  396. /**
  397. * Vertex fetch cache analyzer
  398. * Returns cache hit statistics using a simplified direct mapped model
  399. * Results may not match actual GPU performance
  400. */
  401. MESHOPTIMIZER_API struct meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size);
  402. struct meshopt_Meshlet
  403. {
  404. /* offsets within meshlet_vertices and meshlet_triangles arrays with meshlet data */
  405. unsigned int vertex_offset;
  406. unsigned int triangle_offset;
  407. /* number of vertices and triangles used in the meshlet; data is stored in consecutive range defined by offset and count */
  408. unsigned int vertex_count;
  409. unsigned int triangle_count;
  410. };
  411. /**
  412. * Meshlet builder
  413. * 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
  414. * The resulting data can be used to render meshes using NVidia programmable mesh shading pipeline, or in other cluster-based renderers.
  415. * When using buildMeshlets, vertex positions need to be provided to minimize the size of the resulting clusters.
  416. * When using buildMeshletsScan, for maximum efficiency the index buffer being converted has to be optimized for vertex cache first.
  417. *
  418. * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound
  419. * meshlet_vertices must contain enough space for all meshlets, worst case size is equal to max_meshlets * max_vertices
  420. * meshlet_triangles must contain enough space for all meshlets, worst case size is equal to max_meshlets * max_triangles * 3
  421. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  422. * max_vertices and max_triangles must not exceed implementation limits (max_vertices <= 255 - not 256!, max_triangles <= 512)
  423. * 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
  424. */
  425. 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);
  426. 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);
  427. MESHOPTIMIZER_API size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles);
  428. struct meshopt_Bounds
  429. {
  430. /* bounding sphere, useful for frustum and occlusion culling */
  431. float center[3];
  432. float radius;
  433. /* normal cone, useful for backface culling */
  434. float cone_apex[3];
  435. float cone_axis[3];
  436. float cone_cutoff; /* = cos(angle/2) */
  437. /* normal cone axis and cutoff, stored in 8-bit SNORM format; decode using x/127.0 */
  438. signed char cone_axis_s8[3];
  439. signed char cone_cutoff_s8;
  440. };
  441. /**
  442. * Cluster bounds generator
  443. * Creates bounding volumes that can be used for frustum, backface and occlusion culling.
  444. *
  445. * For backface culling with orthographic projection, use the following formula to reject backfacing clusters:
  446. * dot(view, cone_axis) >= cone_cutoff
  447. *
  448. * For perspective projection, you can the formula that needs cone apex in addition to axis & cutoff:
  449. * dot(normalize(cone_apex - camera_position), cone_axis) >= cone_cutoff
  450. *
  451. * Alternatively, you can use the formula that doesn't need cone apex and uses bounding sphere instead:
  452. * dot(normalize(center - camera_position), cone_axis) >= cone_cutoff + radius / length(center - camera_position)
  453. * or an equivalent formula that doesn't have a singularity at center = camera_position:
  454. * dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius
  455. *
  456. * The formula that uses the apex is slightly more accurate but needs the apex; if you are already using bounding sphere
  457. * to do frustum/occlusion culling, the formula that doesn't use the apex may be preferable.
  458. *
  459. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  460. * index_count/3 should be less than or equal to 512 (the function assumes clusters of limited size)
  461. */
  462. 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);
  463. 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);
  464. /**
  465. * Experimental: Spatial sorter
  466. * Generates a remap table that can be used to reorder points for spatial locality.
  467. * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer.
  468. *
  469. * destination must contain enough space for the resulting remap table (vertex_count elements)
  470. */
  471. MESHOPTIMIZER_EXPERIMENTAL void meshopt_spatialSortRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  472. /**
  473. * Experimental: Spatial sorter
  474. * Reorders triangles for spatial locality, and generates a new index buffer. The resulting index buffer can be used with other functions like optimizeVertexCache.
  475. *
  476. * destination must contain enough space for the resulting index buffer (index_count elements)
  477. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  478. */
  479. 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);
  480. /**
  481. * Set allocation callbacks
  482. * These callbacks will be used instead of the default operator new/operator delete for all temporary allocations in the library.
  483. * Note that all algorithms only allocate memory for temporary use.
  484. * allocate/deallocate are always called in a stack-like order - last pointer to be allocated is deallocated first.
  485. */
  486. MESHOPTIMIZER_API void meshopt_setAllocator(void* (MESHOPTIMIZER_ALLOC_CALLCONV *allocate)(size_t), void (MESHOPTIMIZER_ALLOC_CALLCONV *deallocate)(void*));
  487. #ifdef __cplusplus
  488. } /* extern "C" */
  489. #endif
  490. /* Quantization into commonly supported data formats */
  491. #ifdef __cplusplus
  492. /**
  493. * Quantize a float in [0..1] range into an N-bit fixed point unorm value
  494. * Assumes reconstruction function (q / (2^N-1)), which is the case for fixed-function normalized fixed point conversion
  495. * Maximum reconstruction error: 1/2^(N+1)
  496. */
  497. inline int meshopt_quantizeUnorm(float v, int N);
  498. /**
  499. * Quantize a float in [-1..1] range into an N-bit fixed point snorm value
  500. * Assumes reconstruction function (q / (2^(N-1)-1)), which is the case for fixed-function normalized fixed point conversion (except early OpenGL versions)
  501. * Maximum reconstruction error: 1/2^N
  502. */
  503. inline int meshopt_quantizeSnorm(float v, int N);
  504. /**
  505. * Quantize a float into half-precision floating point value
  506. * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest
  507. * Representable magnitude range: [6e-5; 65504]
  508. * Maximum relative reconstruction error: 5e-4
  509. */
  510. inline unsigned short meshopt_quantizeHalf(float v);
  511. /**
  512. * Quantize a float into a floating point value with a limited number of significant mantissa bits
  513. * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest
  514. * Assumes N is in a valid mantissa precision range, which is 1..23
  515. */
  516. inline float meshopt_quantizeFloat(float v, int N);
  517. #endif
  518. /**
  519. * C++ template interface
  520. *
  521. * These functions mirror the C interface the library provides, providing template-based overloads so that
  522. * the caller can use an arbitrary type for the index data, both for input and output.
  523. * When the supplied type is the same size as that of unsigned int, the wrappers are zero-cost; when it's not,
  524. * the wrappers end up allocating memory and copying index data to convert from one type to another.
  525. */
  526. #if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS)
  527. template <typename T>
  528. 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);
  529. template <typename T>
  530. 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);
  531. template <typename T>
  532. inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap);
  533. template <typename T>
  534. 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);
  535. template <typename T>
  536. 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);
  537. template <typename T>
  538. 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);
  539. template <typename T>
  540. 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);
  541. template <typename T>
  542. inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count);
  543. template <typename T>
  544. inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count);
  545. template <typename T>
  546. inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size);
  547. template <typename T>
  548. 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);
  549. template <typename T>
  550. inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count);
  551. template <typename T>
  552. inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
  553. template <typename T>
  554. inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count);
  555. template <typename T>
  556. inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size);
  557. template <typename T>
  558. inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count);
  559. template <typename T>
  560. inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size);
  561. template <typename T>
  562. 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 = 0);
  563. template <typename T>
  564. 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 = 0);
  565. template <typename T>
  566. inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index);
  567. template <typename T>
  568. inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index);
  569. template <typename T>
  570. 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);
  571. template <typename T>
  572. 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);
  573. template <typename T>
  574. inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size);
  575. template <typename T>
  576. 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);
  577. template <typename T>
  578. 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);
  579. template <typename T>
  580. 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);
  581. template <typename T>
  582. 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);
  583. #endif
  584. /* Inline implementation */
  585. #ifdef __cplusplus
  586. inline int meshopt_quantizeUnorm(float v, int N)
  587. {
  588. const float scale = float((1 << N) - 1);
  589. v = (v >= 0) ? v : 0;
  590. v = (v <= 1) ? v : 1;
  591. return int(v * scale + 0.5f);
  592. }
  593. inline int meshopt_quantizeSnorm(float v, int N)
  594. {
  595. const float scale = float((1 << (N - 1)) - 1);
  596. float round = (v >= 0 ? 0.5f : -0.5f);
  597. v = (v >= -1) ? v : -1;
  598. v = (v <= +1) ? v : +1;
  599. return int(v * scale + round);
  600. }
  601. inline unsigned short meshopt_quantizeHalf(float v)
  602. {
  603. union { float f; unsigned int ui; } u = {v};
  604. unsigned int ui = u.ui;
  605. int s = (ui >> 16) & 0x8000;
  606. int em = ui & 0x7fffffff;
  607. /* bias exponent and round to nearest; 112 is relative exponent bias (127-15) */
  608. int h = (em - (112 << 23) + (1 << 12)) >> 13;
  609. /* underflow: flush to zero; 113 encodes exponent -14 */
  610. h = (em < (113 << 23)) ? 0 : h;
  611. /* overflow: infinity; 143 encodes exponent 16 */
  612. h = (em >= (143 << 23)) ? 0x7c00 : h;
  613. /* NaN; note that we convert all types of NaN to qNaN */
  614. h = (em > (255 << 23)) ? 0x7e00 : h;
  615. return (unsigned short)(s | h);
  616. }
  617. inline float meshopt_quantizeFloat(float v, int N)
  618. {
  619. union { float f; unsigned int ui; } u = {v};
  620. unsigned int ui = u.ui;
  621. const int mask = (1 << (23 - N)) - 1;
  622. const int round = (1 << (23 - N)) >> 1;
  623. int e = ui & 0x7f800000;
  624. unsigned int rui = (ui + round) & ~mask;
  625. /* round all numbers except inf/nan; this is important to make sure nan doesn't overflow into -0 */
  626. ui = e == 0x7f800000 ? ui : rui;
  627. /* flush denormals to zero */
  628. ui = e == 0 ? 0 : ui;
  629. u.ui = ui;
  630. return u.f;
  631. }
  632. #endif
  633. /* Internal implementation helpers */
  634. #ifdef __cplusplus
  635. class meshopt_Allocator
  636. {
  637. public:
  638. template <typename T>
  639. struct StorageT
  640. {
  641. static void* (MESHOPTIMIZER_ALLOC_CALLCONV *allocate)(size_t);
  642. static void (MESHOPTIMIZER_ALLOC_CALLCONV *deallocate)(void*);
  643. };
  644. typedef StorageT<void> Storage;
  645. meshopt_Allocator()
  646. : blocks()
  647. , count(0)
  648. {
  649. }
  650. ~meshopt_Allocator()
  651. {
  652. for (size_t i = count; i > 0; --i)
  653. Storage::deallocate(blocks[i - 1]);
  654. }
  655. template <typename T> T* allocate(size_t size)
  656. {
  657. assert(count < sizeof(blocks) / sizeof(blocks[0]));
  658. T* result = static_cast<T*>(Storage::allocate(size > size_t(-1) / sizeof(T) ? size_t(-1) : size * sizeof(T)));
  659. blocks[count++] = result;
  660. return result;
  661. }
  662. private:
  663. void* blocks[24];
  664. size_t count;
  665. };
  666. // This makes sure that allocate/deallocate are lazily generated in translation units that need them and are deduplicated by the linker
  667. template <typename T> void* (MESHOPTIMIZER_ALLOC_CALLCONV *meshopt_Allocator::StorageT<T>::allocate)(size_t) = operator new;
  668. template <typename T> void (MESHOPTIMIZER_ALLOC_CALLCONV *meshopt_Allocator::StorageT<T>::deallocate)(void*) = operator delete;
  669. #endif
  670. /* Inline implementation for C++ templated wrappers */
  671. #if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS)
  672. template <typename T, bool ZeroCopy = sizeof(T) == sizeof(unsigned int)>
  673. struct meshopt_IndexAdapter;
  674. template <typename T>
  675. struct meshopt_IndexAdapter<T, false>
  676. {
  677. T* result;
  678. unsigned int* data;
  679. size_t count;
  680. meshopt_IndexAdapter(T* result_, const T* input, size_t count_)
  681. : result(result_)
  682. , data(0)
  683. , count(count_)
  684. {
  685. size_t size = count > size_t(-1) / sizeof(unsigned int) ? size_t(-1) : count * sizeof(unsigned int);
  686. data = static_cast<unsigned int*>(meshopt_Allocator::Storage::allocate(size));
  687. if (input)
  688. {
  689. for (size_t i = 0; i < count; ++i)
  690. data[i] = input[i];
  691. }
  692. }
  693. ~meshopt_IndexAdapter()
  694. {
  695. if (result)
  696. {
  697. for (size_t i = 0; i < count; ++i)
  698. result[i] = T(data[i]);
  699. }
  700. meshopt_Allocator::Storage::deallocate(data);
  701. }
  702. };
  703. template <typename T>
  704. struct meshopt_IndexAdapter<T, true>
  705. {
  706. unsigned int* data;
  707. meshopt_IndexAdapter(T* result, const T* input, size_t)
  708. : data(reinterpret_cast<unsigned int*>(result ? result : const_cast<T*>(input)))
  709. {
  710. }
  711. };
  712. template <typename T>
  713. 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)
  714. {
  715. meshopt_IndexAdapter<T> in(0, indices, indices ? index_count : 0);
  716. return meshopt_generateVertexRemap(destination, indices ? in.data : 0, index_count, vertices, vertex_count, vertex_size);
  717. }
  718. template <typename T>
  719. 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)
  720. {
  721. meshopt_IndexAdapter<T> in(0, indices, indices ? index_count : 0);
  722. return meshopt_generateVertexRemapMulti(destination, indices ? in.data : 0, index_count, vertex_count, streams, stream_count);
  723. }
  724. template <typename T>
  725. inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap)
  726. {
  727. meshopt_IndexAdapter<T> in(0, indices, indices ? index_count : 0);
  728. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  729. meshopt_remapIndexBuffer(out.data, indices ? in.data : 0, index_count, remap);
  730. }
  731. template <typename T>
  732. 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)
  733. {
  734. meshopt_IndexAdapter<T> in(0, indices, index_count);
  735. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  736. meshopt_generateShadowIndexBuffer(out.data, in.data, index_count, vertices, vertex_count, vertex_size, vertex_stride);
  737. }
  738. template <typename T>
  739. 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)
  740. {
  741. meshopt_IndexAdapter<T> in(0, indices, index_count);
  742. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  743. meshopt_generateShadowIndexBufferMulti(out.data, in.data, index_count, vertex_count, streams, stream_count);
  744. }
  745. template <typename T>
  746. 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)
  747. {
  748. meshopt_IndexAdapter<T> in(0, indices, index_count);
  749. meshopt_IndexAdapter<T> out(destination, 0, index_count * 2);
  750. meshopt_generateAdjacencyIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  751. }
  752. template <typename T>
  753. 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)
  754. {
  755. meshopt_IndexAdapter<T> in(0, indices, index_count);
  756. meshopt_IndexAdapter<T> out(destination, 0, index_count * 4);
  757. meshopt_generateTessellationIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  758. }
  759. template <typename T>
  760. inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count)
  761. {
  762. meshopt_IndexAdapter<T> in(0, indices, index_count);
  763. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  764. meshopt_optimizeVertexCache(out.data, in.data, index_count, vertex_count);
  765. }
  766. template <typename T>
  767. inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count)
  768. {
  769. meshopt_IndexAdapter<T> in(0, indices, index_count);
  770. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  771. meshopt_optimizeVertexCacheStrip(out.data, in.data, index_count, vertex_count);
  772. }
  773. template <typename T>
  774. inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size)
  775. {
  776. meshopt_IndexAdapter<T> in(0, indices, index_count);
  777. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  778. meshopt_optimizeVertexCacheFifo(out.data, in.data, index_count, vertex_count, cache_size);
  779. }
  780. template <typename T>
  781. 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)
  782. {
  783. meshopt_IndexAdapter<T> in(0, indices, index_count);
  784. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  785. meshopt_optimizeOverdraw(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, threshold);
  786. }
  787. template <typename T>
  788. inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count)
  789. {
  790. meshopt_IndexAdapter<T> in(0, indices, index_count);
  791. return meshopt_optimizeVertexFetchRemap(destination, in.data, index_count, vertex_count);
  792. }
  793. template <typename T>
  794. inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
  795. {
  796. meshopt_IndexAdapter<T> inout(indices, indices, index_count);
  797. return meshopt_optimizeVertexFetch(destination, inout.data, index_count, vertices, vertex_count, vertex_size);
  798. }
  799. template <typename T>
  800. inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count)
  801. {
  802. meshopt_IndexAdapter<T> in(0, indices, index_count);
  803. return meshopt_encodeIndexBuffer(buffer, buffer_size, in.data, index_count);
  804. }
  805. template <typename T>
  806. inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size)
  807. {
  808. char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1];
  809. (void)index_size_valid;
  810. return meshopt_decodeIndexBuffer(destination, index_count, sizeof(T), buffer, buffer_size);
  811. }
  812. template <typename T>
  813. inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count)
  814. {
  815. meshopt_IndexAdapter<T> in(0, indices, index_count);
  816. return meshopt_encodeIndexSequence(buffer, buffer_size, in.data, index_count);
  817. }
  818. template <typename T>
  819. inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size)
  820. {
  821. char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1];
  822. (void)index_size_valid;
  823. return meshopt_decodeIndexSequence(destination, index_count, sizeof(T), buffer, buffer_size);
  824. }
  825. template <typename T>
  826. 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)
  827. {
  828. meshopt_IndexAdapter<T> in(0, indices, index_count);
  829. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  830. return meshopt_simplify(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options, result_error);
  831. }
  832. template <typename T>
  833. 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)
  834. {
  835. meshopt_IndexAdapter<T> in(0, indices, index_count);
  836. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  837. return meshopt_simplifySloppy(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, result_error);
  838. }
  839. template <typename T>
  840. inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index)
  841. {
  842. meshopt_IndexAdapter<T> in(0, indices, index_count);
  843. meshopt_IndexAdapter<T> out(destination, 0, (index_count / 3) * 5);
  844. return meshopt_stripify(out.data, in.data, index_count, vertex_count, unsigned(restart_index));
  845. }
  846. template <typename T>
  847. inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index)
  848. {
  849. meshopt_IndexAdapter<T> in(0, indices, index_count);
  850. meshopt_IndexAdapter<T> out(destination, 0, (index_count - 2) * 3);
  851. return meshopt_unstripify(out.data, in.data, index_count, unsigned(restart_index));
  852. }
  853. template <typename T>
  854. 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)
  855. {
  856. meshopt_IndexAdapter<T> in(0, indices, index_count);
  857. return meshopt_analyzeVertexCache(in.data, index_count, vertex_count, cache_size, warp_size, buffer_size);
  858. }
  859. template <typename T>
  860. 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)
  861. {
  862. meshopt_IndexAdapter<T> in(0, indices, index_count);
  863. return meshopt_analyzeOverdraw(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  864. }
  865. template <typename T>
  866. inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size)
  867. {
  868. meshopt_IndexAdapter<T> in(0, indices, index_count);
  869. return meshopt_analyzeVertexFetch(in.data, index_count, vertex_count, vertex_size);
  870. }
  871. template <typename T>
  872. 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)
  873. {
  874. meshopt_IndexAdapter<T> in(0, indices, index_count);
  875. 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);
  876. }
  877. template <typename T>
  878. 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)
  879. {
  880. meshopt_IndexAdapter<T> in(0, indices, index_count);
  881. return meshopt_buildMeshletsScan(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_count, max_vertices, max_triangles);
  882. }
  883. template <typename T>
  884. 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)
  885. {
  886. meshopt_IndexAdapter<T> in(0, indices, index_count);
  887. return meshopt_computeClusterBounds(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  888. }
  889. template <typename T>
  890. 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)
  891. {
  892. meshopt_IndexAdapter<T> in(0, indices, index_count);
  893. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  894. meshopt_spatialSortTriangles(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  895. }
  896. #endif
  897. /**
  898. * Copyright (c) 2016-2022 Arseny Kapoulkine
  899. *
  900. * Permission is hereby granted, free of charge, to any person
  901. * obtaining a copy of this software and associated documentation
  902. * files (the "Software"), to deal in the Software without
  903. * restriction, including without limitation the rights to use,
  904. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  905. * copies of the Software, and to permit persons to whom the
  906. * Software is furnished to do so, subject to the following
  907. * conditions:
  908. *
  909. * The above copyright notice and this permission notice shall be
  910. * included in all copies or substantial portions of the Software.
  911. *
  912. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  913. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  914. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  915. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  916. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  917. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  918. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  919. * OTHER DEALINGS IN THE SOFTWARE.
  920. */