GJKClosestPoint.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/NonCopyable.h>
  5. #include <Jolt/Core/FPException.h>
  6. #include <Jolt/Geometry/ClosestPoint.h>
  7. #include <Jolt/Geometry/ConvexSupport.h>
  8. //#define JPH_GJK_DEBUG
  9. #ifdef JPH_GJK_DEBUG
  10. #include <Jolt/Core/StringTools.h>
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #endif
  13. JPH_NAMESPACE_BEGIN
  14. /// Convex vs convex collision detection
  15. /// Based on: A Fast and Robust GJK Implementation for Collision Detection of Convex Objects - Gino van den Bergen
  16. class GJKClosestPoint : public NonCopyable
  17. {
  18. private:
  19. /// Get new closest point to origin given simplex mY of mNumPoints points
  20. ///
  21. /// @param inPrevVLenSq Length of |outV|^2 from the previous iteration, used as a maximum value when selecting a new closest point.
  22. /// @param outV Closest point
  23. /// @param outVLenSq |outV|^2
  24. /// @param outSet Set of points that form the new simplex closest to the origin (bit 1 = mY[0], bit 2 = mY[1], ...)
  25. ///
  26. /// @return True if new closest point was found.
  27. /// False if the function failed, in this case the output variables are not modified
  28. bool GetClosest(float inPrevVLenSq, Vec3 &outV, float &outVLenSq, uint32 &outSet) const
  29. {
  30. #ifdef JPH_GJK_DEBUG
  31. for (int i = 0; i < mNumPoints; ++i)
  32. Trace("y[%d] = [%s], |y[%d]| = %g", i, ConvertToString(mY[i]).c_str(), i, (double)mY[i].Length());
  33. #endif
  34. uint32 set;
  35. Vec3 v;
  36. switch (mNumPoints)
  37. {
  38. case 1:
  39. // Single point
  40. set = 0b0001;
  41. v = mY[0];
  42. break;
  43. case 2:
  44. // Line segment
  45. v = ClosestPoint::GetClosestPointOnLine(mY[0], mY[1], set);
  46. break;
  47. case 3:
  48. // Triangle
  49. v = ClosestPoint::GetClosestPointOnTriangle(mY[0], mY[1], mY[2], set);
  50. break;
  51. case 4:
  52. // Tetrahedron
  53. v = ClosestPoint::GetClosestPointOnTetrahedron(mY[0], mY[1], mY[2], mY[3], set);
  54. break;
  55. default:
  56. JPH_ASSERT(false);
  57. return false;
  58. }
  59. #ifdef JPH_GJK_DEBUG
  60. Trace("GetClosest: set = 0b%s, v = [%s], |v| = %g", NibbleToBinary(set), ConvertToString(v).c_str(), (double)v.Length());
  61. #endif
  62. float v_len_sq = v.LengthSq();
  63. if (v_len_sq < inPrevVLenSq) // Note, comparison order important: If v_len_sq is NaN then this expression will be false so we will return false
  64. {
  65. // Return closest point
  66. outV = v;
  67. outVLenSq = v_len_sq;
  68. outSet = set;
  69. return true;
  70. }
  71. // No better match found
  72. #ifdef JPH_GJK_DEBUG
  73. Trace("New closer point is further away, failed to converge");
  74. #endif
  75. return false;
  76. }
  77. // Get max(|Y_0|^2 .. |Y_n|^2)
  78. float GetMaxYLengthSq() const
  79. {
  80. float y_len_sq = mY[0].LengthSq();
  81. for (int i = 1; i < mNumPoints; ++i)
  82. y_len_sq = max(y_len_sq, mY[i].LengthSq());
  83. return y_len_sq;
  84. }
  85. // Remove points that are not in the set, only updates mY
  86. void UpdatePointSetY(uint32 inSet)
  87. {
  88. int num_points = 0;
  89. for (int i = 0; i < mNumPoints; ++i)
  90. if ((inSet & (1 << i)) != 0)
  91. {
  92. mY[num_points] = mY[i];
  93. ++num_points;
  94. }
  95. mNumPoints = num_points;
  96. }
  97. // GCC 11.3 thinks the assignments to mP, mQ and mY below may use uninitialized variables
  98. JPH_SUPPRESS_WARNING_PUSH
  99. JPH_GCC_SUPPRESS_WARNING("-Wmaybe-uninitialized")
  100. // Remove points that are not in the set, only updates mP
  101. void UpdatePointSetP(uint32 inSet)
  102. {
  103. int num_points = 0;
  104. for (int i = 0; i < mNumPoints; ++i)
  105. if ((inSet & (1 << i)) != 0)
  106. {
  107. mP[num_points] = mP[i];
  108. ++num_points;
  109. }
  110. mNumPoints = num_points;
  111. }
  112. // Remove points that are not in the set, only updates mP and mQ
  113. void UpdatePointSetPQ(uint32 inSet)
  114. {
  115. int num_points = 0;
  116. for (int i = 0; i < mNumPoints; ++i)
  117. if ((inSet & (1 << i)) != 0)
  118. {
  119. mP[num_points] = mP[i];
  120. mQ[num_points] = mQ[i];
  121. ++num_points;
  122. }
  123. mNumPoints = num_points;
  124. }
  125. // Remove points that are not in the set, updates mY, mP and mQ
  126. void UpdatePointSetYPQ(uint32 inSet)
  127. {
  128. int num_points = 0;
  129. for (int i = 0; i < mNumPoints; ++i)
  130. if ((inSet & (1 << i)) != 0)
  131. {
  132. mY[num_points] = mY[i];
  133. mP[num_points] = mP[i];
  134. mQ[num_points] = mQ[i];
  135. ++num_points;
  136. }
  137. mNumPoints = num_points;
  138. }
  139. JPH_SUPPRESS_WARNING_POP
  140. // Calculate closest points on A and B
  141. void CalculatePointAAndB(Vec3 &outPointA, Vec3 &outPointB) const
  142. {
  143. switch (mNumPoints)
  144. {
  145. case 1:
  146. outPointA = mP[0];
  147. outPointB = mQ[0];
  148. break;
  149. case 2:
  150. {
  151. float u, v;
  152. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], u, v);
  153. outPointA = u * mP[0] + v * mP[1];
  154. outPointB = u * mQ[0] + v * mQ[1];
  155. }
  156. break;
  157. case 3:
  158. {
  159. float u, v, w;
  160. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], mY[2], u, v, w);
  161. outPointA = u * mP[0] + v * mP[1] + w * mP[2];
  162. outPointB = u * mQ[0] + v * mQ[1] + w * mQ[2];
  163. }
  164. break;
  165. case 4:
  166. #ifdef _DEBUG
  167. memset(&outPointA, 0xcd, sizeof(outPointA));
  168. memset(&outPointB, 0xcd, sizeof(outPointB));
  169. #endif
  170. break;
  171. }
  172. }
  173. public:
  174. /// Test if inA and inB intersect
  175. ///
  176. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  177. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  178. /// @param inTolerance Minimal distance between objects when the objects are considered to be colliding
  179. /// @param ioV is used as initial separating axis (provide a zero vector if you don't know yet)
  180. ///
  181. /// @return True if they intersect (in which case ioV = (0, 0, 0)).
  182. /// False if they don't intersect in which case ioV is a separating axis in the direction from A to B (magnitude is meaningless)
  183. template <typename A, typename B>
  184. bool Intersects(const A &inA, const B &inB, float inTolerance, Vec3 &ioV)
  185. {
  186. float tolerance_sq = Square(inTolerance);
  187. // Reset state
  188. mNumPoints = 0;
  189. #ifdef JPH_GJK_DEBUG
  190. for (int i = 0; i < 4; ++i)
  191. mY[i] = Vec3::sZero();
  192. #endif
  193. // Previous length^2 of v
  194. float prev_v_len_sq = FLT_MAX;
  195. for (;;)
  196. {
  197. #ifdef JPH_GJK_DEBUG
  198. Trace("v = [%s], num_points = %d", ConvertToString(ioV).c_str(), mNumPoints);
  199. #endif
  200. // Get support points for shape A and B in the direction of v
  201. Vec3 p = inA.GetSupport(ioV);
  202. Vec3 q = inB.GetSupport(-ioV);
  203. // Get support point of the minkowski sum A - B of v
  204. Vec3 w = p - q;
  205. // If the support point sA-B(v) is in the opposite direction as v, then we have found a separating axis and there is no intersection
  206. if (ioV.Dot(w) < 0.0f)
  207. {
  208. // Separating axis found
  209. #ifdef JPH_GJK_DEBUG
  210. Trace("Seperating axis");
  211. #endif
  212. return false;
  213. }
  214. // Store the point for later use
  215. mY[mNumPoints] = w;
  216. ++mNumPoints;
  217. #ifdef JPH_GJK_DEBUG
  218. Trace("w = [%s]", ConvertToString(w).c_str());
  219. #endif
  220. // Determine the new closest point
  221. float v_len_sq; // Length^2 of v
  222. uint32 set; // Set of points that form the new simplex
  223. if (!GetClosest(prev_v_len_sq, ioV, v_len_sq, set))
  224. return false;
  225. // If there are 4 points, the origin is inside the tetrahedron and we're done
  226. if (set == 0xf)
  227. {
  228. #ifdef JPH_GJK_DEBUG
  229. Trace("Full simplex");
  230. #endif
  231. ioV = Vec3::sZero();
  232. return true;
  233. }
  234. // If v is very close to zero, we consider this a collision
  235. if (v_len_sq <= tolerance_sq)
  236. {
  237. #ifdef JPH_GJK_DEBUG
  238. Trace("Distance zero");
  239. #endif
  240. ioV = Vec3::sZero();
  241. return true;
  242. }
  243. // If v is very small compared to the length of y, we also consider this a collision
  244. if (v_len_sq <= FLT_EPSILON * GetMaxYLengthSq())
  245. {
  246. #ifdef JPH_GJK_DEBUG
  247. Trace("Machine precision reached");
  248. #endif
  249. ioV = Vec3::sZero();
  250. return true;
  251. }
  252. // The next seperation axis to test is the negative of the closest point of the Minkowski sum to the origin
  253. // Note: This must be done before terminating as converged since the separating axis is -v
  254. ioV = -ioV;
  255. // If the squared length of v is not changing enough, we've converged and there is no collision
  256. JPH_ASSERT(prev_v_len_sq >= v_len_sq);
  257. if (prev_v_len_sq - v_len_sq <= FLT_EPSILON * prev_v_len_sq)
  258. {
  259. // v is a separating axis
  260. #ifdef JPH_GJK_DEBUG
  261. Trace("Converged");
  262. #endif
  263. return false;
  264. }
  265. prev_v_len_sq = v_len_sq;
  266. // Update the points of the simplex
  267. UpdatePointSetY(set);
  268. }
  269. }
  270. /// Get closest points between inA and inB
  271. ///
  272. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  273. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  274. /// @param inTolerance The minimal distance between A and B before the objects are considered colliding and processing is terminated.
  275. /// @param inMaxDistSq The maximum squared distance between A and B before the objects are considered infinitely far away and processing is terminated.
  276. /// @param ioV Initial guess for the separating axis. Start with any non-zero vector if you don't know.
  277. /// If return value is 0, ioV = (0, 0, 0).
  278. /// If the return value is bigger than 0 but smaller than FLT_MAX, ioV will be the separating axis in the direction from A to B and its length the squared distance between A and B.
  279. /// If the return value is FLT_MAX, ioV will be the separating axis in the direction from A to B and the magnitude of the vector is meaningless.
  280. /// @param outPointA , outPointB
  281. /// If the return value is 0 the points are invalid.
  282. /// If the return value is bigger than 0 but smaller than FLT_MAX these will contain the closest point on A and B.
  283. /// If the return value is FLT_MAX the points are invalid.
  284. ///
  285. /// @return The squared distance between A and B or FLT_MAX when they are further away than inMaxDistSq.
  286. template <typename A, typename B>
  287. float GetClosestPoints(const A &inA, const B &inB, float inTolerance, float inMaxDistSq, Vec3 &ioV, Vec3 &outPointA, Vec3 &outPointB)
  288. {
  289. float tolerance_sq = Square(inTolerance);
  290. // Reset state
  291. mNumPoints = 0;
  292. #ifdef JPH_GJK_DEBUG
  293. // Generate the hull of the Minkowski difference for visualization
  294. MinkowskiDifference diff(inA, inB);
  295. mGeometry = DebugRenderer::sInstance->CreateTriangleGeometryForConvex([&diff](Vec3Arg inDirection) { return diff.GetSupport(inDirection); });
  296. for (int i = 0; i < 4; ++i)
  297. {
  298. mY[i] = Vec3::sZero();
  299. mP[i] = Vec3::sZero();
  300. mQ[i] = Vec3::sZero();
  301. }
  302. #endif
  303. // Length^2 of v
  304. float v_len_sq = ioV.LengthSq();
  305. // Previous length^2 of v
  306. float prev_v_len_sq = FLT_MAX;
  307. for (;;)
  308. {
  309. #ifdef JPH_GJK_DEBUG
  310. Trace("v = [%s], num_points = %d", ConvertToString(ioV).c_str(), mNumPoints);
  311. #endif
  312. // Get support points for shape A and B in the direction of v
  313. Vec3 p = inA.GetSupport(ioV);
  314. Vec3 q = inB.GetSupport(-ioV);
  315. // Get support point of the minkowski sum A - B of v
  316. Vec3 w = p - q;
  317. float dot = ioV.Dot(w);
  318. #ifdef JPH_GJK_DEBUG
  319. // Draw -ioV to show the closest point to the origin from the previous simplex
  320. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset - ioV, Color::sOrange, 0.05f);
  321. // Draw ioV to show where we're probing next
  322. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset + ioV, Color::sCyan, 0.05f);
  323. // Draw w, the support point
  324. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset + w, Color::sGreen, 0.05f);
  325. DebugRenderer::sInstance->DrawMarker(mOffset + w, Color::sGreen, 1.0f);
  326. // Draw the simplex and the Minkowski difference around it
  327. DrawState();
  328. #endif
  329. // Test if we have a separation of more than inMaxDistSq, in which case we terminate early
  330. if (dot < 0.0f && dot * dot > v_len_sq * inMaxDistSq)
  331. {
  332. #ifdef JPH_GJK_DEBUG
  333. Trace("Distance bigger than max");
  334. #endif
  335. #ifdef _DEBUG
  336. memset(&outPointA, 0xcd, sizeof(outPointA));
  337. memset(&outPointB, 0xcd, sizeof(outPointB));
  338. #endif
  339. return FLT_MAX;
  340. }
  341. // Store the point for later use
  342. mY[mNumPoints] = w;
  343. mP[mNumPoints] = p;
  344. mQ[mNumPoints] = q;
  345. ++mNumPoints;
  346. #ifdef JPH_GJK_DEBUG
  347. Trace("w = [%s]", ConvertToString(w).c_str());
  348. #endif
  349. uint32 set;
  350. if (!GetClosest(prev_v_len_sq, ioV, v_len_sq, set))
  351. {
  352. --mNumPoints; // Undo add last point
  353. break;
  354. }
  355. // If there are 4 points, the origin is inside the tetrahedron and we're done
  356. if (set == 0xf)
  357. {
  358. #ifdef JPH_GJK_DEBUG
  359. Trace("Full simplex");
  360. #endif
  361. ioV = Vec3::sZero();
  362. v_len_sq = 0.0f;
  363. break;
  364. }
  365. // Update the points of the simplex
  366. UpdatePointSetYPQ(set);
  367. // If v is very close to zero, we consider this a collision
  368. if (v_len_sq <= tolerance_sq)
  369. {
  370. #ifdef JPH_GJK_DEBUG
  371. Trace("Distance zero");
  372. #endif
  373. ioV = Vec3::sZero();
  374. v_len_sq = 0.0f;
  375. break;
  376. }
  377. // If v is very small compared to the length of y, we also consider this a collision
  378. #ifdef JPH_GJK_DEBUG
  379. Trace("Check v small compared to y: %g <= %g", (double)v_len_sq, (double)(FLT_EPSILON * GetMaxYLengthSq()));
  380. #endif
  381. if (v_len_sq <= FLT_EPSILON * GetMaxYLengthSq())
  382. {
  383. #ifdef JPH_GJK_DEBUG
  384. Trace("Machine precision reached");
  385. #endif
  386. ioV = Vec3::sZero();
  387. v_len_sq = 0.0f;
  388. break;
  389. }
  390. // The next seperation axis to test is the negative of the closest point of the Minkowski sum to the origin
  391. // Note: This must be done before terminating as converged since the separating axis is -v
  392. ioV = -ioV;
  393. // If the squared length of v is not changing enough, we've converged and there is no collision
  394. #ifdef JPH_GJK_DEBUG
  395. Trace("Check v not changing enough: %g <= %g", (double)(prev_v_len_sq - v_len_sq), (double)(FLT_EPSILON * prev_v_len_sq));
  396. #endif
  397. JPH_ASSERT(prev_v_len_sq >= v_len_sq);
  398. if (prev_v_len_sq - v_len_sq <= FLT_EPSILON * prev_v_len_sq)
  399. {
  400. // v is a separating axis
  401. #ifdef JPH_GJK_DEBUG
  402. Trace("Converged");
  403. #endif
  404. break;
  405. }
  406. prev_v_len_sq = v_len_sq;
  407. }
  408. // Get the closest points
  409. CalculatePointAAndB(outPointA, outPointB);
  410. #ifdef JPH_GJK_DEBUG
  411. Trace("Return: v = [%s], |v| = %g", ConvertToString(ioV).c_str(), (double)ioV.Length());
  412. // Draw -ioV to show the closest point to the origin from the previous simplex
  413. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset - ioV, Color::sOrange, 0.05f);
  414. // Draw the closest points
  415. DebugRenderer::sInstance->DrawMarker(mOffset + outPointA, Color::sGreen, 1.0f);
  416. DebugRenderer::sInstance->DrawMarker(mOffset + outPointB, Color::sPurple, 1.0f);
  417. // Draw the simplex and the Minkowski difference around it
  418. DrawState();
  419. #endif
  420. JPH_ASSERT(ioV.LengthSq() == v_len_sq);
  421. return v_len_sq;
  422. }
  423. /// Get the resulting simplex after the GetClosestPoints algorithm finishes.
  424. /// If it returned a squared distance of 0, the origin will be contained in the simplex.
  425. void GetClosestPointsSimplex(Vec3 *outY, Vec3 *outP, Vec3 *outQ, uint &outNumPoints) const
  426. {
  427. uint size = sizeof(Vec3) * mNumPoints;
  428. memcpy(outY, mY, size);
  429. memcpy(outP, mP, size);
  430. memcpy(outQ, mQ, size);
  431. outNumPoints = mNumPoints;
  432. }
  433. /// Test if a ray inRayOrigin + lambda * inRayDirection for lambda e [0, ioLambda> instersects inA
  434. ///
  435. /// Code based upon: Ray Casting against General Convex Objects with Application to Continuous Collision Detection - Gino van den Bergen
  436. ///
  437. /// @param inRayOrigin Origin of the ray
  438. /// @param inRayDirection Direction of the ray (ioLambda * inDirection determines length)
  439. /// @param inTolerance The minimal distance between the ray and A before it is considered colliding
  440. /// @param inA A convex object that has the GetSupport(Vec3) function
  441. /// @param ioLambda The max fraction along the ray, on output updated with the actual collision fraction.
  442. ///
  443. /// @return true if a hit was found, ioLambda is the solution for lambda.
  444. template <typename A>
  445. bool CastRay(Vec3Arg inRayOrigin, Vec3Arg inRayDirection, float inTolerance, const A &inA, float &ioLambda)
  446. {
  447. float tolerance_sq = Square(inTolerance);
  448. // Reset state
  449. mNumPoints = 0;
  450. float lambda = 0.0f;
  451. Vec3 x = inRayOrigin;
  452. Vec3 v = x - inA.GetSupport(Vec3::sZero());
  453. float v_len_sq = FLT_MAX;
  454. bool allow_restart = false;
  455. for (;;)
  456. {
  457. #ifdef JPH_GJK_DEBUG
  458. Trace("v = [%s], num_points = %d", ConvertToString(v).c_str(), mNumPoints);
  459. #endif
  460. // Get new support point
  461. Vec3 p = inA.GetSupport(v);
  462. Vec3 w = x - p;
  463. #ifdef JPH_GJK_DEBUG
  464. Trace("w = [%s]", ConvertToString(w).c_str());
  465. #endif
  466. float v_dot_w = v.Dot(w);
  467. #ifdef JPH_GJK_DEBUG
  468. Trace("v . w = %g", (double)v_dot_w);
  469. #endif
  470. if (v_dot_w > 0.0f)
  471. {
  472. // If ray and normal are in the same direction, we've passed A and there's no collision
  473. float v_dot_r = v.Dot(inRayDirection);
  474. #ifdef JPH_GJK_DEBUG
  475. Trace("v . r = %g", (double)v_dot_r);
  476. #endif
  477. if (v_dot_r >= 0.0f)
  478. return false;
  479. // Update the lower bound for lambda
  480. float delta = v_dot_w / v_dot_r;
  481. float old_lambda = lambda;
  482. lambda -= delta;
  483. #ifdef JPH_GJK_DEBUG
  484. Trace("lambda = %g, delta = %g", (double)lambda, (double)delta);
  485. #endif
  486. // If lambda didn't change, we cannot converge any further and we assume a hit
  487. if (old_lambda == lambda)
  488. break;
  489. // If lambda is bigger or equal than max, we don't have a hit
  490. if (lambda >= ioLambda)
  491. return false;
  492. // Update x to new closest point on the ray
  493. x = inRayOrigin + lambda * inRayDirection;
  494. // We've shifted x, so reset v_len_sq so that it is not used as early out for GetClosest
  495. v_len_sq = FLT_MAX;
  496. // We allow rebuilding the simplex once after x changes because the simplex was built
  497. // for another x and numerical round off builds up as you keep adding points to an
  498. // existing simplex
  499. allow_restart = true;
  500. }
  501. // Add p to set P: P = P U {p}
  502. mP[mNumPoints] = p;
  503. ++mNumPoints;
  504. // Calculate Y = {x} - P
  505. for (int i = 0; i < mNumPoints; ++i)
  506. mY[i] = x - mP[i];
  507. // Determine the new closest point from Y to origin
  508. bool needs_restart = false;
  509. uint32 set; // Set of points that form the new simplex
  510. if (!GetClosest(v_len_sq, v, v_len_sq, set))
  511. {
  512. #ifdef JPH_GJK_DEBUG
  513. Trace("Failed to converge");
  514. #endif
  515. // We failed to converge, restart
  516. needs_restart = true;
  517. }
  518. else if (set == 0xf)
  519. {
  520. #ifdef JPH_GJK_DEBUG
  521. Trace("Full simplex");
  522. #endif
  523. // If there are 4 points, x is inside the tetrahedron and we've found a hit
  524. // Double check if this is indeed the case
  525. if (v_len_sq <= tolerance_sq)
  526. break;
  527. // We failed to converge, restart
  528. needs_restart = true;
  529. }
  530. if (needs_restart)
  531. {
  532. // Only allow 1 restart, if we still can't get a closest point
  533. // we're so close that we return this as a hit
  534. if (!allow_restart)
  535. break;
  536. // If we fail to converge, we start again with the last point as simplex
  537. #ifdef JPH_GJK_DEBUG
  538. Trace("Restarting");
  539. #endif
  540. allow_restart = false;
  541. mP[0] = p;
  542. mNumPoints = 1;
  543. v = x - p;
  544. v_len_sq = FLT_MAX;
  545. continue;
  546. }
  547. // Update the points P to form the new simplex
  548. // Note: We're not updating Y as Y will shift with x so we have to calculate it every iteration
  549. UpdatePointSetP(set);
  550. // Check if x is close enough to inA
  551. if (v_len_sq <= tolerance_sq)
  552. {
  553. #ifdef JPH_GJK_DEBUG
  554. Trace("Converged");
  555. #endif
  556. break;
  557. }
  558. }
  559. // Store hit fraction
  560. ioLambda = lambda;
  561. return true;
  562. }
  563. /// Test if a cast shape inA moving from inStart to lambda * inStart.GetTranslation() + inDirection where lambda e [0, ioLambda> instersects inB
  564. ///
  565. /// @param inStart Start position and orientation of the convex object
  566. /// @param inDirection Direction of the sweep (ioLambda * inDirection determines length)
  567. /// @param inTolerance The minimal distance between A and B before they are considered colliding
  568. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  569. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  570. /// @param ioLambda The max fraction along the sweep, on output updated with the actual collision fraction.
  571. ///
  572. /// @return true if a hit was found, ioLambda is the solution for lambda.
  573. template <typename A, typename B>
  574. bool CastShape(Mat44Arg inStart, Vec3Arg inDirection, float inTolerance, const A &inA, const B &inB, float &ioLambda)
  575. {
  576. // Transform the shape to be cast to the starting position
  577. TransformedConvexObject transformed_a(inStart, inA);
  578. // Calculate the minkowski difference inB - inA
  579. // inA is moving, so we need to add the back side of inB to the front side of inA
  580. MinkowskiDifference difference(inB, transformed_a);
  581. // Do a raycast against the Minkowski difference
  582. return CastRay(Vec3::sZero(), inDirection, inTolerance, difference, ioLambda);
  583. }
  584. /// Test if a cast shape inA moving from inStart to lambda * inStart.GetTranslation() + inDirection where lambda e [0, ioLambda> instersects inB
  585. ///
  586. /// @param inStart Start position and orientation of the convex object
  587. /// @param inDirection Direction of the sweep (ioLambda * inDirection determines length)
  588. /// @param inTolerance The minimal distance between A and B before they are considered colliding
  589. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  590. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  591. /// @param inConvexRadiusA The convex radius of A, this will be added on all sides to pad A.
  592. /// @param inConvexRadiusB The convex radius of B, this will be added on all sides to pad B.
  593. /// @param ioLambda The max fraction along the sweep, on output updated with the actual collision fraction.
  594. /// @param outPointA is the contact point on A (if outSeparatingAxis is near zero, this may not be not the deepest point)
  595. /// @param outPointB is the contact point on B (if outSeparatingAxis is near zero, this may not be not the deepest point)
  596. /// @param outSeparatingAxis On return this will contain a vector that points from A to B along the smallest distance of separation.
  597. /// The length of this vector indicates the separation of A and B without their convex radius.
  598. /// If it is near zero, the direction may not be accurate as the bodies may overlap when lambda = 0.
  599. ///
  600. /// @return true if a hit was found, ioLambda is the solution for lambda and outPoint and outSeparatingAxis are valid.
  601. template <typename A, typename B>
  602. bool CastShape(Mat44Arg inStart, Vec3Arg inDirection, float inTolerance, const A &inA, const B &inB, float inConvexRadiusA, float inConvexRadiusB, float &ioLambda, Vec3 &outPointA, Vec3 &outPointB, Vec3 &outSeparatingAxis)
  603. {
  604. float tolerance_sq = Square(inTolerance);
  605. // Calculate how close A and B (without their convex radius) need to be to eachother in order for us to consider this a collision
  606. float sum_convex_radius = inConvexRadiusA + inConvexRadiusB;
  607. // Transform the shape to be cast to the starting position
  608. TransformedConvexObject transformed_a(inStart, inA);
  609. // Reset state
  610. mNumPoints = 0;
  611. float lambda = 0.0f;
  612. Vec3 x = Vec3::sZero(); // Since A is already transformed we can start the cast from zero
  613. Vec3 v = -inB.GetSupport(Vec3::sZero()) + transformed_a.GetSupport(Vec3::sZero()); // See CastRay: v = x - inA.GetSupport(Vec3::sZero()) where inA is the Minkowski difference inB - transformed_a (see CastShape above) and x is zero
  614. float v_len_sq = FLT_MAX;
  615. bool allow_restart = false;
  616. // Keeps track of separating axis of the previous iteration.
  617. // Initialized at zero as we don't know if our first v is actually a separating axis.
  618. Vec3 prev_v = Vec3::sZero();
  619. for (;;)
  620. {
  621. #ifdef JPH_GJK_DEBUG
  622. Trace("v = [%s], num_points = %d", ConvertToString(v).c_str(), mNumPoints);
  623. #endif
  624. // Calculate the minkowski difference inB - inA
  625. // inA is moving, so we need to add the back side of inB to the front side of inA
  626. // Keep the support points on A and B separate so that in the end we can calculate a contact point
  627. Vec3 p = transformed_a.GetSupport(-v);
  628. Vec3 q = inB.GetSupport(v);
  629. Vec3 w = x - (q - p);
  630. #ifdef JPH_GJK_DEBUG
  631. Trace("w = [%s]", ConvertToString(w).c_str());
  632. #endif
  633. // Difference from article to this code:
  634. // We did not include the convex radius in p and q in order to be able to calculate a good separating axis at the end of the algorithm.
  635. // However when moving forward along inDirection we do need to take this into account so that we keep A and B separated by the sum of their convex radii.
  636. // From p we have to subtract: inConvexRadiusA * v / |v|
  637. // To q we have to add: inConvexRadiusB * v / |v|
  638. // This means that to w we have to add: -(inConvexRadiusA + inConvexRadiusB) * v / |v|
  639. // So to v . w we have to add: v . (-(inConvexRadiusA + inConvexRadiusB) * v / |v|) = -(inConvexRadiusA + inConvexRadiusB) * |v|
  640. float v_dot_w = v.Dot(w) - sum_convex_radius * v.Length();
  641. #ifdef JPH_GJK_DEBUG
  642. Trace("v . w = %g", (double)v_dot_w);
  643. #endif
  644. if (v_dot_w > 0.0f)
  645. {
  646. // If ray and normal are in the same direction, we've passed A and there's no collision
  647. float v_dot_r = v.Dot(inDirection);
  648. #ifdef JPH_GJK_DEBUG
  649. Trace("v . r = %g", (double)v_dot_r);
  650. #endif
  651. if (v_dot_r >= 0.0f)
  652. return false;
  653. // Update the lower bound for lambda
  654. float delta = v_dot_w / v_dot_r;
  655. float old_lambda = lambda;
  656. lambda -= delta;
  657. #ifdef JPH_GJK_DEBUG
  658. Trace("lambda = %g, delta = %g", (double)lambda, (double)delta);
  659. #endif
  660. // If lambda didn't change, we cannot converge any further and we assume a hit
  661. if (old_lambda == lambda)
  662. break;
  663. // If lambda is bigger or equal than max, we don't have a hit
  664. if (lambda >= ioLambda)
  665. return false;
  666. // Update x to new closest point on the ray
  667. x = lambda * inDirection;
  668. // We've shifted x, so reset v_len_sq so that it is not used as early out when GetClosest returns false
  669. v_len_sq = FLT_MAX;
  670. // Now that we've moved, we know that A and B are not intersecting at lambda = 0, so we can update our tolerance to stop iterating
  671. // as soon as A and B are inConvexRadiusA + inConvexRadiusB apart
  672. tolerance_sq = Square(inTolerance + sum_convex_radius);
  673. // We allow rebuilding the simplex once after x changes because the simplex was built
  674. // for another x and numerical round off builds up as you keep adding points to an
  675. // existing simplex
  676. allow_restart = true;
  677. }
  678. // Add p to set P, q to set Q: P = P U {p}, Q = Q U {q}
  679. mP[mNumPoints] = p;
  680. mQ[mNumPoints] = q;
  681. ++mNumPoints;
  682. // Calculate Y = {x} - (Q - P)
  683. for (int i = 0; i < mNumPoints; ++i)
  684. mY[i] = x - (mQ[i] - mP[i]);
  685. // Determine the new closest point from Y to origin
  686. bool needs_restart = false;
  687. uint32 set; // Set of points that form the new simplex
  688. if (!GetClosest(v_len_sq, v, v_len_sq, set))
  689. {
  690. #ifdef JPH_GJK_DEBUG
  691. Trace("Failed to converge");
  692. #endif
  693. // We failed to converge, restart
  694. needs_restart = true;
  695. }
  696. else if (set == 0xf)
  697. {
  698. #ifdef JPH_GJK_DEBUG
  699. Trace("Full simplex");
  700. #endif
  701. // If there are 4 points, x is inside the tetrahedron and we've found a hit
  702. // Double check that A and B are indeed touching according to our tolerance
  703. if (v_len_sq <= tolerance_sq)
  704. break;
  705. // We failed to converge, restart
  706. needs_restart = true;
  707. }
  708. if (needs_restart)
  709. {
  710. // Only allow 1 restart, if we still can't get a closest point
  711. // we're so close that we return this as a hit
  712. if (!allow_restart)
  713. break;
  714. // If we fail to converge, we start again with the last point as simplex
  715. #ifdef JPH_GJK_DEBUG
  716. Trace("Restarting");
  717. #endif
  718. allow_restart = false;
  719. mP[0] = p;
  720. mQ[0] = q;
  721. mNumPoints = 1;
  722. v = x - q;
  723. v_len_sq = FLT_MAX;
  724. continue;
  725. }
  726. // Update the points P and Q to form the new simplex
  727. // Note: We're not updating Y as Y will shift with x so we have to calculate it every iteration
  728. UpdatePointSetPQ(set);
  729. // Check if A and B are touching according to our tolerance
  730. if (v_len_sq <= tolerance_sq)
  731. {
  732. #ifdef JPH_GJK_DEBUG
  733. Trace("Converged");
  734. #endif
  735. break;
  736. }
  737. // Store our v to return as separating axis
  738. prev_v = v;
  739. }
  740. // Calculate Y = {x} - (Q - P) again so we can calculate the contact points
  741. for (int i = 0; i < mNumPoints; ++i)
  742. mY[i] = x - (mQ[i] - mP[i]);
  743. // Calculate the offset we need to apply to A and B to correct for the convex radius
  744. Vec3 normalized_v = v.NormalizedOr(Vec3::sZero());
  745. Vec3 convex_radius_a = inConvexRadiusA * normalized_v;
  746. Vec3 convex_radius_b = inConvexRadiusB * normalized_v;
  747. // Get the contact point
  748. // Note that A and B will coincide when lambda > 0. In this case we calculate only B as it is more accurate as it contains less terms.
  749. switch (mNumPoints)
  750. {
  751. case 1:
  752. outPointB = mQ[0] + convex_radius_b;
  753. outPointA = lambda > 0.0f? outPointB : mP[0] - convex_radius_a;
  754. break;
  755. case 2:
  756. {
  757. float bu, bv;
  758. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], bu, bv);
  759. outPointB = bu * mQ[0] + bv * mQ[1] + convex_radius_b;
  760. outPointA = lambda > 0.0f? outPointB : bu * mP[0] + bv * mP[1] - convex_radius_a;
  761. }
  762. break;
  763. case 3:
  764. case 4: // A full simplex, we can't properly determine a contact point! As contact point we take the closest point of the previous iteration.
  765. {
  766. float bu, bv, bw;
  767. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], mY[2], bu, bv, bw);
  768. outPointB = bu * mQ[0] + bv * mQ[1] + bw * mQ[2] + convex_radius_b;
  769. outPointA = lambda > 0.0f? outPointB : bu * mP[0] + bv * mP[1] + bw * mP[2] - convex_radius_a;
  770. }
  771. break;
  772. }
  773. // Store separating axis, in case we have a convex radius we can just return v,
  774. // otherwise v will be very small and we resort to returning previous v as an approximation.
  775. outSeparatingAxis = sum_convex_radius > 0.0f? -v : -prev_v;
  776. // Store hit fraction
  777. ioLambda = lambda;
  778. return true;
  779. }
  780. private:
  781. #ifdef JPH_GJK_DEBUG
  782. /// Draw state of algorithm
  783. void DrawState()
  784. {
  785. Mat44 origin = Mat44::sTranslation(mOffset);
  786. // Draw origin
  787. DebugRenderer::sInstance->DrawCoordinateSystem(origin, 1.0f);
  788. // Draw the hull
  789. DebugRenderer::sInstance->DrawGeometry(origin, mGeometry->mBounds, mGeometry->mBounds.GetExtent().LengthSq(), Color::sYellow, mGeometry);
  790. // Draw Y
  791. for (int i = 0; i < mNumPoints; ++i)
  792. {
  793. // Draw support point
  794. Vec3 y_i = origin * mY[i];
  795. DebugRenderer::sInstance->DrawMarker(y_i, Color::sRed, 1.0f);
  796. for (int j = i + 1; j < mNumPoints; ++j)
  797. {
  798. // Draw edge
  799. Vec3 y_j = origin * mY[j];
  800. DebugRenderer::sInstance->DrawLine(y_i, y_j, Color::sRed);
  801. for (int k = j + 1; k < mNumPoints; ++k)
  802. {
  803. // Make sure triangle faces the origin
  804. Vec3 y_k = origin * mY[k];
  805. Vec3 center = (y_i + y_j + y_k) / 3.0f;
  806. Vec3 normal = (y_j - y_i).Cross(y_k - y_i);
  807. if (normal.Dot(center) < 0.0f)
  808. DebugRenderer::sInstance->DrawTriangle(y_i, y_j, y_k, Color::sLightGrey);
  809. else
  810. DebugRenderer::sInstance->DrawTriangle(y_i, y_k, y_j, Color::sLightGrey);
  811. }
  812. }
  813. }
  814. // Offset to the right
  815. mOffset += Vec3(mGeometry->mBounds.GetSize().GetX() + 2.0f, 0, 0);
  816. }
  817. #endif // JPH_GJK_DEBUG
  818. Vec3 mY[4]; ///< Support points on A - B
  819. Vec3 mP[4]; ///< Support point on A
  820. Vec3 mQ[4]; ///< Support point on B
  821. int mNumPoints = 0; ///< Number of points in mY, mP and mQ that are valid
  822. #ifdef JPH_GJK_DEBUG
  823. DebugRenderer::GeometryRef mGeometry; ///< A visualization of the minkowski difference for state drawing
  824. Vec3 mOffset = Vec3::sZero(); ///< Offset to use for state drawing
  825. #endif
  826. };
  827. JPH_NAMESPACE_END