CollideShapeTests.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include "UnitTestFramework.h"
  4. #include "PhysicsTestContext.h"
  5. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaledShape.h>
  7. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  8. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  9. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  10. #include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
  11. #include <Jolt/Physics/Collision/Shape/TriangleShape.h>
  12. #include <Jolt/Physics/Collision/CollideShape.h>
  13. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  14. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  15. #include <Jolt/Geometry/EPAPenetrationDepth.h>
  16. #include "Layers.h"
  17. TEST_SUITE("CollideShapeTests")
  18. {
  19. // Compares CollideShapeResult for two spheres with given positions and radii
  20. static void sCompareCollideShapeResultSphere(Vec3Arg inPosition1, float inRadius1, Vec3Arg inPosition2, float inRadius2, const CollideShapeResult &inResult)
  21. {
  22. // Test if spheres overlap
  23. Vec3 delta = inPosition2 - inPosition1;
  24. float len = delta.Length();
  25. CHECK(len > 0.0f);
  26. CHECK(len <= inRadius1 + inRadius2);
  27. // Calculate points on surface + vector that will push 2 out of collision
  28. Vec3 expected_point1 = inPosition1 + delta * (inRadius1 / len);
  29. Vec3 expected_point2 = inPosition2 - delta * (inRadius2 / len);
  30. Vec3 expected_penetration_axis = delta / len;
  31. // Get actual results
  32. Vec3 penetration_axis = inResult.mPenetrationAxis.Normalized();
  33. // Compare
  34. CHECK_APPROX_EQUAL(expected_point1, inResult.mContactPointOn1);
  35. CHECK_APPROX_EQUAL(expected_point2, inResult.mContactPointOn2);
  36. CHECK_APPROX_EQUAL(expected_penetration_axis, penetration_axis);
  37. }
  38. // Test CollideShape function for spheres
  39. TEST_CASE("TestCollideShapeSphere")
  40. {
  41. // Locations of test sphere
  42. static const Vec3 cPosition1A(10.0f, 11.0f, 12.0f);
  43. static const Vec3 cPosition1B(10.0f, 21.0f, 12.0f);
  44. static const float cRadius1 = 2.0f;
  45. // Locations of sphere in the physics system
  46. static const Vec3 cPosition2A(13.0f, 11.0f, 12.0f);
  47. static const Vec3 cPosition2B(13.0f, 22.0f, 12.0f);
  48. static const float cRadius2 = 1.5f;
  49. // Create sphere to test with (shape 1)
  50. Ref<Shape> shape1 = new SphereShape(cRadius1);
  51. Mat44 shape1_com = Mat44::sTranslation(shape1->GetCenterOfMass());
  52. Mat44 shape1_transform = Mat44::sTranslation(cPosition1A) * Mat44::sRotationX(0.1f * JPH_PI) * shape1_com;
  53. // Create sphere to collide against (shape 2)
  54. PhysicsTestContext c;
  55. Body &body2 = c.CreateSphere(cPosition2A, cRadius2, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING);
  56. // Filters
  57. SpecifiedBroadPhaseLayerFilter broadphase_moving_filter(BroadPhaseLayers::MOVING);
  58. SpecifiedBroadPhaseLayerFilter broadphase_non_moving_filter(BroadPhaseLayers::NON_MOVING);
  59. SpecifiedObjectLayerFilter object_moving_filter(Layers::MOVING);
  60. SpecifiedObjectLayerFilter object_non_moving_filter(Layers::NON_MOVING);
  61. // Collector that fails the test
  62. class FailCollideShapeCollector : public CollideShapeCollector
  63. {
  64. public:
  65. virtual void AddHit(const CollideShapeResult &inResult) override
  66. {
  67. FAIL("Callback should not be called");
  68. }
  69. };
  70. FailCollideShapeCollector fail_collector;
  71. // Set settings
  72. CollideShapeSettings settings;
  73. settings.mActiveEdgeMode = EActiveEdgeMode::CollideWithAll;
  74. settings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces;
  75. // Test against wrong layer
  76. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(shape1, Vec3::sReplicate(1.0f), shape1_transform, settings, fail_collector, broadphase_moving_filter, object_moving_filter);
  77. // Collector that tests that collision happens at position A
  78. class PositionACollideShapeCollector : public CollideShapeCollector
  79. {
  80. public:
  81. PositionACollideShapeCollector(const Body &inBody2) :
  82. mBody2(inBody2)
  83. {
  84. }
  85. virtual void AddHit(const CollideShapeResult &inResult) override
  86. {
  87. CHECK(mBody2.GetID() == GetContext()->mBodyID);
  88. sCompareCollideShapeResultSphere(cPosition1A, cRadius1, cPosition2A, cRadius2, inResult);
  89. mWasHit = true;
  90. }
  91. bool mWasHit = false;
  92. private:
  93. const Body & mBody2;
  94. };
  95. PositionACollideShapeCollector position_a_collector(body2);
  96. // Test collision against correct layer
  97. CHECK(!position_a_collector.mWasHit);
  98. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(shape1, Vec3::sReplicate(1.0f), shape1_transform, settings, position_a_collector, broadphase_non_moving_filter, object_non_moving_filter);
  99. CHECK(position_a_collector.mWasHit);
  100. // Now move body to position B
  101. c.GetSystem()->GetBodyInterface().SetPositionAndRotation(body2.GetID(), cPosition2B, Quat::sRotation(Vec3::sAxisY(), 0.2f * JPH_PI), EActivation::DontActivate);
  102. // Test that original position doesn't collide anymore
  103. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(shape1, Vec3::sReplicate(1.0f), shape1_transform, settings, fail_collector, broadphase_non_moving_filter, object_non_moving_filter);
  104. // Move test shape to position B
  105. shape1_transform = Mat44::sTranslation(cPosition1B) * Mat44::sRotationZ(0.3f * JPH_PI) * shape1_com;
  106. // Test against wrong layer
  107. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(shape1, Vec3::sReplicate(1.0f), shape1_transform, settings, fail_collector, broadphase_moving_filter, object_moving_filter);
  108. // Callback that tests that collision happens at position B
  109. class PositionBCollideShapeCollector : public CollideShapeCollector
  110. {
  111. public:
  112. PositionBCollideShapeCollector(const Body &inBody2) :
  113. mBody2(inBody2)
  114. {
  115. }
  116. virtual void Reset() override
  117. {
  118. CollideShapeCollector::Reset();
  119. mWasHit = false;
  120. }
  121. virtual void AddHit(const CollideShapeResult &inResult) override
  122. {
  123. CHECK(mBody2.GetID() == GetContext()->mBodyID);
  124. sCompareCollideShapeResultSphere(cPosition1B, cRadius1, cPosition2B, cRadius2, inResult);
  125. mWasHit = true;
  126. }
  127. bool mWasHit = false;
  128. private:
  129. const Body & mBody2;
  130. };
  131. PositionBCollideShapeCollector position_b_collector(body2);
  132. // Test collision
  133. CHECK(!position_b_collector.mWasHit);
  134. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(shape1, Vec3::sReplicate(1.0f), shape1_transform, settings, position_b_collector, broadphase_non_moving_filter, object_non_moving_filter);
  135. CHECK(position_b_collector.mWasHit);
  136. // Update the physics system (optimizes the broadphase)
  137. c.Simulate(c.GetDeltaTime());
  138. // Test against wrong layer
  139. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(shape1, Vec3::sReplicate(1.0f), shape1_transform, settings, fail_collector, broadphase_moving_filter, object_moving_filter);
  140. // Test collision again
  141. position_b_collector.Reset();
  142. CHECK(!position_b_collector.mWasHit);
  143. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(shape1, Vec3::sReplicate(1.0f), shape1_transform, settings, position_b_collector, broadphase_non_moving_filter, object_non_moving_filter);
  144. CHECK(position_b_collector.mWasHit);
  145. }
  146. // Test CollideShape function for a (scaled) sphere vs box
  147. TEST_CASE("TestCollideShapeSphereVsBox")
  148. {
  149. PhysicsTestContext c;
  150. // Create box to collide against (shape 2)
  151. // The box is scaled up by a factor 10 in the X axis and then rotated so that the X axis is up
  152. BoxShapeSettings box(Vec3::sReplicate(1.0f));
  153. box.SetEmbedded();
  154. ScaledShapeSettings scaled_box(&box, Vec3(10, 1, 1));
  155. scaled_box.SetEmbedded();
  156. Body &body2 = c.CreateBody(&scaled_box, Vec3(0, 1, 0), Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, EActivation::DontActivate);
  157. // Set settings
  158. CollideShapeSettings settings;
  159. settings.mActiveEdgeMode = EActiveEdgeMode::CollideWithAll;
  160. settings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces;
  161. {
  162. // Create sphere
  163. Ref<Shape> normal_sphere = new SphereShape(1.0f);
  164. // Collect hit with normal sphere
  165. AllHitCollisionCollector<CollideShapeCollector> collector;
  166. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(normal_sphere, Vec3::sReplicate(1.0f), Mat44::sTranslation(Vec3(0, 11, 0)), settings, collector);
  167. CHECK(collector.mHits.size() == 1);
  168. const CollideShapeResult &result = collector.mHits.front();
  169. CHECK(result.mBodyID2 == body2.GetID());
  170. CHECK_APPROX_EQUAL(result.mContactPointOn1, Vec3(0, 10, 0), 1.0e-4f);
  171. CHECK_APPROX_EQUAL(result.mContactPointOn2, Vec3(0, 11, 0), 1.0e-4f);
  172. Vec3 pen_axis = result.mPenetrationAxis.Normalized();
  173. CHECK_APPROX_EQUAL(pen_axis, Vec3(0, -1, 0), 1.0e-4f);
  174. CHECK_APPROX_EQUAL(result.mPenetrationDepth, 1.0f, 1.0e-5f);
  175. }
  176. {
  177. // This repeats the same test as above but uses scaling at all levels
  178. Ref<Shape> scaled_sphere = new ScaledShape(new SphereShape(0.1f), Vec3::sReplicate(5.0f));
  179. // Collect hit with scaled sphere
  180. AllHitCollisionCollector<CollideShapeCollector> collector;
  181. c.GetSystem()->GetNarrowPhaseQuery().CollideShape(scaled_sphere, Vec3::sReplicate(2.0f), Mat44::sTranslation(Vec3(0, 11, 0)), settings, collector);
  182. CHECK(collector.mHits.size() == 1);
  183. const CollideShapeResult &result = collector.mHits.front();
  184. CHECK(result.mBodyID2 == body2.GetID());
  185. CHECK_APPROX_EQUAL(result.mContactPointOn1, Vec3(0, 10, 0), 1.0e-4f);
  186. CHECK_APPROX_EQUAL(result.mContactPointOn2, Vec3(0, 11, 0), 1.0e-4f);
  187. Vec3 pen_axis = result.mPenetrationAxis.Normalized();
  188. CHECK_APPROX_EQUAL(pen_axis, Vec3(0, -1, 0), 1.0e-4f);
  189. CHECK_APPROX_EQUAL(result.mPenetrationDepth, 1.0f, 1.0e-5f);
  190. }
  191. }
  192. // Test colliding a very long capsule vs a box that is intersecting with the linesegment inside the capsule
  193. // This particular config reported the wrong penetration due to accuracy problems before
  194. TEST_CASE("TestCollideShapeLongCapsuleVsEmbeddedBox")
  195. {
  196. // Create box
  197. Vec3 box_min(-1.0f, -2.0f, 0.5f);
  198. Vec3 box_max(2.0f, -0.5f, 3.0f);
  199. Ref<RotatedTranslatedShapeSettings> box_settings = new RotatedTranslatedShapeSettings(0.5f * (box_min + box_max), Quat::sIdentity(), new BoxShapeSettings(0.5f * (box_max - box_min)));
  200. Ref<Shape> box_shape = box_settings->Create().Get();
  201. Mat44 box_transform(Vec4(0.516170502f, -0.803887904f, -0.295520246f, 0.0f), Vec4(0.815010250f, 0.354940295f, 0.458012700f, 0.0f), Vec4(-0.263298869f, -0.477264702f, 0.838386655f, 0.0f), Vec4(-10.2214508f, -18.6808319f, 40.7468987f, 1.0f));
  202. // Create capsule
  203. float capsule_half_height = 75.0f;
  204. float capsule_radius = 1.5f;
  205. Ref<RotatedTranslatedShapeSettings> capsule_settings = new RotatedTranslatedShapeSettings(Vec3(0, 0, 75), Quat(0.499999970f, -0.499999970f, -0.499999970f, 0.499999970f), new CapsuleShapeSettings(capsule_half_height, capsule_radius));
  206. Ref<Shape> capsule_shape = capsule_settings->Create().Get();
  207. Mat44 capsule_transform = Mat44::sTranslation(Vec3(-9.68538570f, -18.0328083f, 41.3212280f));
  208. // Collision settings
  209. CollideShapeSettings settings;
  210. settings.mActiveEdgeMode = EActiveEdgeMode::CollideWithAll;
  211. settings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces;
  212. settings.mCollectFacesMode = ECollectFacesMode::NoFaces;
  213. // Collide the two shapes
  214. AllHitCollisionCollector<CollideShapeCollector> collector;
  215. CollisionDispatch::sCollideShapeVsShape(capsule_shape, box_shape, Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), capsule_transform, box_transform, SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
  216. // Check that there was a hit
  217. CHECK(collector.mHits.size() == 1);
  218. const CollideShapeResult &result = collector.mHits.front();
  219. // Now move the box 1% further than the returned penetration depth and check that it is no longer in collision
  220. Vec3 distance_to_move_box = result.mPenetrationAxis.Normalized() * result.mPenetrationDepth;
  221. collector.Reset();
  222. CHECK(!collector.HadHit());
  223. CollisionDispatch::sCollideShapeVsShape(capsule_shape, box_shape, Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), capsule_transform, Mat44::sTranslation(1.01f * distance_to_move_box) * box_transform, SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
  224. CHECK(!collector.HadHit());
  225. // Now check that moving 1% less than the penetration distance makes the shapes still overlap
  226. CollisionDispatch::sCollideShapeVsShape(capsule_shape, box_shape, Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), capsule_transform, Mat44::sTranslation(0.99f * distance_to_move_box) * box_transform, SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
  227. CHECK(collector.mHits.size() == 1);
  228. }
  229. // Another test case found in practice of a very large oriented box (convex hull) vs a small triangle outside the hull. This should not report a collision
  230. TEST_CASE("TestCollideShapeSmallTriangleVsLargeBox")
  231. {
  232. // Triangle vertices
  233. Vec3 v0(-81.5637589f, -126.987244f, -146.771729f);
  234. Vec3 v1(-81.8749924f, -127.270691f, -146.544403f);
  235. Vec3 v2(-81.6972275f, -127.383545f, -146.773254f);
  236. // Oriented box vertices
  237. Array<Vec3> obox_points = {
  238. Vec3(125.932892f, -374.712250f, 364.192169f),
  239. Vec3(319.492218f, -73.2614441f, 475.009613f),
  240. Vec3(-122.277550f, -152.200287f, 192.441437f),
  241. Vec3(71.2817841f, 149.250519f, 303.258881f),
  242. Vec3(-77.8921967f, -359.410797f, 678.579712f),
  243. Vec3(115.667137f, -57.9600067f, 789.397095f),
  244. Vec3(-326.102631f, -136.898834f, 506.828949f),
  245. Vec3(-132.543304f, 164.551971f, 617.646362f)
  246. };
  247. ConvexHullShapeSettings hull_settings(obox_points, 0.0f);
  248. RefConst<ConvexShape> convex_hull = static_cast<const ConvexShape *>(hull_settings.Create().Get().GetPtr());
  249. // Create triangle support function
  250. TriangleConvexSupport triangle(v0, v1, v2);
  251. // Create the convex hull support function
  252. ConvexShape::SupportBuffer buffer;
  253. const ConvexShape::Support *support = convex_hull->GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, buffer, Vec3::sReplicate(1.0f));
  254. // Triangle is close enough to make GJK report indeterminate
  255. Vec3 penetration_axis = Vec3::sAxisX(), point1, point2;
  256. EPAPenetrationDepth pen_depth;
  257. EPAPenetrationDepth::EStatus status = pen_depth.GetPenetrationDepthStepGJK(*support, support->GetConvexRadius(), triangle, 0.0f, cDefaultCollisionTolerance, penetration_axis, point1, point2);
  258. CHECK(status == EPAPenetrationDepth::EStatus::Indeterminate);
  259. // But there should not be an actual collision
  260. CHECK(!pen_depth.GetPenetrationDepthStepEPA(*support, triangle, cDefaultPenetrationTolerance, penetration_axis, point1, point2));
  261. }
  262. // A test case of a triangle that's nearly parallel to a capsule and penetrating it. This one was causing numerical issues.
  263. TEST_CASE("TestCollideParallelTriangleVsCapsule")
  264. {
  265. Vec3 v1(-0.479988575f, -1.36185002f, 0.269966960f);
  266. Vec3 v2(-0.104996204f, 0.388152480f, 0.269967079f);
  267. Vec3 v3(-0.104996204f, -1.36185002f, 0.269966960f);
  268. TriangleShape triangle(v1, v2, v3);
  269. triangle.SetEmbedded();
  270. float capsule_radius = 0.37f;
  271. float capsule_half_height = 0.5f;
  272. CapsuleShape capsule(capsule_half_height, capsule_radius);
  273. capsule.SetEmbedded();
  274. CollideShapeSettings settings;
  275. AllHitCollisionCollector<CollideShapeCollector> collector;
  276. CollisionDispatch::sCollideShapeVsShape(&triangle, &capsule, Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), Mat44::sIdentity(), Mat44::sIdentity(), SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
  277. // The capsule's center is closest to the triangle's edge v2 v3
  278. Vec3 capsule_center_to_triangle_v2_v3 = v3;
  279. capsule_center_to_triangle_v2_v3.SetY(0); // The penetration axis will be in x, z only because the triangle is parallel to the capsule axis
  280. float capsule_center_to_triangle_v2_v3_len = capsule_center_to_triangle_v2_v3.Length();
  281. Vec3 expected_penetration_axis = -capsule_center_to_triangle_v2_v3 / capsule_center_to_triangle_v2_v3_len;
  282. float expected_penetration_depth = capsule_radius - capsule_center_to_triangle_v2_v3_len;
  283. CHECK(collector.mHits.size() == 1);
  284. const CollideShapeResult &hit = collector.mHits[0];
  285. Vec3 actual_penetration_axis = hit.mPenetrationAxis.Normalized();
  286. float actual_penetration_depth = hit.mPenetrationDepth;
  287. CHECK_APPROX_EQUAL(actual_penetration_axis, expected_penetration_axis);
  288. CHECK_APPROX_EQUAL(actual_penetration_depth, expected_penetration_depth);
  289. }
  290. }