simplifier.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  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. #ifndef TRACE
  8. #define TRACE 0
  9. #endif
  10. #if TRACE
  11. #include <stdio.h>
  12. #endif
  13. #if TRACE
  14. #define TRACESTATS(i) stats[i]++;
  15. #else
  16. #define TRACESTATS(i) (void)0
  17. #endif
  18. #define ATTRIBUTES 3
  19. // This work is based on:
  20. // Michael Garland and Paul S. Heckbert. Surface simplification using quadric error metrics. 1997
  21. // Michael Garland. Quadric-based polygonal surface simplification. 1999
  22. // Peter Lindstrom. Out-of-Core Simplification of Large Polygonal Models. 2000
  23. // Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 2003
  24. // Peter Van Sandt, Yannis Chronis, Jignesh M. Patel. Efficiently Searching In-Memory Sorted Arrays: Revenge of the Interpolation Search? 2019
  25. namespace meshopt
  26. {
  27. struct EdgeAdjacency
  28. {
  29. struct Edge
  30. {
  31. unsigned int next;
  32. unsigned int prev;
  33. };
  34. unsigned int* counts;
  35. unsigned int* offsets;
  36. Edge* data;
  37. };
  38. static void prepareEdgeAdjacency(EdgeAdjacency& adjacency, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)
  39. {
  40. adjacency.counts = allocator.allocate<unsigned int>(vertex_count);
  41. adjacency.offsets = allocator.allocate<unsigned int>(vertex_count);
  42. adjacency.data = allocator.allocate<EdgeAdjacency::Edge>(index_count);
  43. }
  44. static void updateEdgeAdjacency(EdgeAdjacency& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, const unsigned int* remap)
  45. {
  46. size_t face_count = index_count / 3;
  47. // fill edge counts
  48. memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int));
  49. for (size_t i = 0; i < index_count; ++i)
  50. {
  51. unsigned int v = remap ? remap[indices[i]] : indices[i];
  52. assert(v < vertex_count);
  53. adjacency.counts[v]++;
  54. }
  55. // fill offset table
  56. unsigned int offset = 0;
  57. for (size_t i = 0; i < vertex_count; ++i)
  58. {
  59. adjacency.offsets[i] = offset;
  60. offset += adjacency.counts[i];
  61. }
  62. assert(offset == index_count);
  63. // fill edge data
  64. for (size_t i = 0; i < face_count; ++i)
  65. {
  66. unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
  67. if (remap)
  68. {
  69. a = remap[a];
  70. b = remap[b];
  71. c = remap[c];
  72. }
  73. adjacency.data[adjacency.offsets[a]].next = b;
  74. adjacency.data[adjacency.offsets[a]].prev = c;
  75. adjacency.offsets[a]++;
  76. adjacency.data[adjacency.offsets[b]].next = c;
  77. adjacency.data[adjacency.offsets[b]].prev = a;
  78. adjacency.offsets[b]++;
  79. adjacency.data[adjacency.offsets[c]].next = a;
  80. adjacency.data[adjacency.offsets[c]].prev = b;
  81. adjacency.offsets[c]++;
  82. }
  83. // fix offsets that have been disturbed by the previous pass
  84. for (size_t i = 0; i < vertex_count; ++i)
  85. {
  86. assert(adjacency.offsets[i] >= adjacency.counts[i]);
  87. adjacency.offsets[i] -= adjacency.counts[i];
  88. }
  89. }
  90. struct PositionHasher
  91. {
  92. const float* vertex_positions;
  93. size_t vertex_stride_float;
  94. size_t hash(unsigned int index) const
  95. {
  96. const unsigned int* key = reinterpret_cast<const unsigned int*>(vertex_positions + index * vertex_stride_float);
  97. // scramble bits to make sure that integer coordinates have entropy in lower bits
  98. unsigned int x = key[0] ^ (key[0] >> 17);
  99. unsigned int y = key[1] ^ (key[1] >> 17);
  100. unsigned int z = key[2] ^ (key[2] >> 17);
  101. // Optimized Spatial Hashing for Collision Detection of Deformable Objects
  102. return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791);
  103. }
  104. bool equal(unsigned int lhs, unsigned int rhs) const
  105. {
  106. return memcmp(vertex_positions + lhs * vertex_stride_float, vertex_positions + rhs * vertex_stride_float, sizeof(float) * 3) == 0;
  107. }
  108. };
  109. static size_t hashBuckets2(size_t count)
  110. {
  111. size_t buckets = 1;
  112. while (buckets < count + count / 4)
  113. buckets *= 2;
  114. return buckets;
  115. }
  116. template <typename T, typename Hash>
  117. static T* hashLookup2(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty)
  118. {
  119. assert(buckets > 0);
  120. assert((buckets & (buckets - 1)) == 0);
  121. size_t hashmod = buckets - 1;
  122. size_t bucket = hash.hash(key) & hashmod;
  123. for (size_t probe = 0; probe <= hashmod; ++probe)
  124. {
  125. T& item = table[bucket];
  126. if (item == empty)
  127. return &item;
  128. if (hash.equal(item, key))
  129. return &item;
  130. // hash collision, quadratic probing
  131. bucket = (bucket + probe + 1) & hashmod;
  132. }
  133. assert(false && "Hash table is full"); // unreachable
  134. return 0;
  135. }
  136. static void buildPositionRemap(unsigned int* remap, unsigned int* wedge, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, meshopt_Allocator& allocator)
  137. {
  138. PositionHasher hasher = {vertex_positions_data, vertex_positions_stride / sizeof(float)};
  139. size_t table_size = hashBuckets2(vertex_count);
  140. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  141. memset(table, -1, table_size * sizeof(unsigned int));
  142. // build forward remap: for each vertex, which other (canonical) vertex does it map to?
  143. // we use position equivalence for this, and remap vertices to other existing vertices
  144. for (size_t i = 0; i < vertex_count; ++i)
  145. {
  146. unsigned int index = unsigned(i);
  147. unsigned int* entry = hashLookup2(table, table_size, hasher, index, ~0u);
  148. if (*entry == ~0u)
  149. *entry = index;
  150. remap[index] = *entry;
  151. }
  152. // build wedge table: for each vertex, which other vertex is the next wedge that also maps to the same vertex?
  153. // entries in table form a (cyclic) wedge loop per vertex; for manifold vertices, wedge[i] == remap[i] == i
  154. for (size_t i = 0; i < vertex_count; ++i)
  155. wedge[i] = unsigned(i);
  156. for (size_t i = 0; i < vertex_count; ++i)
  157. if (remap[i] != i)
  158. {
  159. unsigned int r = remap[i];
  160. wedge[i] = wedge[r];
  161. wedge[r] = unsigned(i);
  162. }
  163. }
  164. enum VertexKind
  165. {
  166. Kind_Manifold, // not on an attribute seam, not on any boundary
  167. Kind_Border, // not on an attribute seam, has exactly two open edges
  168. Kind_Seam, // on an attribute seam with exactly two attribute seam edges
  169. Kind_Complex, // none of the above; these vertices can move as long as all wedges move to the target vertex
  170. Kind_Locked, // none of the above; these vertices can't move
  171. Kind_Count
  172. };
  173. // manifold vertices can collapse onto anything
  174. // border/seam vertices can only be collapsed onto border/seam respectively
  175. // complex vertices can collapse onto complex/locked
  176. // a rule of thumb is that collapsing kind A into kind B preserves the kind B in the target vertex
  177. // for example, while we could collapse Complex into Manifold, this would mean the target vertex isn't Manifold anymore
  178. const unsigned char kCanCollapse[Kind_Count][Kind_Count] = {
  179. {1, 1, 1, 1, 1},
  180. {0, 1, 0, 0, 0},
  181. {0, 0, 1, 0, 0},
  182. {0, 0, 0, 1, 1},
  183. {0, 0, 0, 0, 0},
  184. };
  185. // if a vertex is manifold or seam, adjoining edges are guaranteed to have an opposite edge
  186. // note that for seam edges, the opposite edge isn't present in the attribute-based topology
  187. // but is present if you consider a position-only mesh variant
  188. const unsigned char kHasOpposite[Kind_Count][Kind_Count] = {
  189. {1, 1, 1, 0, 1},
  190. {1, 0, 1, 0, 0},
  191. {1, 1, 1, 0, 1},
  192. {0, 0, 0, 0, 0},
  193. {1, 0, 1, 0, 0},
  194. };
  195. static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b)
  196. {
  197. unsigned int count = adjacency.counts[a];
  198. const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[a];
  199. for (size_t i = 0; i < count; ++i)
  200. if (edges[i].next == b)
  201. return true;
  202. return false;
  203. }
  204. static void classifyVertices(unsigned char* result, unsigned int* loop, unsigned int* loopback, size_t vertex_count, const EdgeAdjacency& adjacency, const unsigned int* remap, const unsigned int* wedge)
  205. {
  206. memset(loop, -1, vertex_count * sizeof(unsigned int));
  207. memset(loopback, -1, vertex_count * sizeof(unsigned int));
  208. // incoming & outgoing open edges: ~0u if no open edges, i if there are more than 1
  209. // note that this is the same data as required in loop[] arrays; loop[] data is only valid for border/seam
  210. // but here it's okay to fill the data out for other types of vertices as well
  211. unsigned int* openinc = loopback;
  212. unsigned int* openout = loop;
  213. for (size_t i = 0; i < vertex_count; ++i)
  214. {
  215. unsigned int vertex = unsigned(i);
  216. unsigned int count = adjacency.counts[vertex];
  217. const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[vertex];
  218. for (size_t j = 0; j < count; ++j)
  219. {
  220. unsigned int target = edges[j].next;
  221. if (!hasEdge(adjacency, target, vertex))
  222. {
  223. openinc[target] = (openinc[target] == ~0u) ? vertex : target;
  224. openout[vertex] = (openout[vertex] == ~0u) ? target : vertex;
  225. }
  226. }
  227. }
  228. #if TRACE
  229. size_t stats[4] = {};
  230. #endif
  231. for (size_t i = 0; i < vertex_count; ++i)
  232. {
  233. if (remap[i] == i)
  234. {
  235. if (wedge[i] == i)
  236. {
  237. // no attribute seam, need to check if it's manifold
  238. unsigned int openi = openinc[i], openo = openout[i];
  239. // note: we classify any vertices with no open edges as manifold
  240. // this is technically incorrect - if 4 triangles share an edge, we'll classify vertices as manifold
  241. // it's unclear if this is a problem in practice
  242. if (openi == ~0u && openo == ~0u)
  243. {
  244. result[i] = Kind_Manifold;
  245. }
  246. else if (openi != i && openo != i)
  247. {
  248. result[i] = Kind_Border;
  249. }
  250. else
  251. {
  252. result[i] = Kind_Locked;
  253. TRACESTATS(0);
  254. }
  255. }
  256. else if (wedge[wedge[i]] == i)
  257. {
  258. // attribute seam; need to distinguish between Seam and Locked
  259. unsigned int w = wedge[i];
  260. unsigned int openiv = openinc[i], openov = openout[i];
  261. unsigned int openiw = openinc[w], openow = openout[w];
  262. // seam should have one open half-edge for each vertex, and the edges need to "connect" - point to the same vertex post-remap
  263. if (openiv != ~0u && openiv != i && openov != ~0u && openov != i &&
  264. openiw != ~0u && openiw != w && openow != ~0u && openow != w)
  265. {
  266. if (remap[openiv] == remap[openow] && remap[openov] == remap[openiw])
  267. {
  268. result[i] = Kind_Seam;
  269. }
  270. else
  271. {
  272. result[i] = Kind_Locked;
  273. TRACESTATS(1);
  274. }
  275. }
  276. else
  277. {
  278. result[i] = Kind_Locked;
  279. TRACESTATS(2);
  280. }
  281. }
  282. else
  283. {
  284. // more than one vertex maps to this one; we don't have classification available
  285. result[i] = Kind_Locked;
  286. TRACESTATS(3);
  287. }
  288. }
  289. else
  290. {
  291. assert(remap[i] < i);
  292. result[i] = result[remap[i]];
  293. }
  294. }
  295. #if TRACE
  296. printf("locked: many open edges %d, disconnected seam %d, many seam edges %d, many wedges %d\n",
  297. int(stats[0]), int(stats[1]), int(stats[2]), int(stats[3]));
  298. #endif
  299. }
  300. struct Vector3
  301. {
  302. float x, y, z;
  303. #if ATTRIBUTES
  304. float a[ATTRIBUTES];
  305. #endif
  306. };
  307. static float rescalePositions(Vector3* result, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride)
  308. {
  309. size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
  310. float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};
  311. float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
  312. for (size_t i = 0; i < vertex_count; ++i)
  313. {
  314. const float* v = vertex_positions_data + i * vertex_stride_float;
  315. if (result)
  316. {
  317. result[i].x = v[0];
  318. result[i].y = v[1];
  319. result[i].z = v[2];
  320. }
  321. for (int j = 0; j < 3; ++j)
  322. {
  323. float vj = v[j];
  324. minv[j] = minv[j] > vj ? vj : minv[j];
  325. maxv[j] = maxv[j] < vj ? vj : maxv[j];
  326. }
  327. }
  328. float extent = 0.f;
  329. extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]);
  330. extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]);
  331. extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]);
  332. if (result)
  333. {
  334. float scale = extent == 0 ? 0.f : 1.f / extent;
  335. for (size_t i = 0; i < vertex_count; ++i)
  336. {
  337. result[i].x = (result[i].x - minv[0]) * scale;
  338. result[i].y = (result[i].y - minv[1]) * scale;
  339. result[i].z = (result[i].z - minv[2]) * scale;
  340. }
  341. }
  342. return extent;
  343. }
  344. struct Quadric
  345. {
  346. float a00, a11, a22;
  347. float a10, a20, a21;
  348. float b0, b1, b2, c;
  349. float w;
  350. #if ATTRIBUTES
  351. float gx[ATTRIBUTES];
  352. float gy[ATTRIBUTES];
  353. float gz[ATTRIBUTES];
  354. float gw[ATTRIBUTES];
  355. #endif
  356. };
  357. struct Collapse
  358. {
  359. unsigned int v0;
  360. unsigned int v1;
  361. union
  362. {
  363. unsigned int bidi;
  364. float error;
  365. unsigned int errorui;
  366. };
  367. float distance_error;
  368. };
  369. static float normalize(Vector3& v)
  370. {
  371. float length = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
  372. if (length > 0)
  373. {
  374. v.x /= length;
  375. v.y /= length;
  376. v.z /= length;
  377. }
  378. return length;
  379. }
  380. static void quadricAdd(Quadric& Q, const Quadric& R)
  381. {
  382. Q.a00 += R.a00;
  383. Q.a11 += R.a11;
  384. Q.a22 += R.a22;
  385. Q.a10 += R.a10;
  386. Q.a20 += R.a20;
  387. Q.a21 += R.a21;
  388. Q.b0 += R.b0;
  389. Q.b1 += R.b1;
  390. Q.b2 += R.b2;
  391. Q.c += R.c;
  392. Q.w += R.w;
  393. #if ATTRIBUTES
  394. for (int k = 0; k < ATTRIBUTES; ++k)
  395. {
  396. Q.gx[k] += R.gx[k];
  397. Q.gy[k] += R.gy[k];
  398. Q.gz[k] += R.gz[k];
  399. Q.gw[k] += R.gw[k];
  400. }
  401. #endif
  402. }
  403. static float quadricError(const Quadric& Q, const Vector3& v)
  404. {
  405. float rx = Q.b0;
  406. float ry = Q.b1;
  407. float rz = Q.b2;
  408. rx += Q.a10 * v.y;
  409. ry += Q.a21 * v.z;
  410. rz += Q.a20 * v.x;
  411. rx *= 2;
  412. ry *= 2;
  413. rz *= 2;
  414. rx += Q.a00 * v.x;
  415. ry += Q.a11 * v.y;
  416. rz += Q.a22 * v.z;
  417. float r = Q.c;
  418. r += rx * v.x;
  419. r += ry * v.y;
  420. r += rz * v.z;
  421. #if ATTRIBUTES
  422. // see quadricUpdateAttributes for general derivation; here we need to add the parts of (eval(pos) - attr)^2 that depend on attr
  423. for (int k = 0; k < ATTRIBUTES; ++k)
  424. {
  425. float a = v.a[k];
  426. r += a * a * Q.w;
  427. r -= 2 * a * (v.x * Q.gx[k] + v.y * Q.gy[k] + v.z * Q.gz[k] + Q.gw[k]);
  428. }
  429. #endif
  430. float s = Q.w == 0.f ? 0.f : 1.f / Q.w;
  431. return fabsf(r) * s;
  432. }
  433. static float quadricErrorNoAttributes(const Quadric& Q, const Vector3& v)
  434. {
  435. float rx = Q.b0;
  436. float ry = Q.b1;
  437. float rz = Q.b2;
  438. rx += Q.a10 * v.y;
  439. ry += Q.a21 * v.z;
  440. rz += Q.a20 * v.x;
  441. rx *= 2;
  442. ry *= 2;
  443. rz *= 2;
  444. rx += Q.a00 * v.x;
  445. ry += Q.a11 * v.y;
  446. rz += Q.a22 * v.z;
  447. float r = Q.c;
  448. r += rx * v.x;
  449. r += ry * v.y;
  450. r += rz * v.z;
  451. float s = Q.w == 0.f ? 0.f : 1.f / Q.w;
  452. return fabsf(r) * s;
  453. }
  454. static void quadricFromPlane(Quadric& Q, float a, float b, float c, float d, float w)
  455. {
  456. float aw = a * w;
  457. float bw = b * w;
  458. float cw = c * w;
  459. float dw = d * w;
  460. Q.a00 = a * aw;
  461. Q.a11 = b * bw;
  462. Q.a22 = c * cw;
  463. Q.a10 = a * bw;
  464. Q.a20 = a * cw;
  465. Q.a21 = b * cw;
  466. Q.b0 = a * dw;
  467. Q.b1 = b * dw;
  468. Q.b2 = c * dw;
  469. Q.c = d * dw;
  470. Q.w = w;
  471. #if ATTRIBUTES
  472. memset(Q.gx, 0, sizeof(Q.gx));
  473. memset(Q.gy, 0, sizeof(Q.gy));
  474. memset(Q.gz, 0, sizeof(Q.gz));
  475. memset(Q.gw, 0, sizeof(Q.gw));
  476. #endif
  477. }
  478. static void quadricFromPoint(Quadric& Q, float x, float y, float z, float w)
  479. {
  480. // we need to encode (x - X) ^ 2 + (y - Y)^2 + (z - Z)^2 into the quadric
  481. Q.a00 = w;
  482. Q.a11 = w;
  483. Q.a22 = w;
  484. Q.a10 = 0.f;
  485. Q.a20 = 0.f;
  486. Q.a21 = 0.f;
  487. Q.b0 = -2.f * x * w;
  488. Q.b1 = -2.f * y * w;
  489. Q.b2 = -2.f * z * w;
  490. Q.c = (x * x + y * y + z * z) * w;
  491. Q.w = w;
  492. }
  493. static void quadricFromTriangle(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)
  494. {
  495. Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};
  496. Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};
  497. // normal = cross(p1 - p0, p2 - p0)
  498. Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};
  499. float area = normalize(normal);
  500. float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;
  501. // we use sqrtf(area) so that the error is scaled linearly; this tends to improve silhouettes
  502. quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, sqrtf(area) * weight);
  503. }
  504. static void quadricFromTriangleEdge(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)
  505. {
  506. Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};
  507. float length = normalize(p10);
  508. // p20p = length of projection of p2-p0 onto normalize(p1 - p0)
  509. Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};
  510. float p20p = p20.x * p10.x + p20.y * p10.y + p20.z * p10.z;
  511. // normal = altitude of triangle from point p2 onto edge p1-p0
  512. Vector3 normal = {p20.x - p10.x * p20p, p20.y - p10.y * p20p, p20.z - p10.z * p20p};
  513. normalize(normal);
  514. float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;
  515. // note: the weight is scaled linearly with edge length; this has to match the triangle weight
  516. quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, length * weight);
  517. }
  518. #if ATTRIBUTES
  519. static void quadricUpdateAttributes(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float w)
  520. {
  521. // for each attribute we want to encode the following function into the quadric:
  522. // (eval(pos) - attr)^2
  523. // where eval(pos) interpolates attribute across the triangle like so:
  524. // eval(pos) = pos.x * gx + pos.y * gy + pos.z * gz + gw
  525. // where gx/gy/gz/gw are gradients
  526. Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};
  527. Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};
  528. // we compute gradients using barycentric coordinates; barycentric coordinates can be computed as follows:
  529. // v = (d11 * d20 - d01 * d21) / denom
  530. // w = (d00 * d21 - d01 * d20) / denom
  531. // u = 1 - v - w
  532. // here v0, v1 are triangle edge vectors, v2 is a vector from point to triangle corner, and dij = dot(vi, vj)
  533. const Vector3& v0 = p10;
  534. const Vector3& v1 = p20;
  535. float d00 = v0.x * v0.x + v0.y * v0.y + v0.z * v0.z;
  536. float d01 = v0.x * v1.x + v0.y * v1.y + v0.z * v1.z;
  537. float d11 = v1.x * v1.x + v1.y * v1.y + v1.z * v1.z;
  538. float denom = d00 * d11 - d01 * d01;
  539. float denomr = denom == 0 ? 0.f : 1.f / denom;
  540. // precompute gradient factors
  541. // these are derived by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w and factoring out common factors that are shared between attributes
  542. float gx1 = (d11 * v0.x - d01 * v1.x) * denomr;
  543. float gx2 = (d00 * v1.x - d01 * v0.x) * denomr;
  544. float gy1 = (d11 * v0.y - d01 * v1.y) * denomr;
  545. float gy2 = (d00 * v1.y - d01 * v0.y) * denomr;
  546. float gz1 = (d11 * v0.z - d01 * v1.z) * denomr;
  547. float gz2 = (d00 * v1.z - d01 * v0.z) * denomr;
  548. for (int k = 0; k < ATTRIBUTES; ++k)
  549. {
  550. float a0 = p0.a[k], a1 = p1.a[k], a2 = p2.a[k];
  551. // compute gradient of eval(pos) for x/y/z/w
  552. // the formulas below are obtained by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w
  553. float gx = gx1 * (a1 - a0) + gx2 * (a2 - a0);
  554. float gy = gy1 * (a1 - a0) + gy2 * (a2 - a0);
  555. float gz = gz1 * (a1 - a0) + gz2 * (a2 - a0);
  556. float gw = a0 - p0.x * gx - p0.y * gy - p0.z * gz;
  557. // quadric encodes (eval(pos)-attr)^2; this means that the resulting expansion needs to compute, for example, pos.x * pos.y * K
  558. // since quadrics already encode factors for pos.x * pos.y, we can accumulate almost everything in basic quadric fields
  559. Q.a00 += w * (gx * gx);
  560. Q.a11 += w * (gy * gy);
  561. Q.a22 += w * (gz * gz);
  562. Q.a10 += w * (gy * gx);
  563. Q.a20 += w * (gz * gx);
  564. Q.a21 += w * (gz * gy);
  565. Q.b0 += w * (gx * gw);
  566. Q.b1 += w * (gy * gw);
  567. Q.b2 += w * (gz * gw);
  568. Q.c += w * (gw * gw);
  569. // the only remaining sum components are ones that depend on attr; these will be addded during error evaluation, see quadricError
  570. Q.gx[k] = w * gx;
  571. Q.gy[k] = w * gy;
  572. Q.gz[k] = w * gz;
  573. Q.gw[k] = w * gw;
  574. #if TRACE > 2
  575. printf("attr%d: %e %e %e\n",
  576. k,
  577. (gx * p0.x + gy * p0.y + gz * p0.z + gw - a0),
  578. (gx * p1.x + gy * p1.y + gz * p1.z + gw - a1),
  579. (gx * p2.x + gy * p2.y + gz * p2.z + gw - a2)
  580. );
  581. #endif
  582. }
  583. }
  584. #endif
  585. static void fillFaceQuadrics(Quadric* vertex_quadrics, Quadric* vertex_no_attrib_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap)
  586. {
  587. for (size_t i = 0; i < index_count; i += 3)
  588. {
  589. unsigned int i0 = indices[i + 0];
  590. unsigned int i1 = indices[i + 1];
  591. unsigned int i2 = indices[i + 2];
  592. Quadric Q;
  593. quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], 1.f);
  594. quadricAdd(vertex_no_attrib_quadrics[remap[i0]], Q);
  595. quadricAdd(vertex_no_attrib_quadrics[remap[i1]], Q);
  596. quadricAdd(vertex_no_attrib_quadrics[remap[i2]], Q);
  597. #if ATTRIBUTES
  598. quadricUpdateAttributes(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], Q.w);
  599. #endif
  600. quadricAdd(vertex_quadrics[remap[i0]], Q);
  601. quadricAdd(vertex_quadrics[remap[i1]], Q);
  602. quadricAdd(vertex_quadrics[remap[i2]], Q);
  603. }
  604. }
  605. static void fillEdgeQuadrics(Quadric* vertex_quadrics, Quadric* vertex_no_attrib_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)
  606. {
  607. for (size_t i = 0; i < index_count; i += 3)
  608. {
  609. static const int next[3] = {1, 2, 0};
  610. for (int e = 0; e < 3; ++e)
  611. {
  612. unsigned int i0 = indices[i + e];
  613. unsigned int i1 = indices[i + next[e]];
  614. unsigned char k0 = vertex_kind[i0];
  615. unsigned char k1 = vertex_kind[i1];
  616. // check that either i0 or i1 are border/seam and are on the same edge loop
  617. // note that we need to add the error even for edged that connect e.g. border & locked
  618. // if we don't do that, the adjacent border->border edge won't have correct errors for corners
  619. if (k0 != Kind_Border && k0 != Kind_Seam && k1 != Kind_Border && k1 != Kind_Seam)
  620. continue;
  621. if ((k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)
  622. continue;
  623. if ((k1 == Kind_Border || k1 == Kind_Seam) && loopback[i1] != i0)
  624. continue;
  625. // seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges
  626. if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])
  627. continue;
  628. unsigned int i2 = indices[i + next[next[e]]];
  629. // we try hard to maintain border edge geometry; seam edges can move more freely
  630. // due to topological restrictions on collapses, seam quadrics slightly improves collapse structure but aren't critical
  631. const float kEdgeWeightSeam = 1.f;
  632. const float kEdgeWeightBorder = 10.f;
  633. float edgeWeight = (k0 == Kind_Border || k1 == Kind_Border) ? kEdgeWeightBorder : kEdgeWeightSeam;
  634. Quadric Q;
  635. quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight);
  636. quadricAdd(vertex_quadrics[remap[i0]], Q);
  637. quadricAdd(vertex_quadrics[remap[i1]], Q);
  638. quadricAdd(vertex_no_attrib_quadrics[remap[i0]], Q);
  639. quadricAdd(vertex_no_attrib_quadrics[remap[i1]], Q);
  640. }
  641. }
  642. }
  643. // does triangle ABC flip when C is replaced with D?
  644. static bool hasTriangleFlip(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d)
  645. {
  646. Vector3 eb = {b.x - a.x, b.y - a.y, b.z - a.z};
  647. Vector3 ec = {c.x - a.x, c.y - a.y, c.z - a.z};
  648. Vector3 ed = {d.x - a.x, d.y - a.y, d.z - a.z};
  649. Vector3 nbc = {eb.y * ec.z - eb.z * ec.y, eb.z * ec.x - eb.x * ec.z, eb.x * ec.y - eb.y * ec.x};
  650. Vector3 nbd = {eb.y * ed.z - eb.z * ed.y, eb.z * ed.x - eb.x * ed.z, eb.x * ed.y - eb.y * ed.x};
  651. return nbc.x * nbd.x + nbc.y * nbd.y + nbc.z * nbd.z < 0;
  652. }
  653. static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, const unsigned int* collapse_remap, unsigned int i0, unsigned int i1)
  654. {
  655. assert(collapse_remap[i0] == i0);
  656. assert(collapse_remap[i1] == i1);
  657. const Vector3& v0 = vertex_positions[i0];
  658. const Vector3& v1 = vertex_positions[i1];
  659. const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]];
  660. size_t count = adjacency.counts[i0];
  661. for (size_t i = 0; i < count; ++i)
  662. {
  663. unsigned int a = collapse_remap[edges[i].next];
  664. unsigned int b = collapse_remap[edges[i].prev];
  665. // skip triangles that get collapsed
  666. // note: this is mathematically redundant as if either of these is true, the dot product in hasTriangleFlip should be 0
  667. if (a == i1 || b == i1)
  668. continue;
  669. // early-out when at least one triangle flips due to a collapse
  670. if (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1))
  671. return true;
  672. }
  673. return false;
  674. }
  675. static size_t pickEdgeCollapses(Collapse* collapses, const unsigned int* indices, size_t index_count, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop)
  676. {
  677. size_t collapse_count = 0;
  678. for (size_t i = 0; i < index_count; i += 3)
  679. {
  680. static const int next[3] = {1, 2, 0};
  681. for (int e = 0; e < 3; ++e)
  682. {
  683. unsigned int i0 = indices[i + e];
  684. unsigned int i1 = indices[i + next[e]];
  685. // this can happen either when input has a zero-length edge, or when we perform collapses for complex
  686. // topology w/seams and collapse a manifold vertex that connects to both wedges onto one of them
  687. // we leave edges like this alone since they may be important for preserving mesh integrity
  688. if (remap[i0] == remap[i1])
  689. continue;
  690. unsigned char k0 = vertex_kind[i0];
  691. unsigned char k1 = vertex_kind[i1];
  692. // the edge has to be collapsible in at least one direction
  693. if (!(kCanCollapse[k0][k1] | kCanCollapse[k1][k0]))
  694. continue;
  695. // manifold and seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges
  696. if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])
  697. continue;
  698. // two vertices are on a border or a seam, but there's no direct edge between them
  699. // this indicates that they belong to two different edge loops and we should not collapse this edge
  700. // loop[] tracks half edges so we only need to check i0->i1
  701. if (k0 == k1 && (k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)
  702. continue;
  703. // edge can be collapsed in either direction - we will pick the one with minimum error
  704. // note: we evaluate error later during collapse ranking, here we just tag the edge as bidirectional
  705. if (kCanCollapse[k0][k1] & kCanCollapse[k1][k0])
  706. {
  707. Collapse c = {i0, i1, {/* bidi= */ 1}};
  708. collapses[collapse_count++] = c;
  709. }
  710. else
  711. {
  712. // edge can only be collapsed in one direction
  713. unsigned int e0 = kCanCollapse[k0][k1] ? i0 : i1;
  714. unsigned int e1 = kCanCollapse[k0][k1] ? i1 : i0;
  715. Collapse c = {e0, e1, {/* bidi= */ 0}};
  716. collapses[collapse_count++] = c;
  717. }
  718. }
  719. }
  720. return collapse_count;
  721. }
  722. static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const Quadric* vertex_quadrics, const Quadric* vertex_no_attrib_quadrics, const unsigned int* remap)
  723. {
  724. for (size_t i = 0; i < collapse_count; ++i)
  725. {
  726. Collapse& c = collapses[i];
  727. unsigned int i0 = c.v0;
  728. unsigned int i1 = c.v1;
  729. // most edges are bidirectional which means we need to evaluate errors for two collapses
  730. // to keep this code branchless we just use the same edge for unidirectional edges
  731. unsigned int j0 = c.bidi ? i1 : i0;
  732. unsigned int j1 = c.bidi ? i0 : i1;
  733. const Quadric& qi = vertex_quadrics[remap[i0]];
  734. const Quadric& qj = vertex_quadrics[remap[j0]];
  735. float ei = quadricError(qi, vertex_positions[i1]);
  736. float ej = quadricError(qj, vertex_positions[j1]);
  737. const Quadric& naqi = vertex_no_attrib_quadrics[remap[i0]];
  738. const Quadric& naqj = vertex_no_attrib_quadrics[remap[j0]];
  739. // pick edge direction with minimal error
  740. c.v0 = ei <= ej ? i0 : j0;
  741. c.v1 = ei <= ej ? i1 : j1;
  742. c.error = ei <= ej ? ei : ej;
  743. c.distance_error = ei <= ej ? quadricErrorNoAttributes(naqi, vertex_positions[i1]) : quadricErrorNoAttributes(naqj, vertex_positions[j1]);
  744. }
  745. }
  746. #if TRACE > 1
  747. static void dumpEdgeCollapses(const Collapse* collapses, size_t collapse_count, const unsigned char* vertex_kind)
  748. {
  749. size_t ckinds[Kind_Count][Kind_Count] = {};
  750. float cerrors[Kind_Count][Kind_Count] = {};
  751. for (int k0 = 0; k0 < Kind_Count; ++k0)
  752. for (int k1 = 0; k1 < Kind_Count; ++k1)
  753. cerrors[k0][k1] = FLT_MAX;
  754. for (size_t i = 0; i < collapse_count; ++i)
  755. {
  756. unsigned int i0 = collapses[i].v0;
  757. unsigned int i1 = collapses[i].v1;
  758. unsigned char k0 = vertex_kind[i0];
  759. unsigned char k1 = vertex_kind[i1];
  760. ckinds[k0][k1]++;
  761. cerrors[k0][k1] = (collapses[i].error < cerrors[k0][k1]) ? collapses[i].error : cerrors[k0][k1];
  762. }
  763. for (int k0 = 0; k0 < Kind_Count; ++k0)
  764. for (int k1 = 0; k1 < Kind_Count; ++k1)
  765. if (ckinds[k0][k1])
  766. printf("collapses %d -> %d: %d, min error %e\n", k0, k1, int(ckinds[k0][k1]), ckinds[k0][k1] ? sqrtf(cerrors[k0][k1]) : 0.f);
  767. }
  768. static void dumpLockedCollapses(const unsigned int* indices, size_t index_count, const unsigned char* vertex_kind)
  769. {
  770. size_t locked_collapses[Kind_Count][Kind_Count] = {};
  771. for (size_t i = 0; i < index_count; i += 3)
  772. {
  773. static const int next[3] = {1, 2, 0};
  774. for (int e = 0; e < 3; ++e)
  775. {
  776. unsigned int i0 = indices[i + e];
  777. unsigned int i1 = indices[i + next[e]];
  778. unsigned char k0 = vertex_kind[i0];
  779. unsigned char k1 = vertex_kind[i1];
  780. locked_collapses[k0][k1] += !kCanCollapse[k0][k1] && !kCanCollapse[k1][k0];
  781. }
  782. }
  783. for (int k0 = 0; k0 < Kind_Count; ++k0)
  784. for (int k1 = 0; k1 < Kind_Count; ++k1)
  785. if (locked_collapses[k0][k1])
  786. printf("locked collapses %d -> %d: %d\n", k0, k1, int(locked_collapses[k0][k1]));
  787. }
  788. #endif
  789. static void sortEdgeCollapses(unsigned int* sort_order, const Collapse* collapses, size_t collapse_count)
  790. {
  791. const int sort_bits = 11;
  792. // fill histogram for counting sort
  793. unsigned int histogram[1 << sort_bits];
  794. memset(histogram, 0, sizeof(histogram));
  795. for (size_t i = 0; i < collapse_count; ++i)
  796. {
  797. // skip sign bit since error is non-negative
  798. unsigned int key = (collapses[i].errorui << 1) >> (32 - sort_bits);
  799. histogram[key]++;
  800. }
  801. // compute offsets based on histogram data
  802. size_t histogram_sum = 0;
  803. for (size_t i = 0; i < 1 << sort_bits; ++i)
  804. {
  805. size_t count = histogram[i];
  806. histogram[i] = unsigned(histogram_sum);
  807. histogram_sum += count;
  808. }
  809. assert(histogram_sum == collapse_count);
  810. // compute sort order based on offsets
  811. for (size_t i = 0; i < collapse_count; ++i)
  812. {
  813. // skip sign bit since error is non-negative
  814. unsigned int key = (collapses[i].errorui << 1) >> (32 - sort_bits);
  815. sort_order[histogram[key]++] = unsigned(i);
  816. }
  817. }
  818. static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char* collapse_locked, Quadric* vertex_quadrics, Quadric* vertex_no_attrib_quadrics, const Collapse* collapses, size_t collapse_count, const unsigned int* collapse_order, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const Vector3* vertex_positions, const EdgeAdjacency& adjacency, size_t triangle_collapse_goal, float error_limit, float& result_error)
  819. {
  820. size_t edge_collapses = 0;
  821. size_t triangle_collapses = 0;
  822. // most collapses remove 2 triangles; use this to establish a bound on the pass in terms of error limit
  823. // note that edge_collapse_goal is an estimate; triangle_collapse_goal will be used to actually limit collapses
  824. size_t edge_collapse_goal = triangle_collapse_goal / 2;
  825. #if TRACE
  826. size_t stats[4] = {};
  827. #endif
  828. for (size_t i = 0; i < collapse_count; ++i)
  829. {
  830. const Collapse& c = collapses[collapse_order[i]];
  831. TRACESTATS(0);
  832. if (c.error > error_limit)
  833. break;
  834. if (triangle_collapses >= triangle_collapse_goal)
  835. break;
  836. // we limit the error in each pass based on the error of optimal last collapse; since many collapses will be locked
  837. // as they will share vertices with other successfull collapses, we need to increase the acceptable error by some factor
  838. float error_goal = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX;
  839. // on average, each collapse is expected to lock 6 other collapses; to avoid degenerate passes on meshes with odd
  840. // topology, we only abort if we got over 1/6 collapses accordingly.
  841. if (c.error > error_goal && triangle_collapses > triangle_collapse_goal / 6)
  842. break;
  843. unsigned int i0 = c.v0;
  844. unsigned int i1 = c.v1;
  845. unsigned int r0 = remap[i0];
  846. unsigned int r1 = remap[i1];
  847. // we don't collapse vertices that had source or target vertex involved in a collapse
  848. // it's important to not move the vertices twice since it complicates the tracking/remapping logic
  849. // it's important to not move other vertices towards a moved vertex to preserve error since we don't re-rank collapses mid-pass
  850. if (collapse_locked[r0] | collapse_locked[r1])
  851. {
  852. TRACESTATS(1);
  853. continue;
  854. }
  855. if (hasTriangleFlips(adjacency, vertex_positions, collapse_remap, r0, r1))
  856. {
  857. // adjust collapse goal since this collapse is invalid and shouldn't factor into error goal
  858. edge_collapse_goal++;
  859. TRACESTATS(2);
  860. continue;
  861. }
  862. assert(collapse_remap[r0] == r0);
  863. assert(collapse_remap[r1] == r1);
  864. quadricAdd(vertex_quadrics[r1], vertex_quadrics[r0]);
  865. quadricAdd(vertex_no_attrib_quadrics[r1], vertex_no_attrib_quadrics[r0]);
  866. if (vertex_kind[i0] == Kind_Complex)
  867. {
  868. unsigned int v = i0;
  869. do
  870. {
  871. collapse_remap[v] = r1;
  872. v = wedge[v];
  873. } while (v != i0);
  874. }
  875. else if (vertex_kind[i0] == Kind_Seam)
  876. {
  877. // remap v0 to v1 and seam pair of v0 to seam pair of v1
  878. unsigned int s0 = wedge[i0];
  879. unsigned int s1 = wedge[i1];
  880. assert(s0 != i0 && s1 != i1);
  881. assert(wedge[s0] == i0 && wedge[s1] == i1);
  882. collapse_remap[i0] = i1;
  883. collapse_remap[s0] = s1;
  884. }
  885. else
  886. {
  887. assert(wedge[i0] == i0);
  888. collapse_remap[i0] = i1;
  889. }
  890. collapse_locked[r0] = 1;
  891. collapse_locked[r1] = 1;
  892. // border edges collapse 1 triangle, other edges collapse 2 or more
  893. triangle_collapses += (vertex_kind[i0] == Kind_Border) ? 1 : 2;
  894. edge_collapses++;
  895. result_error = result_error < c.distance_error ? c.distance_error : result_error;
  896. }
  897. #if TRACE
  898. float error_goal_perfect = edge_collapse_goal < collapse_count ? collapses[collapse_order[edge_collapse_goal]].error : 0.f;
  899. printf("removed %d triangles, error %e (goal %e); evaluated %d/%d collapses (done %d, skipped %d, invalid %d)\n",
  900. int(triangle_collapses), sqrtf(result_error), sqrtf(error_goal_perfect),
  901. int(stats[0]), int(collapse_count), int(edge_collapses), int(stats[1]), int(stats[2]));
  902. #endif
  903. return edge_collapses;
  904. }
  905. static size_t remapIndexBuffer(unsigned int* indices, size_t index_count, const unsigned int* collapse_remap)
  906. {
  907. size_t write = 0;
  908. for (size_t i = 0; i < index_count; i += 3)
  909. {
  910. unsigned int v0 = collapse_remap[indices[i + 0]];
  911. unsigned int v1 = collapse_remap[indices[i + 1]];
  912. unsigned int v2 = collapse_remap[indices[i + 2]];
  913. // we never move the vertex twice during a single pass
  914. assert(collapse_remap[v0] == v0);
  915. assert(collapse_remap[v1] == v1);
  916. assert(collapse_remap[v2] == v2);
  917. if (v0 != v1 && v0 != v2 && v1 != v2)
  918. {
  919. indices[write + 0] = v0;
  920. indices[write + 1] = v1;
  921. indices[write + 2] = v2;
  922. write += 3;
  923. }
  924. }
  925. return write;
  926. }
  927. static void remapEdgeLoops(unsigned int* loop, size_t vertex_count, const unsigned int* collapse_remap)
  928. {
  929. for (size_t i = 0; i < vertex_count; ++i)
  930. {
  931. if (loop[i] != ~0u)
  932. {
  933. unsigned int l = loop[i];
  934. unsigned int r = collapse_remap[l];
  935. // i == r is a special case when the seam edge is collapsed in a direction opposite to where loop goes
  936. loop[i] = (i == r) ? loop[l] : r;
  937. }
  938. }
  939. }
  940. struct CellHasher
  941. {
  942. const unsigned int* vertex_ids;
  943. size_t hash(unsigned int i) const
  944. {
  945. unsigned int h = vertex_ids[i];
  946. // MurmurHash2 finalizer
  947. h ^= h >> 13;
  948. h *= 0x5bd1e995;
  949. h ^= h >> 15;
  950. return h;
  951. }
  952. bool equal(unsigned int lhs, unsigned int rhs) const
  953. {
  954. return vertex_ids[lhs] == vertex_ids[rhs];
  955. }
  956. };
  957. struct IdHasher
  958. {
  959. size_t hash(unsigned int id) const
  960. {
  961. unsigned int h = id;
  962. // MurmurHash2 finalizer
  963. h ^= h >> 13;
  964. h *= 0x5bd1e995;
  965. h ^= h >> 15;
  966. return h;
  967. }
  968. bool equal(unsigned int lhs, unsigned int rhs) const
  969. {
  970. return lhs == rhs;
  971. }
  972. };
  973. struct TriangleHasher
  974. {
  975. const unsigned int* indices;
  976. size_t hash(unsigned int i) const
  977. {
  978. const unsigned int* tri = indices + i * 3;
  979. // Optimized Spatial Hashing for Collision Detection of Deformable Objects
  980. return (tri[0] * 73856093) ^ (tri[1] * 19349663) ^ (tri[2] * 83492791);
  981. }
  982. bool equal(unsigned int lhs, unsigned int rhs) const
  983. {
  984. const unsigned int* lt = indices + lhs * 3;
  985. const unsigned int* rt = indices + rhs * 3;
  986. return lt[0] == rt[0] && lt[1] == rt[1] && lt[2] == rt[2];
  987. }
  988. };
  989. static void computeVertexIds(unsigned int* vertex_ids, const Vector3* vertex_positions, size_t vertex_count, int grid_size)
  990. {
  991. assert(grid_size >= 1 && grid_size <= 1024);
  992. float cell_scale = float(grid_size - 1);
  993. for (size_t i = 0; i < vertex_count; ++i)
  994. {
  995. const Vector3& v = vertex_positions[i];
  996. int xi = int(v.x * cell_scale + 0.5f);
  997. int yi = int(v.y * cell_scale + 0.5f);
  998. int zi = int(v.z * cell_scale + 0.5f);
  999. vertex_ids[i] = (xi << 20) | (yi << 10) | zi;
  1000. }
  1001. }
  1002. static size_t countTriangles(const unsigned int* vertex_ids, const unsigned int* indices, size_t index_count)
  1003. {
  1004. size_t result = 0;
  1005. for (size_t i = 0; i < index_count; i += 3)
  1006. {
  1007. unsigned int id0 = vertex_ids[indices[i + 0]];
  1008. unsigned int id1 = vertex_ids[indices[i + 1]];
  1009. unsigned int id2 = vertex_ids[indices[i + 2]];
  1010. result += (id0 != id1) & (id0 != id2) & (id1 != id2);
  1011. }
  1012. return result;
  1013. }
  1014. static size_t fillVertexCells(unsigned int* table, size_t table_size, unsigned int* vertex_cells, const unsigned int* vertex_ids, size_t vertex_count)
  1015. {
  1016. CellHasher hasher = {vertex_ids};
  1017. memset(table, -1, table_size * sizeof(unsigned int));
  1018. size_t result = 0;
  1019. for (size_t i = 0; i < vertex_count; ++i)
  1020. {
  1021. unsigned int* entry = hashLookup2(table, table_size, hasher, unsigned(i), ~0u);
  1022. if (*entry == ~0u)
  1023. {
  1024. *entry = unsigned(i);
  1025. vertex_cells[i] = unsigned(result++);
  1026. }
  1027. else
  1028. {
  1029. vertex_cells[i] = vertex_cells[*entry];
  1030. }
  1031. }
  1032. return result;
  1033. }
  1034. static size_t countVertexCells(unsigned int* table, size_t table_size, const unsigned int* vertex_ids, size_t vertex_count)
  1035. {
  1036. IdHasher hasher;
  1037. memset(table, -1, table_size * sizeof(unsigned int));
  1038. size_t result = 0;
  1039. for (size_t i = 0; i < vertex_count; ++i)
  1040. {
  1041. unsigned int id = vertex_ids[i];
  1042. unsigned int* entry = hashLookup2(table, table_size, hasher, id, ~0u);
  1043. result += (*entry == ~0u);
  1044. *entry = id;
  1045. }
  1046. return result;
  1047. }
  1048. static void fillCellQuadrics(Quadric* cell_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* vertex_cells)
  1049. {
  1050. for (size_t i = 0; i < index_count; i += 3)
  1051. {
  1052. unsigned int i0 = indices[i + 0];
  1053. unsigned int i1 = indices[i + 1];
  1054. unsigned int i2 = indices[i + 2];
  1055. unsigned int c0 = vertex_cells[i0];
  1056. unsigned int c1 = vertex_cells[i1];
  1057. unsigned int c2 = vertex_cells[i2];
  1058. bool single_cell = (c0 == c1) & (c0 == c2);
  1059. Quadric Q;
  1060. quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], single_cell ? 3.f : 1.f);
  1061. if (single_cell)
  1062. {
  1063. quadricAdd(cell_quadrics[c0], Q);
  1064. }
  1065. else
  1066. {
  1067. quadricAdd(cell_quadrics[c0], Q);
  1068. quadricAdd(cell_quadrics[c1], Q);
  1069. quadricAdd(cell_quadrics[c2], Q);
  1070. }
  1071. }
  1072. }
  1073. static void fillCellQuadrics(Quadric* cell_quadrics, const Vector3* vertex_positions, size_t vertex_count, const unsigned int* vertex_cells)
  1074. {
  1075. for (size_t i = 0; i < vertex_count; ++i)
  1076. {
  1077. unsigned int c = vertex_cells[i];
  1078. const Vector3& v = vertex_positions[i];
  1079. Quadric Q;
  1080. quadricFromPoint(Q, v.x, v.y, v.z, 1.f);
  1081. quadricAdd(cell_quadrics[c], Q);
  1082. }
  1083. }
  1084. static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Quadric* cell_quadrics, const Vector3* vertex_positions, size_t vertex_count)
  1085. {
  1086. memset(cell_remap, -1, cell_count * sizeof(unsigned int));
  1087. for (size_t i = 0; i < vertex_count; ++i)
  1088. {
  1089. unsigned int cell = vertex_cells[i];
  1090. float error = quadricError(cell_quadrics[cell], vertex_positions[i]);
  1091. if (cell_remap[cell] == ~0u || cell_errors[cell] > error)
  1092. {
  1093. cell_remap[cell] = unsigned(i);
  1094. cell_errors[cell] = error;
  1095. }
  1096. }
  1097. }
  1098. static size_t filterTriangles(unsigned int* destination, unsigned int* tritable, size_t tritable_size, const unsigned int* indices, size_t index_count, const unsigned int* vertex_cells, const unsigned int* cell_remap)
  1099. {
  1100. TriangleHasher hasher = {destination};
  1101. memset(tritable, -1, tritable_size * sizeof(unsigned int));
  1102. size_t result = 0;
  1103. for (size_t i = 0; i < index_count; i += 3)
  1104. {
  1105. unsigned int c0 = vertex_cells[indices[i + 0]];
  1106. unsigned int c1 = vertex_cells[indices[i + 1]];
  1107. unsigned int c2 = vertex_cells[indices[i + 2]];
  1108. if (c0 != c1 && c0 != c2 && c1 != c2)
  1109. {
  1110. unsigned int a = cell_remap[c0];
  1111. unsigned int b = cell_remap[c1];
  1112. unsigned int c = cell_remap[c2];
  1113. if (b < a && b < c)
  1114. {
  1115. unsigned int t = a;
  1116. a = b, b = c, c = t;
  1117. }
  1118. else if (c < a && c < b)
  1119. {
  1120. unsigned int t = c;
  1121. c = b, b = a, a = t;
  1122. }
  1123. destination[result * 3 + 0] = a;
  1124. destination[result * 3 + 1] = b;
  1125. destination[result * 3 + 2] = c;
  1126. unsigned int* entry = hashLookup2(tritable, tritable_size, hasher, unsigned(result), ~0u);
  1127. if (*entry == ~0u)
  1128. *entry = unsigned(result++);
  1129. }
  1130. }
  1131. return result * 3;
  1132. }
  1133. static float interpolate(float y, float x0, float y0, float x1, float y1, float x2, float y2)
  1134. {
  1135. // three point interpolation from "revenge of interpolation search" paper
  1136. float num = (y1 - y) * (x1 - x2) * (x1 - x0) * (y2 - y0);
  1137. float den = (y2 - y) * (x1 - x2) * (y0 - y1) + (y0 - y) * (x1 - x0) * (y1 - y2);
  1138. return x1 + num / den;
  1139. }
  1140. } // namespace meshopt
  1141. #ifndef NDEBUG
  1142. // Note: this is only exposed for debug visualization purposes; do *not* use these in debug builds
  1143. MESHOPTIMIZER_API unsigned char* meshopt_simplifyDebugKind = 0;
  1144. MESHOPTIMIZER_API unsigned int* meshopt_simplifyDebugLoop = 0;
  1145. MESHOPTIMIZER_API unsigned int* meshopt_simplifyDebugLoopBack = 0;
  1146. #endif
  1147. size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* out_result_error)
  1148. {
  1149. return meshopt_simplifyWithAttributes(destination, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, target_index_count, target_error, out_result_error, 0, 0, 0);
  1150. }
  1151. size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_data, size_t vertex_count, size_t vertex_stride, size_t target_index_count, float target_error, float* out_result_error, const float* attributes, const float* attribute_weights, size_t attribute_count)
  1152. {
  1153. using namespace meshopt;
  1154. assert(index_count % 3 == 0);
  1155. assert(vertex_stride > 0 && vertex_stride <= 256);
  1156. assert(vertex_stride % sizeof(float) == 0);
  1157. assert(target_index_count <= index_count);
  1158. assert(attribute_count <= ATTRIBUTES);
  1159. meshopt_Allocator allocator;
  1160. unsigned int* result = destination;
  1161. // build adjacency information
  1162. EdgeAdjacency adjacency = {};
  1163. prepareEdgeAdjacency(adjacency, index_count, vertex_count, allocator);
  1164. updateEdgeAdjacency(adjacency, indices, index_count, vertex_count, NULL);
  1165. // build position remap that maps each vertex to the one with identical position
  1166. unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);
  1167. unsigned int* wedge = allocator.allocate<unsigned int>(vertex_count);
  1168. buildPositionRemap(remap, wedge, vertex_data, vertex_count, vertex_stride, allocator);
  1169. // classify vertices; vertex kind determines collapse rules, see kCanCollapse
  1170. unsigned char* vertex_kind = allocator.allocate<unsigned char>(vertex_count);
  1171. unsigned int* loop = allocator.allocate<unsigned int>(vertex_count);
  1172. unsigned int* loopback = allocator.allocate<unsigned int>(vertex_count);
  1173. classifyVertices(vertex_kind, loop, loopback, vertex_count, adjacency, remap, wedge);
  1174. #if TRACE
  1175. size_t unique_positions = 0;
  1176. for (size_t i = 0; i < vertex_count; ++i)
  1177. unique_positions += remap[i] == i;
  1178. printf("position remap: %d vertices => %d positions\n", int(vertex_count), int(unique_positions));
  1179. size_t kinds[Kind_Count] = {};
  1180. for (size_t i = 0; i < vertex_count; ++i)
  1181. kinds[vertex_kind[i]] += remap[i] == i;
  1182. printf("kinds: manifold %d, border %d, seam %d, complex %d, locked %d\n",
  1183. int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Locked]));
  1184. #endif
  1185. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  1186. rescalePositions(vertex_positions, vertex_data, vertex_count, vertex_stride);
  1187. #if ATTRIBUTES
  1188. for (size_t i = 0; i < vertex_count; ++i)
  1189. {
  1190. memset(vertex_positions[i].a, 0, sizeof(vertex_positions[i].a));
  1191. for (size_t k = 0; k < attribute_count; ++k)
  1192. {
  1193. float a = attributes[i * attribute_count + k];
  1194. vertex_positions[i].a[k] = a * attribute_weights[k];
  1195. }
  1196. }
  1197. #endif
  1198. Quadric* vertex_quadrics = allocator.allocate<Quadric>(vertex_count);
  1199. memset(vertex_quadrics, 0, vertex_count * sizeof(Quadric));
  1200. Quadric* vertex_no_attrib_quadrics = allocator.allocate<Quadric>(vertex_count);
  1201. memset(vertex_no_attrib_quadrics, 0, vertex_count * sizeof(Quadric));
  1202. fillFaceQuadrics(vertex_quadrics, vertex_no_attrib_quadrics, indices, index_count, vertex_positions, remap);
  1203. fillEdgeQuadrics(vertex_quadrics, vertex_no_attrib_quadrics, indices, index_count, vertex_positions, remap, vertex_kind, loop, loopback);
  1204. if (result != indices)
  1205. memcpy(result, indices, index_count * sizeof(unsigned int));
  1206. #if TRACE
  1207. size_t pass_count = 0;
  1208. #endif
  1209. Collapse* edge_collapses = allocator.allocate<Collapse>(index_count);
  1210. unsigned int* collapse_order = allocator.allocate<unsigned int>(index_count);
  1211. unsigned int* collapse_remap = allocator.allocate<unsigned int>(vertex_count);
  1212. unsigned char* collapse_locked = allocator.allocate<unsigned char>(vertex_count);
  1213. size_t result_count = index_count;
  1214. float result_error = 0;
  1215. // target_error input is linear; we need to adjust it to match quadricError units
  1216. float error_limit = target_error * target_error;
  1217. while (result_count > target_index_count)
  1218. {
  1219. // note: throughout the simplification process adjacency structure reflects welded topology for result-in-progress
  1220. updateEdgeAdjacency(adjacency, result, result_count, vertex_count, remap);
  1221. size_t edge_collapse_count = pickEdgeCollapses(edge_collapses, result, result_count, remap, vertex_kind, loop);
  1222. // no edges can be collapsed any more due to topology restrictions
  1223. if (edge_collapse_count == 0)
  1224. break;
  1225. rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_quadrics, vertex_no_attrib_quadrics, remap);
  1226. #if TRACE > 1
  1227. dumpEdgeCollapses(edge_collapses, edge_collapse_count, vertex_kind);
  1228. #endif
  1229. sortEdgeCollapses(collapse_order, edge_collapses, edge_collapse_count);
  1230. size_t triangle_collapse_goal = (result_count - target_index_count) / 3;
  1231. for (size_t i = 0; i < vertex_count; ++i)
  1232. collapse_remap[i] = unsigned(i);
  1233. memset(collapse_locked, 0, vertex_count);
  1234. #if TRACE
  1235. printf("pass %d: ", int(pass_count++));
  1236. #endif
  1237. size_t collapses = performEdgeCollapses(collapse_remap, collapse_locked, vertex_quadrics, vertex_no_attrib_quadrics, edge_collapses, edge_collapse_count, collapse_order, remap, wedge, vertex_kind, vertex_positions, adjacency, triangle_collapse_goal, error_limit, result_error);
  1238. // no edges can be collapsed any more due to hitting the error limit or triangle collapse limit
  1239. if (collapses == 0)
  1240. break;
  1241. remapEdgeLoops(loop, vertex_count, collapse_remap);
  1242. remapEdgeLoops(loopback, vertex_count, collapse_remap);
  1243. size_t new_count = remapIndexBuffer(result, result_count, collapse_remap);
  1244. assert(new_count < result_count);
  1245. result_count = new_count;
  1246. }
  1247. #if TRACE
  1248. printf("result: %d triangles, error: %e; total %d passes\n", int(result_count), sqrtf(result_error), int(pass_count));
  1249. #endif
  1250. #if TRACE > 1
  1251. dumpLockedCollapses(result, result_count, vertex_kind);
  1252. #endif
  1253. #ifndef NDEBUG
  1254. if (meshopt_simplifyDebugKind)
  1255. memcpy(meshopt_simplifyDebugKind, vertex_kind, vertex_count);
  1256. if (meshopt_simplifyDebugLoop)
  1257. memcpy(meshopt_simplifyDebugLoop, loop, vertex_count * sizeof(unsigned int));
  1258. if (meshopt_simplifyDebugLoopBack)
  1259. memcpy(meshopt_simplifyDebugLoopBack, loopback, vertex_count * sizeof(unsigned int));
  1260. #endif
  1261. // result_error is quadratic; we need to remap it back to linear
  1262. if (out_result_error)
  1263. {
  1264. *out_result_error = sqrtf(result_error);
  1265. }
  1266. return result_count;
  1267. }
  1268. size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* out_result_error)
  1269. {
  1270. using namespace meshopt;
  1271. assert(index_count % 3 == 0);
  1272. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  1273. assert(vertex_positions_stride % sizeof(float) == 0);
  1274. assert(target_index_count <= index_count);
  1275. // we expect to get ~2 triangles/vertex in the output
  1276. size_t target_cell_count = target_index_count / 6;
  1277. meshopt_Allocator allocator;
  1278. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  1279. rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);
  1280. // find the optimal grid size using guided binary search
  1281. #if TRACE
  1282. printf("source: %d vertices, %d triangles\n", int(vertex_count), int(index_count / 3));
  1283. printf("target: %d cells, %d triangles\n", int(target_cell_count), int(target_index_count / 3));
  1284. #endif
  1285. unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);
  1286. const int kInterpolationPasses = 5;
  1287. // invariant: # of triangles in min_grid <= target_count
  1288. int min_grid = int(1.f / (target_error < 1e-3f ? 1e-3f : target_error));
  1289. int max_grid = 1025;
  1290. size_t min_triangles = 0;
  1291. size_t max_triangles = index_count / 3;
  1292. // when we're error-limited, we compute the triangle count for the min. size; this accelerates convergence and provides the correct answer when we can't use a larger grid
  1293. if (min_grid > 1)
  1294. {
  1295. computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);
  1296. min_triangles = countTriangles(vertex_ids, indices, index_count);
  1297. }
  1298. // instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...
  1299. int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);
  1300. for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)
  1301. {
  1302. if (min_triangles >= target_index_count / 3 || max_grid - min_grid <= 1)
  1303. break;
  1304. // we clamp the prediction of the grid size to make sure that the search converges
  1305. int grid_size = next_grid_size;
  1306. grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid) ? max_grid - 1 : grid_size;
  1307. computeVertexIds(vertex_ids, vertex_positions, vertex_count, grid_size);
  1308. size_t triangles = countTriangles(vertex_ids, indices, index_count);
  1309. #if TRACE
  1310. printf("pass %d (%s): grid size %d, triangles %d, %s\n",
  1311. pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses) ? "lerp" : "binary",
  1312. grid_size, int(triangles),
  1313. (triangles <= target_index_count / 3) ? "under" : "over");
  1314. #endif
  1315. float tip = interpolate(float(target_index_count / 3), float(min_grid), float(min_triangles), float(grid_size), float(triangles), float(max_grid), float(max_triangles));
  1316. if (triangles <= target_index_count / 3)
  1317. {
  1318. min_grid = grid_size;
  1319. min_triangles = triangles;
  1320. }
  1321. else
  1322. {
  1323. max_grid = grid_size;
  1324. max_triangles = triangles;
  1325. }
  1326. // we start by using interpolation search - it usually converges faster
  1327. // however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)
  1328. next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;
  1329. }
  1330. if (min_triangles == 0)
  1331. {
  1332. if (out_result_error)
  1333. *out_result_error = 1.f;
  1334. return 0;
  1335. }
  1336. // build vertex->cell association by mapping all vertices with the same quantized position to the same cell
  1337. size_t table_size = hashBuckets2(vertex_count);
  1338. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  1339. unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);
  1340. computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);
  1341. size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);
  1342. // build a quadric for each target cell
  1343. Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count);
  1344. memset(cell_quadrics, 0, cell_count * sizeof(Quadric));
  1345. fillCellQuadrics(cell_quadrics, indices, index_count, vertex_positions, vertex_cells);
  1346. // for each target cell, find the vertex with the minimal error
  1347. unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);
  1348. float* cell_errors = allocator.allocate<float>(cell_count);
  1349. fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count);
  1350. // compute error
  1351. float result_error = 0.f;
  1352. for (size_t i = 0; i < cell_count; ++i)
  1353. result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error;
  1354. // collapse triangles!
  1355. // note that we need to filter out triangles that we've already output because we very frequently generate redundant triangles between cells :(
  1356. size_t tritable_size = hashBuckets2(min_triangles);
  1357. unsigned int* tritable = allocator.allocate<unsigned int>(tritable_size);
  1358. size_t write = filterTriangles(destination, tritable, tritable_size, indices, index_count, vertex_cells, cell_remap);
  1359. #if TRACE
  1360. printf("result: %d cells, %d triangles (%d unfiltered), error %e\n", int(cell_count), int(write / 3), int(min_triangles), sqrtf(result_error));
  1361. #endif
  1362. if (out_result_error)
  1363. *out_result_error = sqrtf(result_error);
  1364. return write;
  1365. }
  1366. size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_vertex_count)
  1367. {
  1368. using namespace meshopt;
  1369. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  1370. assert(vertex_positions_stride % sizeof(float) == 0);
  1371. assert(target_vertex_count <= vertex_count);
  1372. size_t target_cell_count = target_vertex_count;
  1373. if (target_cell_count == 0)
  1374. return 0;
  1375. meshopt_Allocator allocator;
  1376. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  1377. rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);
  1378. // find the optimal grid size using guided binary search
  1379. #if TRACE
  1380. printf("source: %d vertices\n", int(vertex_count));
  1381. printf("target: %d cells\n", int(target_cell_count));
  1382. #endif
  1383. unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);
  1384. size_t table_size = hashBuckets2(vertex_count);
  1385. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  1386. const int kInterpolationPasses = 5;
  1387. // invariant: # of vertices in min_grid <= target_count
  1388. int min_grid = 0;
  1389. int max_grid = 1025;
  1390. size_t min_vertices = 0;
  1391. size_t max_vertices = vertex_count;
  1392. // instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...
  1393. int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);
  1394. for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)
  1395. {
  1396. assert(min_vertices < target_vertex_count);
  1397. assert(max_grid - min_grid > 1);
  1398. // we clamp the prediction of the grid size to make sure that the search converges
  1399. int grid_size = next_grid_size;
  1400. grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid) ? max_grid - 1 : grid_size;
  1401. computeVertexIds(vertex_ids, vertex_positions, vertex_count, grid_size);
  1402. size_t vertices = countVertexCells(table, table_size, vertex_ids, vertex_count);
  1403. #if TRACE
  1404. printf("pass %d (%s): grid size %d, vertices %d, %s\n",
  1405. pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses) ? "lerp" : "binary",
  1406. grid_size, int(vertices),
  1407. (vertices <= target_vertex_count) ? "under" : "over");
  1408. #endif
  1409. float tip = interpolate(float(target_vertex_count), float(min_grid), float(min_vertices), float(grid_size), float(vertices), float(max_grid), float(max_vertices));
  1410. if (vertices <= target_vertex_count)
  1411. {
  1412. min_grid = grid_size;
  1413. min_vertices = vertices;
  1414. }
  1415. else
  1416. {
  1417. max_grid = grid_size;
  1418. max_vertices = vertices;
  1419. }
  1420. if (vertices == target_vertex_count || max_grid - min_grid <= 1)
  1421. break;
  1422. // we start by using interpolation search - it usually converges faster
  1423. // however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)
  1424. next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;
  1425. }
  1426. if (min_vertices == 0)
  1427. return 0;
  1428. // build vertex->cell association by mapping all vertices with the same quantized position to the same cell
  1429. unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);
  1430. computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);
  1431. size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);
  1432. // build a quadric for each target cell
  1433. Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count);
  1434. memset(cell_quadrics, 0, cell_count * sizeof(Quadric));
  1435. fillCellQuadrics(cell_quadrics, vertex_positions, vertex_count, vertex_cells);
  1436. // for each target cell, find the vertex with the minimal error
  1437. unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);
  1438. float* cell_errors = allocator.allocate<float>(cell_count);
  1439. fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count);
  1440. // copy results to the output
  1441. assert(cell_count <= target_vertex_count);
  1442. memcpy(destination, cell_remap, sizeof(unsigned int) * cell_count);
  1443. #if TRACE
  1444. printf("result: %d cells\n", int(cell_count));
  1445. #endif
  1446. return cell_count;
  1447. }
  1448. float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  1449. {
  1450. using namespace meshopt;
  1451. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  1452. assert(vertex_positions_stride % sizeof(float) == 0);
  1453. float extent = rescalePositions(NULL, vertex_positions, vertex_count, vertex_positions_stride);
  1454. return extent;
  1455. }