ConvexHullBuilder.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Geometry/ConvexHullBuilder.h>
  5. #include <Jolt/Geometry/ConvexHullBuilder2D.h>
  6. #include <Jolt/Geometry/ClosestPoint.h>
  7. #include <Jolt/Core/StringTools.h>
  8. #include <unordered_set>
  9. #include <fstream>
  10. #ifdef JPH_CONVEX_BUILDER_DEBUG
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #endif
  13. namespace JPH {
  14. ConvexHullBuilder::Face::~Face()
  15. {
  16. // Free all edges
  17. Edge *e = mFirstEdge;
  18. if (e != nullptr)
  19. {
  20. do
  21. {
  22. Edge *next = e->mNextEdge;
  23. delete e;
  24. e = next;
  25. } while (e != mFirstEdge);
  26. }
  27. }
  28. void ConvexHullBuilder::Face::CalculateNormalAndCentroid(const Vec3 *inPositions)
  29. {
  30. // Get point that we use to construct a triangle fan
  31. Edge *e = mFirstEdge;
  32. Vec3 y0 = inPositions[e->mStartIdx];
  33. // Get the 2nd point
  34. e = e->mNextEdge;
  35. Vec3 y1 = inPositions[e->mStartIdx];
  36. // Start accumulating the centroid
  37. mCentroid = y0 + y1;
  38. int n = 2;
  39. // Start accumulating the normal
  40. mNormal = Vec3::sZero();
  41. // Loop over remaining edges accumulating normals in a triangle fan fashion
  42. for (e = e->mNextEdge; e != mFirstEdge; e = e->mNextEdge)
  43. {
  44. // Get the 3rd point
  45. Vec3 y2 = inPositions[e->mStartIdx];
  46. // Calculate edges (counter clockwise)
  47. Vec3 e0 = y1 - y0;
  48. Vec3 e1 = y2 - y1;
  49. Vec3 e2 = y0 - y2;
  50. // The best normal is calculated by using the two shortest edges
  51. // See: https://box2d.org/posts/2014/01/troublesome-triangle/
  52. // The difference in normals is most pronounced when one edge is much smaller than the others (in which case the others must have roughly the same length).
  53. // Therefore we can suffice by just picking the shortest from 2 edges and use that with the 3rd edge to calculate the normal.
  54. // We first check which of the edges is shorter: e1 or e2
  55. UVec4 e1_shorter_than_e2 = Vec4::sLess(e1.DotV4(e1), e2.DotV4(e2));
  56. // We calculate both normals and then select the one that had the shortest edge for our normal (this avoids branching)
  57. Vec3 normal_e01 = e0.Cross(e1);
  58. Vec3 normal_e02 = e2.Cross(e0);
  59. mNormal += Vec3::sSelect(normal_e02, normal_e01, e1_shorter_than_e2);
  60. // Accumulate centroid
  61. mCentroid += y2;
  62. n++;
  63. // Update y1 for next triangle
  64. y1 = y2;
  65. }
  66. // Finalize centroid
  67. mCentroid /= float(n);
  68. }
  69. void ConvexHullBuilder::Face::Initialize(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions)
  70. {
  71. JPH_ASSERT(mFirstEdge == nullptr);
  72. JPH_ASSERT(inIdx0 != inIdx1 && inIdx0 != inIdx2 && inIdx1 != inIdx2);
  73. // Create 3 edges
  74. Edge *e0 = new Edge(this, inIdx0);
  75. Edge *e1 = new Edge(this, inIdx1);
  76. Edge *e2 = new Edge(this, inIdx2);
  77. // Link edges
  78. e0->mNextEdge = e1;
  79. e1->mNextEdge = e2;
  80. e2->mNextEdge = e0;
  81. mFirstEdge = e0;
  82. CalculateNormalAndCentroid(inPositions);
  83. }
  84. ConvexHullBuilder::ConvexHullBuilder(const Positions &inPositions) :
  85. mPositions(inPositions)
  86. {
  87. #ifdef JPH_CONVEX_BUILDER_DEBUG
  88. mIteration = 0;
  89. // Center the drawing of the first hull around the origin and calculate the delta offset between states
  90. mOffset = Vec3::sZero();
  91. if (mPositions.empty())
  92. {
  93. // No hull will be generated
  94. mDelta = Vec3::sZero();
  95. }
  96. else
  97. {
  98. Vec3 maxv = Vec3::sReplicate(-FLT_MAX), minv = Vec3::sReplicate(FLT_MAX);
  99. for (Vec3 v : mPositions)
  100. {
  101. minv = Vec3::sMin(minv, v);
  102. maxv = Vec3::sMax(maxv, v);
  103. mOffset -= v;
  104. }
  105. mOffset /= float(mPositions.size());
  106. mDelta = Vec3((maxv - minv).GetX() + 0.5f, 0, 0);
  107. mOffset += mDelta; // Don't start at origin, we're already drawing the final hull there
  108. }
  109. #endif
  110. }
  111. void ConvexHullBuilder::FreeFaces()
  112. {
  113. for (Face *f : mFaces)
  114. delete f;
  115. mFaces.clear();
  116. }
  117. void ConvexHullBuilder::AssignPointToFace(int inPositionIdx, const Faces &inFaces) const
  118. {
  119. Vec3 point = mPositions[inPositionIdx];
  120. Face *best_face = nullptr;
  121. float best_dist_sq = 0.0f;
  122. // Test against all faces
  123. for (Face *f : inFaces)
  124. if (!f->mRemoved)
  125. {
  126. // Determine distance to face
  127. float dot = f->mNormal.Dot(point - f->mCentroid);
  128. if (dot > 0.0f)
  129. {
  130. float dist_sq = dot * dot / f->mNormal.LengthSq();
  131. if (dist_sq > best_dist_sq)
  132. {
  133. best_face = f;
  134. best_dist_sq = dist_sq;
  135. }
  136. }
  137. }
  138. // If this point is in front of the face, add it to the conflict list
  139. if (best_face != nullptr)
  140. {
  141. if (best_dist_sq > best_face->mFurthestPointDistanceSq)
  142. {
  143. // This point is futher away than any others, update the distance and add point as last point
  144. best_face->mFurthestPointDistanceSq = best_dist_sq;
  145. best_face->mConflictList.push_back(inPositionIdx);
  146. }
  147. else
  148. {
  149. // Not the furthest point, add it as the before last point
  150. best_face->mConflictList.push_back(best_face->mConflictList.back());
  151. best_face->mConflictList[best_face->mConflictList.size() - 2] = inPositionIdx;
  152. }
  153. }
  154. }
  155. float ConvexHullBuilder::DetermineCoplanarDistance() const
  156. {
  157. // Formula as per: Implementing Quickhull - Dirk Gregorius.
  158. Vec3 vmax = Vec3::sZero();
  159. for (Vec3 v : mPositions)
  160. vmax = Vec3::sMax(vmax, v.Abs());
  161. return 3.0f * FLT_EPSILON * (vmax.GetX() + vmax.GetY() + vmax.GetZ());
  162. }
  163. int ConvexHullBuilder::GetNumVerticesUsed() const
  164. {
  165. unordered_set<int> used_verts;
  166. for (Face *f : mFaces)
  167. {
  168. Edge *e = f->mFirstEdge;
  169. do
  170. {
  171. used_verts.insert(e->mStartIdx);
  172. e = e->mNextEdge;
  173. } while (e != f->mFirstEdge);
  174. }
  175. return (int)used_verts.size();
  176. }
  177. bool ConvexHullBuilder::ContainsFace(const vector<int> &inIndices)
  178. {
  179. for (Face *f : mFaces)
  180. {
  181. Edge *e = f->mFirstEdge;
  182. vector<int>::const_iterator index = find(inIndices.begin(), inIndices.end(), e->mStartIdx);
  183. if (index != inIndices.end())
  184. {
  185. size_t matches = 0;
  186. do
  187. {
  188. // Check if index matches
  189. if (*index != e->mStartIdx)
  190. break;
  191. // Increment number of matches
  192. matches++;
  193. // Next index in list of inIndices
  194. index++;
  195. if (index == inIndices.end())
  196. index = inIndices.begin();
  197. // Next edge
  198. e = e->mNextEdge;
  199. } while (e != f->mFirstEdge);
  200. if (matches == inIndices.size())
  201. return true;
  202. }
  203. }
  204. return false;
  205. }
  206. ConvexHullBuilder::EResult ConvexHullBuilder::Initialize(int inMaxVertices, float inTolerance, string &outError)
  207. {
  208. // Free the faces possibly left over from an earlier hull
  209. FreeFaces();
  210. // Test that we have at least 3 points
  211. if (mPositions.size() < 3)
  212. {
  213. outError = "Need at least 3 points to make a hull";
  214. return EResult::TooFewPoints;
  215. }
  216. // Determine a suitable tolerance for detecting that points are coplanar
  217. float coplanar_tolerance_sq = Square(DetermineCoplanarDistance());
  218. // Increase desired tolerance if accuracy doesn't allow it
  219. float tolerance_sq = max(coplanar_tolerance_sq, Square(inTolerance));
  220. // Find point furthest from the origin
  221. int idx1 = -1;
  222. float max_dist_sq = -1.0f;
  223. for (int i = 0; i < (int)mPositions.size(); ++i)
  224. {
  225. float dist_sq = mPositions[i].LengthSq();
  226. if (dist_sq > max_dist_sq)
  227. {
  228. max_dist_sq = dist_sq;
  229. idx1 = i;
  230. }
  231. }
  232. JPH_ASSERT(idx1 >= 0);
  233. // Find point that is furthest away from this point
  234. int idx2 = -1;
  235. max_dist_sq = -1.0f;
  236. for (int i = 0; i < (int)mPositions.size(); ++i)
  237. if (i != idx1)
  238. {
  239. float dist_sq = (mPositions[i] - mPositions[idx1]).LengthSq();
  240. if (dist_sq > max_dist_sq)
  241. {
  242. max_dist_sq = dist_sq;
  243. idx2 = i;
  244. }
  245. }
  246. JPH_ASSERT(idx2 >= 0);
  247. // Find point that forms the biggest triangle
  248. int idx3 = -1;
  249. float best_triangle_area_sq = -1.0f;
  250. for (int i = 0; i < (int)mPositions.size(); ++i)
  251. if (i != idx1 && i != idx2)
  252. {
  253. float triangle_area_sq = (mPositions[idx1] - mPositions[i]).Cross(mPositions[idx2] - mPositions[i]).LengthSq();
  254. if (triangle_area_sq > best_triangle_area_sq)
  255. {
  256. best_triangle_area_sq = triangle_area_sq;
  257. idx3 = i;
  258. }
  259. }
  260. JPH_ASSERT(idx3 >= 0);
  261. if (best_triangle_area_sq < FLT_EPSILON)
  262. {
  263. outError = "Could not find a suitable initial triangle because its area was too small";
  264. return EResult::Degenerate;
  265. }
  266. // Check if we have only 3 vertices
  267. if (mPositions.size() == 3)
  268. {
  269. // Create two triangles (back to back)
  270. Face *t1 = CreateTriangle(idx1, idx2, idx3);
  271. Face *t2 = CreateTriangle(idx1, idx3, idx2);
  272. // Link faces edges
  273. LinkFace(t1->mFirstEdge, t2->mFirstEdge->mNextEdge->mNextEdge);
  274. LinkFace(t1->mFirstEdge->mNextEdge, t2->mFirstEdge->mNextEdge);
  275. LinkFace(t1->mFirstEdge->mNextEdge->mNextEdge, t2->mFirstEdge);
  276. #ifdef JPH_CONVEX_BUILDER_DEBUG
  277. // Draw current state
  278. DrawState();
  279. #endif
  280. return EResult::Success;
  281. }
  282. // Find point that forms the biggest tetrahedron
  283. Vec3 initial_plane_normal = (mPositions[idx2] - mPositions[idx1]).Cross(mPositions[idx3] - mPositions[idx1]).Normalized();
  284. Vec3 initial_plane_centroid = (mPositions[idx1] + mPositions[idx2] + mPositions[idx3]) / 3.0f;
  285. int idx4 = -1;
  286. float max_dist = 0.0f;
  287. for (int i = 0; i < (int)mPositions.size(); ++i)
  288. if (i != idx1 && i != idx2 && i != idx3)
  289. {
  290. float dist = (mPositions[i] - initial_plane_centroid).Dot(initial_plane_normal);
  291. if (abs(dist) > abs(max_dist))
  292. {
  293. max_dist = dist;
  294. idx4 = i;
  295. }
  296. }
  297. // Check if the hull is coplanar
  298. if (Square(max_dist) <= 25.0f * coplanar_tolerance_sq)
  299. {
  300. // First project all points in 2D space
  301. Vec3 base1 = initial_plane_normal.GetNormalizedPerpendicular();
  302. Vec3 base2 = initial_plane_normal.Cross(base1);
  303. vector<Vec3> positions_2d;
  304. positions_2d.reserve(mPositions.size());
  305. for (Vec3 v : mPositions)
  306. positions_2d.push_back(Vec3(base1.Dot(v), base2.Dot(v), 0));
  307. // Build hull
  308. vector<int> edges_2d;
  309. ConvexHullBuilder2D builder_2d(positions_2d);
  310. ConvexHullBuilder2D::EResult result = builder_2d.Initialize(idx1, idx2, idx3, inMaxVertices, inTolerance, edges_2d);
  311. // Create faces (back to back)
  312. Face *f1 = CreateFace();
  313. Face *f2 = CreateFace();
  314. // Create edges for face 1
  315. vector<Edge *> edges_f1;
  316. edges_f1.reserve(edges_2d.size());
  317. for (int i = 0; i < (int)edges_2d.size(); ++i)
  318. {
  319. Edge *edge = new Edge(f1, edges_2d[i]);
  320. if (edges_f1.empty())
  321. f1->mFirstEdge = edge;
  322. else
  323. edges_f1.back()->mNextEdge = edge;
  324. edges_f1.push_back(edge);
  325. }
  326. edges_f1.back()->mNextEdge = f1->mFirstEdge;
  327. // Create edges for face 2
  328. vector<Edge *> edges_f2;
  329. edges_f2.reserve(edges_2d.size());
  330. for (int i = (int)edges_2d.size() - 1; i >= 0; --i)
  331. {
  332. Edge *edge = new Edge(f2, edges_2d[i]);
  333. if (edges_f2.empty())
  334. f2->mFirstEdge = edge;
  335. else
  336. edges_f2.back()->mNextEdge = edge;
  337. edges_f2.push_back(edge);
  338. }
  339. edges_f2.back()->mNextEdge = f2->mFirstEdge;
  340. // Link edges
  341. for (size_t i = 0; i < edges_2d.size(); ++i)
  342. LinkFace(edges_f1[i], edges_f2[(2 * edges_2d.size() - 2 - i) % edges_2d.size()]);
  343. // Calculate the plane for both faces
  344. f1->CalculateNormalAndCentroid(mPositions.data());
  345. f2->mNormal = -f1->mNormal;
  346. f2->mCentroid = f1->mCentroid;
  347. #ifdef JPH_CONVEX_BUILDER_DEBUG
  348. // Draw current state
  349. DrawState();
  350. #endif
  351. return result == ConvexHullBuilder2D::EResult::MaxVerticesReached? EResult::MaxVerticesReached : EResult::Success;
  352. }
  353. // Ensure the planes are facing outwards
  354. if (max_dist < 0.0f)
  355. swap(idx2, idx3);
  356. // Create tetrahedron
  357. Face *t1 = CreateTriangle(idx1, idx2, idx4);
  358. Face *t2 = CreateTriangle(idx2, idx3, idx4);
  359. Face *t3 = CreateTriangle(idx3, idx1, idx4);
  360. Face *t4 = CreateTriangle(idx1, idx3, idx2);
  361. // Link face edges
  362. LinkFace(t1->mFirstEdge, t4->mFirstEdge->mNextEdge->mNextEdge);
  363. LinkFace(t1->mFirstEdge->mNextEdge, t2->mFirstEdge->mNextEdge->mNextEdge);
  364. LinkFace(t1->mFirstEdge->mNextEdge->mNextEdge, t3->mFirstEdge->mNextEdge);
  365. LinkFace(t2->mFirstEdge, t4->mFirstEdge->mNextEdge);
  366. LinkFace(t2->mFirstEdge->mNextEdge, t3->mFirstEdge->mNextEdge->mNextEdge);
  367. LinkFace(t3->mFirstEdge, t4->mFirstEdge);
  368. // Build the initial conflict lists
  369. Faces faces { t1, t2, t3, t4 };
  370. for (int idx = 0; idx < (int)mPositions.size(); ++idx)
  371. if (idx != idx1 && idx != idx2 && idx != idx3 && idx != idx4)
  372. AssignPointToFace(idx, faces);
  373. #ifdef JPH_CONVEX_BUILDER_DEBUG
  374. // Draw current state including conflict list
  375. DrawState(true);
  376. // Increment iteration counter
  377. ++mIteration;
  378. #endif
  379. // Overestimate of the actual amount of vertices we use, for limiting the amount of vertices in the hull
  380. int num_vertices_used = 4;
  381. // Loop through the remainder of the points and add them
  382. for (;;)
  383. {
  384. // Find the face with the furthest point on it
  385. Face *face_with_furthest_point = nullptr;
  386. float furthest_dist_sq = 0.0f;
  387. for (Face *f : mFaces)
  388. if (f->mFurthestPointDistanceSq > furthest_dist_sq)
  389. {
  390. furthest_dist_sq = f->mFurthestPointDistanceSq;
  391. face_with_furthest_point = f;
  392. }
  393. // If there is none closer than our tolerance value, we're done
  394. if (face_with_furthest_point == nullptr || furthest_dist_sq < tolerance_sq)
  395. break;
  396. // Check if we have a limit on the max vertices that we should produce
  397. if (num_vertices_used >= inMaxVertices)
  398. {
  399. // Count the actual amount of used vertices (we did not take the removal of any vertices into account)
  400. num_vertices_used = GetNumVerticesUsed();
  401. // Check if there are too many
  402. if (num_vertices_used >= inMaxVertices)
  403. return EResult::MaxVerticesReached;
  404. }
  405. // We're about to add another vertex
  406. ++num_vertices_used;
  407. // Take the furthest point
  408. int furthest_point_idx = face_with_furthest_point->mConflictList.back();
  409. face_with_furthest_point->mConflictList.pop_back();
  410. // Add the point to the hull
  411. Faces new_faces;
  412. AddPoint(face_with_furthest_point, furthest_point_idx, coplanar_tolerance_sq, new_faces);
  413. // Redistribute points on conflict lists belonging to removed faces
  414. for (Face *face : mFaces)
  415. if (face->mRemoved)
  416. for (int idx : face->mConflictList)
  417. AssignPointToFace(idx, new_faces);
  418. // Permanently delete faces that we removed in AddPoint()
  419. GarbageCollectFaces();
  420. #ifdef JPH_CONVEX_BUILDER_DEBUG
  421. // Draw state at the end of this step including conflict list
  422. DrawState(true);
  423. // Increment iteration counter
  424. ++mIteration;
  425. #endif
  426. }
  427. return EResult::Success;
  428. }
  429. void ConvexHullBuilder::AddPoint(Face *inFacingFace, int inIdx, float inCoplanarToleranceSq, Faces &outNewFaces)
  430. {
  431. // Get position
  432. Vec3 pos = mPositions[inIdx];
  433. #ifdef JPH_CONVEX_BUILDER_DEBUG
  434. // Draw point to be added
  435. DebugRenderer::sInstance->DrawMarker(cDrawScale * (mOffset + pos), Color::sYellow, 0.1f);
  436. DebugRenderer::sInstance->DrawText3D(cDrawScale * (mOffset + pos), ConvertToString(inIdx), Color::sWhite);
  437. #endif
  438. #ifdef JPH_ENABLE_ASSERTS
  439. // Check if structure is intact
  440. ValidateFaces();
  441. #endif
  442. // Find edge of convex hull of faces that are not facing the new vertex
  443. FullEdges edges;
  444. FindEdge(inFacingFace, pos, edges);
  445. JPH_ASSERT(edges.size() >= 3);
  446. // Create new faces
  447. outNewFaces.reserve(edges.size());
  448. for (FullEdge &e : edges)
  449. {
  450. JPH_ASSERT(e.mStartIdx != e.mEndIdx);
  451. Face *f = CreateTriangle(e.mStartIdx, e.mEndIdx, inIdx);
  452. outNewFaces.push_back(f);
  453. }
  454. // Link edges
  455. for (Faces::size_type i = 0; i < outNewFaces.size(); ++i)
  456. {
  457. LinkFace(outNewFaces[i]->mFirstEdge, edges[i].mNeighbourEdge);
  458. LinkFace(outNewFaces[i]->mFirstEdge->mNextEdge, outNewFaces[(i + 1) % outNewFaces.size()]->mFirstEdge->mNextEdge->mNextEdge);
  459. }
  460. // Loop on faces that were modified until nothing needs to be checked anymore
  461. Faces affected_faces = outNewFaces;
  462. while (!affected_faces.empty())
  463. {
  464. // Take the next face
  465. Face *face = affected_faces.back();
  466. affected_faces.pop_back();
  467. if (!face->mRemoved)
  468. {
  469. // Merge with neighbour if this is a degenerate face
  470. MergeDegenerateFace(face, 1.0e-12f, affected_faces);
  471. // Merge with coplanar neighbours (or when the neighbour forms a concave edge)
  472. if (!face->mRemoved)
  473. MergeCoplanarOrConcaveFaces(face, inCoplanarToleranceSq, affected_faces);
  474. }
  475. }
  476. #ifdef JPH_ENABLE_ASSERTS
  477. // Check if structure is intact
  478. ValidateFaces();
  479. #endif
  480. }
  481. void ConvexHullBuilder::GarbageCollectFaces()
  482. {
  483. for (int i = (int)mFaces.size() - 1; i >= 0; --i)
  484. {
  485. Face *f = mFaces[i];
  486. if (f->mRemoved)
  487. {
  488. FreeFace(f);
  489. mFaces.erase(mFaces.begin() + i);
  490. }
  491. }
  492. }
  493. ConvexHullBuilder::Face *ConvexHullBuilder::CreateFace()
  494. {
  495. // Call provider to create face
  496. Face *f = new Face();
  497. #ifdef JPH_CONVEX_BUILDER_DEBUG
  498. // Remember iteration counter
  499. f->mIteration = mIteration;
  500. #endif
  501. // Add to list
  502. mFaces.push_back(f);
  503. return f;
  504. }
  505. ConvexHullBuilder::Face *ConvexHullBuilder::CreateTriangle(int inIdx1, int inIdx2, int inIdx3)
  506. {
  507. Face *f = CreateFace();
  508. f->Initialize(inIdx1, inIdx2, inIdx3, mPositions.data());
  509. return f;
  510. }
  511. void ConvexHullBuilder::FreeFace(Face *inFace)
  512. {
  513. JPH_ASSERT(inFace->mRemoved);
  514. #ifdef JPH_ENABLE_ASSERTS
  515. // Make sure that this face is not connected
  516. Edge *e = inFace->mFirstEdge;
  517. if (e != nullptr)
  518. do
  519. {
  520. JPH_ASSERT(e->mNeighbourEdge == nullptr);
  521. e = e->mNextEdge;
  522. } while (e != inFace->mFirstEdge);
  523. #endif
  524. // Free the face
  525. delete inFace;
  526. }
  527. void ConvexHullBuilder::LinkFace(Edge *inEdge1, Edge *inEdge2)
  528. {
  529. // Check not connected yet
  530. JPH_ASSERT(inEdge1->mNeighbourEdge == nullptr);
  531. JPH_ASSERT(inEdge2->mNeighbourEdge == nullptr);
  532. JPH_ASSERT(inEdge1->mFace != inEdge2->mFace);
  533. // Check vertices match
  534. JPH_ASSERT(inEdge1->mStartIdx == inEdge2->mNextEdge->mStartIdx);
  535. JPH_ASSERT(inEdge2->mStartIdx == inEdge1->mNextEdge->mStartIdx);
  536. // Link up
  537. inEdge1->mNeighbourEdge = inEdge2;
  538. inEdge2->mNeighbourEdge = inEdge1;
  539. }
  540. void ConvexHullBuilder::UnlinkFace(Face *inFace)
  541. {
  542. // Unlink from neighbours
  543. Edge *e = inFace->mFirstEdge;
  544. do
  545. {
  546. if (e->mNeighbourEdge != nullptr)
  547. {
  548. // Validate that neighbour points to us
  549. JPH_ASSERT(e->mNeighbourEdge->mNeighbourEdge == e);
  550. // Unlink
  551. e->mNeighbourEdge->mNeighbourEdge = nullptr;
  552. e->mNeighbourEdge = nullptr;
  553. }
  554. e = e->mNextEdge;
  555. } while (e != inFace->mFirstEdge);
  556. }
  557. void ConvexHullBuilder::FindEdge(Face *inFacingFace, Vec3Arg inVertex, FullEdges &outEdges)
  558. {
  559. // Assert that we were given an empty array
  560. JPH_ASSERT(outEdges.empty());
  561. // Should start with a facing face
  562. JPH_ASSERT(inFacingFace->IsFacing(inVertex));
  563. // Flag as removed
  564. inFacingFace->mRemoved = true;
  565. // Instead of recursing, we build our own stack with the information we need
  566. struct StackEntry
  567. {
  568. Edge * mFirstEdge;
  569. Edge * mCurrentEdge;
  570. };
  571. constexpr int cMaxEdgeLength = 128;
  572. StackEntry stack[cMaxEdgeLength];
  573. int cur_stack_pos = 0;
  574. static_assert(alignof(Edge) >= 2, "Need lowest bit to indicate to tell if we completed the loop");
  575. // Start with the face / edge provided
  576. stack[0].mFirstEdge = inFacingFace->mFirstEdge;
  577. stack[0].mCurrentEdge = reinterpret_cast<Edge *>(reinterpret_cast<uintptr_t>(inFacingFace->mFirstEdge) | 1); // Set lowest bit of pointer to make it different from the first edge
  578. for (;;)
  579. {
  580. StackEntry &cur_entry = stack[cur_stack_pos];
  581. // Next edge
  582. Edge *raw_e = cur_entry.mCurrentEdge;
  583. Edge *e = reinterpret_cast<Edge *>(reinterpret_cast<uintptr_t>(raw_e) & ~uintptr_t(1)); // Remove the lowest bit which was used to indicate that this is the first edge we're testing
  584. cur_entry.mCurrentEdge = e->mNextEdge;
  585. // If we're back at the first edge we've completed the face and we're done
  586. if (raw_e == cur_entry.mFirstEdge)
  587. {
  588. // This face needs to be removed, unlink it now, caller will free
  589. UnlinkFace(e->mFace);
  590. // Pop from stack
  591. if (--cur_stack_pos < 0)
  592. break;
  593. }
  594. else
  595. {
  596. // Visit neighbour face
  597. Edge *ne = e->mNeighbourEdge;
  598. if (ne != nullptr)
  599. {
  600. Face *n = ne->mFace;
  601. if (!n->mRemoved)
  602. {
  603. // Check if vertex is on the front side of this face
  604. if (n->IsFacing(inVertex))
  605. {
  606. // Vertex on front, this face needs to be removed
  607. n->mRemoved = true;
  608. // Add element to the stack of elements to visit
  609. cur_stack_pos++;
  610. JPH_ASSERT(cur_stack_pos < cMaxEdgeLength);
  611. StackEntry &new_entry = stack[cur_stack_pos];
  612. new_entry.mFirstEdge = ne;
  613. new_entry.mCurrentEdge = ne->mNextEdge; // We don't need to test this edge again since we came from it
  614. }
  615. else
  616. {
  617. // Vertex behind, keep edge
  618. FullEdge full;
  619. full.mNeighbourEdge = ne;
  620. full.mStartIdx = e->mStartIdx;
  621. full.mEndIdx = ne->mStartIdx;
  622. outEdges.push_back(full);
  623. }
  624. }
  625. }
  626. }
  627. }
  628. // Assert that we have a fully connected loop
  629. #ifdef JPH_ENABLE_ASSERTS
  630. for (int i = 0; i < (int)outEdges.size(); ++i)
  631. JPH_ASSERT(outEdges[i].mEndIdx == outEdges[(i + 1) % outEdges.size()].mStartIdx);
  632. #endif
  633. #ifdef JPH_CONVEX_BUILDER_DEBUG
  634. // Draw edge of facing faces
  635. for (int i = 0; i < (int)outEdges.size(); ++i)
  636. DebugRenderer::sInstance->DrawArrow(cDrawScale * (mPositions[outEdges[i].mStartIdx] + mOffset), cDrawScale * (mPositions[outEdges[i].mEndIdx] + mOffset), Color::sWhite, 0.01f);
  637. DrawState();
  638. #endif
  639. }
  640. void ConvexHullBuilder::MergeFaces(Edge *inEdge)
  641. {
  642. // Get the face
  643. Face *face = inEdge->mFace;
  644. // Find the previous and next edge
  645. Edge *next_edge = inEdge->mNextEdge;
  646. Edge *prev_edge = inEdge->GetPreviousEdge();
  647. // Get the other face
  648. Edge *other_edge = inEdge->mNeighbourEdge;
  649. Face *other_face = other_edge->mFace;
  650. // Check if attempting to merge with self
  651. JPH_ASSERT(face != other_face);
  652. #ifdef JPH_CONVEX_BUILDER_DEBUG
  653. DrawWireFace(face, Color::sGreen);
  654. DrawWireFace(other_face, Color::sRed);
  655. DrawState();
  656. #endif
  657. // Loop over the edges of the other face and make them belong to inFace
  658. Edge *edge = other_edge->mNextEdge;
  659. prev_edge->mNextEdge = edge;
  660. for (;;)
  661. {
  662. edge->mFace = face;
  663. if (edge->mNextEdge == other_edge)
  664. {
  665. // Terminate when we are back at other_edge
  666. edge->mNextEdge = next_edge;
  667. break;
  668. }
  669. edge = edge->mNextEdge;
  670. }
  671. // If the first edge happens to be inEdge we need to fix it because this edge is no longer part of the face.
  672. // Note that we replace it with the first edge of the merged face so that if the MergeFace function is called
  673. // from a loop that loops around the face that it will still terminate after visiting all edges once.
  674. if (face->mFirstEdge == inEdge)
  675. face->mFirstEdge = prev_edge->mNextEdge;
  676. // Free the edges
  677. delete inEdge;
  678. delete other_edge;
  679. // Mark the other face as removed
  680. other_face->mFirstEdge = nullptr;
  681. other_face->mRemoved = true;
  682. // Recalculate plane
  683. face->CalculateNormalAndCentroid(mPositions.data());
  684. // Merge conflict lists
  685. if (face->mFurthestPointDistanceSq > other_face->mFurthestPointDistanceSq)
  686. {
  687. // This face has a point that's further away, make sure it remains the last one as we add the other points to this faces list
  688. face->mConflictList.insert(face->mConflictList.end() - 1, other_face->mConflictList.begin(), other_face->mConflictList.end());
  689. }
  690. else
  691. {
  692. // The other face has a point that's furthest away, add that list at the end.
  693. face->mConflictList.insert(face->mConflictList.end(), other_face->mConflictList.begin(), other_face->mConflictList.end());
  694. face->mFurthestPointDistanceSq = other_face->mFurthestPointDistanceSq;
  695. }
  696. other_face->mConflictList.clear();
  697. #ifdef JPH_CONVEX_BUILDER_DEBUG
  698. DrawWireFace(face, Color::sWhite);
  699. DrawState();
  700. #endif
  701. }
  702. void ConvexHullBuilder::MergeDegenerateFace(Face *inFace, float inMinAreaSq, Faces &ioAffectedFaces)
  703. {
  704. // Check area of face
  705. if (inFace->mNormal.LengthSq() < inMinAreaSq)
  706. {
  707. // Find longest edge, since this face is a sliver this should keep the face convex
  708. float max_length_sq = 0.0f;
  709. Edge *longest_edge = nullptr;
  710. Edge *e = inFace->mFirstEdge;
  711. Vec3 p1 = mPositions[e->mStartIdx];
  712. do
  713. {
  714. Edge *next = e->mNextEdge;
  715. Vec3 p2 = mPositions[next->mStartIdx];
  716. float length_sq = (p2 - p1).LengthSq();
  717. if (length_sq >= max_length_sq)
  718. {
  719. max_length_sq = length_sq;
  720. longest_edge = e;
  721. }
  722. p1 = p2;
  723. e = next;
  724. } while (e != inFace->mFirstEdge);
  725. // Merge with face on longest edge
  726. MergeFaces(longest_edge);
  727. // Remove any invalid edges
  728. RemoveInvalidEdges(inFace, ioAffectedFaces);
  729. }
  730. }
  731. void ConvexHullBuilder::MergeCoplanarOrConcaveFaces(Face *inFace, float inCoplanarToleranceSq, Faces &ioAffectedFaces)
  732. {
  733. bool merged = false;
  734. Edge *edge = inFace->mFirstEdge;
  735. do
  736. {
  737. // Store next edge since this edge can be removed
  738. Edge *next_edge = edge->mNextEdge;
  739. // Test if centroid of one face is above plane of the other face by inCoplanarToleranceSq.
  740. // If so we need to merge other face into inFace.
  741. Face *other_face = edge->mNeighbourEdge->mFace;
  742. Vec3 delta_centroid = other_face->mCentroid - inFace->mCentroid;
  743. float dist_other_face_centroid = inFace->mNormal.Dot(delta_centroid);
  744. float signed_dist_other_face_centroid_sq = abs(dist_other_face_centroid) * dist_other_face_centroid;
  745. float dist_face_centroid = -other_face->mNormal.Dot(delta_centroid);
  746. float signed_dist_face_centroid_sq = abs(dist_face_centroid) * dist_face_centroid;
  747. float face_normal_len_sq = inFace->mNormal.LengthSq();
  748. float other_face_normal_len_sq = other_face->mNormal.LengthSq();
  749. if ((signed_dist_other_face_centroid_sq > -inCoplanarToleranceSq * face_normal_len_sq
  750. || signed_dist_face_centroid_sq > -inCoplanarToleranceSq * other_face_normal_len_sq)
  751. && inFace->mNormal.Dot(other_face->mNormal) > 0.0f) // Never merge faces that are back to back
  752. {
  753. MergeFaces(edge);
  754. merged = true;
  755. }
  756. edge = next_edge;
  757. } while (edge != inFace->mFirstEdge);
  758. if (merged)
  759. RemoveInvalidEdges(inFace, ioAffectedFaces);
  760. }
  761. void ConvexHullBuilder::sMarkAffected(Face *inFace, Faces &ioAffectedFaces)
  762. {
  763. if (find(ioAffectedFaces.begin(), ioAffectedFaces.end(), inFace) == ioAffectedFaces.end())
  764. ioAffectedFaces.push_back(inFace);
  765. }
  766. void ConvexHullBuilder::RemoveInvalidEdges(Face *inFace, Faces &ioAffectedFaces)
  767. {
  768. // This marks that the plane needs to be recalculated (we delay this until the end of the
  769. // function since we don't use the plane and we want to avoid calculating it multiple times)
  770. bool recalculate_plane = false;
  771. // We keep going through this loop until no more edges were removed
  772. bool removed;
  773. do
  774. {
  775. removed = false;
  776. // Loop over all edges in this face
  777. Edge *edge = inFace->mFirstEdge;
  778. Face *neighbour_face = edge->mNeighbourEdge->mFace;
  779. do
  780. {
  781. Edge *next_edge = edge->mNextEdge;
  782. Face *next_neighbour_face = next_edge->mNeighbourEdge->mFace;
  783. if (neighbour_face == inFace)
  784. {
  785. // We only remove 1 edge at a time, check if this edge's next edge is our neighbour.
  786. // If this check fails, we will continue to scan along the edge until we find an edge where this is the case.
  787. if (edge->mNeighbourEdge == next_edge)
  788. {
  789. // This edge leads back to the starting point, this means the edge is interior and needs to be removed
  790. #ifdef JPH_CONVEX_BUILDER_DEBUG
  791. DrawWireFace(inFace, Color::sBlue);
  792. DrawState();
  793. #endif
  794. // Remove edge
  795. Edge *prev_edge = edge->GetPreviousEdge();
  796. prev_edge->mNextEdge = next_edge->mNextEdge;
  797. if (inFace->mFirstEdge == edge || inFace->mFirstEdge == next_edge)
  798. inFace->mFirstEdge = prev_edge;
  799. delete edge;
  800. delete next_edge;
  801. #ifdef JPH_CONVEX_BUILDER_DEBUG
  802. DrawWireFace(inFace, Color::sGreen);
  803. DrawState();
  804. #endif
  805. // Check if inFace now has only 2 edges left
  806. if (RemoveTwoEdgeFace(inFace, ioAffectedFaces))
  807. return; // Bail if face no longer exists
  808. // Restart the loop
  809. recalculate_plane = true;
  810. removed = true;
  811. break;
  812. }
  813. }
  814. else if (neighbour_face == next_neighbour_face)
  815. {
  816. // There are two edges that connect to the same face, we will remove the second one
  817. #ifdef JPH_CONVEX_BUILDER_DEBUG
  818. DrawWireFace(inFace, Color::sYellow);
  819. DrawWireFace(neighbour_face, Color::sRed);
  820. DrawState();
  821. #endif
  822. // First merge the neighbours edges
  823. Edge *neighbour_edge = next_edge->mNeighbourEdge;
  824. Edge *next_neighbour_edge = neighbour_edge->mNextEdge;
  825. if (neighbour_face->mFirstEdge == next_neighbour_edge)
  826. neighbour_face->mFirstEdge = neighbour_edge;
  827. neighbour_edge->mNextEdge = next_neighbour_edge->mNextEdge;
  828. neighbour_edge->mNeighbourEdge = edge;
  829. delete next_neighbour_edge;
  830. // Then merge my own edges
  831. if (inFace->mFirstEdge == next_edge)
  832. inFace->mFirstEdge = edge;
  833. edge->mNextEdge = next_edge->mNextEdge;
  834. edge->mNeighbourEdge = neighbour_edge;
  835. delete next_edge;
  836. #ifdef JPH_CONVEX_BUILDER_DEBUG
  837. DrawWireFace(inFace, Color::sYellow);
  838. DrawWireFace(neighbour_face, Color::sGreen);
  839. DrawState();
  840. #endif
  841. // Check if neighbour has only 2 edges left
  842. if (!RemoveTwoEdgeFace(neighbour_face, ioAffectedFaces))
  843. {
  844. // No, we need to recalculate its plane
  845. neighbour_face->CalculateNormalAndCentroid(mPositions.data());
  846. // Mark neighbour face as affected
  847. sMarkAffected(neighbour_face, ioAffectedFaces);
  848. }
  849. // Check if inFace now has only 2 edges left
  850. if (RemoveTwoEdgeFace(inFace, ioAffectedFaces))
  851. return; // Bail if face no longer exists
  852. // Restart loop
  853. recalculate_plane = true;
  854. removed = true;
  855. break;
  856. }
  857. // This edge is ok, go to the next edge
  858. edge = next_edge;
  859. neighbour_face = next_neighbour_face;
  860. } while (edge != inFace->mFirstEdge);
  861. } while (removed);
  862. // Recalculate plane?
  863. if (recalculate_plane)
  864. inFace->CalculateNormalAndCentroid(mPositions.data());
  865. }
  866. bool ConvexHullBuilder::RemoveTwoEdgeFace(Face *inFace, Faces &ioAffectedFaces)
  867. {
  868. // Check if this face contains only 2 edges
  869. Edge *edge = inFace->mFirstEdge;
  870. Edge *next_edge = edge->mNextEdge;
  871. JPH_ASSERT(edge != next_edge); // 1 edge faces should not exist
  872. if (next_edge->mNextEdge == edge)
  873. {
  874. #ifdef JPH_CONVEX_BUILDER_DEBUG
  875. DrawWireFace(inFace, Color::sRed);
  876. DrawState();
  877. #endif
  878. // Schedule both neighbours for re-checking
  879. Edge *neighbour_edge = edge->mNeighbourEdge;
  880. Face *neighbour_face = neighbour_edge->mFace;
  881. Edge *next_neighbour_edge = next_edge->mNeighbourEdge;
  882. Face *next_neighbour_face = next_neighbour_edge->mFace;
  883. sMarkAffected(neighbour_face, ioAffectedFaces);
  884. sMarkAffected(next_neighbour_face, ioAffectedFaces);
  885. // Link my neighbours to each other
  886. neighbour_edge->mNeighbourEdge = next_neighbour_edge;
  887. next_neighbour_edge->mNeighbourEdge = neighbour_edge;
  888. // Unlink my edges
  889. edge->mNeighbourEdge = nullptr;
  890. next_edge->mNeighbourEdge = nullptr;
  891. // Mark this face as removed
  892. inFace->mRemoved = true;
  893. return true;
  894. }
  895. return false;
  896. }
  897. #ifdef JPH_ENABLE_ASSERTS
  898. void ConvexHullBuilder::DumpFace(const Face *inFace) const
  899. {
  900. Trace("f:0x%p", inFace);
  901. const Edge *e = inFace->mFirstEdge;
  902. do
  903. {
  904. Trace("\te:0x%p { i:%d e:0x%p f:0x%p }", e, e->mStartIdx, e->mNeighbourEdge, e->mNeighbourEdge->mFace);
  905. e = e->mNextEdge;
  906. } while (e != inFace->mFirstEdge);
  907. }
  908. void ConvexHullBuilder::DumpFaces() const
  909. {
  910. Trace("Dump Faces:");
  911. for (const Face *f : mFaces)
  912. if (!f->mRemoved)
  913. DumpFace(f);
  914. }
  915. void ConvexHullBuilder::ValidateFace(const Face *inFace) const
  916. {
  917. if (inFace->mRemoved)
  918. {
  919. const Edge *e = inFace->mFirstEdge;
  920. if (e != nullptr)
  921. do
  922. {
  923. JPH_ASSERT(e->mNeighbourEdge == nullptr);
  924. e = e->mNextEdge;
  925. } while (e != inFace->mFirstEdge);
  926. }
  927. else
  928. {
  929. int edge_count = 0;
  930. const Edge *e = inFace->mFirstEdge;
  931. do
  932. {
  933. // Count edge
  934. ++edge_count;
  935. // Validate that adjacent faces are all different
  936. if (mFaces.size() > 2)
  937. for (const Edge *other_edge = e->mNextEdge; other_edge != inFace->mFirstEdge; other_edge = other_edge->mNextEdge)
  938. JPH_ASSERT(e->mNeighbourEdge->mFace != other_edge->mNeighbourEdge->mFace);
  939. // Assert that the face is correct
  940. JPH_ASSERT(e->mFace == inFace);
  941. // Assert that we have a neighbour
  942. const Edge *nb_edge = e->mNeighbourEdge;
  943. JPH_ASSERT(nb_edge != nullptr);
  944. if (nb_edge != nullptr)
  945. {
  946. // Assert that our neighbours edge points to us
  947. JPH_ASSERT(nb_edge->mNeighbourEdge == e);
  948. // Assert that it belongs to a different face
  949. JPH_ASSERT(nb_edge->mFace != inFace);
  950. // Assert that the next edge of the neighbour points to the same vertex as this edge's vertex
  951. JPH_ASSERT(nb_edge->mNextEdge->mStartIdx == e->mStartIdx);
  952. // Assert that my next edge points to the same vertex as my neighbours vertex
  953. JPH_ASSERT(e->mNextEdge->mStartIdx == nb_edge->mStartIdx);
  954. }
  955. e = e->mNextEdge;
  956. } while (e != inFace->mFirstEdge);
  957. // Assert that we have 3 or more edges
  958. JPH_ASSERT(edge_count >= 3);
  959. }
  960. }
  961. void ConvexHullBuilder::ValidateFaces() const
  962. {
  963. for (const Face *f : mFaces)
  964. ValidateFace(f);
  965. }
  966. #endif // JPH_ENABLE_ASSERTS
  967. void ConvexHullBuilder::GetCenterOfMassAndVolume(Vec3 &outCenterOfMass, float &outVolume) const
  968. {
  969. // Fourth point is the average of all face centroids
  970. Vec3 v4 = Vec3::sZero();
  971. for (const Face *f : mFaces)
  972. v4 += f->mCentroid;
  973. v4 /= float(mFaces.size());
  974. // Calculate mass and center of mass of this convex hull by summing all tetrahedrons
  975. outVolume = 0.0f;
  976. outCenterOfMass = Vec3::sZero();
  977. for (const Face *f : mFaces)
  978. {
  979. // Get the first vertex that we'll use to create a triangle fan
  980. Edge *e = f->mFirstEdge;
  981. Vec3 v1 = mPositions[e->mStartIdx];
  982. // Get the second vertex
  983. e = e->mNextEdge;
  984. Vec3 v2 = mPositions[e->mStartIdx];
  985. for (e = e->mNextEdge; e != f->mFirstEdge; e = e->mNextEdge)
  986. {
  987. // Fetch the last point of the triangle
  988. Vec3 v3 = mPositions[e->mStartIdx];
  989. // Calculate center of mass and mass of this tetrahedron,
  990. // see: https://en.wikipedia.org/wiki/Tetrahedron#Volume
  991. float volume_tetrahedron = (v1 - v4).Dot((v2 - v4).Cross(v3 - v4)); // Needs to be divided by 6, postpone this until the end of the loop
  992. Vec3 center_of_mass_tetrahedron = v1 + v2 + v3 + v4; // Needs to be divided by 4, postpone this until the end of the loop
  993. // Accumulate results
  994. outVolume += volume_tetrahedron;
  995. outCenterOfMass += volume_tetrahedron * center_of_mass_tetrahedron;
  996. // Update v2 for next triangle
  997. v2 = v3;
  998. } while (e != f->mFirstEdge);
  999. }
  1000. // Calculate center of mass, fall back to average point in case there is no volume (everything is on a plane in this case)
  1001. if (outVolume > FLT_EPSILON)
  1002. outCenterOfMass /= 4.0f * outVolume;
  1003. else
  1004. outCenterOfMass = v4;
  1005. outVolume /= 6.0f;
  1006. }
  1007. void ConvexHullBuilder::DetermineMaxError(Face *&outFaceWithMaxError, float &outMaxError, int &outMaxErrorPositionIdx, float &outCoplanarDistance) const
  1008. {
  1009. outCoplanarDistance = DetermineCoplanarDistance();
  1010. // This measures the distance from a polygon to the furthest point outside of the hull
  1011. float max_error = 0.0f;
  1012. Face *max_error_face = nullptr;
  1013. int max_error_point = -1;
  1014. for (int i = 0; i < (int)mPositions.size(); ++i)
  1015. {
  1016. Vec3 v = mPositions[i];
  1017. // This measures the closest edge from all faces to point v
  1018. // Note that we take the min of all faces since there may be multiple near coplanar faces so if we were to test this per face
  1019. // we may find that a point is outside of a polygon and mark it as an error, while it is actually inside a nearly coplanar
  1020. // polygon.
  1021. float min_edge_dist = FLT_MAX;
  1022. Face *min_edge_dist_face = nullptr;
  1023. for (Face *f : mFaces)
  1024. {
  1025. // Check if point is on or in front of plane
  1026. float normal_len = f->mNormal.Length();
  1027. JPH_ASSERT(normal_len > 0.0f);
  1028. float plane_dist = f->mNormal.Dot(v - f->mCentroid) / normal_len;
  1029. if (plane_dist > -outCoplanarDistance)
  1030. {
  1031. bool all_inside = true;
  1032. // Test if it is inside the edges of the polygon
  1033. Edge *edge = f->mFirstEdge;
  1034. Vec3 p1 = mPositions[edge->GetPreviousEdge()->mStartIdx];
  1035. do
  1036. {
  1037. Vec3 p2 = mPositions[edge->mStartIdx];
  1038. if ((p2 - p1).Cross(v - p1).Dot(f->mNormal) < 0.0f)
  1039. {
  1040. // It is outside
  1041. all_inside = false;
  1042. // Measure distance to this edge
  1043. uint32 s;
  1044. float edge_dist = ClosestPoint::GetClosestPointOnLine(p1 - v, p2 - v, s).Length();
  1045. if (edge_dist < min_edge_dist)
  1046. {
  1047. min_edge_dist = edge_dist;
  1048. min_edge_dist_face = f;
  1049. }
  1050. }
  1051. p1 = p2;
  1052. edge = edge->mNextEdge;
  1053. } while (edge != f->mFirstEdge);
  1054. if (all_inside)
  1055. {
  1056. // The point is inside the polygon, reset distance to edge
  1057. min_edge_dist = 0.0f;
  1058. min_edge_dist_face = f;
  1059. // If the point is in front of the plane, measure the distance
  1060. if (plane_dist > max_error)
  1061. {
  1062. max_error = plane_dist;
  1063. max_error_face = f;
  1064. max_error_point = i;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. // If the minimum distance to an edge is further than our current max error, we use that as max error
  1070. if (min_edge_dist_face != nullptr && min_edge_dist > max_error)
  1071. {
  1072. max_error = min_edge_dist;
  1073. max_error_face = min_edge_dist_face;
  1074. max_error_point = i;
  1075. }
  1076. }
  1077. outFaceWithMaxError = max_error_face;
  1078. outMaxError = max_error;
  1079. outMaxErrorPositionIdx = max_error_point;
  1080. }
  1081. #ifdef JPH_CONVEX_BUILDER_DEBUG
  1082. void ConvexHullBuilder::DrawState(bool inDrawConflictList)
  1083. {
  1084. // Draw origin
  1085. DebugRenderer::sInstance->DrawMarker(cDrawScale * mOffset, Color::sRed, 0.2f);
  1086. int face_idx = 0;
  1087. // Draw faces
  1088. for (const Face *f : mFaces)
  1089. if (!f->mRemoved)
  1090. {
  1091. Color iteration_color = Color::sGetDistinctColor(f->mIteration);
  1092. Color face_color = Color::sGetDistinctColor(face_idx++);
  1093. // First point
  1094. const Edge *e = f->mFirstEdge;
  1095. Vec3 p1 = cDrawScale * (mPositions[e->mStartIdx] + mOffset);
  1096. // Second point
  1097. e = e->mNextEdge;
  1098. Vec3 p2 = cDrawScale * (mPositions[e->mStartIdx] + mOffset);
  1099. // First line
  1100. DebugRenderer::sInstance->DrawLine(p1, p2, Color::sGrey);
  1101. do
  1102. {
  1103. // Third point
  1104. e = e->mNextEdge;
  1105. Vec3 p3 = cDrawScale * (mPositions[e->mStartIdx] + mOffset);
  1106. DebugRenderer::sInstance->DrawTriangle(p1, p2, p3, iteration_color);
  1107. DebugRenderer::sInstance->DrawLine(p2, p3, Color::sGrey);
  1108. p2 = p3;
  1109. }
  1110. while (e != f->mFirstEdge);
  1111. // Draw normal
  1112. Vec3 centroid = cDrawScale * (f->mCentroid + mOffset);
  1113. DebugRenderer::sInstance->DrawArrow(centroid, centroid + f->mNormal.Normalized(), face_color, 0.01f);
  1114. // Draw conflict list
  1115. if (inDrawConflictList)
  1116. for (int idx : f->mConflictList)
  1117. DebugRenderer::sInstance->DrawMarker(cDrawScale * (mOffset + mPositions[idx]), face_color, 0.05f);
  1118. }
  1119. // Offset to the right
  1120. mOffset += mDelta;
  1121. }
  1122. void ConvexHullBuilder::DrawWireFace(const Face *inFace, ColorArg inColor) const
  1123. {
  1124. const Edge *e = inFace->mFirstEdge;
  1125. Vec3 prev = cDrawScale * (mPositions[e->mStartIdx] + mOffset);
  1126. do
  1127. {
  1128. const Edge *next = e->mNextEdge;
  1129. Vec3 cur = cDrawScale * (mPositions[next->mStartIdx] + mOffset);
  1130. DebugRenderer::sInstance->DrawArrow(prev, cur, inColor, 0.01f);
  1131. DebugRenderer::sInstance->DrawText3D(prev, ConvertToString(e->mStartIdx), inColor);
  1132. e = next;
  1133. prev = cur;
  1134. } while (e != inFace->mFirstEdge);
  1135. }
  1136. void ConvexHullBuilder::DrawEdge(const Edge *inEdge, ColorArg inColor) const
  1137. {
  1138. Vec3 p1 = cDrawScale * (mPositions[inEdge->mStartIdx] + mOffset);
  1139. Vec3 p2 = cDrawScale * (mPositions[inEdge->mNextEdge->mStartIdx] + mOffset);
  1140. DebugRenderer::sInstance->DrawArrow(p1, p2, inColor, 0.01f);
  1141. }
  1142. #endif // JPH_CONVEX_BUILDER_DEBUG
  1143. #ifdef JPH_CONVEX_BUILDER_DUMP_SHAPE
  1144. void ConvexHullBuilder::DumpShape() const
  1145. {
  1146. static atomic<int> sShapeNo = 1;
  1147. int shape_no = sShapeNo++;
  1148. ofstream f;
  1149. f.open(StringFormat("dumped_shape%d.cpp", shape_no).c_str(), ofstream::out | ofstream::trunc);
  1150. if (!f.is_open())
  1151. return;
  1152. f << "{\n";
  1153. for (Vec3 v : mPositions)
  1154. f << StringFormat("\tVec3(%.9gf, %.9gf, %.9gf),\n", v.GetX(), v.GetY(), v.GetZ());
  1155. f << "},\n";
  1156. }
  1157. #endif // JPH_CONVEX_BUILDER_DUMP_SHAPE
  1158. } // JPH