meshoptimizer.h 62 KB

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