EPAConvexHullBuilder.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. // Define to validate the integrity of the hull structure
  6. //#define JPH_EPA_CONVEX_BUILDER_VALIDATE
  7. // Define to draw the building of the hull for debugging purposes
  8. //#define JPH_EPA_CONVEX_BUILDER_DRAW
  9. #include <Jolt/Core/NonCopyable.h>
  10. #include <Jolt/Core/BinaryHeap.h>
  11. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  12. #include <Jolt/Renderer/DebugRenderer.h>
  13. #include <Jolt/Core/StringTools.h>
  14. #endif
  15. JPH_NAMESPACE_BEGIN
  16. /// A convex hull builder specifically made for the EPA penetration depth calculation. It trades accuracy for speed and will simply abort of the hull forms defects due to numerical precision problems.
  17. class EPAConvexHullBuilder : public NonCopyable
  18. {
  19. private:
  20. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  21. /// Factor to scale convex hull when debug drawing the construction process
  22. static constexpr Real cDrawScale = 10;
  23. #endif
  24. public:
  25. // Due to the Euler characteristic (https://en.wikipedia.org/wiki/Euler_characteristic) we know that Vertices - Edges + Faces = 2
  26. // In our case we only have triangles and they are always fully connected, so each edge is shared exactly between 2 faces: Edges = Faces * 3 / 2
  27. // Substituting: Vertices = Faces / 2 + 2 which is approximately Faces / 2.
  28. static constexpr int cMaxTriangles = 256; ///< Max triangles in hull
  29. static constexpr int cMaxPoints = cMaxTriangles / 2; ///< Max number of points in hull
  30. // Constants
  31. static constexpr int cMaxEdgeLength = 128; ///< Max number of edges in FindEdge
  32. static constexpr float cMinTriangleArea = 1.0e-10f; ///< Minimum area of a triangle before, if smaller than this it will not be added to the priority queue
  33. static constexpr float cBarycentricEpsilon = 1.0e-3f; ///< Epsilon value used to determine if a point is in the interior of a triangle
  34. // Forward declare
  35. class Triangle;
  36. /// Class that holds the information of an edge
  37. class Edge
  38. {
  39. public:
  40. /// Information about neighbouring triangle
  41. Triangle * mNeighbourTriangle; ///< Triangle that neighbours this triangle
  42. int mNeighbourEdge; ///< Index in mEdge that specifies edge that this Edge is connected to
  43. int mStartIdx; ///< Vertex index in mPositions that indicates the start vertex of this edge
  44. };
  45. using Edges = StaticArray<Edge, cMaxEdgeLength>;
  46. using NewTriangles = StaticArray<Triangle *, cMaxEdgeLength>;
  47. /// Class that holds the information of one triangle
  48. class Triangle : public NonCopyable
  49. {
  50. public:
  51. /// Constructor
  52. inline Triangle(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions);
  53. /// Check if triangle is facing inPosition
  54. inline bool IsFacing(Vec3Arg inPosition) const
  55. {
  56. JPH_ASSERT(!mRemoved);
  57. return mNormal.Dot(inPosition - mCentroid) > 0.0f;
  58. }
  59. /// Check if triangle is facing the origin
  60. inline bool IsFacingOrigin() const
  61. {
  62. JPH_ASSERT(!mRemoved);
  63. return mNormal.Dot(mCentroid) < 0.0f;
  64. }
  65. /// Get the next edge of edge inIndex
  66. inline const Edge & GetNextEdge(int inIndex) const
  67. {
  68. return mEdge[(inIndex + 1) % 3];
  69. }
  70. Edge mEdge[3]; ///< 3 edges of this triangle
  71. Vec3 mNormal; ///< Normal of this triangle, length is 2 times area of triangle
  72. Vec3 mCentroid; ///< Center of the triangle
  73. float mClosestLenSq = FLT_MAX; ///< Closest distance^2 from origin to triangle
  74. float mLambda[2]; ///< Barycentric coordinates of closest point to origin on triangle
  75. bool mLambdaRelativeTo0; ///< How to calculate the closest point, true: y0 + l0 * (y1 - y0) + l1 * (y2 - y0), false: y1 + l0 * (y0 - y1) + l1 * (y2 - y1)
  76. bool mClosestPointInterior = false; ///< Flag that indicates that the closest point from this triangle to the origin is an interior point
  77. bool mRemoved = false; ///< Flag that indicates that triangle has been removed
  78. bool mInQueue = false; ///< Flag that indicates that this triangle was placed in the sorted heap (stays true after it is popped because the triangle is freed by the main EPA algorithm loop)
  79. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  80. int mIteration; ///< Iteration that this triangle was created
  81. #endif
  82. };
  83. /// Factory that creates triangles in a fixed size buffer
  84. class TriangleFactory : public NonCopyable
  85. {
  86. private:
  87. /// Struct that stores both a triangle or a next pointer in case the triangle is unused
  88. union alignas(Triangle) Block
  89. {
  90. uint8 mTriangle[sizeof(Triangle)];
  91. Block * mNextFree;
  92. };
  93. /// Storage for triangle data
  94. Block mTriangles[cMaxTriangles]; ///< Storage for triangles
  95. Block * mNextFree = nullptr; ///< List of free triangles
  96. int mHighWatermark = 0; ///< High water mark for used triangles (if mNextFree == nullptr we can take one from here)
  97. public:
  98. /// Return all triangles to the free pool
  99. void Clear()
  100. {
  101. mNextFree = nullptr;
  102. mHighWatermark = 0;
  103. }
  104. /// Allocate a new triangle with 3 indexes
  105. Triangle * CreateTriangle(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions)
  106. {
  107. Triangle *t;
  108. if (mNextFree != nullptr)
  109. {
  110. // Entry available from the free list
  111. t = reinterpret_cast<Triangle *>(&mNextFree->mTriangle);
  112. mNextFree = mNextFree->mNextFree;
  113. }
  114. else
  115. {
  116. // Allocate from never used before triangle store
  117. if (mHighWatermark >= cMaxTriangles)
  118. return nullptr; // Buffer full
  119. t = reinterpret_cast<Triangle *>(&mTriangles[mHighWatermark].mTriangle);
  120. ++mHighWatermark;
  121. }
  122. // Call constructor
  123. new (t) Triangle(inIdx0, inIdx1, inIdx2, inPositions);
  124. return t;
  125. }
  126. /// Free a triangle
  127. void FreeTriangle(Triangle *inT)
  128. {
  129. // Destruct triangle
  130. inT->~Triangle();
  131. #ifdef JPH_DEBUG
  132. memset(inT, 0xcd, sizeof(Triangle));
  133. #endif
  134. // Add triangle to the free list
  135. Block *tu = reinterpret_cast<Block *>(inT);
  136. tu->mNextFree = mNextFree;
  137. mNextFree = tu;
  138. }
  139. };
  140. // Typedefs
  141. using PointsBase = StaticArray<Vec3, cMaxPoints>;
  142. using Triangles = StaticArray<Triangle *, cMaxTriangles>;
  143. /// Specialized points list that allows direct access to the size
  144. class Points : public PointsBase
  145. {
  146. public:
  147. size_type & GetSizeRef()
  148. {
  149. return mSize;
  150. }
  151. };
  152. /// Specialized triangles list that keeps them sorted on closest distance to origin
  153. class TriangleQueue : public Triangles
  154. {
  155. public:
  156. /// Function to sort triangles on closest distance to origin
  157. static bool sTriangleSorter(const Triangle *inT1, const Triangle *inT2)
  158. {
  159. return inT1->mClosestLenSq > inT2->mClosestLenSq;
  160. }
  161. /// Add triangle to the list
  162. void push_back(Triangle *inT)
  163. {
  164. // Add to base
  165. Triangles::push_back(inT);
  166. // Mark in queue
  167. inT->mInQueue = true;
  168. // Resort heap
  169. BinaryHeapPush(begin(), end(), sTriangleSorter);
  170. }
  171. /// Peek the next closest triangle without removing it
  172. Triangle * PeekClosest()
  173. {
  174. return front();
  175. }
  176. /// Get next closest triangle
  177. Triangle * PopClosest()
  178. {
  179. // Move closest to end
  180. BinaryHeapPop(begin(), end(), sTriangleSorter);
  181. // Remove last triangle
  182. Triangle *t = back();
  183. pop_back();
  184. return t;
  185. }
  186. };
  187. /// Constructor
  188. explicit EPAConvexHullBuilder(const Points &inPositions) :
  189. mPositions(inPositions)
  190. {
  191. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  192. mIteration = 0;
  193. mOffset = RVec3::sZero();
  194. #endif
  195. }
  196. /// Initialize the hull with 3 points
  197. void Initialize(int inIdx1, int inIdx2, int inIdx3)
  198. {
  199. // Release triangles
  200. mFactory.Clear();
  201. // Create triangles (back to back)
  202. Triangle *t1 = CreateTriangle(inIdx1, inIdx2, inIdx3);
  203. Triangle *t2 = CreateTriangle(inIdx1, inIdx3, inIdx2);
  204. // Link triangles edges
  205. sLinkTriangle(t1, 0, t2, 2);
  206. sLinkTriangle(t1, 1, t2, 1);
  207. sLinkTriangle(t1, 2, t2, 0);
  208. // Always add both triangles to the priority queue
  209. mTriangleQueue.push_back(t1);
  210. mTriangleQueue.push_back(t2);
  211. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  212. // Draw current state
  213. DrawState();
  214. // Increment iteration counter
  215. ++mIteration;
  216. #endif
  217. }
  218. /// Check if there's another triangle to process from the queue
  219. bool HasNextTriangle() const
  220. {
  221. return !mTriangleQueue.empty();
  222. }
  223. /// Access to the next closest triangle to the origin (won't remove it from the queue).
  224. Triangle * PeekClosestTriangleInQueue()
  225. {
  226. return mTriangleQueue.PeekClosest();
  227. }
  228. /// Access to the next closest triangle to the origin and remove it from the queue.
  229. Triangle * PopClosestTriangleFromQueue()
  230. {
  231. return mTriangleQueue.PopClosest();
  232. }
  233. /// Find the triangle on which inPosition is the furthest to the front
  234. /// Note this function works as long as all points added have been added with AddPoint(..., FLT_MAX).
  235. Triangle * FindFacingTriangle(Vec3Arg inPosition, float &outBestDistSq)
  236. {
  237. Triangle *best = nullptr;
  238. float best_dist_sq = 0.0f;
  239. for (Triangle *t : mTriangleQueue)
  240. if (!t->mRemoved)
  241. {
  242. float dot = t->mNormal.Dot(inPosition - t->mCentroid);
  243. if (dot > 0.0f)
  244. {
  245. float dist_sq = dot * dot / t->mNormal.LengthSq();
  246. if (dist_sq > best_dist_sq)
  247. {
  248. best = t;
  249. best_dist_sq = dist_sq;
  250. }
  251. }
  252. }
  253. outBestDistSq = best_dist_sq;
  254. return best;
  255. }
  256. /// Add a new point to the convex hull
  257. bool AddPoint(Triangle *inFacingTriangle, int inIdx, float inClosestDistSq, NewTriangles &outTriangles)
  258. {
  259. // Get position
  260. Vec3 pos = mPositions[inIdx];
  261. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  262. // Draw new support point
  263. DrawMarker(pos, Color::sYellow, 1.0f);
  264. #endif
  265. #ifdef JPH_EPA_CONVEX_BUILDER_VALIDATE
  266. // Check if structure is intact
  267. ValidateTriangles();
  268. #endif
  269. // Find edge of convex hull of triangles that are not facing the new vertex w
  270. Edges edges;
  271. if (!FindEdge(inFacingTriangle, pos, edges))
  272. return false;
  273. // Create new triangles
  274. int num_edges = edges.size();
  275. for (int i = 0; i < num_edges; ++i)
  276. {
  277. // Create new triangle
  278. Triangle *nt = CreateTriangle(edges[i].mStartIdx, edges[(i + 1) % num_edges].mStartIdx, inIdx);
  279. if (nt == nullptr)
  280. return false;
  281. outTriangles.push_back(nt);
  282. // Check if we need to put this triangle in the priority queue
  283. if ((nt->mClosestPointInterior && nt->mClosestLenSq < inClosestDistSq) // For the main algorithm
  284. || nt->mClosestLenSq < 0.0f) // For when the origin is not inside the hull yet
  285. mTriangleQueue.push_back(nt);
  286. }
  287. // Link edges
  288. for (int i = 0; i < num_edges; ++i)
  289. {
  290. sLinkTriangle(outTriangles[i], 0, edges[i].mNeighbourTriangle, edges[i].mNeighbourEdge);
  291. sLinkTriangle(outTriangles[i], 1, outTriangles[(i + 1) % num_edges], 2);
  292. }
  293. #ifdef JPH_EPA_CONVEX_BUILDER_VALIDATE
  294. // Check if structure is intact
  295. ValidateTriangles();
  296. #endif
  297. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  298. // Draw state of the hull
  299. DrawState();
  300. // Increment iteration counter
  301. ++mIteration;
  302. #endif
  303. return true;
  304. }
  305. /// Free a triangle
  306. void FreeTriangle(Triangle *inT)
  307. {
  308. #ifdef JPH_ENABLE_ASSERTS
  309. // Make sure that this triangle is not connected
  310. JPH_ASSERT(inT->mRemoved);
  311. for (const Edge &e : inT->mEdge)
  312. JPH_ASSERT(e.mNeighbourTriangle == nullptr);
  313. #endif
  314. #if defined(JPH_EPA_CONVEX_BUILDER_VALIDATE) || defined(JPH_EPA_CONVEX_BUILDER_DRAW)
  315. // Remove from list of all triangles
  316. Triangles::iterator i = std::find(mTriangles.begin(), mTriangles.end(), inT);
  317. JPH_ASSERT(i != mTriangles.end());
  318. mTriangles.erase(i);
  319. #endif
  320. mFactory.FreeTriangle(inT);
  321. }
  322. private:
  323. /// Create a new triangle
  324. Triangle * CreateTriangle(int inIdx1, int inIdx2, int inIdx3)
  325. {
  326. // Call provider to create triangle
  327. Triangle *t = mFactory.CreateTriangle(inIdx1, inIdx2, inIdx3, mPositions.data());
  328. if (t == nullptr)
  329. return nullptr;
  330. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  331. // Remember iteration counter
  332. t->mIteration = mIteration;
  333. #endif
  334. #if defined(JPH_EPA_CONVEX_BUILDER_VALIDATE) || defined(JPH_EPA_CONVEX_BUILDER_DRAW)
  335. // Add to list of triangles for debugging purposes
  336. mTriangles.push_back(t);
  337. #endif
  338. return t;
  339. }
  340. /// Link triangle edge to other triangle edge
  341. static void sLinkTriangle(Triangle *inT1, int inEdge1, Triangle *inT2, int inEdge2)
  342. {
  343. JPH_ASSERT(inEdge1 >= 0 && inEdge1 < 3);
  344. JPH_ASSERT(inEdge2 >= 0 && inEdge2 < 3);
  345. Edge &e1 = inT1->mEdge[inEdge1];
  346. Edge &e2 = inT2->mEdge[inEdge2];
  347. // Check not connected yet
  348. JPH_ASSERT(e1.mNeighbourTriangle == nullptr);
  349. JPH_ASSERT(e2.mNeighbourTriangle == nullptr);
  350. // Check vertices match
  351. JPH_ASSERT(e1.mStartIdx == inT2->GetNextEdge(inEdge2).mStartIdx);
  352. JPH_ASSERT(e2.mStartIdx == inT1->GetNextEdge(inEdge1).mStartIdx);
  353. // Link up
  354. e1.mNeighbourTriangle = inT2;
  355. e1.mNeighbourEdge = inEdge2;
  356. e2.mNeighbourTriangle = inT1;
  357. e2.mNeighbourEdge = inEdge1;
  358. }
  359. /// Unlink this triangle
  360. void UnlinkTriangle(Triangle *inT)
  361. {
  362. // Unlink from neighbours
  363. for (int i = 0; i < 3; ++i)
  364. {
  365. Edge &edge = inT->mEdge[i];
  366. if (edge.mNeighbourTriangle != nullptr)
  367. {
  368. Edge &neighbour_edge = edge.mNeighbourTriangle->mEdge[edge.mNeighbourEdge];
  369. // Validate that neighbour points to us
  370. JPH_ASSERT(neighbour_edge.mNeighbourTriangle == inT);
  371. JPH_ASSERT(neighbour_edge.mNeighbourEdge == i);
  372. // Unlink
  373. neighbour_edge.mNeighbourTriangle = nullptr;
  374. edge.mNeighbourTriangle = nullptr;
  375. }
  376. }
  377. // If this triangle is not in the priority queue, we can delete it now
  378. if (!inT->mInQueue)
  379. FreeTriangle(inT);
  380. }
  381. /// Given one triangle that faces inVertex, find the edges of the triangles that are not facing inVertex.
  382. /// Will flag all those triangles for removal.
  383. bool FindEdge(Triangle *inFacingTriangle, Vec3Arg inVertex, Edges &outEdges)
  384. {
  385. // Assert that we were given an empty array
  386. JPH_ASSERT(outEdges.empty());
  387. // Should start with a facing triangle
  388. JPH_ASSERT(inFacingTriangle->IsFacing(inVertex));
  389. // Flag as removed
  390. inFacingTriangle->mRemoved = true;
  391. // Instead of recursing, we build our own stack with the information we need
  392. struct StackEntry
  393. {
  394. Triangle * mTriangle;
  395. int mEdge;
  396. int mIter;
  397. };
  398. StackEntry stack[cMaxEdgeLength];
  399. int cur_stack_pos = 0;
  400. // Start with the triangle / edge provided
  401. stack[0].mTriangle = inFacingTriangle;
  402. stack[0].mEdge = 0;
  403. stack[0].mIter = -1; // Start with edge 0 (is incremented below before use)
  404. // Next index that we expect to find, if we don't then there are 'islands'
  405. int next_expected_start_idx = -1;
  406. for (;;)
  407. {
  408. StackEntry &cur_entry = stack[cur_stack_pos];
  409. // Next iteration
  410. if (++cur_entry.mIter >= 3)
  411. {
  412. // This triangle needs to be removed, unlink it now
  413. UnlinkTriangle(cur_entry.mTriangle);
  414. // Pop from stack
  415. if (--cur_stack_pos < 0)
  416. break;
  417. }
  418. else
  419. {
  420. // Visit neighbour
  421. Edge &e = cur_entry.mTriangle->mEdge[(cur_entry.mEdge + cur_entry.mIter) % 3];
  422. Triangle *n = e.mNeighbourTriangle;
  423. if (n != nullptr && !n->mRemoved)
  424. {
  425. // Check if vertex is on the front side of this triangle
  426. if (n->IsFacing(inVertex))
  427. {
  428. // Vertex on front, this triangle needs to be removed
  429. n->mRemoved = true;
  430. // Add element to the stack of elements to visit
  431. cur_stack_pos++;
  432. JPH_ASSERT(cur_stack_pos < cMaxEdgeLength);
  433. StackEntry &new_entry = stack[cur_stack_pos];
  434. new_entry.mTriangle = n;
  435. new_entry.mEdge = e.mNeighbourEdge;
  436. new_entry.mIter = 0; // Is incremented before use, we don't need to test this edge again since we came from it
  437. }
  438. else
  439. {
  440. // Detect if edge doesn't connect to previous edge, if this happens we have found and 'island' which means
  441. // the newly added point is so close to the triangles of the hull that we classified some (nearly) coplanar
  442. // triangles as before and some behind the point. At this point we just abort adding the point because
  443. // we've reached numerical precision.
  444. // Note that we do not need to test if the first and last edge connect, since when there are islands
  445. // there should be at least 2 disconnects.
  446. if (e.mStartIdx != next_expected_start_idx && next_expected_start_idx != -1)
  447. return false;
  448. // Next expected index is the start index of our neighbour's edge
  449. next_expected_start_idx = n->mEdge[e.mNeighbourEdge].mStartIdx;
  450. // Vertex behind, keep edge
  451. outEdges.push_back(e);
  452. }
  453. }
  454. }
  455. }
  456. // Assert that we have a fully connected loop
  457. JPH_ASSERT(outEdges.empty() || outEdges[0].mStartIdx == next_expected_start_idx);
  458. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  459. // Draw edge of facing triangles
  460. for (int i = 0; i < (int)outEdges.size(); ++i)
  461. {
  462. RVec3 edge_start = cDrawScale * (mOffset + mPositions[outEdges[i].mStartIdx]);
  463. DebugRenderer::sInstance->DrawArrow(edge_start, cDrawScale * (mOffset + mPositions[outEdges[(i + 1) % outEdges.size()].mStartIdx]), Color::sYellow, 0.01f);
  464. DebugRenderer::sInstance->DrawText3D(edge_start, ConvertToString(outEdges[i].mStartIdx), Color::sWhite);
  465. }
  466. // Draw the state with the facing triangles removed
  467. DrawState();
  468. #endif
  469. // When we start with two triangles facing away from each other and adding a point that is on the plane,
  470. // sometimes we consider the point in front of both causing both triangles to be removed resulting in an empty edge list.
  471. // In this case we fail to add the point which will result in no collision reported (the shapes are contacting in 1 point so there's 0 penetration)
  472. return outEdges.size() >= 3;
  473. }
  474. #ifdef JPH_EPA_CONVEX_BUILDER_VALIDATE
  475. /// Check consistency of 1 triangle
  476. void ValidateTriangle(const Triangle *inT) const
  477. {
  478. if (inT->mRemoved)
  479. {
  480. // Validate that removed triangles are not connected to anything
  481. for (const Edge &my_edge : inT->mEdge)
  482. JPH_ASSERT(my_edge.mNeighbourTriangle == nullptr);
  483. }
  484. else
  485. {
  486. for (int i = 0; i < 3; ++i)
  487. {
  488. const Edge &my_edge = inT->mEdge[i];
  489. // Assert that we have a neighbour
  490. const Triangle *nb = my_edge.mNeighbourTriangle;
  491. JPH_ASSERT(nb != nullptr);
  492. if (nb != nullptr)
  493. {
  494. // Assert that our neighbours edge points to us
  495. const Edge &nb_edge = nb->mEdge[my_edge.mNeighbourEdge];
  496. JPH_ASSERT(nb_edge.mNeighbourTriangle == inT);
  497. JPH_ASSERT(nb_edge.mNeighbourEdge == i);
  498. // Assert that the next edge of the neighbour points to the same vertex as this edge's vertex
  499. const Edge &nb_next_edge = nb->GetNextEdge(my_edge.mNeighbourEdge);
  500. JPH_ASSERT(nb_next_edge.mStartIdx == my_edge.mStartIdx);
  501. // Assert that my next edge points to the same vertex as my neighbours vertex
  502. const Edge &my_next_edge = inT->GetNextEdge(i);
  503. JPH_ASSERT(my_next_edge.mStartIdx == nb_edge.mStartIdx);
  504. }
  505. }
  506. }
  507. }
  508. /// Check consistency of all triangles
  509. void ValidateTriangles() const
  510. {
  511. for (const Triangle *t : mTriangles)
  512. ValidateTriangle(t);
  513. }
  514. #endif
  515. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  516. public:
  517. /// Draw state of algorithm
  518. void DrawState()
  519. {
  520. // Draw origin
  521. DebugRenderer::sInstance->DrawCoordinateSystem(RMat44::sTranslation(cDrawScale * mOffset), 1.0f);
  522. // Draw triangles
  523. for (const Triangle *t : mTriangles)
  524. if (!t->mRemoved)
  525. {
  526. // Calculate the triangle vertices
  527. RVec3 p1 = cDrawScale * (mOffset + mPositions[t->mEdge[0].mStartIdx]);
  528. RVec3 p2 = cDrawScale * (mOffset + mPositions[t->mEdge[1].mStartIdx]);
  529. RVec3 p3 = cDrawScale * (mOffset + mPositions[t->mEdge[2].mStartIdx]);
  530. // Draw triangle
  531. DebugRenderer::sInstance->DrawTriangle(p1, p2, p3, Color::sGetDistinctColor(t->mIteration));
  532. DebugRenderer::sInstance->DrawWireTriangle(p1, p2, p3, Color::sGrey);
  533. // Draw normal
  534. RVec3 centroid = cDrawScale * (mOffset + t->mCentroid);
  535. float len = t->mNormal.Length();
  536. if (len > 0.0f)
  537. DebugRenderer::sInstance->DrawArrow(centroid, centroid + t->mNormal / len, Color::sDarkGreen, 0.01f);
  538. }
  539. // Determine max position
  540. float min_x = FLT_MAX;
  541. float max_x = -FLT_MAX;
  542. for (Vec3 p : mPositions)
  543. {
  544. min_x = min(min_x, p.GetX());
  545. max_x = max(max_x, p.GetX());
  546. }
  547. // Offset to the right
  548. mOffset += Vec3(max_x - min_x + 0.5f, 0.0f, 0.0f);
  549. }
  550. /// Draw a label to indicate the next stage in the algorithm
  551. void DrawLabel(const string_view &inText)
  552. {
  553. DebugRenderer::sInstance->DrawText3D(cDrawScale * mOffset, inText, Color::sWhite, 0.1f * cDrawScale);
  554. mOffset += Vec3(5.0f, 0.0f, 0.0f);
  555. }
  556. /// Draw geometry for debugging purposes
  557. void DrawGeometry(const DebugRenderer::GeometryRef &inGeometry, ColorArg inColor)
  558. {
  559. RMat44 origin = RMat44::sScale(Vec3::sReplicate(cDrawScale)) * RMat44::sTranslation(mOffset);
  560. DebugRenderer::sInstance->DrawGeometry(origin, inGeometry->mBounds.Transformed(origin), inGeometry->mBounds.GetExtent().LengthSq(), inColor, inGeometry);
  561. mOffset += Vec3(inGeometry->mBounds.GetSize().GetX(), 0, 0);
  562. }
  563. /// Draw a triangle for debugging purposes
  564. void DrawWireTriangle(const Triangle &inTriangle, ColorArg inColor)
  565. {
  566. RVec3 prev = cDrawScale * (mOffset + mPositions[inTriangle.mEdge[2].mStartIdx]);
  567. for (const Edge &edge : inTriangle.mEdge)
  568. {
  569. RVec3 cur = cDrawScale * (mOffset + mPositions[edge.mStartIdx]);
  570. DebugRenderer::sInstance->DrawArrow(prev, cur, inColor, 0.01f);
  571. prev = cur;
  572. }
  573. }
  574. /// Draw a marker for debugging purposes
  575. void DrawMarker(Vec3Arg inPosition, ColorArg inColor, float inSize)
  576. {
  577. DebugRenderer::sInstance->DrawMarker(cDrawScale * (mOffset + inPosition), inColor, inSize);
  578. }
  579. /// Draw an arrow for debugging purposes
  580. void DrawArrow(Vec3Arg inFrom, Vec3Arg inTo, ColorArg inColor, float inArrowSize)
  581. {
  582. DebugRenderer::sInstance->DrawArrow(cDrawScale * (mOffset + inFrom), cDrawScale * (mOffset + inTo), inColor, inArrowSize);
  583. }
  584. #endif
  585. private:
  586. TriangleFactory mFactory; ///< Factory to create new triangles and remove old ones
  587. const Points & mPositions; ///< List of positions (some of them are part of the hull)
  588. TriangleQueue mTriangleQueue; ///< List of triangles that are part of the hull that still need to be checked (if !mRemoved)
  589. #if defined(JPH_EPA_CONVEX_BUILDER_VALIDATE) || defined(JPH_EPA_CONVEX_BUILDER_DRAW)
  590. Triangles mTriangles; ///< The list of all triangles in this hull (for debug purposes)
  591. #endif
  592. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  593. int mIteration; ///< Number of iterations we've had so far (for debug purposes)
  594. RVec3 mOffset; ///< Offset to use for state drawing
  595. #endif
  596. };
  597. // The determinant that is calculated in the Triangle constructor is really sensitive
  598. // to numerical round off, disable the fmadd instructions to maintain precision.
  599. JPH_PRECISE_MATH_ON
  600. EPAConvexHullBuilder::Triangle::Triangle(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions)
  601. {
  602. // Fill in indexes
  603. JPH_ASSERT(inIdx0 != inIdx1 && inIdx0 != inIdx2 && inIdx1 != inIdx2);
  604. mEdge[0].mStartIdx = inIdx0;
  605. mEdge[1].mStartIdx = inIdx1;
  606. mEdge[2].mStartIdx = inIdx2;
  607. // Clear links
  608. mEdge[0].mNeighbourTriangle = nullptr;
  609. mEdge[1].mNeighbourTriangle = nullptr;
  610. mEdge[2].mNeighbourTriangle = nullptr;
  611. // Get vertex positions
  612. Vec3 y0 = inPositions[inIdx0];
  613. Vec3 y1 = inPositions[inIdx1];
  614. Vec3 y2 = inPositions[inIdx2];
  615. // Calculate centroid
  616. mCentroid = (y0 + y1 + y2) / 3.0f;
  617. // Calculate edges
  618. Vec3 y10 = y1 - y0;
  619. Vec3 y20 = y2 - y0;
  620. Vec3 y21 = y2 - y1;
  621. // The most accurate normal is calculated by using the two shortest edges
  622. // See: https://box2d.org/posts/2014/01/troublesome-triangle/
  623. // The difference in normals is most pronounced when one edge is much smaller than the others (in which case the other 2 must have roughly the same length).
  624. // Therefore we can suffice by just picking the shortest from 2 edges and use that with the 3rd edge to calculate the normal.
  625. // We first check which of the edges is shorter.
  626. float y20_dot_y20 = y20.Dot(y20);
  627. float y21_dot_y21 = y21.Dot(y21);
  628. if (y20_dot_y20 < y21_dot_y21)
  629. {
  630. // We select the edges y10 and y20
  631. mNormal = y10.Cross(y20);
  632. // Check if triangle is degenerate
  633. float normal_len_sq = mNormal.LengthSq();
  634. if (normal_len_sq > cMinTriangleArea)
  635. {
  636. // Determine distance between triangle and origin: distance = (centroid - origin) . normal / |normal|
  637. // Note that this way of calculating the closest point is much more accurate than first calculating barycentric coordinates and then calculating the closest
  638. // point based on those coordinates. Note that we preserve the sign of the distance to check on which side the origin is.
  639. float c_dot_n = mCentroid.Dot(mNormal);
  640. mClosestLenSq = abs(c_dot_n) * c_dot_n / normal_len_sq;
  641. // Calculate closest point to origin using barycentric coordinates:
  642. //
  643. // v = y0 + l0 * (y1 - y0) + l1 * (y2 - y0)
  644. // v . (y1 - y0) = 0
  645. // v . (y2 - y0) = 0
  646. //
  647. // Written in matrix form:
  648. //
  649. // | y10.y10 y20.y10 | | l0 | = | -y0.y10 |
  650. // | y10.y20 y20.y20 | | l1 | | -y0.y20 |
  651. //
  652. // (y10 = y1 - y0 etc.)
  653. //
  654. // Cramers rule to invert matrix:
  655. float y10_dot_y10 = y10.LengthSq();
  656. float y10_dot_y20 = y10.Dot(y20);
  657. float determinant = y10_dot_y10 * y20_dot_y20 - y10_dot_y20 * y10_dot_y20;
  658. if (determinant > 0.0f) // If determinant == 0 then the system is linearly dependent and the triangle is degenerate, since y10.10 * y20.y20 > y10.y20^2 it should also be > 0
  659. {
  660. float y0_dot_y10 = y0.Dot(y10);
  661. float y0_dot_y20 = y0.Dot(y20);
  662. float l0 = (y10_dot_y20 * y0_dot_y20 - y20_dot_y20 * y0_dot_y10) / determinant;
  663. float l1 = (y10_dot_y20 * y0_dot_y10 - y10_dot_y10 * y0_dot_y20) / determinant;
  664. mLambda[0] = l0;
  665. mLambda[1] = l1;
  666. mLambdaRelativeTo0 = true;
  667. // Check if closest point is interior to the triangle. For a convex hull which contains the origin each face must contain the origin, but because
  668. // our faces are triangles, we can have multiple coplanar triangles and only 1 will have the origin as an interior point. We want to use this triangle
  669. // to calculate the contact points because it gives the most accurate results, so we will only add these triangles to the priority queue.
  670. if (l0 > -cBarycentricEpsilon && l1 > -cBarycentricEpsilon && l0 + l1 < 1.0f + cBarycentricEpsilon)
  671. mClosestPointInterior = true;
  672. }
  673. }
  674. }
  675. else
  676. {
  677. // We select the edges y10 and y21
  678. mNormal = y10.Cross(y21);
  679. // Check if triangle is degenerate
  680. float normal_len_sq = mNormal.LengthSq();
  681. if (normal_len_sq > cMinTriangleArea)
  682. {
  683. // Again calculate distance between triangle and origin
  684. float c_dot_n = mCentroid.Dot(mNormal);
  685. mClosestLenSq = abs(c_dot_n) * c_dot_n / normal_len_sq;
  686. // Calculate closest point to origin using barycentric coordinates but this time using y1 as the reference vertex
  687. //
  688. // v = y1 + l0 * (y0 - y1) + l1 * (y2 - y1)
  689. // v . (y0 - y1) = 0
  690. // v . (y2 - y1) = 0
  691. //
  692. // Written in matrix form:
  693. //
  694. // | y10.y10 -y21.y10 | | l0 | = | y1.y10 |
  695. // | -y10.y21 y21.y21 | | l1 | | -y1.y21 |
  696. //
  697. // Cramers rule to invert matrix:
  698. float y10_dot_y10 = y10.LengthSq();
  699. float y10_dot_y21 = y10.Dot(y21);
  700. float determinant = y10_dot_y10 * y21_dot_y21 - y10_dot_y21 * y10_dot_y21;
  701. if (determinant > 0.0f)
  702. {
  703. float y1_dot_y10 = y1.Dot(y10);
  704. float y1_dot_y21 = y1.Dot(y21);
  705. float l0 = (y21_dot_y21 * y1_dot_y10 - y10_dot_y21 * y1_dot_y21) / determinant;
  706. float l1 = (y10_dot_y21 * y1_dot_y10 - y10_dot_y10 * y1_dot_y21) / determinant;
  707. mLambda[0] = l0;
  708. mLambda[1] = l1;
  709. mLambdaRelativeTo0 = false;
  710. // Again check if the closest point is inside the triangle
  711. if (l0 > -cBarycentricEpsilon && l1 > -cBarycentricEpsilon && l0 + l1 < 1.0f + cBarycentricEpsilon)
  712. mClosestPointInterior = true;
  713. }
  714. }
  715. }
  716. }
  717. JPH_PRECISE_MATH_OFF
  718. JPH_NAMESPACE_END