EPAPenetrationDepth.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/StaticArray.h>
  5. #include <Jolt/Core/Profiler.h>
  6. #include <Jolt/Geometry/GJKClosestPoint.h>
  7. #include <Jolt/Geometry/EPAConvexHullBuilder.h>
  8. JPH_NAMESPACE_BEGIN
  9. /// Implementation of Expanding Polytope Algorithm as described in:
  10. ///
  11. /// Proximity Queries and Penetration Depth Computation on 3D Game Objects - Gino van den Bergen
  12. ///
  13. /// The implementation of this algorithm does not completely follow the article, instead of splitting
  14. /// triangles at each edge as in fig. 7 in the article, we build a convex hull (removing any triangles that
  15. /// are facing the new point, thereby avoiding the problem of getting really oblong triangles as mentioned in
  16. /// the article).
  17. ///
  18. /// The algorithm roughly works like:
  19. ///
  20. /// - Start with a simplex of the Minkowski sum (difference) of two objects that was calculated by GJK
  21. /// - This simplex should contain the origin (or else GJK would have reported: no collision)
  22. /// - In cases where the simplex consists of 1 - 3 points, find some extra support points (of the Minkowski sum) to get to at least 4 points
  23. /// - Convert this into a convex hull with non-zero volume (which includes the origin)
  24. /// - A: Calculate the closest point to the origin for all triangles of the hull and take the closest one
  25. /// - Calculate a new support point (of the Minkowski sum) in this direction and add this point to the convex hull
  26. /// - This will remove all faces that are facing the new point and will create new triangles to fill up the hole
  27. /// - Loop to A until no closer point found
  28. /// - The closest point indicates the position / direction of least penetration
  29. class EPAPenetrationDepth
  30. {
  31. private:
  32. // Typedefs
  33. static constexpr int cMaxPoints = EPAConvexHullBuilder::cMaxPoints;
  34. static constexpr int cMaxPointsToIncludeOriginInHull = 32;
  35. static_assert(cMaxPointsToIncludeOriginInHull < cMaxPoints);
  36. using Triangle = EPAConvexHullBuilder::Triangle;
  37. using Points = EPAConvexHullBuilder::Points;
  38. /// The GJK algorithm, used to start the EPA algorithm
  39. GJKClosestPoint mGJK;
  40. /// A list of support points for the EPA algorithm
  41. class SupportPoints
  42. {
  43. public:
  44. /// List of support points
  45. Points mY;
  46. Vec3 mP[cMaxPoints];
  47. Vec3 mQ[cMaxPoints];
  48. /// Calculate and add new support point to the list of points
  49. template <typename A, typename B>
  50. Vec3 Add(const A &inA, const B &inB, Vec3Arg inDirection, int &outIndex)
  51. {
  52. // Get support point of the minkowski sum A - B
  53. Vec3 p = inA.GetSupport(inDirection);
  54. Vec3 q = inB.GetSupport(-inDirection);
  55. Vec3 w = p - q;
  56. // Store new point
  57. outIndex = mY.size();
  58. mY.push_back(w);
  59. mP[outIndex] = p;
  60. mQ[outIndex] = q;
  61. return w;
  62. }
  63. };
  64. public:
  65. /// Return code for GetPenetrationDepthStepGJK
  66. enum class EStatus
  67. {
  68. NotColliding, ///< Returned if the objects don't collide, in this case outPointA/outPointB are invalid
  69. Colliding, ///< Returned if the objects penetrate
  70. Indeterminate ///< Returned if the objects penetrate further than the convex radius. In this case you need to call GetPenetrationDepthStepEPA to get the actual penetration depth.
  71. };
  72. /// Calculates penetration depth between two objects, first step of two (the GJK step)
  73. ///
  74. /// @param inAExcludingConvexRadius Object A without convex radius.
  75. /// @param inBExcludingConvexRadius Object B without convex radius.
  76. /// @param inConvexRadiusA Convex radius for A.
  77. /// @param inConvexRadiusB Convex radius for B.
  78. /// @param ioV Pass in previously returned value or (1, 0, 0). On return this value is changed to direction to move B out of collision along the shortest path (magnitude is meaningless).
  79. /// @param inTolerance Minimal distance before A and B are considered colliding.
  80. /// @param outPointA Position on A that has the least amount of penetration.
  81. /// @param outPointB Position on B that has the least amount of penetration.
  82. /// Use |outPointB - outPointA| to get the distance of penetration.
  83. template <typename AE, typename BE>
  84. EStatus GetPenetrationDepthStepGJK(const AE &inAExcludingConvexRadius, float inConvexRadiusA, const BE &inBExcludingConvexRadius, float inConvexRadiusB, float inTolerance, Vec3 &ioV, Vec3 &outPointA, Vec3 &outPointB)
  85. {
  86. JPH_PROFILE_FUNCTION();
  87. // Don't supply a zero ioV, we only want to get points on the hull of the Minkowsky sum and not internal points
  88. JPH_ASSERT(!ioV.IsNearZero());
  89. // Get closest points
  90. float combined_radius = inConvexRadiusA + inConvexRadiusB;
  91. float combined_radius_sq = combined_radius * combined_radius;
  92. float closest_points_dist_sq = mGJK.GetClosestPoints(inAExcludingConvexRadius, inBExcludingConvexRadius, inTolerance, combined_radius_sq, ioV, outPointA, outPointB);
  93. if (closest_points_dist_sq > combined_radius_sq)
  94. {
  95. // No collision
  96. return EStatus::NotColliding;
  97. }
  98. if (closest_points_dist_sq > 0.0f)
  99. {
  100. // Collision within convex radius, adjust points for convex radius
  101. float v_len = sqrt(closest_points_dist_sq); // GetClosestPoints function returns |ioV|^2 when return value < FLT_MAX
  102. outPointA += ioV * (inConvexRadiusA / v_len);
  103. outPointB -= ioV * (inConvexRadiusB / v_len);
  104. return EStatus::Colliding;
  105. }
  106. return EStatus::Indeterminate;
  107. }
  108. /// Calculates penetration depth between two objects, second step (the EPA step)
  109. ///
  110. /// @param inAIncludingConvexRadius Object A with convex radius
  111. /// @param inBIncludingConvexRadius Object B with convex radius
  112. /// @param inTolerance A factor that determines the accuracy of the result. If the change of the squared distance is less than inTolerance * current_penetration_depth^2 the algorithm will terminate. Should be bigger or equal to FLT_EPSILON.
  113. /// @param outV Direction to move B out of collision along the shortest path (magnitude is meaningless)
  114. /// @param outPointA Position on A that has the least amount of penetration
  115. /// @param outPointB Position on B that has the least amount of penetration
  116. /// Use |outPointB - outPointA| to get the distance of penetration
  117. ///
  118. /// @return False if the objects don't collide, in this case outPointA/outPointB are invalid.
  119. /// True if the objects penetrate
  120. template <typename AI, typename BI>
  121. bool GetPenetrationDepthStepEPA(const AI &inAIncludingConvexRadius, const BI &inBIncludingConvexRadius, float inTolerance, Vec3 &outV, Vec3 &outPointA, Vec3 &outPointB)
  122. {
  123. JPH_PROFILE_FUNCTION();
  124. // Check that the tolerance makes sense (smaller value than this will just result in needless iterations)
  125. JPH_ASSERT(inTolerance >= FLT_EPSILON);
  126. // Fetch the simplex from GJK algorithm
  127. SupportPoints support_points;
  128. mGJK.GetClosestPointsSimplex(support_points.mY.data(), support_points.mP, support_points.mQ, support_points.mY.GetSizeRef());
  129. // Fill up the amount of support points to 4
  130. switch (support_points.mY.size())
  131. {
  132. case 1:
  133. {
  134. // 1 vertex, which must be at the origin, which is useless for our purpose
  135. JPH_ASSERT(support_points.mY[0].IsNearZero(1.0e-8f));
  136. support_points.mY.pop_back();
  137. // Add support points in 4 directions to form a tetrahedron around the origin
  138. int p1, p2, p3, p4;
  139. (void)support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, Vec3(0, 1, 0), p1);
  140. (void)support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, Vec3(-1, -1, -1), p2);
  141. (void)support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, Vec3(1, -1, -1), p3);
  142. (void)support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, Vec3(0, -1, 1), p4);
  143. JPH_ASSERT(p1 == 0);
  144. JPH_ASSERT(p2 == 1);
  145. JPH_ASSERT(p3 == 2);
  146. JPH_ASSERT(p4 == 3);
  147. break;
  148. }
  149. case 2:
  150. {
  151. // Two vertices, create 3 extra by taking perpendicular axis and rotating it around in 120 degree increments
  152. Vec3 axis = (support_points.mY[1] - support_points.mY[0]).Normalized();
  153. Mat44 rotation = Mat44::sRotation(axis, DegreesToRadians(120.0f));
  154. Vec3 dir1 = axis.GetNormalizedPerpendicular();
  155. Vec3 dir2 = rotation * dir1;
  156. Vec3 dir3 = rotation * dir2;
  157. int p1, p2, p3;
  158. (void)support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, dir1, p1);
  159. (void)support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, dir2, p2);
  160. (void)support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, dir3, p3);
  161. JPH_ASSERT(p1 == 2);
  162. JPH_ASSERT(p2 == 3);
  163. JPH_ASSERT(p3 == 4);
  164. break;
  165. }
  166. case 3:
  167. case 4:
  168. // We already have enough points
  169. break;
  170. }
  171. // Create hull out of the initial points
  172. JPH_ASSERT(support_points.mY.size() >= 3);
  173. EPAConvexHullBuilder hull(support_points.mY);
  174. hull.Initialize(0, 1, 2);
  175. for (typename Points::size_type i = 3; i < support_points.mY.size(); ++i)
  176. {
  177. float dist_sq;
  178. Triangle *t = hull.FindFacingTriangle(support_points.mY[i], dist_sq);
  179. if (t != nullptr)
  180. {
  181. EPAConvexHullBuilder::NewTriangles new_triangles;
  182. if (!hull.AddPoint(t, i, FLT_MAX, new_triangles))
  183. {
  184. // We can't recover from a failure to add a point to the hull because the old triangles have been unlinked already.
  185. // Assume no collision. This can happen if the shapes touch in 1 point (or plane) in which case the hull is degenerate.
  186. return false;
  187. }
  188. }
  189. }
  190. // Loop until we are sure that the origin is inside the hull
  191. for (;;)
  192. {
  193. // Get the next closest triangle
  194. Triangle *t = hull.PeekClosestTriangleInQueue();
  195. // Don't process removed triangles, just free them (because they're in a heap we don't remove them earlier since we would have to rebuild the sorted heap)
  196. if (t->mRemoved)
  197. {
  198. hull.PopClosestTriangleFromQueue();
  199. // If we run out of triangles, we couldn't include the origin in the hull so there must be very little penetration and we report no collision.
  200. if (!hull.HasNextTriangle())
  201. return false;
  202. hull.FreeTriangle(t);
  203. continue;
  204. }
  205. // If the closest to the triangle is zero or positive, the origin is in the hull and we can proceed to the main algorithm
  206. if (t->mClosestLenSq >= 0.0f)
  207. break;
  208. // Remove the triangle from the queue before we start adding new ones (which may result in a new closest triangle at the front of the queue)
  209. hull.PopClosestTriangleFromQueue();
  210. // Add a support point to get the origin inside the hull
  211. int new_index;
  212. Vec3 w = support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, t->mNormal, new_index);
  213. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  214. // Draw the point that we're adding
  215. hull.DrawMarker(w, Color::sRed, 1.0f);
  216. hull.DrawWireTriangle(*t, Color::sRed);
  217. hull.DrawState();
  218. #endif
  219. // Add the point to the hull, if we fail we terminate and report no collision
  220. EPAConvexHullBuilder::NewTriangles new_triangles;
  221. if (!t->IsFacing(w) || !hull.AddPoint(t, new_index, FLT_MAX, new_triangles))
  222. return false;
  223. // If the triangle was removed we can free it now
  224. if (t->mRemoved)
  225. hull.FreeTriangle(t);
  226. // If we run out of triangles or points, we couldn't include the origin in the hull so there must be very little penetration and we report no collision.
  227. if (!hull.HasNextTriangle() || support_points.mY.size() >= cMaxPointsToIncludeOriginInHull)
  228. return false;
  229. }
  230. // Current closest distance to origin
  231. float closest_dist_sq = FLT_MAX;
  232. // Remember last good triangle
  233. Triangle *last = nullptr;
  234. // Loop until closest point found
  235. do
  236. {
  237. // Get closest triangle to the origin
  238. Triangle *t = hull.PopClosestTriangleFromQueue();
  239. // Don't process removed triangles, just free them (because they're in a heap we don't remove them earlier since we would have to rebuild the sorted heap)
  240. if (t->mRemoved)
  241. {
  242. hull.FreeTriangle(t);
  243. continue;
  244. }
  245. // Check if next triangle is further away than closest point, we've found the closest point
  246. if (t->mClosestLenSq >= closest_dist_sq)
  247. break;
  248. // Replace last good with this triangle
  249. if (last != nullptr)
  250. hull.FreeTriangle(last);
  251. last = t;
  252. // Add support point in direction of normal of the plane
  253. // Note that the article uses the closest point between the origin and plane, but this always has the exact same direction as the normal (if the origin is behind the plane)
  254. // and this way we do less calculations and lose less precision
  255. int new_index;
  256. Vec3 w = support_points.Add(inAIncludingConvexRadius, inBIncludingConvexRadius, t->mNormal, new_index);
  257. // Project w onto the triangle normal
  258. float dot = t->mNormal.Dot(w);
  259. // Check if we just found a separating axis. This can happen if the shape shrunk by convex radius and then expanded by
  260. // convex radius is bigger then the original shape due to inaccuracies in the shrinking process.
  261. if (dot < 0.0f)
  262. return false;
  263. // Get the distance squared (along normal) to the support point
  264. float dist_sq = dot * dot / t->mNormal.LengthSq();
  265. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  266. // Draw the point that we're adding
  267. hull.DrawMarker(w, Color::sPurple, 1.0f);
  268. hull.DrawWireTriangle(*t, Color::sPurple);
  269. hull.DrawState();
  270. #endif
  271. // If the error became small enough, we've converged
  272. if (dist_sq - t->mClosestLenSq < t->mClosestLenSq * inTolerance)
  273. break;
  274. // Keep track of the minimum distance
  275. closest_dist_sq = min(closest_dist_sq, dist_sq);
  276. // If the triangle thinks this point is not front facing, we've reached numerical precision and we're done
  277. if (!t->IsFacing(w))
  278. break;
  279. // Add point to hull
  280. EPAConvexHullBuilder::NewTriangles new_triangles;
  281. if (!hull.AddPoint(t, new_index, closest_dist_sq, new_triangles))
  282. break;
  283. // If the hull is starting to form defects then we're reaching numerical precision and we have to stop
  284. bool has_defect = false;
  285. for (const Triangle *nt : new_triangles)
  286. if (nt->IsFacingOrigin())
  287. {
  288. has_defect = true;
  289. break;
  290. }
  291. if (has_defect)
  292. break;
  293. }
  294. while (hull.HasNextTriangle() && support_points.mY.size() < cMaxPoints);
  295. // Determine closest points, if last == null it means the hull was a plane so there's no penetration
  296. if (last == nullptr)
  297. return false;
  298. // Should be an interior point
  299. JPH_ASSERT(last->mClosestPointInterior);
  300. // Calculate penetration by getting the vector from the origin to the closest point on the triangle:
  301. // distance = (centroid - origin) . normal / |normal|, closest = origin + distance * normal / |normal|
  302. outV = (last->mCentroid.Dot(last->mNormal) / last->mNormal.LengthSq()) * last->mNormal;
  303. // If penetration is near zero, treat this as a non collision since we cannot find a good normal
  304. if (outV.IsNearZero())
  305. return false;
  306. // Use the barycentric coordinates for the closest point to the origin to find the contact points on A and B
  307. Vec3 p0 = support_points.mP[last->mEdge[0].mStartIdx];
  308. Vec3 p1 = support_points.mP[last->mEdge[1].mStartIdx];
  309. Vec3 p2 = support_points.mP[last->mEdge[2].mStartIdx];
  310. Vec3 q0 = support_points.mQ[last->mEdge[0].mStartIdx];
  311. Vec3 q1 = support_points.mQ[last->mEdge[1].mStartIdx];
  312. Vec3 q2 = support_points.mQ[last->mEdge[2].mStartIdx];
  313. if (last->mLambdaRelativeTo0)
  314. {
  315. // y0 was the reference vertex
  316. outPointA = p0 + last->mLambda[0] * (p1 - p0) + last->mLambda[1] * (p2 - p0);
  317. outPointB = q0 + last->mLambda[0] * (q1 - q0) + last->mLambda[1] * (q2 - q0);
  318. }
  319. else
  320. {
  321. // y1 was the reference vertex
  322. outPointA = p1 + last->mLambda[0] * (p0 - p1) + last->mLambda[1] * (p2 - p1);
  323. outPointB = q1 + last->mLambda[0] * (q0 - q1) + last->mLambda[1] * (q2 - q1);
  324. }
  325. return true;
  326. }
  327. /// This function combines the GJK and EPA steps and is provided as a convenience function.
  328. /// Note: less performant since you're providing all support functions in one go
  329. /// Note 2: You need to initialize ioV, see documentation at GetPenetrationDepthStepGJK!
  330. template <typename AE, typename AI, typename BE, typename BI>
  331. bool GetPenetrationDepth(const AE &inAExcludingConvexRadius, const AI &inAIncludingConvexRadius, float inConvexRadiusA, const BE &inBExcludingConvexRadius, const BI &inBIncludingConvexRadius, float inConvexRadiusB, float inCollisionToleranceSq, float inPenetrationTolerance, Vec3 &ioV, Vec3 &outPointA, Vec3 &outPointB)
  332. {
  333. // Check result of collision detection
  334. switch (GetPenetrationDepthStepGJK(inAExcludingConvexRadius, inConvexRadiusA, inBExcludingConvexRadius, inConvexRadiusB, inCollisionToleranceSq, ioV, outPointA, outPointB))
  335. {
  336. case EPAPenetrationDepth::EStatus::Colliding:
  337. return true;
  338. case EPAPenetrationDepth::EStatus::NotColliding:
  339. return false;
  340. case EPAPenetrationDepth::EStatus::Indeterminate:
  341. return GetPenetrationDepthStepEPA(inAIncludingConvexRadius, inBIncludingConvexRadius, inPenetrationTolerance, ioV, outPointA, outPointB);
  342. }
  343. JPH_ASSERT(false);
  344. return false;
  345. }
  346. /// Test if a cast shape inA moving from inStart to lambda * inStart.GetTranslation() + inDirection where lambda e [0, ioLambda> instersects inB
  347. ///
  348. /// @param inStart Start position and orientation of the convex object
  349. /// @param inDirection Direction of the sweep (ioLambda * inDirection determines length)
  350. /// @param inCollisionTolerance The minimal distance between A and B before they are considered colliding
  351. /// @param inPenetrationTolerance A factor that determines the accuracy of the result. If the change of the squared distance is less than inTolerance * current_penetration_depth^2 the algorithm will terminate. Should be bigger or equal to FLT_EPSILON.
  352. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  353. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  354. /// @param inConvexRadiusA The convex radius of A, this will be added on all sides to pad A.
  355. /// @param inConvexRadiusB The convex radius of B, this will be added on all sides to pad B.
  356. /// @param inReturnDeepestPoint If the shapes are initially interesecting this determines if the EPA algorithm will run to find the deepest point
  357. /// @param ioLambda The max fraction along the sweep, on output updated with the actual collision fraction.
  358. /// @param outPointA is the contact point on A
  359. /// @param outPointB is the contact point on B
  360. /// @param outContactNormal is either the contact normal when the objects are touching or the penetration axis when the objects are penetrating at the start of the sweep (pointing from A to B, length will not be 1)
  361. ///
  362. /// @return true if the a hit was found, in which case ioLambda, outPointA, outPointB and outSurfaceNormal are updated.
  363. template <typename A, typename B>
  364. bool CastShape(Mat44Arg inStart, Vec3Arg inDirection, float inCollisionTolerance, float inPenetrationTolerance, const A &inA, const B &inB, float inConvexRadiusA, float inConvexRadiusB, bool inReturnDeepestPoint, float &ioLambda, Vec3 &outPointA, Vec3 &outPointB, Vec3 &outContactNormal)
  365. {
  366. // First determine if there's a collision at all
  367. if (!mGJK.CastShape(inStart, inDirection, inCollisionTolerance, inA, inB, inConvexRadiusA, inConvexRadiusB, ioLambda, outPointA, outPointB, outContactNormal))
  368. return false;
  369. // When our contact normal is too small, we don't have an accurate result
  370. bool contact_normal_invalid = outContactNormal.IsNearZero(Square(inCollisionTolerance));
  371. if (inReturnDeepestPoint
  372. && ioLambda == 0.0f // Only when lambda = 0 we can have the bodies overlap
  373. && (inConvexRadiusA + inConvexRadiusB == 0.0f // When no convex radius was provided we can never trust contact points at lambda = 0
  374. || contact_normal_invalid))
  375. {
  376. // If we're initially intersecting, we need to run the EPA algorithm in order to find the deepest contact point
  377. AddConvexRadius<A> add_convex_a(inA, inConvexRadiusA);
  378. AddConvexRadius<B> add_convex_b(inB, inConvexRadiusB);
  379. TransformedConvexObject<AddConvexRadius<A>> transformed_a(inStart, add_convex_a);
  380. if (!GetPenetrationDepthStepEPA(transformed_a, add_convex_b, inPenetrationTolerance, outContactNormal, outPointA, outPointB))
  381. return false;
  382. }
  383. else if (contact_normal_invalid)
  384. {
  385. // If we weren't able to calculate a contact normal, use the cast direction instead
  386. outContactNormal = inDirection;
  387. }
  388. return true;
  389. }
  390. };
  391. JPH_NAMESPACE_END