PhysicsTests.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  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;
  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;
  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;
  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;
  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;
  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;
  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;
  323. TestPhysicsFreeFall(c);
  324. }
  325. TEST_CASE("TestPhysicsFreeFallStep")
  326. {
  327. PhysicsTestContext c1(2.0f / 60.0f, 2);
  328. TestPhysicsFreeFall(c1);
  329. PhysicsTestContext c2(4.0f / 60.0f, 4);
  330. TestPhysicsFreeFall(c2);
  331. }
  332. // Test acceleration of a box with force applied
  333. static void TestPhysicsApplyForce(PhysicsTestContext &ioContext)
  334. {
  335. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  336. const Vec3 cAcceleration(2.0f, 0.0f, 0.0f);
  337. const float cSimulationTime = 2.0f;
  338. // Create box
  339. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  340. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  341. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  342. // Validate mass
  343. float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  344. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  345. // Simulate while applying force
  346. ioContext.Simulate(cSimulationTime, [&]() { body.AddForce(mass * cAcceleration); });
  347. // Test resulting velocity (due to gravity and applied force)
  348. CHECK_APPROX_EQUAL(cSimulationTime * (cGravity + cAcceleration), body.GetLinearVelocity(), 1.0e-4f);
  349. // Test resulting position
  350. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity + cAcceleration, cSimulationTime);
  351. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  352. }
  353. TEST_CASE("TestPhysicsApplyForce")
  354. {
  355. PhysicsTestContext c;
  356. TestPhysicsApplyForce(c);
  357. }
  358. TEST_CASE("TestPhysicsApplyForceStep")
  359. {
  360. PhysicsTestContext c1(2.0f / 60.0f, 2);
  361. TestPhysicsApplyForce(c1);
  362. PhysicsTestContext c2(4.0f / 60.0f, 4);
  363. TestPhysicsApplyForce(c2);
  364. }
  365. // Test angular accelartion for a box by applying torque every frame
  366. static void TestPhysicsApplyTorque(PhysicsTestContext &ioContext)
  367. {
  368. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  369. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  370. const float cSimulationTime = 2.0f;
  371. // Create box
  372. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  373. CHECK_APPROX_EQUAL(Quat::sIdentity(), body.GetRotation());
  374. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  375. // Validate mass and inertia
  376. constexpr float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  377. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  378. constexpr float inertia = mass * 8.0f / 12.0f; // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  379. CHECK_APPROX_EQUAL(Mat44::sScale(1.0f / inertia), body.GetMotionProperties()->GetLocalSpaceInverseInertia());
  380. // Simulate while applying torque
  381. ioContext.Simulate(cSimulationTime, [&]() { body.AddTorque(inertia * cAngularAcceleration); });
  382. // Get resulting angular velocity
  383. CHECK_APPROX_EQUAL(cSimulationTime * cAngularAcceleration, body.GetAngularVelocity(), 1.0e-4f);
  384. // Test resulting rotation
  385. Quat expected_rot = ioContext.PredictOrientation(Quat::sIdentity(), Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  386. CHECK_APPROX_EQUAL(expected_rot, body.GetRotation(), 1.0e-4f);
  387. }
  388. TEST_CASE("TestPhysicsApplyTorque")
  389. {
  390. PhysicsTestContext c;
  391. TestPhysicsApplyTorque(c);
  392. }
  393. TEST_CASE("TestPhysicsApplyTorqueStep")
  394. {
  395. PhysicsTestContext c1(2.0f / 60.0f, 2);
  396. TestPhysicsApplyTorque(c1);
  397. PhysicsTestContext c2(4.0f / 60.0f, 4);
  398. TestPhysicsApplyTorque(c2);
  399. }
  400. // Let a sphere bounce on the floor with restition = 1
  401. static void TestPhysicsCollisionElastic(PhysicsTestContext &ioContext)
  402. {
  403. const float cSimulationTime = 1.0f;
  404. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  405. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  406. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  407. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  408. // Create sphere
  409. ioContext.CreateFloor();
  410. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  411. body.SetRestitution(1.0f);
  412. // Simulate until at floor
  413. ioContext.Simulate(cSimulationTime);
  414. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  415. // Assert collision not yet processed
  416. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  417. // Simulate one more step to process the collision
  418. ioContext.Simulate(ioContext.GetDeltaTime());
  419. // Assert that collision is processed and velocity is reversed (which is required for a fully elastic collision).
  420. // Note that the physics engine will first apply gravity for the time step and then do collision detection,
  421. // hence the reflected velocity is actually 1 step times gravity bigger than it would be in reality
  422. // For the remainder of cDeltaTime normal gravity will be applied
  423. float sub_step_delta_time = ioContext.GetStepDeltaTime();
  424. float remaining_step_time = ioContext.GetDeltaTime() - ioContext.GetStepDeltaTime();
  425. Vec3 reflected_velocity_after_sub_step = -(cSimulationTime + sub_step_delta_time) * cGravity;
  426. Vec3 reflected_velocity_after_full_step = reflected_velocity_after_sub_step + remaining_step_time * cGravity;
  427. CHECK_APPROX_EQUAL(reflected_velocity_after_full_step, body.GetLinearVelocity(), 1.0e-4f);
  428. // Body should have bounced back
  429. RVec3 pos_after_bounce_sub_step = cFloorHitPos + reflected_velocity_after_sub_step * sub_step_delta_time;
  430. RVec3 pos_after_bounce_full_step = ioContext.PredictPosition(pos_after_bounce_sub_step, reflected_velocity_after_sub_step, cGravity, remaining_step_time);
  431. CHECK_APPROX_EQUAL(pos_after_bounce_full_step, body.GetPosition());
  432. // Simulate same time, with a fully elastic body we should reach the initial position again
  433. // In our physics engine because of the velocity being too big we actually end up a bit higher than our initial position
  434. RVec3 expected_pos = ioContext.PredictPosition(pos_after_bounce_full_step, reflected_velocity_after_full_step, cGravity, cSimulationTime);
  435. ioContext.Simulate(cSimulationTime);
  436. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition(), 1.0e-4f);
  437. CHECK(expected_pos.GetY() >= cInitialPos.GetY());
  438. }
  439. TEST_CASE("TestPhysicsCollisionElastic")
  440. {
  441. PhysicsTestContext c;
  442. TestPhysicsCollisionElastic(c);
  443. }
  444. TEST_CASE("TestPhysicsCollisionElasticStep")
  445. {
  446. PhysicsTestContext c1(2.0f / 60.0f, 2);
  447. TestPhysicsCollisionElastic(c1);
  448. PhysicsTestContext c2(4.0f / 60.0f, 4);
  449. TestPhysicsCollisionElastic(c2);
  450. }
  451. // Let a sphere bounce on the floor with restitution = 0
  452. static void TestPhysicsCollisionInelastic(PhysicsTestContext &ioContext)
  453. {
  454. const float cSimulationTime = 1.0f;
  455. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  456. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  457. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  458. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  459. // Create sphere
  460. ioContext.CreateFloor();
  461. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  462. body.SetRestitution(0.0f);
  463. // Simulate until at floor
  464. ioContext.Simulate(cSimulationTime);
  465. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  466. // Assert collision not yet processed
  467. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  468. // Simulate one more step to process the collision
  469. ioContext.Simulate(ioContext.GetDeltaTime());
  470. // Assert that all velocity was lost in the collision
  471. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  472. // Assert that we're on the floor
  473. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  474. // Simulate some more to validate that we remain on the floor
  475. ioContext.Simulate(cSimulationTime);
  476. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  477. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  478. }
  479. TEST_CASE("TestPhysicsCollisionInelastic")
  480. {
  481. PhysicsTestContext c;
  482. TestPhysicsCollisionInelastic(c);
  483. }
  484. TEST_CASE("TestPhysicsCollisionInelasticStep")
  485. {
  486. PhysicsTestContext c1(2.0f / 60.0f, 2);
  487. TestPhysicsCollisionInelastic(c1);
  488. PhysicsTestContext c2(4.0f / 60.0f, 4);
  489. TestPhysicsCollisionInelastic(c2);
  490. }
  491. // Let box intersect with floor by cPenetrationSlop. It should not move, this is the maximum penetration allowed.
  492. static void TestPhysicsPenetrationSlop1(PhysicsTestContext &ioContext)
  493. {
  494. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  495. const float cSimulationTime = 1.0f;
  496. const RVec3 cInitialPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  497. // Create box, penetrating with floor
  498. ioContext.CreateFloor();
  499. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  500. // Simulate
  501. ioContext.Simulate(cSimulationTime);
  502. // Test slop not resolved
  503. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  504. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  505. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  506. }
  507. TEST_CASE("TestPhysicsPenetrationSlop1")
  508. {
  509. PhysicsTestContext c;
  510. TestPhysicsPenetrationSlop1(c);
  511. }
  512. TEST_CASE("TestPhysicsPenetrationSlop1Step")
  513. {
  514. PhysicsTestContext c(2.0f / 60.0f, 2);
  515. TestPhysicsPenetrationSlop1(c);
  516. PhysicsTestContext c2(4.0f / 60.0f, 4);
  517. TestPhysicsPenetrationSlop1(c2);
  518. }
  519. // Let box intersect with floor with more than cPenetrationSlop. It should be resolved by SolvePositionConstraint until interpenetration is cPenetrationSlop.
  520. static void TestPhysicsPenetrationSlop2(PhysicsTestContext &ioContext)
  521. {
  522. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  523. const float cSimulationTime = 1.0f;
  524. const RVec3 cInitialPos(0.0f, 1.0f - 2.0f * cPenetrationSlop, 0.0f);
  525. const RVec3 cFinalPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  526. // Create box, penetrating with floor
  527. ioContext.CreateFloor();
  528. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  529. // Simulate
  530. ioContext.Simulate(cSimulationTime);
  531. // Test resolved until slop
  532. CHECK_APPROX_EQUAL(cFinalPos, body.GetPosition(), 1.0e-5f);
  533. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  534. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  535. }
  536. TEST_CASE("TestPhysicsPenetrationSlop2")
  537. {
  538. PhysicsTestContext c;
  539. TestPhysicsPenetrationSlop2(c);
  540. }
  541. TEST_CASE("TestPhysicsPenetrationSlop2Step")
  542. {
  543. PhysicsTestContext c(2.0f / 60.0f, 2);
  544. TestPhysicsPenetrationSlop2(c);
  545. PhysicsTestContext c2(4.0f / 60.0f, 4);
  546. TestPhysicsPenetrationSlop2(c2);
  547. }
  548. // Let box intersect with floor with less than cPenetrationSlop. Body should not move because SolveVelocityConstraint should reset velocity.
  549. static void TestPhysicsPenetrationSlop3(PhysicsTestContext &ioContext)
  550. {
  551. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  552. const float cSimulationTime = 1.0f;
  553. const RVec3 cInitialPos(0.0f, 1.0f - 0.1f * cPenetrationSlop, 0.0f);
  554. // Create box, penetrating with floor
  555. ioContext.CreateFloor();
  556. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  557. // Simulate
  558. ioContext.Simulate(cSimulationTime);
  559. // Test body remained static
  560. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  561. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  562. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  563. }
  564. TEST_CASE("TestPhysicsPenetrationSlop3")
  565. {
  566. PhysicsTestContext c;
  567. TestPhysicsPenetrationSlop3(c);
  568. }
  569. TEST_CASE("TestPhysicsPenetrationSlop3Step")
  570. {
  571. PhysicsTestContext c(2.0f / 60.0f, 2);
  572. TestPhysicsPenetrationSlop3(c);
  573. PhysicsTestContext c2(4.0f / 60.0f, 4);
  574. TestPhysicsPenetrationSlop3(c2);
  575. }
  576. TEST_CASE("TestPhysicsOutsideOfSpeculativeContactDistance")
  577. {
  578. PhysicsTestContext c;
  579. Body &floor = c.CreateFloor();
  580. c.ZeroGravity();
  581. LoggingContactListener contact_listener;
  582. c.GetSystem()->SetContactListener(&contact_listener);
  583. // Create a box and a sphere just outside the speculative contact distance
  584. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  585. const float cDistanceAboveFloor = 1.1f * cSpeculativeContactDistance;
  586. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  587. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  588. // Make it move 1 m per step down
  589. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  590. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  591. box.SetLinearVelocity(cVelocity);
  592. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  593. sphere.SetLinearVelocity(cVelocity);
  594. // Simulate a step
  595. c.SimulateSingleStep();
  596. // 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)
  597. CHECK(contact_listener.GetEntryCount() == 0);
  598. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  599. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  600. // Simulate a step
  601. c.SimulateSingleStep();
  602. // Check that the contacts are detected now
  603. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  604. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  605. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  606. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  607. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  608. }
  609. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoRestitution")
  610. {
  611. PhysicsTestContext c;
  612. Body &floor = c.CreateFloor();
  613. c.ZeroGravity();
  614. LoggingContactListener contact_listener;
  615. c.GetSystem()->SetContactListener(&contact_listener);
  616. // Create a box and a sphere just inside the speculative contact distance
  617. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  618. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  619. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  620. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  621. // Make it move 1 m per step down
  622. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  623. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  624. box.SetLinearVelocity(cVelocity);
  625. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  626. sphere.SetLinearVelocity(cVelocity);
  627. // Simulate a step
  628. c.SimulateSingleStep();
  629. // Check that it is now on the floor and that 2 collisions have been detected
  630. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  631. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  632. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  633. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  634. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  635. contact_listener.Clear();
  636. // Velocity should have been reduced to exactly hit the floor in this step
  637. const Vec3 cExpectedVelocity(0, -cDistanceAboveFloor / c.GetDeltaTime(), 0);
  638. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  639. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  640. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cExpectedVelocity, 0.05f);
  641. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  642. // Sphere has only 1 contact point so is much more accurate
  643. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0));
  644. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cExpectedVelocity, 1.0e-4f);
  645. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  646. // Simulate a step
  647. c.SimulateSingleStep();
  648. // Check that the contacts persisted
  649. CHECK(contact_listener.GetEntryCount() >= 2); // 2 persist and possibly 2 validates depending on if the cache got reused
  650. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, box.GetID(), floor.GetID()));
  651. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  652. // Box should have come to rest
  653. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  654. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero(), 0.05f);
  655. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  656. // Sphere should have come to rest
  657. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0), 1.0e-4f);
  658. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), Vec3::sZero(), 1.0e-4f);
  659. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  660. }
  661. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceWithRestitution")
  662. {
  663. PhysicsTestContext c;
  664. Body &floor = c.CreateFloor();
  665. c.ZeroGravity();
  666. LoggingContactListener contact_listener;
  667. c.GetSystem()->SetContactListener(&contact_listener);
  668. // Create a box and a sphere just inside the speculative contact distance
  669. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  670. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  671. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  672. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  673. // Make it move 1 m per step down
  674. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  675. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  676. box.SetLinearVelocity(cVelocity);
  677. box.SetRestitution(1.0f);
  678. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  679. sphere.SetLinearVelocity(cVelocity);
  680. sphere.SetRestitution(1.0f);
  681. // Simulate a step
  682. c.SimulateSingleStep();
  683. // 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)
  684. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  685. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  686. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  687. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  688. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  689. contact_listener.Clear();
  690. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  691. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox - cVelocity * c.GetDeltaTime(), 0.01f);
  692. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), -cVelocity, 0.1f);
  693. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 0.02f);
  694. // Sphere has only 1 contact point so is much more accurate
  695. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere - cVelocity * c.GetDeltaTime(), 1.0e-5f);
  696. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), -cVelocity, 2.0e-4f);
  697. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 2.0e-4f);
  698. // Simulate a step
  699. c.SimulateSingleStep();
  700. // Check that all contact points are removed
  701. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  702. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  703. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  704. }
  705. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoHit")
  706. {
  707. PhysicsTestContext c;
  708. Body &floor = c.CreateFloor();
  709. floor.SetRestitution(1.0f);
  710. c.ZeroGravity();
  711. // Turn off the minimum velocity for restitution, our velocity is lower than the default
  712. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  713. settings.mMinVelocityForRestitution = 0.0f;
  714. c.GetSystem()->SetPhysicsSettings(settings);
  715. LoggingContactListener contact_listener;
  716. c.GetSystem()->SetContactListener(&contact_listener);
  717. // Create a sphere inside speculative contact distance from the ground
  718. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  719. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  720. const RVec3 cInitialPosSphere(0, 1.0f + cDistanceAboveFloor, 0.0f);
  721. // Make it move slow enough so that it will not touch the floor in 1 time step
  722. const Vec3 cVelocity(0, -0.9f * cDistanceAboveFloor / c.GetDeltaTime(), 0);
  723. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  724. sphere.SetLinearVelocity(cVelocity);
  725. sphere.SetRestitution(1.0f);
  726. sphere.GetMotionProperties()->SetLinearDamping(0.0f);
  727. // Simulate a step
  728. c.SimulateSingleStep();
  729. // Check that it has triggered contact points from the speculative contacts
  730. CHECK(contact_listener.GetEntryCount() == 2);
  731. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  732. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  733. contact_listener.Clear();
  734. // Check that sphere didn't actually change velocity (it hasn't actually interacted with the floor, the speculative contact was not an actual contact)
  735. CHECK(sphere.GetLinearVelocity() == cVelocity);
  736. // Simulate a step
  737. c.SimulateSingleStep();
  738. // Check again that it triggered contact points
  739. CHECK(contact_listener.GetEntryCount() == 2);
  740. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  741. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  742. contact_listener.Clear();
  743. // It should have bounced back up and inverted velocity due to restitution being 1
  744. CHECK_APPROX_EQUAL(-sphere.GetLinearVelocity(), cVelocity);
  745. }
  746. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  747. {
  748. PhysicsTestContext c;
  749. Body &floor = c.CreateFloor();
  750. c.ZeroGravity();
  751. LoggingContactListener contact_listener;
  752. c.GetSystem()->SetContactListener(&contact_listener);
  753. // Create a box and a sphere just inside the speculative contact distance
  754. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  755. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  756. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  757. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  758. // Make it move 1 m per step up
  759. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  760. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  761. box.SetLinearVelocity(cVelocity);
  762. box.SetRestitution(1.0f);
  763. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  764. sphere.SetLinearVelocity(cVelocity);
  765. sphere.SetRestitution(1.0f);
  766. // Simulate a step
  767. c.SimulateSingleStep();
  768. // 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)
  769. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  770. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  771. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  772. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  773. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  774. contact_listener.Clear();
  775. // Box should have moved unimpeded
  776. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  777. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  778. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  779. // Sphere should have moved unimpeded
  780. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  781. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  782. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  783. // Simulate a step
  784. c.SimulateSingleStep();
  785. // Check that all contact points are removed
  786. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  787. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  788. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  789. }
  790. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  791. {
  792. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  793. // Install activation listener
  794. LoggingBodyActivationListener activation_listener;
  795. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  796. // Create floor
  797. Body &floor = ioContext.CreateBox(RVec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  798. CHECK(!floor.IsActive());
  799. // Create inactive box
  800. Body &box = ioContext.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  801. CHECK(!box.IsActive());
  802. CHECK(activation_listener.GetEntryCount() == 0);
  803. // Box should not activate by itself
  804. ioContext.Simulate(1.0f);
  805. CHECK(box.GetPosition() == RVec3(0, 5, 0));
  806. CHECK(!box.IsActive());
  807. CHECK(activation_listener.GetEntryCount() == 0);
  808. // Activate the body and validate it is active now
  809. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  810. CHECK(box.IsActive());
  811. CHECK(box.GetLinearVelocity().IsNearZero());
  812. CHECK(activation_listener.GetEntryCount() == 1);
  813. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  814. activation_listener.Clear();
  815. // Do a single step and check that the body is still active and has gained some velocity
  816. ioContext.SimulateSingleStep();
  817. CHECK(box.IsActive());
  818. CHECK(activation_listener.GetEntryCount() == 0);
  819. CHECK(!box.GetLinearVelocity().IsNearZero());
  820. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  821. ioContext.Simulate(5.0f);
  822. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  823. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  824. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  825. CHECK(!box.IsActive());
  826. CHECK(activation_listener.GetEntryCount() == 1);
  827. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  828. }
  829. TEST_CASE("TestPhysicsActivationDeactivation")
  830. {
  831. PhysicsTestContext c1(1.0f / 60.0f, 1);
  832. TestPhysicsActivationDeactivation(c1);
  833. PhysicsTestContext c2(2.0f / 60.0f, 2);
  834. TestPhysicsActivationDeactivation(c2);
  835. PhysicsTestContext c3(4.0f / 60.0f, 4);
  836. TestPhysicsActivationDeactivation(c3);
  837. }
  838. // 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
  839. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  840. {
  841. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  842. const int cNumBodies = 10;
  843. const float cBoxExtent = 0.5f;
  844. PhysicsSystem *system = ioContext.GetSystem();
  845. BodyInterface &bi = ioContext.GetBodyInterface();
  846. LoggingBodyActivationListener activation_listener;
  847. system->SetBodyActivationListener(&activation_listener);
  848. LoggingContactListener contact_listener;
  849. system->SetContactListener(&contact_listener);
  850. // 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
  851. BodyIDVector body_ids;
  852. if (inReverseCreate)
  853. for (int i = cNumBodies - 1; i >= 0; --i)
  854. 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());
  855. else
  856. for (int i = 0; i < cNumBodies; ++i)
  857. 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());
  858. // Test that nothing is active yet
  859. CHECK(activation_listener.GetEntryCount() == 0);
  860. CHECK(contact_listener.GetEntryCount() == 0);
  861. for (BodyID id : body_ids)
  862. CHECK(!bi.IsActive(id));
  863. // 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
  864. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  865. // Test that only the left most box is active
  866. CHECK(activation_listener.GetEntryCount() == 1);
  867. CHECK(contact_listener.GetEntryCount() == 0);
  868. CHECK(bi.IsActive(body_ids.front()));
  869. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  870. for (int i = 1; i < cNumBodies; ++i)
  871. CHECK(!bi.IsActive(body_ids[i]));
  872. activation_listener.Clear();
  873. // Step the world
  874. ioContext.SimulateSingleStep();
  875. // Other bodies should now be awake and each body should only collide with its neighbour
  876. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  877. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  878. for (int i = 0; i < cNumBodies; ++i)
  879. {
  880. BodyID id = body_ids[i];
  881. // Check body is active
  882. CHECK(bi.IsActive(id));
  883. // Check that body moved to the right
  884. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  885. }
  886. for (int i = 1; i < cNumBodies; ++i)
  887. {
  888. BodyID id1 = body_ids[i - 1];
  889. BodyID id2 = body_ids[i];
  890. // Check that we received activation events for each body
  891. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  892. // Check that we received a validate and an add for each body pair
  893. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  894. CHECK(validate >= 0);
  895. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  896. CHECK(add >= 0);
  897. CHECK(add > validate);
  898. // Check that bodies did not tunnel through each other
  899. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  900. }
  901. }
  902. TEST_CASE("TestPhysicsActivateDuringStep")
  903. {
  904. PhysicsTestContext c;
  905. TestPhysicsActivateDuringStep(c, false);
  906. PhysicsTestContext c2;
  907. TestPhysicsActivateDuringStep(c2, true);
  908. }
  909. TEST_CASE("TestPhysicsBroadPhaseLayers")
  910. {
  911. PhysicsTestContext c;
  912. BodyInterface &bi = c.GetBodyInterface();
  913. // Reduce slop
  914. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  915. settings.mPenetrationSlop = 0.0f;
  916. c.GetSystem()->SetPhysicsSettings(settings);
  917. // Create static floor
  918. c.CreateFloor();
  919. // Create MOVING boxes
  920. Body &moving1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  921. Body &moving2 = c.CreateBox(RVec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  922. // Create HQ_DEBRIS boxes
  923. Body &hq_debris1 = c.CreateBox(RVec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  924. Body &hq_debris2 = c.CreateBox(RVec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  925. // Create LQ_DEBRIS boxes
  926. Body &lq_debris1 = c.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  927. Body &lq_debris2 = c.CreateBox(RVec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  928. // Check layers
  929. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  930. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  931. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  932. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  933. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  934. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  935. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  936. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  937. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  938. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  939. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  940. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  941. // Simulate the boxes falling
  942. c.Simulate(5.0f);
  943. // Everything should sleep
  944. CHECK_FALSE(moving1.IsActive());
  945. CHECK_FALSE(moving2.IsActive());
  946. CHECK_FALSE(hq_debris1.IsActive());
  947. CHECK_FALSE(hq_debris2.IsActive());
  948. CHECK_FALSE(lq_debris1.IsActive());
  949. CHECK_FALSE(lq_debris2.IsActive());
  950. // MOVING boxes should have stacked
  951. float slop = 0.02f;
  952. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  953. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  954. // HQ_DEBRIS boxes should have stacked on MOVING boxes but don't collide with each other
  955. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 2.5f, 0), slop);
  956. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 2.5f, 0), slop);
  957. // LQ_DEBRIS should have fallen through all but the floor
  958. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  959. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  960. // Now change HQ_DEBRIS to LQ_DEBRIS
  961. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  962. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  963. bi.ActivateBody(hq_debris1.GetID());
  964. bi.ActivateBody(hq_debris2.GetID());
  965. // Check layers
  966. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  967. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  968. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  969. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  970. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  971. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  972. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  973. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  974. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  975. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  976. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  977. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  978. // Simulate again
  979. c.Simulate(5.0f);
  980. // Everything should sleep
  981. CHECK_FALSE(moving1.IsActive());
  982. CHECK_FALSE(moving2.IsActive());
  983. CHECK_FALSE(hq_debris1.IsActive());
  984. CHECK_FALSE(hq_debris2.IsActive());
  985. CHECK_FALSE(lq_debris1.IsActive());
  986. CHECK_FALSE(lq_debris2.IsActive());
  987. // MOVING boxes should have stacked
  988. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  989. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  990. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  991. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  992. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  993. // LQ_DEBRIS should have fallen through all but the floor
  994. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  995. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  996. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  997. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  998. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  999. bi.ActivateBody(moving1.GetID());
  1000. bi.ActivateBody(moving2.GetID());
  1001. // Check layers
  1002. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1003. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1004. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1005. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1006. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1007. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1008. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  1009. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1010. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1011. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1012. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1013. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1014. // Simulate again
  1015. c.Simulate(5.0f);
  1016. // Everything should sleep
  1017. CHECK_FALSE(moving1.IsActive());
  1018. CHECK_FALSE(moving2.IsActive());
  1019. CHECK_FALSE(hq_debris1.IsActive());
  1020. CHECK_FALSE(hq_debris2.IsActive());
  1021. CHECK_FALSE(lq_debris1.IsActive());
  1022. CHECK_FALSE(lq_debris2.IsActive());
  1023. // MOVING boxes now also fall through
  1024. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1025. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1026. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1027. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1028. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1029. // LQ_DEBRIS should have fallen through all but the floor
  1030. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1031. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1032. }
  1033. TEST_CASE("TestMultiplePhysicsSystems")
  1034. {
  1035. PhysicsTestContext c1;
  1036. c1.ZeroGravity();
  1037. PhysicsTestContext c2;
  1038. c2.ZeroGravity();
  1039. const RVec3 cBox1Position(1.0f, 2.0f, 3.0f);
  1040. Body &box1 = c1.CreateBox(cBox1Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1041. const RVec3 cBox2Position(4.0f, 5.0f, 6.0f);
  1042. Body& box2 = c2.CreateBox(cBox2Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1043. const Vec3 cBox1Velocity(1.0f, 0, 0);
  1044. const Vec3 cBox2Velocity(2.0f, 0, 0);
  1045. {
  1046. // 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)
  1047. BodyLockWrite lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1048. BodyLockWrite lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1049. CHECK(lock1.GetBody().GetPosition() == cBox1Position);
  1050. CHECK(lock2.GetBody().GetPosition() == cBox2Position);
  1051. lock1.GetBody().SetLinearVelocity(cBox1Velocity);
  1052. lock2.GetBody().SetLinearVelocity(cBox2Velocity);
  1053. }
  1054. const float cTime = 1.0f;
  1055. c1.Simulate(cTime);
  1056. c2.Simulate(cTime);
  1057. {
  1058. BodyLockRead lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1059. BodyLockRead lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1060. // Check that the bodies in the different systems updated correctly
  1061. CHECK_APPROX_EQUAL(lock1.GetBody().GetPosition(), cBox1Position + cBox1Velocity * cTime, 1.0e-5f);
  1062. CHECK_APPROX_EQUAL(lock2.GetBody().GetPosition(), cBox2Position + cBox2Velocity * cTime, 1.0e-5f);
  1063. }
  1064. }
  1065. TEST_CASE("TestOutOfBodies")
  1066. {
  1067. // Create a context with space for a single body
  1068. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1);
  1069. BodyInterface& bi = c.GetBodyInterface();
  1070. // First body
  1071. Body *b1 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1072. CHECK(b1 != nullptr);
  1073. // Second body should fail
  1074. Body *b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1075. CHECK(b2 == nullptr);
  1076. // Free first body
  1077. bi.DestroyBody(b1->GetID());
  1078. // Second body creation should succeed
  1079. b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1080. CHECK(b2 != nullptr);
  1081. // Clean up
  1082. bi.DestroyBody(b2->GetID());
  1083. }
  1084. TEST_CASE("TestOutOfContactConstraints")
  1085. {
  1086. // Create a context with space for 8 constraints
  1087. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1088. c.CreateFloor();
  1089. // The first 8 boxes should be fine
  1090. for (int i = 0; i < 8; ++i)
  1091. 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);
  1092. // Step
  1093. EPhysicsUpdateError errors = c.SimulateSingleStep();
  1094. CHECK(errors == EPhysicsUpdateError::None);
  1095. // Adding one more box should introduce an error
  1096. c.CreateBox(RVec3(24.0_r, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1097. // Step
  1098. {
  1099. JPH_IF_ENABLE_ASSERTS(ExpectAssert expect_assert(1);)
  1100. errors = c.SimulateSingleStep();
  1101. }
  1102. CHECK((errors & EPhysicsUpdateError::ContactConstraintsFull) != EPhysicsUpdateError::None);
  1103. }
  1104. TEST_CASE("TestFriction")
  1105. {
  1106. const float friction_floor = 0.9f;
  1107. const float friction_box = 0.8f;
  1108. const float combined_friction = sqrt(friction_floor * friction_box);
  1109. for (float angle = 0; angle < 360.0f; angle += 30.0f)
  1110. {
  1111. // Create a context with space for 8 constraints
  1112. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1113. // Create floor
  1114. Body &floor = c.CreateFloor();
  1115. floor.SetFriction(friction_floor);
  1116. // Create box with a velocity that will make it slide over the floor (making sure it intersects a little bit initially)
  1117. BodyCreationSettings box_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3(0, 0.999_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1118. box_settings.mFriction = friction_box;
  1119. box_settings.mLinearDamping = 0;
  1120. box_settings.mLinearVelocity = Vec3(Sin(DegreesToRadians(angle)), 0, Cos(DegreesToRadians(angle))) * 20.0f;
  1121. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1122. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1123. // We know that the friction force equals the normal force times the friction coefficient
  1124. float friction_acceleration = combined_friction * c.GetSystem()->GetGravity().Length();
  1125. // Simulate
  1126. Vec3 velocity = box_settings.mLinearVelocity;
  1127. RVec3 position = box_settings.mPosition;
  1128. for (int i = 0; i < 60; ++i)
  1129. {
  1130. c.SimulateSingleStep();
  1131. // Integrate our own simulation
  1132. velocity -= velocity.Normalized() * friction_acceleration * c.GetDeltaTime();
  1133. position += velocity * c.GetDeltaTime();
  1134. }
  1135. // Note that the result is not very accurate so we need quite a high tolerance
  1136. CHECK_APPROX_EQUAL(box.GetCenterOfMassPosition(), position, 1.0e-2f);
  1137. CHECK_APPROX_EQUAL(box.GetRotation(), box_settings.mRotation, 1.0e-2f);
  1138. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), velocity, 2.0e-2f);
  1139. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  1140. }
  1141. }
  1142. TEST_CASE("TestAllowedDOFs")
  1143. {
  1144. for (uint allowed_dofs = 1; allowed_dofs <= 0b111111; ++allowed_dofs)
  1145. {
  1146. // Create a context
  1147. PhysicsTestContext c;
  1148. c.ZeroGravity();
  1149. // Create box
  1150. RVec3 initial_position(1, 2, 3);
  1151. Quat initial_rotation = Quat::sRotation(Vec3::sReplicate(sqrt(1.0f / 3.0f)), DegreesToRadians(20.0f));
  1152. ShapeRefC box_shape = new BoxShape(Vec3(0.3f, 0.5f, 0.7f));
  1153. BodyCreationSettings box_settings(box_shape, initial_position, initial_rotation, EMotionType::Dynamic, Layers::MOVING);
  1154. box_settings.mLinearDamping = 0;
  1155. box_settings.mAngularDamping = 0;
  1156. box_settings.mAllowedDOFs = (EAllowedDOFs)allowed_dofs;
  1157. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1158. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1159. // Apply a force and torque in 3D
  1160. Vec3 force(100000, 110000, 120000);
  1161. box.AddForce(force);
  1162. Vec3 local_torque(13000, 14000, 15000);
  1163. box.AddTorque(initial_rotation * local_torque);
  1164. // Simulate
  1165. c.SimulateSingleStep();
  1166. // Cancel components that should not be allowed by the allowed DOFs
  1167. for (uint axis = 0; axis < 3; ++axis)
  1168. {
  1169. if ((allowed_dofs & (1 << axis)) == 0)
  1170. force.SetComponent(axis, 0.0f);
  1171. if ((allowed_dofs & (0b1000 << axis)) == 0)
  1172. local_torque.SetComponent(axis, 0.0f);
  1173. }
  1174. // Check resulting linear velocity
  1175. MassProperties mp = box_shape->GetMassProperties();
  1176. Vec3 expected_linear_velocity = force / mp.mMass * c.GetDeltaTime();
  1177. CHECK((force == Vec3::sZero() || expected_linear_velocity.Length() > 1.0f)); // Just to check that we applied a high enough force
  1178. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), expected_linear_velocity);
  1179. RVec3 expected_position = initial_position + expected_linear_velocity * c.GetDeltaTime();
  1180. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position);
  1181. // Check resulting angular velocity
  1182. Vec3 expected_angular_velocity = initial_rotation * (mp.mInertia.Inversed3x3() * local_torque) * c.GetDeltaTime();
  1183. CHECK((local_torque == Vec3::sZero() || expected_angular_velocity.Length() > 1.0f)); // Just to check that we applied a high enough torque
  1184. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), expected_angular_velocity);
  1185. float expected_angular_velocity_len = expected_angular_velocity.Length();
  1186. Quat expected_rotation = expected_angular_velocity_len > 0.0f? Quat::sRotation(expected_angular_velocity / expected_angular_velocity_len, expected_angular_velocity_len * c.GetDeltaTime()) * initial_rotation : initial_rotation;
  1187. CHECK_APPROX_EQUAL(box.GetRotation(), expected_rotation);
  1188. }
  1189. }
  1190. }