PhysicsTests.cpp 50 KB

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