PhysicsTests.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include "UnitTestFramework.h"
  5. #include "PhysicsTestContext.h"
  6. #include "Layers.h"
  7. #include "LoggingBodyActivationListener.h"
  8. #include "LoggingContactListener.h"
  9. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  10. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  11. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  12. #include <Jolt/Physics/Body/BodyLockMulti.h>
  13. #include <Jolt/Physics/Constraints/PointConstraint.h>
  14. TEST_SUITE("PhysicsTests")
  15. {
  16. // Gravity vector
  17. const Vec3 cGravity = Vec3(0.0f, -9.81f, 0.0f);
  18. // Test the test framework's helper functions
  19. TEST_CASE("TestPhysicsTestContext")
  20. {
  21. // Test that the Symplectic Euler integrator is close enough to the real value
  22. const float cSimulationTime = 2.0f;
  23. // For position: x = x0 + v0 * t + 1/2 * a * t^2
  24. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  25. PhysicsTestContext c;
  26. RVec3 simulated_pos = c.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  27. RVec3 integrated_position = cInitialPos + 0.5f * cGravity * Square(cSimulationTime);
  28. CHECK_APPROX_EQUAL(integrated_position, simulated_pos, 0.2f);
  29. // For rotation
  30. const Quat cInitialRot(Quat::sRotation(Vec3::sAxisY(), 0.1f));
  31. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  32. Quat simulated_rot = c.PredictOrientation(cInitialRot, Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  33. Vec3 integrated_acceleration = 0.5f * cAngularAcceleration * Square(cSimulationTime);
  34. float integrated_acceleration_len = integrated_acceleration.Length();
  35. Quat integrated_rot = Quat::sRotation(integrated_acceleration / integrated_acceleration_len, integrated_acceleration_len) * cInitialRot;
  36. CHECK_APPROX_EQUAL(integrated_rot, simulated_rot, 0.02f);
  37. }
  38. TEST_CASE("TestPhysicsBodyLock")
  39. {
  40. PhysicsTestContext c;
  41. // Check that we cannot lock the invalid body ID
  42. {
  43. BodyLockRead lock(c.GetSystem()->GetBodyLockInterface(), BodyID());
  44. CHECK_FALSE(lock.Succeeded());
  45. CHECK_FALSE(lock.SucceededAndIsInBroadPhase());
  46. }
  47. BodyID body1_id;
  48. {
  49. // Create a box
  50. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  51. body1_id = body1.GetID();
  52. CHECK(body1_id.GetIndex() == 0);
  53. CHECK(body1_id.GetSequenceNumber() == 1);
  54. // Create another box
  55. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  56. BodyID body2_id = body2.GetID();
  57. CHECK(body2_id.GetIndex() == 1);
  58. CHECK(body2_id.GetSequenceNumber() == 1);
  59. // Check that we can lock the first box
  60. {
  61. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  62. CHECK(lock1.Succeeded());
  63. CHECK(lock1.SucceededAndIsInBroadPhase());
  64. }
  65. // Remove the first box
  66. c.GetSystem()->GetBodyInterface().RemoveBody(body1_id);
  67. // Check that we can lock the first box
  68. {
  69. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  70. CHECK(lock1.Succeeded());
  71. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  72. }
  73. // Destroy the first box
  74. c.GetSystem()->GetBodyInterface().DestroyBody(body1_id);
  75. // Check that we can not lock the body anymore
  76. {
  77. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  78. CHECK_FALSE(lock1.Succeeded());
  79. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  80. }
  81. }
  82. // Create another box
  83. Body &body3 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  84. BodyID body3_id = body3.GetID();
  85. CHECK(body3_id.GetIndex() == 0); // Check index reused
  86. CHECK(body3_id.GetSequenceNumber() == 2); // Check sequence number changed
  87. // Check that we can lock it
  88. {
  89. BodyLockRead lock3(c.GetSystem()->GetBodyLockInterface(), body3_id);
  90. CHECK(lock3.Succeeded());
  91. CHECK(lock3.SucceededAndIsInBroadPhase());
  92. }
  93. // Check that we can't lock the old body with the same body index anymore
  94. {
  95. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  96. CHECK_FALSE(lock1.Succeeded());
  97. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  98. }
  99. }
  100. TEST_CASE("TestPhysicsBodyLockMulti")
  101. {
  102. PhysicsTestContext c;
  103. // Check that we cannot lock the invalid body ID
  104. {
  105. BodyID bodies[] = { BodyID(), BodyID() };
  106. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  107. CHECK(lock.GetBody(0) == nullptr);
  108. CHECK(lock.GetBody(1) == nullptr);
  109. }
  110. {
  111. // Create two bodies
  112. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  113. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  114. BodyID bodies[] = { body1.GetID(), body2.GetID() };
  115. {
  116. // Lock the bodies
  117. BodyLockMultiWrite lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  118. CHECK(lock.GetBody(0) == &body1);
  119. CHECK(lock.GetBody(1) == &body2);
  120. }
  121. // Destroy body 1
  122. c.GetSystem()->GetBodyInterface().RemoveBody(bodies[0]);
  123. c.GetSystem()->GetBodyInterface().DestroyBody(bodies[0]);
  124. {
  125. // Lock the bodies
  126. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  127. CHECK(lock.GetBody(0) == nullptr);
  128. CHECK(lock.GetBody(1) == &body2);
  129. }
  130. }
  131. }
  132. TEST_CASE("TestPhysicsBodyID")
  133. {
  134. {
  135. BodyID body_id(0);
  136. CHECK(body_id.GetIndex() == 0);
  137. CHECK(body_id.GetSequenceNumber() == 0);
  138. }
  139. {
  140. BodyID body_id(~BodyID::cBroadPhaseBit);
  141. CHECK(body_id.GetIndex() == BodyID::cMaxBodyIndex);
  142. CHECK(body_id.GetSequenceNumber() == BodyID::cMaxSequenceNumber);
  143. }
  144. }
  145. TEST_CASE("TestPhysicsBodyIDSequenceNumber")
  146. {
  147. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  148. BodyInterface &bi = c.GetBodyInterface();
  149. // Create a body and check it's id
  150. BodyID body0_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  151. CHECK(body0_id == BodyID(0, 1)); // Body 0, sequence number 1
  152. // Check that the sequence numbers aren't reused until after 256 iterations
  153. for (int seq_no = 1; seq_no < 258; ++seq_no)
  154. {
  155. BodyID body1_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  156. CHECK(body1_id == BodyID(1, uint8(seq_no))); // Body 1
  157. bi.RemoveBody(body1_id);
  158. bi.DestroyBody(body1_id);
  159. }
  160. bi.RemoveBody(body0_id);
  161. bi.DestroyBody(body0_id);
  162. }
  163. TEST_CASE("TestPhysicsBodyIDOverride")
  164. {
  165. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  166. BodyInterface &bi = c.GetBodyInterface();
  167. // Dummy creation settings
  168. BodyCreationSettings bc(new BoxShape(Vec3::sReplicate(1.0f)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  169. // Create a body
  170. Body *b1 = bi.CreateBody(bc);
  171. CHECK(b1->GetID() == BodyID(0, 1));
  172. // Create body with same ID and same sequence number
  173. Body *b2 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  174. CHECK(b2 == nullptr);
  175. // Create body with same ID and different sequence number
  176. b2 = bi.CreateBodyWithID(BodyID(0, 2), bc);
  177. CHECK(b2 == nullptr);
  178. // Create body with different ID (leave 1 open slot)
  179. b2 = bi.CreateBodyWithoutID(bc); // Using syntax that allows separation of allocation and assigning an ID
  180. CHECK(b2 != nullptr);
  181. CHECK(b2->GetID().IsInvalid());
  182. bi.AssignBodyID(b2, BodyID(2, 1));
  183. CHECK(b2->GetID() == BodyID(2, 1));
  184. // Create another body and check that the open slot is returned
  185. Body *b3 = bi.CreateBody(bc);
  186. CHECK(b3->GetID() == BodyID(1, 1));
  187. // Create another body and check that we do not hand out the body with specified ID
  188. Body *b4 = bi.CreateBody(bc);
  189. CHECK(b4->GetID() == BodyID(3, 1));
  190. // Delete and recreate body 4
  191. CHECK(bi.CreateBodyWithID(BodyID(3, 1), bc) == nullptr);
  192. bi.DestroyBody(b4->GetID());
  193. b4 = bi.CreateBodyWithID(BodyID(3, 1), bc);
  194. CHECK(b4 != nullptr);
  195. CHECK(b4->GetID() == BodyID(3, 1));
  196. // Destroy 1st body
  197. CHECK(bi.UnassignBodyID(b1->GetID()) == b1); // Use syntax that allows separation of unassigning and deallocation
  198. CHECK(b1->GetID().IsInvalid());
  199. bi.DestroyBodyWithoutID(b1);
  200. // Clean up remaining bodies
  201. bi.DestroyBody(b2->GetID());
  202. bi.DestroyBody(b3->GetID());
  203. bi.DestroyBody(b4->GetID());
  204. // Recreate body 1
  205. b1 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  206. CHECK(b1 != nullptr);
  207. CHECK(b1->GetID() == BodyID(0, 1));
  208. // Destroy last body
  209. bi.DestroyBody(b1->GetID());
  210. }
  211. TEST_CASE("TestPhysicsBodyUserData")
  212. {
  213. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  214. BodyInterface &bi = c.GetBodyInterface();
  215. // Create a body and pass user data through the creation settings
  216. BodyCreationSettings body_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  217. body_settings.mUserData = 0x1234567887654321;
  218. Body *body = bi.CreateBody(body_settings);
  219. CHECK(body->GetUserData() == 0x1234567887654321);
  220. // Change the user data
  221. body->SetUserData(0x5678123443218765);
  222. CHECK(body->GetUserData() == 0x5678123443218765);
  223. // Convert back to body settings
  224. BodyCreationSettings body_settings2 = body->GetBodyCreationSettings();
  225. CHECK(body_settings2.mUserData == 0x5678123443218765);
  226. }
  227. TEST_CASE("TestPhysicsConstraintUserData")
  228. {
  229. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  230. // Create a body
  231. Body &body = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f));
  232. // Create constraint with user data
  233. PointConstraintSettings constraint_settings;
  234. constraint_settings.mUserData = 0x1234567887654321;
  235. Ref<Constraint> constraint = constraint_settings.Create(body, Body::sFixedToWorld);
  236. CHECK(constraint->GetUserData() == 0x1234567887654321);
  237. // Change the user data
  238. constraint->SetUserData(0x5678123443218765);
  239. CHECK(constraint->GetUserData() == 0x5678123443218765);
  240. // Convert back to constraint settings
  241. Ref<ConstraintSettings> constraint_settings2 = constraint->GetConstraintSettings();
  242. CHECK(constraint_settings2->mUserData == 0x5678123443218765);
  243. }
  244. TEST_CASE("TestPhysicsPosition")
  245. {
  246. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  247. BodyInterface &bi = c.GetBodyInterface();
  248. // Translate / rotate the box
  249. Vec3 box_pos(1, 2, 3);
  250. Quat box_rotation = Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI);
  251. // Translate / rotate the body
  252. RVec3 body_pos(4, 5, 6);
  253. Quat body_rotation = Quat::sRotation(Vec3::sAxisY(), 0.3f * JPH_PI);
  254. RMat44 body_transform = RMat44::sRotationTranslation(body_rotation, body_pos);
  255. RMat44 com_transform = body_transform * Mat44::sTranslation(box_pos);
  256. // Create body
  257. BodyCreationSettings body_settings(new RotatedTranslatedShapeSettings(box_pos, box_rotation, new BoxShape(Vec3::sReplicate(1.0f))), body_pos, body_rotation, EMotionType::Static, Layers::NON_MOVING);
  258. Body *body = bi.CreateBody(body_settings);
  259. // Check that the correct positions / rotations are reported
  260. CHECK_APPROX_EQUAL(body->GetPosition(), body_pos);
  261. CHECK_APPROX_EQUAL(body->GetRotation(), body_rotation);
  262. CHECK_APPROX_EQUAL(body->GetWorldTransform(), body_transform);
  263. CHECK_APPROX_EQUAL(body->GetCenterOfMassPosition(), com_transform.GetTranslation());
  264. CHECK_APPROX_EQUAL(body->GetCenterOfMassTransform(), com_transform);
  265. CHECK_APPROX_EQUAL(body->GetInverseCenterOfMassTransform(), com_transform.InversedRotationTranslation(), 1.0e-5f);
  266. }
  267. TEST_CASE("TestPhysicsOverrideMassAndInertia")
  268. {
  269. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  270. BodyInterface &bi = c.GetBodyInterface();
  271. const float cDensity = 1234.0f;
  272. const Vec3 cBoxExtent(2.0f, 4.0f, 6.0f);
  273. const float cExpectedMass = cBoxExtent.GetX() * cBoxExtent.GetY() * cBoxExtent.GetZ() * cDensity;
  274. // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  275. const Vec3 cSquaredExtents = Vec3(Square(cBoxExtent.GetY()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetY()));
  276. const Vec3 cExpectedInertiaDiagonal = cExpectedMass / 12.0f * cSquaredExtents;
  277. Ref<BoxShapeSettings> shape_settings = new BoxShapeSettings(0.5f * cBoxExtent);
  278. shape_settings->SetDensity(cDensity);
  279. BodyCreationSettings body_settings(shape_settings, RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  280. // Create body as is
  281. Body &b1 = *bi.CreateBody(body_settings);
  282. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseMass(), 1.0f / cExpectedMass);
  283. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  284. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseInertiaDiagonal(), cExpectedInertiaDiagonal.Reciprocal());
  285. // Override only the mass
  286. const float cOverriddenMass = 13.0f;
  287. const Vec3 cOverriddenMassInertiaDiagonal = cOverriddenMass / 12.0f * cSquaredExtents;
  288. body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  289. body_settings.mMassPropertiesOverride.mMass = cOverriddenMass;
  290. Body &b2 = *bi.CreateBody(body_settings);
  291. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  292. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  293. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenMassInertiaDiagonal.Reciprocal());
  294. // Override both the mass and inertia
  295. const Vec3 cOverriddenInertiaDiagonal(3.0f, 2.0f, 1.0f); // From big to small so that MassProperties::DecomposePrincipalMomentsOfInertia returns the same rotation as we put in
  296. const Quat cOverriddenInertiaRotation = Quat::sRotation(Vec3(1, 1, 1).Normalized(), 0.1f * JPH_PI);
  297. body_settings.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  298. body_settings.mMassPropertiesOverride.mInertia = Mat44::sRotation(cOverriddenInertiaRotation) * Mat44::sScale(cOverriddenInertiaDiagonal) * Mat44::sRotation(cOverriddenInertiaRotation.Inversed());
  299. Body &b3 = *bi.CreateBody(body_settings);
  300. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  301. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInertiaRotation(), cOverriddenInertiaRotation);
  302. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenInertiaDiagonal.Reciprocal());
  303. }
  304. // Test a box free falling under gravity
  305. static void TestPhysicsFreeFall(PhysicsTestContext &ioContext)
  306. {
  307. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  308. const float cSimulationTime = 2.0f;
  309. // Create box
  310. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  311. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  312. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  313. ioContext.Simulate(cSimulationTime);
  314. // Test resulting velocity (due to gravity)
  315. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  316. // Test resulting position
  317. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  318. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  319. }
  320. TEST_CASE("TestPhysicsFreeFall")
  321. {
  322. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  323. TestPhysicsFreeFall(c);
  324. }
  325. TEST_CASE("TestPhysicsFreeFallSubStep")
  326. {
  327. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  328. TestPhysicsFreeFall(c1);
  329. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  330. TestPhysicsFreeFall(c2);
  331. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  332. TestPhysicsFreeFall(c3);
  333. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  334. TestPhysicsFreeFall(c4);
  335. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  336. TestPhysicsFreeFall(c5);
  337. PhysicsTestContext c6(4.0f / 60.0f, 4, 1);
  338. TestPhysicsFreeFall(c6);
  339. }
  340. // Test acceleration of a box with force applied
  341. static void TestPhysicsApplyForce(PhysicsTestContext &ioContext)
  342. {
  343. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  344. const Vec3 cAcceleration(2.0f, 0.0f, 0.0f);
  345. const float cSimulationTime = 2.0f;
  346. // Create box
  347. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  348. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  349. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  350. // Validate mass
  351. float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  352. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  353. // Simulate while applying force
  354. ioContext.Simulate(cSimulationTime, [&]() { body.AddForce(mass * cAcceleration); });
  355. // Test resulting velocity (due to gravity and applied force)
  356. CHECK_APPROX_EQUAL(cSimulationTime * (cGravity + cAcceleration), body.GetLinearVelocity(), 1.0e-4f);
  357. // Test resulting position
  358. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity + cAcceleration, cSimulationTime);
  359. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  360. }
  361. TEST_CASE("TestPhysicsApplyForce")
  362. {
  363. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  364. TestPhysicsApplyForce(c);
  365. }
  366. TEST_CASE("TestPhysicsApplyForceSubStep")
  367. {
  368. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  369. TestPhysicsApplyForce(c1);
  370. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  371. TestPhysicsApplyForce(c2);
  372. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  373. TestPhysicsApplyForce(c3);
  374. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  375. TestPhysicsApplyForce(c4);
  376. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  377. TestPhysicsApplyForce(c5);
  378. PhysicsTestContext c6(4.0f / 60.0f, 4, 1);
  379. TestPhysicsApplyForce(c6);
  380. }
  381. // Test angular accelartion for a box by applying torque every frame
  382. static void TestPhysicsApplyTorque(PhysicsTestContext &ioContext)
  383. {
  384. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  385. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  386. const float cSimulationTime = 2.0f;
  387. // Create box
  388. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  389. CHECK_APPROX_EQUAL(Quat::sIdentity(), body.GetRotation());
  390. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  391. // Validate mass and inertia
  392. constexpr float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  393. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  394. constexpr float inertia = mass * 8.0f / 12.0f; // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  395. CHECK_APPROX_EQUAL(Mat44::sScale(1.0f / inertia), body.GetMotionProperties()->GetLocalSpaceInverseInertia());
  396. // Simulate while applying torque
  397. ioContext.Simulate(cSimulationTime, [&]() { body.AddTorque(inertia * cAngularAcceleration); });
  398. // Get resulting angular velocity
  399. CHECK_APPROX_EQUAL(cSimulationTime * cAngularAcceleration, body.GetAngularVelocity(), 1.0e-4f);
  400. // Test resulting rotation
  401. Quat expected_rot = ioContext.PredictOrientation(Quat::sIdentity(), Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  402. CHECK_APPROX_EQUAL(expected_rot, body.GetRotation(), 1.0e-4f);
  403. }
  404. TEST_CASE("TestPhysicsApplyTorque")
  405. {
  406. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  407. TestPhysicsApplyTorque(c);
  408. }
  409. TEST_CASE("TestPhysicsApplyTorqueSubStep")
  410. {
  411. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  412. TestPhysicsApplyTorque(c1);
  413. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  414. TestPhysicsApplyTorque(c2);
  415. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  416. TestPhysicsApplyTorque(c3);
  417. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  418. TestPhysicsApplyTorque(c4);
  419. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  420. TestPhysicsApplyTorque(c5);
  421. PhysicsTestContext c6(4.0f / 60.0f, 4, 1);
  422. TestPhysicsApplyTorque(c6);
  423. }
  424. // Let a sphere bounce on the floor with restition = 1
  425. static void TestPhysicsCollisionElastic(PhysicsTestContext &ioContext)
  426. {
  427. const float cSimulationTime = 1.0f;
  428. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  429. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  430. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  431. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  432. // Create sphere
  433. ioContext.CreateFloor();
  434. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  435. body.SetRestitution(1.0f);
  436. // Simulate until at floor
  437. ioContext.Simulate(cSimulationTime);
  438. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  439. // Assert collision not yet processed
  440. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  441. // Simulate one more step to process the collision
  442. ioContext.Simulate(ioContext.GetDeltaTime());
  443. // Assert that collision is processed and velocity is reversed (which is required for a fully elastic collision).
  444. // Note that the physics engine will first apply gravity for the time step and then do collision detection,
  445. // hence the reflected velocity is actually 1 sub-step times gravity bigger than it would be in reality
  446. // For the remainder of cDeltaTime normal gravity will be applied
  447. float sub_step_delta_time = ioContext.GetSubStepDeltaTime();
  448. float remaining_step_time = ioContext.GetDeltaTime() - ioContext.GetSubStepDeltaTime();
  449. Vec3 reflected_velocity_after_sub_step = -(cSimulationTime + sub_step_delta_time) * cGravity;
  450. Vec3 reflected_velocity_after_full_step = reflected_velocity_after_sub_step + remaining_step_time * cGravity;
  451. CHECK_APPROX_EQUAL(reflected_velocity_after_full_step, body.GetLinearVelocity(), 1.0e-4f);
  452. // Body should have bounced back
  453. RVec3 pos_after_bounce_sub_step = cFloorHitPos + reflected_velocity_after_sub_step * sub_step_delta_time;
  454. RVec3 pos_after_bounce_full_step = ioContext.PredictPosition(pos_after_bounce_sub_step, reflected_velocity_after_sub_step, cGravity, remaining_step_time);
  455. CHECK_APPROX_EQUAL(pos_after_bounce_full_step, body.GetPosition());
  456. // Simulate same time, with a fully elastic body we should reach the initial position again
  457. // In our physics engine because of the velocity being too big we actually end up a bit higher than our initial position
  458. RVec3 expected_pos = ioContext.PredictPosition(pos_after_bounce_full_step, reflected_velocity_after_full_step, cGravity, cSimulationTime);
  459. ioContext.Simulate(cSimulationTime);
  460. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition(), 1.0e-4f);
  461. CHECK(expected_pos.GetY() >= cInitialPos.GetY());
  462. }
  463. TEST_CASE("TestPhysicsCollisionElastic")
  464. {
  465. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  466. TestPhysicsCollisionElastic(c);
  467. }
  468. TEST_CASE("TestPhysicsCollisionElasticSubStep")
  469. {
  470. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  471. TestPhysicsCollisionElastic(c1);
  472. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  473. TestPhysicsCollisionElastic(c2);
  474. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  475. TestPhysicsCollisionElastic(c3);
  476. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  477. TestPhysicsCollisionElastic(c4);
  478. PhysicsTestContext c5(4.0f / 60.0f, 4, 1);
  479. TestPhysicsCollisionElastic(c5);
  480. }
  481. // Let a sphere bounce on the floor with restitution = 0
  482. static void TestPhysicsCollisionInelastic(PhysicsTestContext &ioContext)
  483. {
  484. const float cSimulationTime = 1.0f;
  485. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  486. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  487. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  488. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  489. // Create sphere
  490. ioContext.CreateFloor();
  491. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  492. body.SetRestitution(0.0f);
  493. // Simulate until at floor
  494. ioContext.Simulate(cSimulationTime);
  495. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  496. // Assert collision not yet processed
  497. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  498. // Simulate one more step to process the collision
  499. ioContext.Simulate(ioContext.GetDeltaTime());
  500. // Assert that all velocity was lost in the collision
  501. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  502. // Assert that we're on the floor
  503. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  504. // Simulate some more to validate that we remain on the floor
  505. ioContext.Simulate(cSimulationTime);
  506. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  507. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  508. }
  509. TEST_CASE("TestPhysicsCollisionInelastic")
  510. {
  511. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  512. TestPhysicsCollisionInelastic(c);
  513. }
  514. TEST_CASE("TestPhysicsCollisionInelasticSubStep")
  515. {
  516. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  517. TestPhysicsCollisionInelastic(c1);
  518. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  519. TestPhysicsCollisionInelastic(c2);
  520. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  521. TestPhysicsCollisionInelastic(c3);
  522. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  523. TestPhysicsCollisionInelastic(c4);
  524. PhysicsTestContext c5(4.0f / 60.0f, 4, 1);
  525. TestPhysicsCollisionInelastic(c5);
  526. }
  527. // Let box intersect with floor by cPenetrationSlop. It should not move, this is the maximum penetration allowed.
  528. static void TestPhysicsPenetrationSlop1(PhysicsTestContext &ioContext)
  529. {
  530. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  531. const float cSimulationTime = 1.0f;
  532. const RVec3 cInitialPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  533. // Create box, penetrating with floor
  534. ioContext.CreateFloor();
  535. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  536. // Simulate
  537. ioContext.Simulate(cSimulationTime);
  538. // Test slop not resolved
  539. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  540. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  541. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  542. }
  543. TEST_CASE("TestPhysicsPenetrationSlop1")
  544. {
  545. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  546. TestPhysicsPenetrationSlop1(c);
  547. }
  548. TEST_CASE("TestPhysicsPenetrationSlop1SubStep")
  549. {
  550. PhysicsTestContext c(1.0f / 30.0f, 1, 2);
  551. TestPhysicsPenetrationSlop1(c);
  552. PhysicsTestContext c2(1.0f / 30.0f, 2, 1);
  553. TestPhysicsPenetrationSlop1(c2);
  554. }
  555. // Let box intersect with floor with more than cPenetrationSlop. It should be resolved by SolvePositionConstraint until interpenetration is cPenetrationSlop.
  556. static void TestPhysicsPenetrationSlop2(PhysicsTestContext &ioContext)
  557. {
  558. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  559. const float cSimulationTime = 1.0f;
  560. const RVec3 cInitialPos(0.0f, 1.0f - 2.0f * cPenetrationSlop, 0.0f);
  561. const RVec3 cFinalPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  562. // Create box, penetrating with floor
  563. ioContext.CreateFloor();
  564. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  565. // Simulate
  566. ioContext.Simulate(cSimulationTime);
  567. // Test resolved until slop
  568. CHECK_APPROX_EQUAL(cFinalPos, body.GetPosition(), 1.0e-5f);
  569. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  570. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  571. }
  572. TEST_CASE("TestPhysicsPenetrationSlop2")
  573. {
  574. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  575. TestPhysicsPenetrationSlop2(c);
  576. }
  577. TEST_CASE("TestPhysicsPenetrationSlop2SubStep")
  578. {
  579. PhysicsTestContext c(1.0f / 30.0f, 1, 2);
  580. TestPhysicsPenetrationSlop2(c);
  581. PhysicsTestContext c2(1.0f / 30.0f, 2, 1);
  582. TestPhysicsPenetrationSlop2(c2);
  583. }
  584. // Let box intersect with floor with less than cPenetrationSlop. Body should not move because SolveVelocityConstraint should reset velocity.
  585. static void TestPhysicsPenetrationSlop3(PhysicsTestContext &ioContext)
  586. {
  587. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  588. const float cSimulationTime = 1.0f;
  589. const RVec3 cInitialPos(0.0f, 1.0f - 0.1f * cPenetrationSlop, 0.0f);
  590. // Create box, penetrating with floor
  591. ioContext.CreateFloor();
  592. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  593. // Simulate
  594. ioContext.Simulate(cSimulationTime);
  595. // Test body remained static
  596. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  597. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  598. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  599. }
  600. TEST_CASE("TestPhysicsPenetrationSlop3")
  601. {
  602. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  603. TestPhysicsPenetrationSlop3(c);
  604. }
  605. TEST_CASE("TestPhysicsPenetrationSlop3SubStep")
  606. {
  607. PhysicsTestContext c(1.0f / 30.0f, 1, 2);
  608. TestPhysicsPenetrationSlop3(c);
  609. PhysicsTestContext c2(1.0f / 30.0f, 2, 1);
  610. TestPhysicsPenetrationSlop3(c2);
  611. }
  612. TEST_CASE("TestPhysicsOutsideOfSpeculativeContactDistance")
  613. {
  614. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  615. Body &floor = c.CreateFloor();
  616. c.ZeroGravity();
  617. LoggingContactListener contact_listener;
  618. c.GetSystem()->SetContactListener(&contact_listener);
  619. // Create a box and a sphere just outside the speculative contact distance
  620. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  621. const float cDistanceAboveFloor = 1.1f * cSpeculativeContactDistance;
  622. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  623. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  624. // Make it move 1 m per step down
  625. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  626. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  627. box.SetLinearVelocity(cVelocity);
  628. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  629. sphere.SetLinearVelocity(cVelocity);
  630. // Simulate a step
  631. c.SimulateSingleStep();
  632. // Check that it is now penetrating the floor (collision should not have been detected as it is a discrete body and there was no collision initially)
  633. CHECK(contact_listener.GetEntryCount() == 0);
  634. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  635. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  636. // Simulate a step
  637. c.SimulateSingleStep();
  638. // Check that the contacts are detected now
  639. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  640. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  641. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  642. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  643. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  644. }
  645. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoRestitution")
  646. {
  647. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  648. Body &floor = c.CreateFloor();
  649. c.ZeroGravity();
  650. LoggingContactListener contact_listener;
  651. c.GetSystem()->SetContactListener(&contact_listener);
  652. // Create a box and a sphere just inside the speculative contact distance
  653. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  654. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  655. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  656. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  657. // Make it move 1 m per step down
  658. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  659. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  660. box.SetLinearVelocity(cVelocity);
  661. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  662. sphere.SetLinearVelocity(cVelocity);
  663. // Simulate a step
  664. c.SimulateSingleStep();
  665. // Check that it is now on the floor and that 2 collisions have been detected
  666. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  667. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  668. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  669. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  670. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  671. contact_listener.Clear();
  672. // Velocity should have been reduced to exactly hit the floor in this step
  673. const Vec3 cExpectedVelocity(0, -cDistanceAboveFloor / c.GetDeltaTime(), 0);
  674. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  675. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  676. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cExpectedVelocity, 0.05f);
  677. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  678. // Sphere has only 1 contact point so is much more accurate
  679. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0));
  680. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cExpectedVelocity, 1.0e-4f);
  681. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  682. // Simulate a step
  683. c.SimulateSingleStep();
  684. // Check that the contacts persisted
  685. CHECK(contact_listener.GetEntryCount() >= 2); // 2 persist and possibly 2 validates depending on if the cache got reused
  686. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, box.GetID(), floor.GetID()));
  687. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  688. // Box should have come to rest
  689. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  690. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero(), 0.05f);
  691. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  692. // Sphere should have come to rest
  693. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0), 1.0e-4f);
  694. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), Vec3::sZero(), 1.0e-4f);
  695. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  696. }
  697. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceWithRestitution")
  698. {
  699. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  700. Body &floor = c.CreateFloor();
  701. c.ZeroGravity();
  702. LoggingContactListener contact_listener;
  703. c.GetSystem()->SetContactListener(&contact_listener);
  704. // Create a box and a sphere just inside the speculative contact distance
  705. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  706. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  707. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  708. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  709. // Make it move 1 m per step down
  710. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  711. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  712. box.SetLinearVelocity(cVelocity);
  713. box.SetRestitution(1.0f);
  714. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  715. sphere.SetLinearVelocity(cVelocity);
  716. sphere.SetRestitution(1.0f);
  717. // Simulate a step
  718. c.SimulateSingleStep();
  719. // Check that it has triggered contact points and has bounced from it's initial position (effectively travelling the extra distance to the floor and back for free)
  720. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  721. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  722. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  723. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  724. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  725. contact_listener.Clear();
  726. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  727. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox - cVelocity * c.GetDeltaTime(), 0.01f);
  728. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), -cVelocity, 0.1f);
  729. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 0.02f);
  730. // Sphere has only 1 contact point so is much more accurate
  731. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere - cVelocity * c.GetDeltaTime(), 1.0e-5f);
  732. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), -cVelocity, 2.0e-4f);
  733. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 2.0e-4f);
  734. // Simulate a step
  735. c.SimulateSingleStep();
  736. // Check that all contact points are removed
  737. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  738. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  739. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  740. }
  741. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoHit")
  742. {
  743. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  744. Body &floor = c.CreateFloor();
  745. floor.SetRestitution(1.0f);
  746. c.ZeroGravity();
  747. // Turn off the minimum velocity for restitution, our velocity is lower than the default
  748. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  749. settings.mMinVelocityForRestitution = 0.0f;
  750. c.GetSystem()->SetPhysicsSettings(settings);
  751. LoggingContactListener contact_listener;
  752. c.GetSystem()->SetContactListener(&contact_listener);
  753. // Create a sphere inside speculative contact distance from the ground
  754. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  755. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  756. const RVec3 cInitialPosSphere(0, 1.0f + cDistanceAboveFloor, 0.0f);
  757. // Make it move slow enough so that it will not touch the floor in 1 time step
  758. const Vec3 cVelocity(0, -0.9f * cDistanceAboveFloor / c.GetDeltaTime(), 0);
  759. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  760. sphere.SetLinearVelocity(cVelocity);
  761. sphere.SetRestitution(1.0f);
  762. sphere.GetMotionProperties()->SetLinearDamping(0.0f);
  763. // Simulate a step
  764. c.SimulateSingleStep();
  765. // Check that it has triggered contact points from the speculative contacts
  766. CHECK(contact_listener.GetEntryCount() == 2);
  767. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  768. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  769. contact_listener.Clear();
  770. // Check that sphere didn't actually change velocity (it hasn't actually interacted with the floor, the speculative contact was not an actual contact)
  771. CHECK(sphere.GetLinearVelocity() == cVelocity);
  772. // Simulate a step
  773. c.SimulateSingleStep();
  774. // Check again that it triggered contact points
  775. CHECK(contact_listener.GetEntryCount() == 2);
  776. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  777. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  778. contact_listener.Clear();
  779. // It should have bounced back up and inverted velocity due to restitution being 1
  780. CHECK_APPROX_EQUAL(-sphere.GetLinearVelocity(), cVelocity);
  781. }
  782. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  783. {
  784. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  785. Body &floor = c.CreateFloor();
  786. c.ZeroGravity();
  787. LoggingContactListener contact_listener;
  788. c.GetSystem()->SetContactListener(&contact_listener);
  789. // Create a box and a sphere just inside the speculative contact distance
  790. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  791. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  792. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  793. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  794. // Make it move 1 m per step up
  795. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  796. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  797. box.SetLinearVelocity(cVelocity);
  798. box.SetRestitution(1.0f);
  799. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  800. sphere.SetLinearVelocity(cVelocity);
  801. sphere.SetRestitution(1.0f);
  802. // Simulate a step
  803. c.SimulateSingleStep();
  804. // Check that it has triggered contact points (note that this is wrong since the object never touched the floor but that's the downside of the speculative contacts -> you'll get an incorrect collision callback)
  805. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  806. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  807. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  808. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  809. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  810. contact_listener.Clear();
  811. // Box should have moved unimpeded
  812. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  813. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  814. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  815. // Sphere should have moved unimpeded
  816. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  817. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  818. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  819. // Simulate a step
  820. c.SimulateSingleStep();
  821. // Check that all contact points are removed
  822. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  823. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  824. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  825. }
  826. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  827. {
  828. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  829. // Install activation listener
  830. LoggingBodyActivationListener activation_listener;
  831. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  832. // Create floor
  833. Body &floor = ioContext.CreateBox(RVec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  834. CHECK(!floor.IsActive());
  835. // Create inactive box
  836. Body &box = ioContext.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  837. CHECK(!box.IsActive());
  838. CHECK(activation_listener.GetEntryCount() == 0);
  839. // Box should not activate by itself
  840. ioContext.Simulate(1.0f);
  841. CHECK(box.GetPosition() == RVec3(0, 5, 0));
  842. CHECK(!box.IsActive());
  843. CHECK(activation_listener.GetEntryCount() == 0);
  844. // Activate the body and validate it is active now
  845. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  846. CHECK(box.IsActive());
  847. CHECK(box.GetLinearVelocity().IsNearZero());
  848. CHECK(activation_listener.GetEntryCount() == 1);
  849. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  850. activation_listener.Clear();
  851. // Do a single step and check that the body is still active and has gained some velocity
  852. ioContext.SimulateSingleStep();
  853. CHECK(box.IsActive());
  854. CHECK(activation_listener.GetEntryCount() == 0);
  855. CHECK(!box.GetLinearVelocity().IsNearZero());
  856. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  857. ioContext.Simulate(5.0f);
  858. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  859. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  860. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  861. CHECK(!box.IsActive());
  862. CHECK(activation_listener.GetEntryCount() == 1);
  863. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  864. }
  865. TEST_CASE("TestPhysicsActivationDeactivation")
  866. {
  867. PhysicsTestContext c1(1.0f / 60.0f, 1, 1);
  868. TestPhysicsActivationDeactivation(c1);
  869. PhysicsTestContext c2(2.0f / 60.0f, 1, 2);
  870. TestPhysicsActivationDeactivation(c2);
  871. PhysicsTestContext c3(2.0f / 60.0f, 2, 1);
  872. TestPhysicsActivationDeactivation(c3);
  873. PhysicsTestContext c4(4.0f / 60.0f, 4, 1);
  874. TestPhysicsActivationDeactivation(c4);
  875. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  876. TestPhysicsActivationDeactivation(c5);
  877. }
  878. // A test that checks that a row of penetrating boxes will all activate and handle collision in 1 frame so that active bodies cannot tunnel through inactive bodies
  879. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  880. {
  881. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  882. const int cNumBodies = 10;
  883. const float cBoxExtent = 0.5f;
  884. PhysicsSystem *system = ioContext.GetSystem();
  885. BodyInterface &bi = ioContext.GetBodyInterface();
  886. LoggingBodyActivationListener activation_listener;
  887. system->SetBodyActivationListener(&activation_listener);
  888. LoggingContactListener contact_listener;
  889. system->SetContactListener(&contact_listener);
  890. // Create a row of penetrating boxes. Since some of the algorithms rely on body index, we create them normally and reversed to test both cases
  891. BodyIDVector body_ids;
  892. if (inReverseCreate)
  893. for (int i = cNumBodies - 1; i >= 0; --i)
  894. body_ids.insert(body_ids.begin(), ioContext.CreateBox(RVec3(i * (2.0f * cBoxExtent - cPenetrationSlop), 0, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(cBoxExtent), EActivation::DontActivate).GetID());
  895. else
  896. for (int i = 0; i < cNumBodies; ++i)
  897. body_ids.push_back(ioContext.CreateBox(RVec3(i * (2.0f * cBoxExtent - cPenetrationSlop), 0, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate).GetID());
  898. // Test that nothing is active yet
  899. CHECK(activation_listener.GetEntryCount() == 0);
  900. CHECK(contact_listener.GetEntryCount() == 0);
  901. for (BodyID id : body_ids)
  902. CHECK(!bi.IsActive(id));
  903. // Activate the left most box and give it a velocity that is high enough to make it tunnel through the second box in a single step
  904. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  905. // Test that only the left most box is active
  906. CHECK(activation_listener.GetEntryCount() == 1);
  907. CHECK(contact_listener.GetEntryCount() == 0);
  908. CHECK(bi.IsActive(body_ids.front()));
  909. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  910. for (int i = 1; i < cNumBodies; ++i)
  911. CHECK(!bi.IsActive(body_ids[i]));
  912. activation_listener.Clear();
  913. // Step the world
  914. ioContext.SimulateSingleStep();
  915. // Other bodies should now be awake and each body should only collide with its neighbour
  916. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  917. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  918. for (int i = 0; i < cNumBodies; ++i)
  919. {
  920. BodyID id = body_ids[i];
  921. // Check body is active
  922. CHECK(bi.IsActive(id));
  923. // Check that body moved to the right
  924. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  925. }
  926. for (int i = 1; i < cNumBodies; ++i)
  927. {
  928. BodyID id1 = body_ids[i - 1];
  929. BodyID id2 = body_ids[i];
  930. // Check that we received activation events for each body
  931. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  932. // Check that we received a validate and an add for each body pair
  933. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  934. CHECK(validate >= 0);
  935. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  936. CHECK(add >= 0);
  937. CHECK(add > validate);
  938. // Check that bodies did not tunnel through each other
  939. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  940. }
  941. }
  942. TEST_CASE("TestPhysicsActivateDuringStep")
  943. {
  944. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  945. TestPhysicsActivateDuringStep(c, false);
  946. PhysicsTestContext c2(1.0f / 60.0f, 1, 1);
  947. TestPhysicsActivateDuringStep(c2, true);
  948. }
  949. TEST_CASE("TestPhysicsBroadPhaseLayers")
  950. {
  951. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  952. BodyInterface &bi = c.GetBodyInterface();
  953. // Reduce slop
  954. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  955. settings.mPenetrationSlop = 0.0f;
  956. c.GetSystem()->SetPhysicsSettings(settings);
  957. // Create static floor
  958. c.CreateFloor();
  959. // Create MOVING boxes
  960. Body &moving1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  961. Body &moving2 = c.CreateBox(RVec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  962. // Create HQ_DEBRIS boxes
  963. Body &hq_debris1 = c.CreateBox(RVec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  964. Body &hq_debris2 = c.CreateBox(RVec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  965. // Create LQ_DEBRIS boxes
  966. Body &lq_debris1 = c.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  967. Body &lq_debris2 = c.CreateBox(RVec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  968. // Check layers
  969. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  970. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  971. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  972. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  973. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  974. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  975. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  976. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  977. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  978. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  979. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  980. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  981. // Simulate the boxes falling
  982. c.Simulate(5.0f);
  983. // Everything should sleep
  984. CHECK_FALSE(moving1.IsActive());
  985. CHECK_FALSE(moving2.IsActive());
  986. CHECK_FALSE(hq_debris1.IsActive());
  987. CHECK_FALSE(hq_debris2.IsActive());
  988. CHECK_FALSE(lq_debris1.IsActive());
  989. CHECK_FALSE(lq_debris2.IsActive());
  990. // MOVING boxes should have stacked
  991. float slop = 0.02f;
  992. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  993. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  994. // HQ_DEBRIS boxes should have stacked on MOVING boxes but don't collide with each other
  995. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 2.5f, 0), slop);
  996. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 2.5f, 0), slop);
  997. // LQ_DEBRIS should have fallen through all but the floor
  998. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  999. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1000. // Now change HQ_DEBRIS to LQ_DEBRIS
  1001. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  1002. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  1003. bi.ActivateBody(hq_debris1.GetID());
  1004. bi.ActivateBody(hq_debris2.GetID());
  1005. // Check layers
  1006. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  1007. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  1008. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1009. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1010. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1011. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1012. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1013. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1014. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1015. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1016. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1017. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1018. // Simulate again
  1019. c.Simulate(5.0f);
  1020. // Everything should sleep
  1021. CHECK_FALSE(moving1.IsActive());
  1022. CHECK_FALSE(moving2.IsActive());
  1023. CHECK_FALSE(hq_debris1.IsActive());
  1024. CHECK_FALSE(hq_debris2.IsActive());
  1025. CHECK_FALSE(lq_debris1.IsActive());
  1026. CHECK_FALSE(lq_debris2.IsActive());
  1027. // MOVING boxes should have stacked
  1028. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1029. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  1030. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1031. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1032. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1033. // LQ_DEBRIS should have fallen through all but the floor
  1034. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1035. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1036. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  1037. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  1038. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  1039. bi.ActivateBody(moving1.GetID());
  1040. bi.ActivateBody(moving2.GetID());
  1041. // Check layers
  1042. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1043. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1044. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1045. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1046. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1047. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1048. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  1049. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1050. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1051. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1052. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1053. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1054. // Simulate again
  1055. c.Simulate(5.0f);
  1056. // Everything should sleep
  1057. CHECK_FALSE(moving1.IsActive());
  1058. CHECK_FALSE(moving2.IsActive());
  1059. CHECK_FALSE(hq_debris1.IsActive());
  1060. CHECK_FALSE(hq_debris2.IsActive());
  1061. CHECK_FALSE(lq_debris1.IsActive());
  1062. CHECK_FALSE(lq_debris2.IsActive());
  1063. // MOVING boxes now also fall through
  1064. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1065. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1066. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1067. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1068. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1069. // LQ_DEBRIS should have fallen through all but the floor
  1070. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1071. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1072. }
  1073. TEST_CASE("TestMultiplePhysicsSystems")
  1074. {
  1075. PhysicsTestContext c1(1.0f / 60.0f, 1, 1);
  1076. c1.ZeroGravity();
  1077. PhysicsTestContext c2(1.0f / 60.0f, 1, 1);
  1078. c2.ZeroGravity();
  1079. const RVec3 cBox1Position(1.0f, 2.0f, 3.0f);
  1080. Body &box1 = c1.CreateBox(cBox1Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1081. const RVec3 cBox2Position(4.0f, 5.0f, 6.0f);
  1082. Body& box2 = c2.CreateBox(cBox2Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1083. const Vec3 cBox1Velocity(1.0f, 0, 0);
  1084. const Vec3 cBox2Velocity(2.0f, 0, 0);
  1085. {
  1086. // This tests if we can lock bodies from multiple physics systems (normally locking 2 bodies at the same time without using BodyLockMultiWrite would trigger an assert)
  1087. BodyLockWrite lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1088. BodyLockWrite lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1089. CHECK(lock1.GetBody().GetPosition() == cBox1Position);
  1090. CHECK(lock2.GetBody().GetPosition() == cBox2Position);
  1091. lock1.GetBody().SetLinearVelocity(cBox1Velocity);
  1092. lock2.GetBody().SetLinearVelocity(cBox2Velocity);
  1093. }
  1094. const float cTime = 1.0f;
  1095. c1.Simulate(cTime);
  1096. c2.Simulate(cTime);
  1097. {
  1098. BodyLockRead lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1099. BodyLockRead lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1100. // Check that the bodies in the different systems updated correctly
  1101. CHECK_APPROX_EQUAL(lock1.GetBody().GetPosition(), cBox1Position + cBox1Velocity * cTime, 1.0e-5f);
  1102. CHECK_APPROX_EQUAL(lock2.GetBody().GetPosition(), cBox2Position + cBox2Velocity * cTime, 1.0e-5f);
  1103. }
  1104. }
  1105. TEST_CASE("TestOutOfBodies")
  1106. {
  1107. // Create a context with space for a single body
  1108. PhysicsTestContext c(1.0f / 60.0f, 1, 1, 0, 1);
  1109. BodyInterface& bi = c.GetBodyInterface();
  1110. // First body
  1111. Body *b1 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1112. CHECK(b1 != nullptr);
  1113. // Second body should fail
  1114. Body *b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1115. CHECK(b2 == nullptr);
  1116. // Free first body
  1117. bi.DestroyBody(b1->GetID());
  1118. // Second body creation should succeed
  1119. b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1120. CHECK(b2 != nullptr);
  1121. // Clean up
  1122. bi.DestroyBody(b2->GetID());
  1123. }
  1124. TEST_CASE("TestOutOfContactConstraints")
  1125. {
  1126. // Create a context with space for 8 constraints
  1127. PhysicsTestContext c(1.0f / 60.0f, 1, 1, 0, 1024, 4096, 8);
  1128. c.CreateFloor();
  1129. // The first 8 boxes should be fine
  1130. for (int i = 0; i < 8; ++i)
  1131. c.CreateBox(RVec3(3.0_r * i, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1132. // Step
  1133. EPhysicsUpdateError errors = c.SimulateSingleStep();
  1134. CHECK(errors == EPhysicsUpdateError::None);
  1135. // Adding one more box should introduce an error
  1136. c.CreateBox(RVec3(24.0_r, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1137. // Step
  1138. {
  1139. JPH_IF_ENABLE_ASSERTS(ExpectAssert expect_assert(1);)
  1140. errors = c.SimulateSingleStep();
  1141. }
  1142. CHECK((errors & EPhysicsUpdateError::ContactConstraintsFull) != EPhysicsUpdateError::None);
  1143. }
  1144. }