clusterizer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. // This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
  2. #include "meshoptimizer.h"
  3. #include <assert.h>
  4. #include <float.h>
  5. #include <math.h>
  6. #include <string.h>
  7. // This work is based on:
  8. // Graham Wihlidal. Optimizing the Graphics Pipeline with Compute. 2016
  9. // Matthaeus Chajdas. GeometryFX 1.2 - Cluster Culling. 2016
  10. // Jack Ritter. An Efficient Bounding Sphere. 1990
  11. namespace meshopt
  12. {
  13. // This must be <= 255 since index 0xff is used internally to indice a vertex that doesn't belong to a meshlet
  14. const size_t kMeshletMaxVertices = 255;
  15. // A reasonable limit is around 2*max_vertices or less
  16. const size_t kMeshletMaxTriangles = 512;
  17. struct TriangleAdjacency2
  18. {
  19. unsigned int* counts;
  20. unsigned int* offsets;
  21. unsigned int* data;
  22. };
  23. static void buildTriangleAdjacency(TriangleAdjacency2& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)
  24. {
  25. size_t face_count = index_count / 3;
  26. // allocate arrays
  27. adjacency.counts = allocator.allocate<unsigned int>(vertex_count);
  28. adjacency.offsets = allocator.allocate<unsigned int>(vertex_count);
  29. adjacency.data = allocator.allocate<unsigned int>(index_count);
  30. // fill triangle counts
  31. memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int));
  32. for (size_t i = 0; i < index_count; ++i)
  33. {
  34. assert(indices[i] < vertex_count);
  35. adjacency.counts[indices[i]]++;
  36. }
  37. // fill offset table
  38. unsigned int offset = 0;
  39. for (size_t i = 0; i < vertex_count; ++i)
  40. {
  41. adjacency.offsets[i] = offset;
  42. offset += adjacency.counts[i];
  43. }
  44. assert(offset == index_count);
  45. // fill triangle data
  46. for (size_t i = 0; i < face_count; ++i)
  47. {
  48. unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
  49. adjacency.data[adjacency.offsets[a]++] = unsigned(i);
  50. adjacency.data[adjacency.offsets[b]++] = unsigned(i);
  51. adjacency.data[adjacency.offsets[c]++] = unsigned(i);
  52. }
  53. // fix offsets that have been disturbed by the previous pass
  54. for (size_t i = 0; i < vertex_count; ++i)
  55. {
  56. assert(adjacency.offsets[i] >= adjacency.counts[i]);
  57. adjacency.offsets[i] -= adjacency.counts[i];
  58. }
  59. }
  60. static void computeBoundingSphere(float result[4], const float points[][3], size_t count)
  61. {
  62. assert(count > 0);
  63. // find extremum points along all 3 axes; for each axis we get a pair of points with min/max coordinates
  64. size_t pmin[3] = {0, 0, 0};
  65. size_t pmax[3] = {0, 0, 0};
  66. for (size_t i = 0; i < count; ++i)
  67. {
  68. const float* p = points[i];
  69. for (int axis = 0; axis < 3; ++axis)
  70. {
  71. pmin[axis] = (p[axis] < points[pmin[axis]][axis]) ? i : pmin[axis];
  72. pmax[axis] = (p[axis] > points[pmax[axis]][axis]) ? i : pmax[axis];
  73. }
  74. }
  75. // find the pair of points with largest distance
  76. float paxisd2 = 0;
  77. int paxis = 0;
  78. for (int axis = 0; axis < 3; ++axis)
  79. {
  80. const float* p1 = points[pmin[axis]];
  81. const float* p2 = points[pmax[axis]];
  82. float d2 = (p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[2] - p1[2]) * (p2[2] - p1[2]);
  83. if (d2 > paxisd2)
  84. {
  85. paxisd2 = d2;
  86. paxis = axis;
  87. }
  88. }
  89. // use the longest segment as the initial sphere diameter
  90. const float* p1 = points[pmin[paxis]];
  91. const float* p2 = points[pmax[paxis]];
  92. float center[3] = {(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2, (p1[2] + p2[2]) / 2};
  93. float radius = sqrtf(paxisd2) / 2;
  94. // iteratively adjust the sphere up until all points fit
  95. for (size_t i = 0; i < count; ++i)
  96. {
  97. const float* p = points[i];
  98. float d2 = (p[0] - center[0]) * (p[0] - center[0]) + (p[1] - center[1]) * (p[1] - center[1]) + (p[2] - center[2]) * (p[2] - center[2]);
  99. if (d2 > radius * radius)
  100. {
  101. float d = sqrtf(d2);
  102. assert(d > 0);
  103. float k = 0.5f + (radius / d) / 2;
  104. center[0] = center[0] * k + p[0] * (1 - k);
  105. center[1] = center[1] * k + p[1] * (1 - k);
  106. center[2] = center[2] * k + p[2] * (1 - k);
  107. radius = (radius + d) / 2;
  108. }
  109. }
  110. result[0] = center[0];
  111. result[1] = center[1];
  112. result[2] = center[2];
  113. result[3] = radius;
  114. }
  115. struct Cone
  116. {
  117. float px, py, pz;
  118. float nx, ny, nz;
  119. };
  120. static float getMeshletScore(float distance2, float spread, float cone_weight, float expected_radius)
  121. {
  122. float cone = 1.f - spread * cone_weight;
  123. float cone_clamped = cone < 1e-3f ? 1e-3f : cone;
  124. return (1 + sqrtf(distance2) / expected_radius * (1 - cone_weight)) * cone_clamped;
  125. }
  126. static Cone getMeshletCone(const Cone& acc, unsigned int triangle_count)
  127. {
  128. Cone result = acc;
  129. float center_scale = triangle_count == 0 ? 0.f : 1.f / float(triangle_count);
  130. result.px *= center_scale;
  131. result.py *= center_scale;
  132. result.pz *= center_scale;
  133. float axis_length = result.nx * result.nx + result.ny * result.ny + result.nz * result.nz;
  134. float axis_scale = axis_length == 0.f ? 0.f : 1.f / sqrtf(axis_length);
  135. result.nx *= axis_scale;
  136. result.ny *= axis_scale;
  137. result.nz *= axis_scale;
  138. return result;
  139. }
  140. static float computeTriangleCones(Cone* triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  141. {
  142. (void)vertex_count;
  143. size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
  144. size_t face_count = index_count / 3;
  145. float mesh_area = 0;
  146. for (size_t i = 0; i < face_count; ++i)
  147. {
  148. unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
  149. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  150. const float* p0 = vertex_positions + vertex_stride_float * a;
  151. const float* p1 = vertex_positions + vertex_stride_float * b;
  152. const float* p2 = vertex_positions + vertex_stride_float * c;
  153. float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]};
  154. float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]};
  155. float normalx = p10[1] * p20[2] - p10[2] * p20[1];
  156. float normaly = p10[2] * p20[0] - p10[0] * p20[2];
  157. float normalz = p10[0] * p20[1] - p10[1] * p20[0];
  158. float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz);
  159. float invarea = (area == 0.f) ? 0.f : 1.f / area;
  160. triangles[i].px = (p0[0] + p1[0] + p2[0]) / 3.f;
  161. triangles[i].py = (p0[1] + p1[1] + p2[1]) / 3.f;
  162. triangles[i].pz = (p0[2] + p1[2] + p2[2]) / 3.f;
  163. triangles[i].nx = normalx * invarea;
  164. triangles[i].ny = normaly * invarea;
  165. triangles[i].nz = normalz * invarea;
  166. mesh_area += area;
  167. }
  168. return mesh_area;
  169. }
  170. static void finishMeshlet(meshopt_Meshlet& meshlet, unsigned char* meshlet_triangles)
  171. {
  172. size_t offset = meshlet.triangle_offset + meshlet.triangle_count * 3;
  173. // fill 4b padding with 0
  174. while (offset & 3)
  175. meshlet_triangles[offset++] = 0;
  176. }
  177. static bool appendMeshlet(meshopt_Meshlet& meshlet, unsigned int a, unsigned int b, unsigned int c, unsigned char* used, meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t meshlet_offset, size_t max_vertices, size_t max_triangles)
  178. {
  179. unsigned char& av = used[a];
  180. unsigned char& bv = used[b];
  181. unsigned char& cv = used[c];
  182. bool result = false;
  183. unsigned int used_extra = (av == 0xff) + (bv == 0xff) + (cv == 0xff);
  184. if (meshlet.vertex_count + used_extra > max_vertices || meshlet.triangle_count >= max_triangles)
  185. {
  186. meshlets[meshlet_offset] = meshlet;
  187. for (size_t j = 0; j < meshlet.vertex_count; ++j)
  188. used[meshlet_vertices[meshlet.vertex_offset + j]] = 0xff;
  189. finishMeshlet(meshlet, meshlet_triangles);
  190. meshlet.vertex_offset += meshlet.vertex_count;
  191. meshlet.triangle_offset += (meshlet.triangle_count * 3 + 3) & ~3; // 4b padding
  192. meshlet.vertex_count = 0;
  193. meshlet.triangle_count = 0;
  194. result = true;
  195. }
  196. if (av == 0xff)
  197. {
  198. av = (unsigned char)meshlet.vertex_count;
  199. meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = a;
  200. }
  201. if (bv == 0xff)
  202. {
  203. bv = (unsigned char)meshlet.vertex_count;
  204. meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = b;
  205. }
  206. if (cv == 0xff)
  207. {
  208. cv = (unsigned char)meshlet.vertex_count;
  209. meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = c;
  210. }
  211. meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 0] = av;
  212. meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 1] = bv;
  213. meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 2] = cv;
  214. meshlet.triangle_count++;
  215. return result;
  216. }
  217. struct KDNode
  218. {
  219. union
  220. {
  221. float split;
  222. unsigned int index;
  223. };
  224. // leaves: axis = 3, children = number of extra points after this one (0 if 'index' is the only point)
  225. // branches: axis != 3, left subtree = skip 1, right subtree = skip 1+children
  226. unsigned int axis : 2;
  227. unsigned int children : 30;
  228. };
  229. static size_t kdtreePartition(unsigned int* indices, size_t count, const float* points, size_t stride, unsigned int axis, float pivot)
  230. {
  231. size_t m = 0;
  232. // invariant: elements in range [0, m) are < pivot, elements in range [m, i) are >= pivot
  233. for (size_t i = 0; i < count; ++i)
  234. {
  235. float v = points[indices[i] * stride + axis];
  236. // swap(m, i) unconditionally
  237. unsigned int t = indices[m];
  238. indices[m] = indices[i];
  239. indices[i] = t;
  240. // when v >= pivot, we swap i with m without advancing it, preserving invariants
  241. m += v < pivot;
  242. }
  243. return m;
  244. }
  245. static size_t kdtreeBuildLeaf(size_t offset, KDNode* nodes, size_t node_count, unsigned int* indices, size_t count)
  246. {
  247. assert(offset + count <= node_count);
  248. (void)node_count;
  249. KDNode& result = nodes[offset];
  250. result.index = indices[0];
  251. result.axis = 3;
  252. result.children = unsigned(count - 1);
  253. // all remaining points are stored in nodes immediately following the leaf
  254. for (size_t i = 1; i < count; ++i)
  255. {
  256. KDNode& tail = nodes[offset + i];
  257. tail.index = indices[i];
  258. tail.axis = 3;
  259. tail.children = ~0u >> 2; // bogus value to prevent misuse
  260. }
  261. return offset + count;
  262. }
  263. static size_t kdtreeBuild(size_t offset, KDNode* nodes, size_t node_count, const float* points, size_t stride, unsigned int* indices, size_t count, size_t leaf_size)
  264. {
  265. assert(count > 0);
  266. assert(offset < node_count);
  267. if (count <= leaf_size)
  268. return kdtreeBuildLeaf(offset, nodes, node_count, indices, count);
  269. float mean[3] = {};
  270. float vars[3] = {};
  271. float runc = 1, runs = 1;
  272. // gather statistics on the points in the subtree using Welford's algorithm
  273. for (size_t i = 0; i < count; ++i, runc += 1.f, runs = 1.f / runc)
  274. {
  275. const float* point = points + indices[i] * stride;
  276. for (int k = 0; k < 3; ++k)
  277. {
  278. float delta = point[k] - mean[k];
  279. mean[k] += delta * runs;
  280. vars[k] += delta * (point[k] - mean[k]);
  281. }
  282. }
  283. // split axis is one where the variance is largest
  284. unsigned int axis = vars[0] >= vars[1] && vars[0] >= vars[2] ? 0 : vars[1] >= vars[2] ? 1
  285. : 2;
  286. float split = mean[axis];
  287. size_t middle = kdtreePartition(indices, count, points, stride, axis, split);
  288. // when the partition is degenerate simply consolidate the points into a single node
  289. if (middle <= leaf_size / 2 || middle >= count - leaf_size / 2)
  290. return kdtreeBuildLeaf(offset, nodes, node_count, indices, count);
  291. KDNode& result = nodes[offset];
  292. result.split = split;
  293. result.axis = axis;
  294. // left subtree is right after our node
  295. size_t next_offset = kdtreeBuild(offset + 1, nodes, node_count, points, stride, indices, middle, leaf_size);
  296. // distance to the right subtree is represented explicitly
  297. result.children = unsigned(next_offset - offset - 1);
  298. return kdtreeBuild(next_offset, nodes, node_count, points, stride, indices + middle, count - middle, leaf_size);
  299. }
  300. static void kdtreeNearest(KDNode* nodes, unsigned int root, const float* points, size_t stride, const unsigned char* emitted_flags, const float* position, unsigned int& result, float& limit)
  301. {
  302. const KDNode& node = nodes[root];
  303. if (node.axis == 3)
  304. {
  305. // leaf
  306. for (unsigned int i = 0; i <= node.children; ++i)
  307. {
  308. unsigned int index = nodes[root + i].index;
  309. if (emitted_flags[index])
  310. continue;
  311. const float* point = points + index * stride;
  312. float distance2 =
  313. (point[0] - position[0]) * (point[0] - position[0]) +
  314. (point[1] - position[1]) * (point[1] - position[1]) +
  315. (point[2] - position[2]) * (point[2] - position[2]);
  316. float distance = sqrtf(distance2);
  317. if (distance < limit)
  318. {
  319. result = index;
  320. limit = distance;
  321. }
  322. }
  323. }
  324. else
  325. {
  326. // branch; we order recursion to process the node that search position is in first
  327. float delta = position[node.axis] - node.split;
  328. unsigned int first = (delta <= 0) ? 0 : node.children;
  329. unsigned int second = first ^ node.children;
  330. kdtreeNearest(nodes, root + 1 + first, points, stride, emitted_flags, position, result, limit);
  331. // only process the other node if it can have a match based on closest distance so far
  332. if (fabsf(delta) <= limit)
  333. kdtreeNearest(nodes, root + 1 + second, points, stride, emitted_flags, position, result, limit);
  334. }
  335. }
  336. } // namespace meshopt
  337. size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles)
  338. {
  339. using namespace meshopt;
  340. assert(index_count % 3 == 0);
  341. assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices);
  342. assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles);
  343. assert(max_triangles % 4 == 0); // ensures the caller will compute output space properly as index data is 4b aligned
  344. (void)kMeshletMaxVertices;
  345. (void)kMeshletMaxTriangles;
  346. // meshlet construction is limited by max vertices and max triangles per meshlet
  347. // the worst case is that the input is an unindexed stream since this equally stresses both limits
  348. // note that we assume that in the worst case, we leave 2 vertices unpacked in each meshlet - if we have space for 3 we can pack any triangle
  349. size_t max_vertices_conservative = max_vertices - 2;
  350. size_t meshlet_limit_vertices = (index_count + max_vertices_conservative - 1) / max_vertices_conservative;
  351. size_t meshlet_limit_triangles = (index_count / 3 + max_triangles - 1) / max_triangles;
  352. return meshlet_limit_vertices > meshlet_limit_triangles ? meshlet_limit_vertices : meshlet_limit_triangles;
  353. }
  354. size_t meshopt_buildMeshlets(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)
  355. {
  356. using namespace meshopt;
  357. assert(index_count % 3 == 0);
  358. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  359. assert(vertex_positions_stride % sizeof(float) == 0);
  360. assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices);
  361. assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles);
  362. assert(max_triangles % 4 == 0); // ensures the caller will compute output space properly as index data is 4b aligned
  363. meshopt_Allocator allocator;
  364. TriangleAdjacency2 adjacency = {};
  365. buildTriangleAdjacency(adjacency, indices, index_count, vertex_count, allocator);
  366. unsigned int* live_triangles = allocator.allocate<unsigned int>(vertex_count);
  367. memcpy(live_triangles, adjacency.counts, vertex_count * sizeof(unsigned int));
  368. size_t face_count = index_count / 3;
  369. unsigned char* emitted_flags = allocator.allocate<unsigned char>(face_count);
  370. memset(emitted_flags, 0, face_count);
  371. // for each triangle, precompute centroid & normal to use for scoring
  372. Cone* triangles = allocator.allocate<Cone>(face_count);
  373. float mesh_area = computeTriangleCones(triangles, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  374. // assuming each meshlet is a square patch, expected radius is sqrt(expected area)
  375. float triangle_area_avg = face_count == 0 ? 0.f : mesh_area / float(face_count) * 0.5f;
  376. float meshlet_expected_radius = sqrtf(triangle_area_avg * max_triangles) * 0.5f;
  377. // build a kd-tree for nearest neighbor lookup
  378. unsigned int* kdindices = allocator.allocate<unsigned int>(face_count);
  379. for (size_t i = 0; i < face_count; ++i)
  380. kdindices[i] = unsigned(i);
  381. KDNode* nodes = allocator.allocate<KDNode>(face_count * 2);
  382. kdtreeBuild(0, nodes, face_count * 2, &triangles[0].px, sizeof(Cone) / sizeof(float), kdindices, face_count, /* leaf_size= */ 8);
  383. // index of the vertex in the meshlet, 0xff if the vertex isn't used
  384. unsigned char* used = allocator.allocate<unsigned char>(vertex_count);
  385. memset(used, -1, vertex_count);
  386. meshopt_Meshlet meshlet = {};
  387. size_t meshlet_offset = 0;
  388. Cone meshlet_cone_acc = {};
  389. for (;;)
  390. {
  391. unsigned int best_triangle = ~0u;
  392. unsigned int best_extra = 5;
  393. float best_score = FLT_MAX;
  394. Cone meshlet_cone = getMeshletCone(meshlet_cone_acc, meshlet.triangle_count);
  395. for (size_t i = 0; i < meshlet.vertex_count; ++i)
  396. {
  397. unsigned int index = meshlet_vertices[meshlet.vertex_offset + i];
  398. unsigned int* neighbours = &adjacency.data[0] + adjacency.offsets[index];
  399. size_t neighbours_size = adjacency.counts[index];
  400. for (size_t j = 0; j < neighbours_size; ++j)
  401. {
  402. unsigned int triangle = neighbours[j];
  403. assert(!emitted_flags[triangle]);
  404. unsigned int a = indices[triangle * 3 + 0], b = indices[triangle * 3 + 1], c = indices[triangle * 3 + 2];
  405. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  406. unsigned int extra = (used[a] == 0xff) + (used[b] == 0xff) + (used[c] == 0xff);
  407. // triangles that don't add new vertices to meshlets are max. priority
  408. if (extra != 0)
  409. {
  410. // artificially increase the priority of dangling triangles as they're expensive to add to new meshlets
  411. if (live_triangles[a] == 1 || live_triangles[b] == 1 || live_triangles[c] == 1)
  412. extra = 0;
  413. extra++;
  414. }
  415. // since topology-based priority is always more important than the score, we can skip scoring in some cases
  416. if (extra > best_extra)
  417. continue;
  418. const Cone& tri_cone = triangles[triangle];
  419. float distance2 =
  420. (tri_cone.px - meshlet_cone.px) * (tri_cone.px - meshlet_cone.px) +
  421. (tri_cone.py - meshlet_cone.py) * (tri_cone.py - meshlet_cone.py) +
  422. (tri_cone.pz - meshlet_cone.pz) * (tri_cone.pz - meshlet_cone.pz);
  423. float spread = tri_cone.nx * meshlet_cone.nx + tri_cone.ny * meshlet_cone.ny + tri_cone.nz * meshlet_cone.nz;
  424. float score = getMeshletScore(distance2, spread, cone_weight, meshlet_expected_radius);
  425. // note that topology-based priority is always more important than the score
  426. // this helps maintain reasonable effectiveness of meshlet data and reduces scoring cost
  427. if (extra < best_extra || score < best_score)
  428. {
  429. best_triangle = triangle;
  430. best_extra = extra;
  431. best_score = score;
  432. }
  433. }
  434. }
  435. if (best_triangle == ~0u)
  436. {
  437. float position[3] = {meshlet_cone.px, meshlet_cone.py, meshlet_cone.pz};
  438. unsigned int index = ~0u;
  439. float limit = FLT_MAX;
  440. kdtreeNearest(nodes, 0, &triangles[0].px, sizeof(Cone) / sizeof(float), emitted_flags, position, index, limit);
  441. best_triangle = index;
  442. }
  443. if (best_triangle == ~0u)
  444. break;
  445. unsigned int a = indices[best_triangle * 3 + 0], b = indices[best_triangle * 3 + 1], c = indices[best_triangle * 3 + 2];
  446. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  447. // add meshlet to the output; when the current meshlet is full we reset the accumulated bounds
  448. if (appendMeshlet(meshlet, a, b, c, used, meshlets, meshlet_vertices, meshlet_triangles, meshlet_offset, max_vertices, max_triangles))
  449. {
  450. meshlet_offset++;
  451. memset(&meshlet_cone_acc, 0, sizeof(meshlet_cone_acc));
  452. }
  453. live_triangles[a]--;
  454. live_triangles[b]--;
  455. live_triangles[c]--;
  456. // remove emitted triangle from adjacency data
  457. // this makes sure that we spend less time traversing these lists on subsequent iterations
  458. for (size_t k = 0; k < 3; ++k)
  459. {
  460. unsigned int index = indices[best_triangle * 3 + k];
  461. unsigned int* neighbours = &adjacency.data[0] + adjacency.offsets[index];
  462. size_t neighbours_size = adjacency.counts[index];
  463. for (size_t i = 0; i < neighbours_size; ++i)
  464. {
  465. unsigned int tri = neighbours[i];
  466. if (tri == best_triangle)
  467. {
  468. neighbours[i] = neighbours[neighbours_size - 1];
  469. adjacency.counts[index]--;
  470. break;
  471. }
  472. }
  473. }
  474. // update aggregated meshlet cone data for scoring subsequent triangles
  475. meshlet_cone_acc.px += triangles[best_triangle].px;
  476. meshlet_cone_acc.py += triangles[best_triangle].py;
  477. meshlet_cone_acc.pz += triangles[best_triangle].pz;
  478. meshlet_cone_acc.nx += triangles[best_triangle].nx;
  479. meshlet_cone_acc.ny += triangles[best_triangle].ny;
  480. meshlet_cone_acc.nz += triangles[best_triangle].nz;
  481. emitted_flags[best_triangle] = 1;
  482. }
  483. if (meshlet.triangle_count)
  484. {
  485. finishMeshlet(meshlet, meshlet_triangles);
  486. meshlets[meshlet_offset++] = meshlet;
  487. }
  488. assert(meshlet_offset <= meshopt_buildMeshletsBound(index_count, max_vertices, max_triangles));
  489. return meshlet_offset;
  490. }
  491. size_t meshopt_buildMeshletsScan(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)
  492. {
  493. using namespace meshopt;
  494. assert(index_count % 3 == 0);
  495. assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices);
  496. assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles);
  497. assert(max_triangles % 4 == 0); // ensures the caller will compute output space properly as index data is 4b aligned
  498. meshopt_Allocator allocator;
  499. // index of the vertex in the meshlet, 0xff if the vertex isn't used
  500. unsigned char* used = allocator.allocate<unsigned char>(vertex_count);
  501. memset(used, -1, vertex_count);
  502. meshopt_Meshlet meshlet = {};
  503. size_t meshlet_offset = 0;
  504. for (size_t i = 0; i < index_count; i += 3)
  505. {
  506. unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];
  507. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  508. // appends triangle to the meshlet and writes previous meshlet to the output if full
  509. meshlet_offset += appendMeshlet(meshlet, a, b, c, used, meshlets, meshlet_vertices, meshlet_triangles, meshlet_offset, max_vertices, max_triangles);
  510. }
  511. if (meshlet.triangle_count)
  512. {
  513. finishMeshlet(meshlet, meshlet_triangles);
  514. meshlets[meshlet_offset++] = meshlet;
  515. }
  516. assert(meshlet_offset <= meshopt_buildMeshletsBound(index_count, max_vertices, max_triangles));
  517. return meshlet_offset;
  518. }
  519. 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)
  520. {
  521. using namespace meshopt;
  522. assert(index_count % 3 == 0);
  523. assert(index_count / 3 <= kMeshletMaxTriangles);
  524. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  525. assert(vertex_positions_stride % sizeof(float) == 0);
  526. (void)vertex_count;
  527. size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
  528. // compute triangle normals and gather triangle corners
  529. float normals[kMeshletMaxTriangles][3];
  530. float corners[kMeshletMaxTriangles][3][3];
  531. size_t triangles = 0;
  532. for (size_t i = 0; i < index_count; i += 3)
  533. {
  534. unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];
  535. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  536. const float* p0 = vertex_positions + vertex_stride_float * a;
  537. const float* p1 = vertex_positions + vertex_stride_float * b;
  538. const float* p2 = vertex_positions + vertex_stride_float * c;
  539. float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]};
  540. float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]};
  541. float normalx = p10[1] * p20[2] - p10[2] * p20[1];
  542. float normaly = p10[2] * p20[0] - p10[0] * p20[2];
  543. float normalz = p10[0] * p20[1] - p10[1] * p20[0];
  544. float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz);
  545. // no need to include degenerate triangles - they will be invisible anyway
  546. if (area == 0.f)
  547. continue;
  548. // record triangle normals & corners for future use; normal and corner 0 define a plane equation
  549. normals[triangles][0] = normalx / area;
  550. normals[triangles][1] = normaly / area;
  551. normals[triangles][2] = normalz / area;
  552. memcpy(corners[triangles][0], p0, 3 * sizeof(float));
  553. memcpy(corners[triangles][1], p1, 3 * sizeof(float));
  554. memcpy(corners[triangles][2], p2, 3 * sizeof(float));
  555. triangles++;
  556. }
  557. meshopt_Bounds bounds = {};
  558. // degenerate cluster, no valid triangles => trivial reject (cone data is 0)
  559. if (triangles == 0)
  560. return bounds;
  561. // compute cluster bounding sphere; we'll use the center to determine normal cone apex as well
  562. float psphere[4] = {};
  563. computeBoundingSphere(psphere, corners[0], triangles * 3);
  564. float center[3] = {psphere[0], psphere[1], psphere[2]};
  565. // treating triangle normals as points, find the bounding sphere - the sphere center determines the optimal cone axis
  566. float nsphere[4] = {};
  567. computeBoundingSphere(nsphere, normals, triangles);
  568. float axis[3] = {nsphere[0], nsphere[1], nsphere[2]};
  569. float axislength = sqrtf(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]);
  570. float invaxislength = axislength == 0.f ? 0.f : 1.f / axislength;
  571. axis[0] *= invaxislength;
  572. axis[1] *= invaxislength;
  573. axis[2] *= invaxislength;
  574. // compute a tight cone around all normals, mindp = cos(angle/2)
  575. float mindp = 1.f;
  576. for (size_t i = 0; i < triangles; ++i)
  577. {
  578. float dp = normals[i][0] * axis[0] + normals[i][1] * axis[1] + normals[i][2] * axis[2];
  579. mindp = (dp < mindp) ? dp : mindp;
  580. }
  581. // fill bounding sphere info; note that below we can return bounds without cone information for degenerate cones
  582. bounds.center[0] = center[0];
  583. bounds.center[1] = center[1];
  584. bounds.center[2] = center[2];
  585. bounds.radius = psphere[3];
  586. // degenerate cluster, normal cone is larger than a hemisphere => trivial accept
  587. // note that if mindp is positive but close to 0, the triangle intersection code below gets less stable
  588. // we arbitrarily decide that if a normal cone is ~168 degrees wide or more, the cone isn't useful
  589. if (mindp <= 0.1f)
  590. {
  591. bounds.cone_cutoff = 1;
  592. bounds.cone_cutoff_s8 = 127;
  593. return bounds;
  594. }
  595. float maxt = 0;
  596. // we need to find the point on center-t*axis ray that lies in negative half-space of all triangles
  597. for (size_t i = 0; i < triangles; ++i)
  598. {
  599. // dot(center-t*axis-corner, trinormal) = 0
  600. // dot(center-corner, trinormal) - t * dot(axis, trinormal) = 0
  601. float cx = center[0] - corners[i][0][0];
  602. float cy = center[1] - corners[i][0][1];
  603. float cz = center[2] - corners[i][0][2];
  604. float dc = cx * normals[i][0] + cy * normals[i][1] + cz * normals[i][2];
  605. float dn = axis[0] * normals[i][0] + axis[1] * normals[i][1] + axis[2] * normals[i][2];
  606. // dn should be larger than mindp cutoff above
  607. assert(dn > 0.f);
  608. float t = dc / dn;
  609. maxt = (t > maxt) ? t : maxt;
  610. }
  611. // cone apex should be in the negative half-space of all cluster triangles by construction
  612. bounds.cone_apex[0] = center[0] - axis[0] * maxt;
  613. bounds.cone_apex[1] = center[1] - axis[1] * maxt;
  614. bounds.cone_apex[2] = center[2] - axis[2] * maxt;
  615. // note: this axis is the axis of the normal cone, but our test for perspective camera effectively negates the axis
  616. bounds.cone_axis[0] = axis[0];
  617. bounds.cone_axis[1] = axis[1];
  618. bounds.cone_axis[2] = axis[2];
  619. // cos(a) for normal cone is mindp; we need to add 90 degrees on both sides and invert the cone
  620. // which gives us -cos(a+90) = -(-sin(a)) = sin(a) = sqrt(1 - cos^2(a))
  621. bounds.cone_cutoff = sqrtf(1 - mindp * mindp);
  622. // quantize axis & cutoff to 8-bit SNORM format
  623. bounds.cone_axis_s8[0] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[0], 8));
  624. bounds.cone_axis_s8[1] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[1], 8));
  625. bounds.cone_axis_s8[2] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[2], 8));
  626. // for the 8-bit test to be conservative, we need to adjust the cutoff by measuring the max. error
  627. float cone_axis_s8_e0 = fabsf(bounds.cone_axis_s8[0] / 127.f - bounds.cone_axis[0]);
  628. float cone_axis_s8_e1 = fabsf(bounds.cone_axis_s8[1] / 127.f - bounds.cone_axis[1]);
  629. float cone_axis_s8_e2 = fabsf(bounds.cone_axis_s8[2] / 127.f - bounds.cone_axis[2]);
  630. // note that we need to round this up instead of rounding to nearest, hence +1
  631. int cone_cutoff_s8 = int(127 * (bounds.cone_cutoff + cone_axis_s8_e0 + cone_axis_s8_e1 + cone_axis_s8_e2) + 1);
  632. bounds.cone_cutoff_s8 = (cone_cutoff_s8 > 127) ? 127 : (signed char)(cone_cutoff_s8);
  633. return bounds;
  634. }
  635. 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)
  636. {
  637. using namespace meshopt;
  638. assert(triangle_count <= kMeshletMaxTriangles);
  639. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  640. assert(vertex_positions_stride % sizeof(float) == 0);
  641. unsigned int indices[kMeshletMaxTriangles * 3];
  642. for (size_t i = 0; i < triangle_count * 3; ++i)
  643. {
  644. unsigned int index = meshlet_vertices[meshlet_triangles[i]];
  645. assert(index < vertex_count);
  646. indices[i] = index;
  647. }
  648. return meshopt_computeClusterBounds(indices, triangle_count * 3, vertex_positions, vertex_count, vertex_positions_stride);
  649. }