PhysicsTests.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  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/Collision/Shape/StaticCompoundShape.h>
  13. #include <Jolt/Physics/Body/BodyLockMulti.h>
  14. #include <Jolt/Physics/Constraints/PointConstraint.h>
  15. #include <Jolt/Physics/StateRecorderImpl.h>
  16. TEST_SUITE("PhysicsTests")
  17. {
  18. // Gravity vector
  19. const Vec3 cGravity = Vec3(0.0f, -9.81f, 0.0f);
  20. // Test the test framework's helper functions
  21. TEST_CASE("TestPhysicsTestContext")
  22. {
  23. // Test that the Symplectic Euler integrator is close enough to the real value
  24. const float cSimulationTime = 2.0f;
  25. // For position: x = x0 + v0 * t + 1/2 * a * t^2
  26. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  27. PhysicsTestContext c;
  28. RVec3 simulated_pos = c.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  29. RVec3 integrated_position = cInitialPos + 0.5f * cGravity * Square(cSimulationTime);
  30. CHECK_APPROX_EQUAL(integrated_position, simulated_pos, 0.2f);
  31. // For rotation
  32. const Quat cInitialRot(Quat::sRotation(Vec3::sAxisY(), 0.1f));
  33. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  34. Quat simulated_rot = c.PredictOrientation(cInitialRot, Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  35. Vec3 integrated_acceleration = 0.5f * cAngularAcceleration * Square(cSimulationTime);
  36. float integrated_acceleration_len = integrated_acceleration.Length();
  37. Quat integrated_rot = Quat::sRotation(integrated_acceleration / integrated_acceleration_len, integrated_acceleration_len) * cInitialRot;
  38. CHECK_APPROX_EQUAL(integrated_rot, simulated_rot, 0.02f);
  39. }
  40. TEST_CASE("TestPhysicsBodyLock")
  41. {
  42. PhysicsTestContext c;
  43. // Check that we cannot lock the invalid body ID
  44. {
  45. BodyLockRead lock(c.GetSystem()->GetBodyLockInterface(), BodyID());
  46. CHECK_FALSE(lock.Succeeded());
  47. CHECK_FALSE(lock.SucceededAndIsInBroadPhase());
  48. }
  49. BodyID body1_id;
  50. {
  51. // Create a box
  52. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  53. body1_id = body1.GetID();
  54. CHECK(body1_id.GetIndex() == 0);
  55. CHECK(body1_id.GetSequenceNumber() == 1);
  56. // Create another box
  57. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  58. BodyID body2_id = body2.GetID();
  59. CHECK(body2_id.GetIndex() == 1);
  60. CHECK(body2_id.GetSequenceNumber() == 1);
  61. // Check that we can lock the first box
  62. {
  63. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  64. CHECK(lock1.Succeeded());
  65. CHECK(lock1.SucceededAndIsInBroadPhase());
  66. }
  67. // Remove the first box
  68. c.GetSystem()->GetBodyInterface().RemoveBody(body1_id);
  69. // Check that we can lock the first box
  70. {
  71. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  72. CHECK(lock1.Succeeded());
  73. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  74. }
  75. // Destroy the first box
  76. c.GetSystem()->GetBodyInterface().DestroyBody(body1_id);
  77. // Check that we can not lock the body anymore
  78. {
  79. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  80. CHECK_FALSE(lock1.Succeeded());
  81. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  82. }
  83. }
  84. // Create another box
  85. Body &body3 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  86. BodyID body3_id = body3.GetID();
  87. CHECK(body3_id.GetIndex() == 0); // Check index reused
  88. CHECK(body3_id.GetSequenceNumber() == 2); // Check sequence number changed
  89. // Check that we can lock it
  90. {
  91. BodyLockRead lock3(c.GetSystem()->GetBodyLockInterface(), body3_id);
  92. CHECK(lock3.Succeeded());
  93. CHECK(lock3.SucceededAndIsInBroadPhase());
  94. }
  95. // Check that we can't lock the old body with the same body index anymore
  96. {
  97. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  98. CHECK_FALSE(lock1.Succeeded());
  99. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  100. }
  101. }
  102. TEST_CASE("TestPhysicsBodyLockMulti")
  103. {
  104. PhysicsTestContext c;
  105. // Check that we cannot lock the invalid body ID
  106. {
  107. BodyID bodies[] = { BodyID(), BodyID() };
  108. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  109. CHECK(lock.GetBody(0) == nullptr);
  110. CHECK(lock.GetBody(1) == nullptr);
  111. }
  112. {
  113. // Create two bodies
  114. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  115. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  116. BodyID bodies[] = { body1.GetID(), body2.GetID() };
  117. {
  118. // Lock the bodies
  119. BodyLockMultiWrite lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  120. CHECK(lock.GetBody(0) == &body1);
  121. CHECK(lock.GetBody(1) == &body2);
  122. }
  123. // Destroy body 1
  124. c.GetSystem()->GetBodyInterface().RemoveBody(bodies[0]);
  125. c.GetSystem()->GetBodyInterface().DestroyBody(bodies[0]);
  126. {
  127. // Lock the bodies
  128. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  129. CHECK(lock.GetBody(0) == nullptr);
  130. CHECK(lock.GetBody(1) == &body2);
  131. }
  132. }
  133. }
  134. TEST_CASE("TestPhysicsBodyID")
  135. {
  136. {
  137. BodyID body_id(0);
  138. CHECK(body_id.GetIndex() == 0);
  139. CHECK(body_id.GetSequenceNumber() == 0);
  140. }
  141. {
  142. BodyID body_id(~BodyID::cBroadPhaseBit);
  143. CHECK(body_id.GetIndex() == BodyID::cMaxBodyIndex);
  144. CHECK(body_id.GetSequenceNumber() == BodyID::cMaxSequenceNumber);
  145. }
  146. }
  147. TEST_CASE("TestPhysicsBodyIDSequenceNumber")
  148. {
  149. PhysicsTestContext c;
  150. BodyInterface &bi = c.GetBodyInterface();
  151. // Create a body and check it's id
  152. BodyID body0_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  153. CHECK(body0_id == BodyID(0, 1)); // Body 0, sequence number 1
  154. // Check that the sequence numbers aren't reused until after 256 iterations
  155. for (int seq_no = 1; seq_no < 258; ++seq_no)
  156. {
  157. BodyID body1_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  158. CHECK(body1_id == BodyID(1, uint8(seq_no))); // Body 1
  159. bi.RemoveBody(body1_id);
  160. bi.DestroyBody(body1_id);
  161. }
  162. bi.RemoveBody(body0_id);
  163. bi.DestroyBody(body0_id);
  164. }
  165. TEST_CASE("TestPhysicsBodyIDOverride")
  166. {
  167. PhysicsTestContext c;
  168. BodyInterface &bi = c.GetBodyInterface();
  169. // Dummy creation settings
  170. BodyCreationSettings bc(new BoxShape(Vec3::sReplicate(1.0f)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  171. // Create a body
  172. Body *b1 = bi.CreateBody(bc);
  173. CHECK(b1->GetID() == BodyID(0, 1));
  174. // Create body with same ID and same sequence number
  175. Body *b2 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  176. CHECK(b2 == nullptr);
  177. // Create body with same ID and different sequence number
  178. b2 = bi.CreateBodyWithID(BodyID(0, 2), bc);
  179. CHECK(b2 == nullptr);
  180. // Create body with different ID (leave 1 open slot)
  181. b2 = bi.CreateBodyWithoutID(bc); // Using syntax that allows separation of allocation and assigning an ID
  182. CHECK(b2 != nullptr);
  183. CHECK(b2->GetID().IsInvalid());
  184. bi.AssignBodyID(b2, BodyID(2, 1));
  185. CHECK(b2->GetID() == BodyID(2, 1));
  186. // Create another body and check that the open slot is returned
  187. Body *b3 = bi.CreateBody(bc);
  188. CHECK(b3->GetID() == BodyID(1, 1));
  189. // Create another body and check that we do not hand out the body with specified ID
  190. Body *b4 = bi.CreateBody(bc);
  191. CHECK(b4->GetID() == BodyID(3, 1));
  192. // Delete and recreate body 4
  193. CHECK(bi.CreateBodyWithID(BodyID(3, 1), bc) == nullptr);
  194. bi.DestroyBody(b4->GetID());
  195. b4 = bi.CreateBodyWithID(BodyID(3, 1), bc);
  196. CHECK(b4 != nullptr);
  197. CHECK(b4->GetID() == BodyID(3, 1));
  198. // Destroy 1st body
  199. CHECK(bi.UnassignBodyID(b1->GetID()) == b1); // Use syntax that allows separation of unassigning and deallocation
  200. CHECK(b1->GetID().IsInvalid());
  201. bi.DestroyBodyWithoutID(b1);
  202. // Clean up remaining bodies
  203. bi.DestroyBody(b2->GetID());
  204. bi.DestroyBody(b3->GetID());
  205. bi.DestroyBody(b4->GetID());
  206. // Recreate body 1
  207. b1 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  208. CHECK(b1 != nullptr);
  209. CHECK(b1->GetID() == BodyID(0, 1));
  210. // Destroy last body
  211. bi.DestroyBody(b1->GetID());
  212. }
  213. TEST_CASE("TestPhysicsBodyUserData")
  214. {
  215. PhysicsTestContext c;
  216. BodyInterface &bi = c.GetBodyInterface();
  217. // Create a body and pass user data through the creation settings
  218. BodyCreationSettings body_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  219. body_settings.mUserData = 0x1234567887654321;
  220. Body *body = bi.CreateBody(body_settings);
  221. CHECK(body->GetUserData() == 0x1234567887654321);
  222. // Change the user data
  223. body->SetUserData(0x5678123443218765);
  224. CHECK(body->GetUserData() == 0x5678123443218765);
  225. // Convert back to body settings
  226. BodyCreationSettings body_settings2 = body->GetBodyCreationSettings();
  227. CHECK(body_settings2.mUserData == 0x5678123443218765);
  228. }
  229. TEST_CASE("TestPhysicsConstraintUserData")
  230. {
  231. PhysicsTestContext c;
  232. // Create a body
  233. Body &body = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f));
  234. // Create constraint with user data
  235. PointConstraintSettings constraint_settings;
  236. constraint_settings.mUserData = 0x1234567887654321;
  237. Ref<Constraint> constraint = constraint_settings.Create(body, Body::sFixedToWorld);
  238. CHECK(constraint->GetUserData() == 0x1234567887654321);
  239. // Change the user data
  240. constraint->SetUserData(0x5678123443218765);
  241. CHECK(constraint->GetUserData() == 0x5678123443218765);
  242. // Convert back to constraint settings
  243. Ref<ConstraintSettings> constraint_settings2 = constraint->GetConstraintSettings();
  244. CHECK(constraint_settings2->mUserData == 0x5678123443218765);
  245. }
  246. TEST_CASE("TestPhysicsPosition")
  247. {
  248. PhysicsTestContext c;
  249. BodyInterface &bi = c.GetBodyInterface();
  250. // Translate / rotate the box
  251. Vec3 box_pos(1, 2, 3);
  252. Quat box_rotation = Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI);
  253. // Translate / rotate the body
  254. RVec3 body_pos(4, 5, 6);
  255. Quat body_rotation = Quat::sRotation(Vec3::sAxisY(), 0.3f * JPH_PI);
  256. RMat44 body_transform = RMat44::sRotationTranslation(body_rotation, body_pos);
  257. RMat44 com_transform = body_transform * Mat44::sTranslation(box_pos);
  258. // Create body
  259. BodyCreationSettings body_settings(new RotatedTranslatedShapeSettings(box_pos, box_rotation, new BoxShape(Vec3::sReplicate(1.0f))), body_pos, body_rotation, EMotionType::Static, Layers::NON_MOVING);
  260. Body *body = bi.CreateBody(body_settings);
  261. // Check that the correct positions / rotations are reported
  262. CHECK_APPROX_EQUAL(body->GetPosition(), body_pos);
  263. CHECK_APPROX_EQUAL(body->GetRotation(), body_rotation);
  264. CHECK_APPROX_EQUAL(body->GetWorldTransform(), body_transform);
  265. CHECK_APPROX_EQUAL(body->GetCenterOfMassPosition(), com_transform.GetTranslation());
  266. CHECK_APPROX_EQUAL(body->GetCenterOfMassTransform(), com_transform);
  267. CHECK_APPROX_EQUAL(body->GetInverseCenterOfMassTransform(), com_transform.InversedRotationTranslation(), 1.0e-5f);
  268. }
  269. TEST_CASE("TestPhysicsOverrideMassAndInertia")
  270. {
  271. PhysicsTestContext c;
  272. BodyInterface &bi = c.GetBodyInterface();
  273. const float cDensity = 1234.0f;
  274. const Vec3 cBoxExtent(2.0f, 4.0f, 6.0f);
  275. const float cExpectedMass = cBoxExtent.GetX() * cBoxExtent.GetY() * cBoxExtent.GetZ() * cDensity;
  276. // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  277. const Vec3 cSquaredExtents = Vec3(Square(cBoxExtent.GetY()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetY()));
  278. const Vec3 cExpectedInertiaDiagonal = cExpectedMass / 12.0f * cSquaredExtents;
  279. Ref<BoxShapeSettings> shape_settings = new BoxShapeSettings(0.5f * cBoxExtent);
  280. shape_settings->SetDensity(cDensity);
  281. BodyCreationSettings body_settings(shape_settings, RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  282. // Create body as is
  283. Body &b1 = *bi.CreateBody(body_settings);
  284. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseMass(), 1.0f / cExpectedMass);
  285. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  286. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseInertiaDiagonal(), cExpectedInertiaDiagonal.Reciprocal());
  287. // Override only the mass
  288. const float cOverriddenMass = 13.0f;
  289. const Vec3 cOverriddenMassInertiaDiagonal = cOverriddenMass / 12.0f * cSquaredExtents;
  290. body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  291. body_settings.mMassPropertiesOverride.mMass = cOverriddenMass;
  292. Body &b2 = *bi.CreateBody(body_settings);
  293. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  294. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  295. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenMassInertiaDiagonal.Reciprocal());
  296. // Override both the mass and inertia
  297. 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
  298. const Quat cOverriddenInertiaRotation = Quat::sRotation(Vec3(1, 1, 1).Normalized(), 0.1f * JPH_PI);
  299. body_settings.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  300. body_settings.mMassPropertiesOverride.mInertia = Mat44::sRotation(cOverriddenInertiaRotation) * Mat44::sScale(cOverriddenInertiaDiagonal) * Mat44::sRotation(cOverriddenInertiaRotation.Inversed());
  301. Body &b3 = *bi.CreateBody(body_settings);
  302. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  303. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInertiaRotation(), cOverriddenInertiaRotation);
  304. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenInertiaDiagonal.Reciprocal());
  305. }
  306. // Test a box free falling under gravity
  307. static void TestPhysicsFreeFall(PhysicsTestContext &ioContext)
  308. {
  309. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  310. const float cSimulationTime = 2.0f;
  311. // Create box
  312. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  313. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  314. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  315. ioContext.Simulate(cSimulationTime);
  316. // Test resulting velocity (due to gravity)
  317. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  318. // Test resulting position
  319. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  320. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  321. }
  322. TEST_CASE("TestPhysicsFreeFall")
  323. {
  324. PhysicsTestContext c;
  325. TestPhysicsFreeFall(c);
  326. }
  327. TEST_CASE("TestPhysicsFreeFallStep")
  328. {
  329. PhysicsTestContext c1(2.0f / 60.0f, 2);
  330. TestPhysicsFreeFall(c1);
  331. PhysicsTestContext c2(4.0f / 60.0f, 4);
  332. TestPhysicsFreeFall(c2);
  333. }
  334. // Test acceleration of a box with force applied
  335. static void TestPhysicsApplyForce(PhysicsTestContext &ioContext)
  336. {
  337. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  338. const Vec3 cAcceleration(2.0f, 0.0f, 0.0f);
  339. const float cSimulationTime = 2.0f;
  340. // Create box
  341. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  342. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  343. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  344. // Validate mass
  345. float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  346. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  347. // Simulate while applying force
  348. ioContext.Simulate(cSimulationTime, [&]() { body.AddForce(mass * cAcceleration); });
  349. // Test resulting velocity (due to gravity and applied force)
  350. CHECK_APPROX_EQUAL(cSimulationTime * (cGravity + cAcceleration), body.GetLinearVelocity(), 1.0e-4f);
  351. // Test resulting position
  352. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity + cAcceleration, cSimulationTime);
  353. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  354. }
  355. TEST_CASE("TestPhysicsApplyForce")
  356. {
  357. PhysicsTestContext c;
  358. TestPhysicsApplyForce(c);
  359. }
  360. TEST_CASE("TestPhysicsApplyForceStep")
  361. {
  362. PhysicsTestContext c1(2.0f / 60.0f, 2);
  363. TestPhysicsApplyForce(c1);
  364. PhysicsTestContext c2(4.0f / 60.0f, 4);
  365. TestPhysicsApplyForce(c2);
  366. }
  367. // Test angular accelartion for a box by applying torque every frame
  368. static void TestPhysicsApplyTorque(PhysicsTestContext &ioContext)
  369. {
  370. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  371. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  372. const float cSimulationTime = 2.0f;
  373. // Create box
  374. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  375. CHECK_APPROX_EQUAL(Quat::sIdentity(), body.GetRotation());
  376. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  377. // Validate mass and inertia
  378. constexpr float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  379. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  380. constexpr float inertia = mass * 8.0f / 12.0f; // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  381. CHECK_APPROX_EQUAL(Mat44::sScale(1.0f / inertia), body.GetMotionProperties()->GetLocalSpaceInverseInertia());
  382. // Simulate while applying torque
  383. ioContext.Simulate(cSimulationTime, [&]() { body.AddTorque(inertia * cAngularAcceleration); });
  384. // Get resulting angular velocity
  385. CHECK_APPROX_EQUAL(cSimulationTime * cAngularAcceleration, body.GetAngularVelocity(), 1.0e-4f);
  386. // Test resulting rotation
  387. Quat expected_rot = ioContext.PredictOrientation(Quat::sIdentity(), Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  388. CHECK_APPROX_EQUAL(expected_rot, body.GetRotation(), 1.0e-4f);
  389. }
  390. TEST_CASE("TestPhysicsApplyTorque")
  391. {
  392. PhysicsTestContext c;
  393. TestPhysicsApplyTorque(c);
  394. }
  395. TEST_CASE("TestPhysicsApplyTorqueStep")
  396. {
  397. PhysicsTestContext c1(2.0f / 60.0f, 2);
  398. TestPhysicsApplyTorque(c1);
  399. PhysicsTestContext c2(4.0f / 60.0f, 4);
  400. TestPhysicsApplyTorque(c2);
  401. }
  402. // Let a sphere bounce on the floor with restition = 1
  403. static void TestPhysicsCollisionElastic(PhysicsTestContext &ioContext)
  404. {
  405. const float cSimulationTime = 1.0f;
  406. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  407. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  408. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  409. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  410. // Create sphere
  411. ioContext.CreateFloor();
  412. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  413. body.SetRestitution(1.0f);
  414. // Simulate until at floor
  415. ioContext.Simulate(cSimulationTime);
  416. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  417. // Assert collision not yet processed
  418. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  419. // Simulate one more step to process the collision
  420. ioContext.Simulate(ioContext.GetDeltaTime());
  421. // Assert that collision is processed and velocity is reversed (which is required for a fully elastic collision).
  422. // Note that the physics engine will first apply gravity for the time step and then do collision detection,
  423. // hence the reflected velocity is actually 1 step times gravity bigger than it would be in reality
  424. // For the remainder of cDeltaTime normal gravity will be applied
  425. float sub_step_delta_time = ioContext.GetStepDeltaTime();
  426. float remaining_step_time = ioContext.GetDeltaTime() - ioContext.GetStepDeltaTime();
  427. Vec3 reflected_velocity_after_sub_step = -(cSimulationTime + sub_step_delta_time) * cGravity;
  428. Vec3 reflected_velocity_after_full_step = reflected_velocity_after_sub_step + remaining_step_time * cGravity;
  429. CHECK_APPROX_EQUAL(reflected_velocity_after_full_step, body.GetLinearVelocity(), 1.0e-4f);
  430. // Body should have bounced back
  431. RVec3 pos_after_bounce_sub_step = cFloorHitPos + reflected_velocity_after_sub_step * sub_step_delta_time;
  432. RVec3 pos_after_bounce_full_step = ioContext.PredictPosition(pos_after_bounce_sub_step, reflected_velocity_after_sub_step, cGravity, remaining_step_time);
  433. CHECK_APPROX_EQUAL(pos_after_bounce_full_step, body.GetPosition());
  434. // Simulate same time, with a fully elastic body we should reach the initial position again
  435. // In our physics engine because of the velocity being too big we actually end up a bit higher than our initial position
  436. RVec3 expected_pos = ioContext.PredictPosition(pos_after_bounce_full_step, reflected_velocity_after_full_step, cGravity, cSimulationTime);
  437. ioContext.Simulate(cSimulationTime);
  438. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition(), 1.0e-4f);
  439. CHECK(expected_pos.GetY() >= cInitialPos.GetY());
  440. }
  441. TEST_CASE("TestPhysicsCollisionElastic")
  442. {
  443. PhysicsTestContext c;
  444. TestPhysicsCollisionElastic(c);
  445. }
  446. TEST_CASE("TestPhysicsCollisionElasticStep")
  447. {
  448. PhysicsTestContext c1(2.0f / 60.0f, 2);
  449. TestPhysicsCollisionElastic(c1);
  450. PhysicsTestContext c2(4.0f / 60.0f, 4);
  451. TestPhysicsCollisionElastic(c2);
  452. }
  453. // Let a sphere bounce on the floor with restitution = 0
  454. static void TestPhysicsCollisionInelastic(PhysicsTestContext &ioContext)
  455. {
  456. const float cSimulationTime = 1.0f;
  457. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  458. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  459. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  460. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  461. // Create sphere
  462. ioContext.CreateFloor();
  463. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  464. body.SetRestitution(0.0f);
  465. // Simulate until at floor
  466. ioContext.Simulate(cSimulationTime);
  467. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  468. // Assert collision not yet processed
  469. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  470. // Simulate one more step to process the collision
  471. ioContext.Simulate(ioContext.GetDeltaTime());
  472. // Assert that all velocity was lost in the collision
  473. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  474. // Assert that we're on the floor
  475. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  476. // Simulate some more to validate that we remain on the floor
  477. ioContext.Simulate(cSimulationTime);
  478. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  479. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  480. }
  481. TEST_CASE("TestPhysicsCollisionInelastic")
  482. {
  483. PhysicsTestContext c;
  484. TestPhysicsCollisionInelastic(c);
  485. }
  486. TEST_CASE("TestPhysicsCollisionInelasticStep")
  487. {
  488. PhysicsTestContext c1(2.0f / 60.0f, 2);
  489. TestPhysicsCollisionInelastic(c1);
  490. PhysicsTestContext c2(4.0f / 60.0f, 4);
  491. TestPhysicsCollisionInelastic(c2);
  492. }
  493. // Let box intersect with floor by cPenetrationSlop. It should not move, this is the maximum penetration allowed.
  494. static void TestPhysicsPenetrationSlop1(PhysicsTestContext &ioContext)
  495. {
  496. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  497. const float cSimulationTime = 1.0f;
  498. const RVec3 cInitialPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  499. // Create box, penetrating with floor
  500. ioContext.CreateFloor();
  501. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  502. // Simulate
  503. ioContext.Simulate(cSimulationTime);
  504. // Test slop not resolved
  505. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  506. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  507. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  508. }
  509. TEST_CASE("TestPhysicsPenetrationSlop1")
  510. {
  511. PhysicsTestContext c;
  512. TestPhysicsPenetrationSlop1(c);
  513. }
  514. TEST_CASE("TestPhysicsPenetrationSlop1Step")
  515. {
  516. PhysicsTestContext c(2.0f / 60.0f, 2);
  517. TestPhysicsPenetrationSlop1(c);
  518. PhysicsTestContext c2(4.0f / 60.0f, 4);
  519. TestPhysicsPenetrationSlop1(c2);
  520. }
  521. // Let box intersect with floor with more than cPenetrationSlop. It should be resolved by SolvePositionConstraint until interpenetration is cPenetrationSlop.
  522. static void TestPhysicsPenetrationSlop2(PhysicsTestContext &ioContext)
  523. {
  524. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  525. const float cSimulationTime = 1.0f;
  526. const RVec3 cInitialPos(0.0f, 1.0f - 2.0f * cPenetrationSlop, 0.0f);
  527. const RVec3 cFinalPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  528. // Create box, penetrating with floor
  529. ioContext.CreateFloor();
  530. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  531. // Simulate
  532. ioContext.Simulate(cSimulationTime);
  533. // Test resolved until slop
  534. CHECK_APPROX_EQUAL(cFinalPos, body.GetPosition(), 1.0e-5f);
  535. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  536. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  537. }
  538. TEST_CASE("TestPhysicsPenetrationSlop2")
  539. {
  540. PhysicsTestContext c;
  541. TestPhysicsPenetrationSlop2(c);
  542. }
  543. TEST_CASE("TestPhysicsPenetrationSlop2Step")
  544. {
  545. PhysicsTestContext c(2.0f / 60.0f, 2);
  546. TestPhysicsPenetrationSlop2(c);
  547. PhysicsTestContext c2(4.0f / 60.0f, 4);
  548. TestPhysicsPenetrationSlop2(c2);
  549. }
  550. // Let box intersect with floor with less than cPenetrationSlop. Body should not move because SolveVelocityConstraint should reset velocity.
  551. static void TestPhysicsPenetrationSlop3(PhysicsTestContext &ioContext)
  552. {
  553. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  554. const float cSimulationTime = 1.0f;
  555. const RVec3 cInitialPos(0.0f, 1.0f - 0.1f * cPenetrationSlop, 0.0f);
  556. // Create box, penetrating with floor
  557. ioContext.CreateFloor();
  558. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  559. // Simulate
  560. ioContext.Simulate(cSimulationTime);
  561. // Test body remained static
  562. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  563. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  564. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  565. }
  566. TEST_CASE("TestPhysicsPenetrationSlop3")
  567. {
  568. PhysicsTestContext c;
  569. TestPhysicsPenetrationSlop3(c);
  570. }
  571. TEST_CASE("TestPhysicsPenetrationSlop3Step")
  572. {
  573. PhysicsTestContext c(2.0f / 60.0f, 2);
  574. TestPhysicsPenetrationSlop3(c);
  575. PhysicsTestContext c2(4.0f / 60.0f, 4);
  576. TestPhysicsPenetrationSlop3(c2);
  577. }
  578. TEST_CASE("TestPhysicsOutsideOfSpeculativeContactDistance")
  579. {
  580. PhysicsTestContext c;
  581. Body &floor = c.CreateFloor();
  582. c.ZeroGravity();
  583. LoggingContactListener contact_listener;
  584. c.GetSystem()->SetContactListener(&contact_listener);
  585. // Create a box and a sphere just outside the speculative contact distance
  586. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  587. const float cDistanceAboveFloor = 1.1f * cSpeculativeContactDistance;
  588. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  589. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  590. // Make it move 1 m per step down
  591. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  592. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  593. box.SetLinearVelocity(cVelocity);
  594. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  595. sphere.SetLinearVelocity(cVelocity);
  596. // Simulate a step
  597. c.SimulateSingleStep();
  598. // 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)
  599. CHECK(contact_listener.GetEntryCount() == 0);
  600. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  601. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  602. // Simulate a step
  603. c.SimulateSingleStep();
  604. // Check that the contacts are detected now
  605. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  606. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  607. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  608. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  609. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  610. }
  611. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoRestitution")
  612. {
  613. PhysicsTestContext c;
  614. Body &floor = c.CreateFloor();
  615. c.ZeroGravity();
  616. LoggingContactListener contact_listener;
  617. c.GetSystem()->SetContactListener(&contact_listener);
  618. // Create a box and a sphere just inside the speculative contact distance
  619. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  620. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  621. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  622. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  623. // Make it move 1 m per step down
  624. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  625. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  626. box.SetLinearVelocity(cVelocity);
  627. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  628. sphere.SetLinearVelocity(cVelocity);
  629. // Simulate a step
  630. c.SimulateSingleStep();
  631. // Check that it is now on the floor and that 2 collisions have been detected
  632. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  633. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  634. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  635. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  636. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  637. contact_listener.Clear();
  638. // Velocity should have been reduced to exactly hit the floor in this step
  639. const Vec3 cExpectedVelocity(0, -cDistanceAboveFloor / c.GetDeltaTime(), 0);
  640. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  641. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  642. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cExpectedVelocity, 0.05f);
  643. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  644. // Sphere has only 1 contact point so is much more accurate
  645. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0));
  646. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cExpectedVelocity, 1.0e-4f);
  647. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  648. // Simulate a step
  649. c.SimulateSingleStep();
  650. // Check that the contacts persisted
  651. CHECK(contact_listener.GetEntryCount() >= 2); // 2 persist and possibly 2 validates depending on if the cache got reused
  652. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, box.GetID(), floor.GetID()));
  653. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  654. // Box should have come to rest
  655. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  656. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero(), 0.05f);
  657. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  658. // Sphere should have come to rest
  659. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0), 1.0e-4f);
  660. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), Vec3::sZero(), 1.0e-4f);
  661. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  662. }
  663. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceWithRestitution")
  664. {
  665. PhysicsTestContext c;
  666. Body &floor = c.CreateFloor();
  667. c.ZeroGravity();
  668. LoggingContactListener contact_listener;
  669. c.GetSystem()->SetContactListener(&contact_listener);
  670. // Create a box and a sphere just inside the speculative contact distance
  671. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  672. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  673. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  674. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  675. // Make it move 1 m per step down
  676. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  677. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  678. box.SetLinearVelocity(cVelocity);
  679. box.SetRestitution(1.0f);
  680. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  681. sphere.SetLinearVelocity(cVelocity);
  682. sphere.SetRestitution(1.0f);
  683. // Simulate a step
  684. c.SimulateSingleStep();
  685. // 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)
  686. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  687. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  688. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  689. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  690. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  691. contact_listener.Clear();
  692. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  693. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox - cVelocity * c.GetDeltaTime(), 0.01f);
  694. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), -cVelocity, 0.1f);
  695. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 0.02f);
  696. // Sphere has only 1 contact point so is much more accurate
  697. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere - cVelocity * c.GetDeltaTime(), 1.0e-5f);
  698. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), -cVelocity, 2.0e-4f);
  699. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 2.0e-4f);
  700. // Simulate a step
  701. c.SimulateSingleStep();
  702. // Check that all contact points are removed
  703. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  704. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  705. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  706. }
  707. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoHit")
  708. {
  709. PhysicsTestContext c;
  710. Body &floor = c.CreateFloor();
  711. floor.SetRestitution(1.0f);
  712. c.ZeroGravity();
  713. // Turn off the minimum velocity for restitution, our velocity is lower than the default
  714. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  715. settings.mMinVelocityForRestitution = 0.0f;
  716. c.GetSystem()->SetPhysicsSettings(settings);
  717. LoggingContactListener contact_listener;
  718. c.GetSystem()->SetContactListener(&contact_listener);
  719. // Create a sphere inside speculative contact distance from the ground
  720. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  721. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  722. const RVec3 cInitialPosSphere(0, 1.0f + cDistanceAboveFloor, 0.0f);
  723. // Make it move slow enough so that it will not touch the floor in 1 time step
  724. const Vec3 cVelocity(0, -0.9f * cDistanceAboveFloor / c.GetDeltaTime(), 0);
  725. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  726. sphere.SetLinearVelocity(cVelocity);
  727. sphere.SetRestitution(1.0f);
  728. sphere.GetMotionProperties()->SetLinearDamping(0.0f);
  729. // Simulate a step
  730. c.SimulateSingleStep();
  731. // Check that it has triggered contact points from the speculative contacts
  732. CHECK(contact_listener.GetEntryCount() == 2);
  733. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  734. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  735. contact_listener.Clear();
  736. // Check that sphere didn't actually change velocity (it hasn't actually interacted with the floor, the speculative contact was not an actual contact)
  737. CHECK(sphere.GetLinearVelocity() == cVelocity);
  738. // Simulate a step
  739. c.SimulateSingleStep();
  740. // Check again that it triggered contact points
  741. CHECK(contact_listener.GetEntryCount() == 2);
  742. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  743. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  744. contact_listener.Clear();
  745. // It should have bounced back up and inverted velocity due to restitution being 1
  746. CHECK_APPROX_EQUAL(-sphere.GetLinearVelocity(), cVelocity);
  747. }
  748. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  749. {
  750. PhysicsTestContext c;
  751. Body &floor = c.CreateFloor();
  752. c.ZeroGravity();
  753. LoggingContactListener contact_listener;
  754. c.GetSystem()->SetContactListener(&contact_listener);
  755. // Create a box and a sphere just inside the speculative contact distance
  756. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  757. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  758. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  759. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  760. // Make it move 1 m per step up
  761. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  762. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  763. box.SetLinearVelocity(cVelocity);
  764. box.SetRestitution(1.0f);
  765. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  766. sphere.SetLinearVelocity(cVelocity);
  767. sphere.SetRestitution(1.0f);
  768. // Simulate a step
  769. c.SimulateSingleStep();
  770. // 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)
  771. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  772. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  773. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  774. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  775. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  776. contact_listener.Clear();
  777. // Box should have moved unimpeded
  778. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  779. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  780. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  781. // Sphere should have moved unimpeded
  782. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  783. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  784. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  785. // Simulate a step
  786. c.SimulateSingleStep();
  787. // Check that all contact points are removed
  788. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  789. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  790. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  791. }
  792. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  793. {
  794. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  795. // Install activation listener
  796. LoggingBodyActivationListener activation_listener;
  797. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  798. // Create floor
  799. Body &floor = ioContext.CreateBox(RVec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  800. CHECK(!floor.IsActive());
  801. // Create inactive box
  802. Body &box = ioContext.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  803. CHECK(!box.IsActive());
  804. CHECK(activation_listener.GetEntryCount() == 0);
  805. // Box should not activate by itself
  806. ioContext.Simulate(1.0f);
  807. CHECK(box.GetPosition() == RVec3(0, 5, 0));
  808. CHECK(!box.IsActive());
  809. CHECK(activation_listener.GetEntryCount() == 0);
  810. // Activate the body and validate it is active now
  811. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  812. CHECK(box.IsActive());
  813. CHECK(box.GetLinearVelocity().IsNearZero());
  814. CHECK(activation_listener.GetEntryCount() == 1);
  815. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  816. activation_listener.Clear();
  817. // Do a single step and check that the body is still active and has gained some velocity
  818. ioContext.SimulateSingleStep();
  819. CHECK(box.IsActive());
  820. CHECK(activation_listener.GetEntryCount() == 0);
  821. CHECK(!box.GetLinearVelocity().IsNearZero());
  822. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  823. ioContext.Simulate(5.0f);
  824. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  825. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  826. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  827. CHECK(!box.IsActive());
  828. CHECK(activation_listener.GetEntryCount() == 1);
  829. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  830. }
  831. TEST_CASE("TestPhysicsActivationDeactivation")
  832. {
  833. PhysicsTestContext c1(1.0f / 60.0f, 1);
  834. TestPhysicsActivationDeactivation(c1);
  835. PhysicsTestContext c2(2.0f / 60.0f, 2);
  836. TestPhysicsActivationDeactivation(c2);
  837. PhysicsTestContext c3(4.0f / 60.0f, 4);
  838. TestPhysicsActivationDeactivation(c3);
  839. }
  840. // 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
  841. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  842. {
  843. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  844. const int cNumBodies = 10;
  845. const float cBoxExtent = 0.5f;
  846. PhysicsSystem *system = ioContext.GetSystem();
  847. BodyInterface &bi = ioContext.GetBodyInterface();
  848. LoggingBodyActivationListener activation_listener;
  849. system->SetBodyActivationListener(&activation_listener);
  850. LoggingContactListener contact_listener;
  851. system->SetContactListener(&contact_listener);
  852. // 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
  853. BodyIDVector body_ids;
  854. if (inReverseCreate)
  855. for (int i = cNumBodies - 1; i >= 0; --i)
  856. 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());
  857. else
  858. for (int i = 0; i < cNumBodies; ++i)
  859. 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());
  860. // Test that nothing is active yet
  861. CHECK(activation_listener.GetEntryCount() == 0);
  862. CHECK(contact_listener.GetEntryCount() == 0);
  863. for (BodyID id : body_ids)
  864. CHECK(!bi.IsActive(id));
  865. // 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
  866. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  867. // Test that only the left most box is active
  868. CHECK(activation_listener.GetEntryCount() == 1);
  869. CHECK(contact_listener.GetEntryCount() == 0);
  870. CHECK(bi.IsActive(body_ids.front()));
  871. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  872. for (int i = 1; i < cNumBodies; ++i)
  873. CHECK(!bi.IsActive(body_ids[i]));
  874. activation_listener.Clear();
  875. // Step the world
  876. ioContext.SimulateSingleStep();
  877. // Other bodies should now be awake and each body should only collide with its neighbour
  878. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  879. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  880. for (int i = 0; i < cNumBodies; ++i)
  881. {
  882. BodyID id = body_ids[i];
  883. // Check body is active
  884. CHECK(bi.IsActive(id));
  885. // Check that body moved to the right
  886. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  887. }
  888. for (int i = 1; i < cNumBodies; ++i)
  889. {
  890. BodyID id1 = body_ids[i - 1];
  891. BodyID id2 = body_ids[i];
  892. // Check that we received activation events for each body
  893. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  894. // Check that we received a validate and an add for each body pair
  895. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  896. CHECK(validate >= 0);
  897. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  898. CHECK(add >= 0);
  899. CHECK(add > validate);
  900. // Check that bodies did not tunnel through each other
  901. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  902. }
  903. }
  904. TEST_CASE("TestPhysicsActivateDuringStep")
  905. {
  906. PhysicsTestContext c;
  907. TestPhysicsActivateDuringStep(c, false);
  908. PhysicsTestContext c2;
  909. TestPhysicsActivateDuringStep(c2, true);
  910. }
  911. TEST_CASE("TestPhysicsBroadPhaseLayers")
  912. {
  913. PhysicsTestContext c;
  914. BodyInterface &bi = c.GetBodyInterface();
  915. // Reduce slop
  916. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  917. settings.mPenetrationSlop = 0.0f;
  918. c.GetSystem()->SetPhysicsSettings(settings);
  919. // Create static floor
  920. c.CreateFloor();
  921. // Create MOVING boxes
  922. Body &moving1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  923. Body &moving2 = c.CreateBox(RVec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  924. // Create HQ_DEBRIS boxes
  925. Body &hq_debris1 = c.CreateBox(RVec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  926. Body &hq_debris2 = c.CreateBox(RVec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  927. // Create LQ_DEBRIS boxes
  928. Body &lq_debris1 = c.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  929. Body &lq_debris2 = c.CreateBox(RVec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  930. // Check layers
  931. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  932. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  933. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  934. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  935. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  936. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  937. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  938. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  939. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  940. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  941. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  942. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  943. // Simulate the boxes falling
  944. c.Simulate(5.0f);
  945. // Everything should sleep
  946. CHECK_FALSE(moving1.IsActive());
  947. CHECK_FALSE(moving2.IsActive());
  948. CHECK_FALSE(hq_debris1.IsActive());
  949. CHECK_FALSE(hq_debris2.IsActive());
  950. CHECK_FALSE(lq_debris1.IsActive());
  951. CHECK_FALSE(lq_debris2.IsActive());
  952. // MOVING boxes should have stacked
  953. float slop = 0.02f;
  954. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  955. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  956. // HQ_DEBRIS boxes should have stacked on MOVING boxes but don't collide with each other
  957. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 2.5f, 0), slop);
  958. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 2.5f, 0), slop);
  959. // LQ_DEBRIS should have fallen through all but the floor
  960. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  961. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  962. // Now change HQ_DEBRIS to LQ_DEBRIS
  963. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  964. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  965. bi.ActivateBody(hq_debris1.GetID());
  966. bi.ActivateBody(hq_debris2.GetID());
  967. // Check layers
  968. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  969. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  970. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  971. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  972. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  973. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  974. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  975. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  976. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  977. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  978. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  979. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  980. // Simulate again
  981. c.Simulate(5.0f);
  982. // Everything should sleep
  983. CHECK_FALSE(moving1.IsActive());
  984. CHECK_FALSE(moving2.IsActive());
  985. CHECK_FALSE(hq_debris1.IsActive());
  986. CHECK_FALSE(hq_debris2.IsActive());
  987. CHECK_FALSE(lq_debris1.IsActive());
  988. CHECK_FALSE(lq_debris2.IsActive());
  989. // MOVING boxes should have stacked
  990. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  991. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  992. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  993. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  994. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  995. // LQ_DEBRIS should have fallen through all but the floor
  996. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  997. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  998. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  999. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  1000. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  1001. bi.ActivateBody(moving1.GetID());
  1002. bi.ActivateBody(moving2.GetID());
  1003. // Check layers
  1004. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1005. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1006. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1007. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1008. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1009. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1010. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  1011. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1012. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1013. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1014. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1015. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1016. // Simulate again
  1017. c.Simulate(5.0f);
  1018. // Everything should sleep
  1019. CHECK_FALSE(moving1.IsActive());
  1020. CHECK_FALSE(moving2.IsActive());
  1021. CHECK_FALSE(hq_debris1.IsActive());
  1022. CHECK_FALSE(hq_debris2.IsActive());
  1023. CHECK_FALSE(lq_debris1.IsActive());
  1024. CHECK_FALSE(lq_debris2.IsActive());
  1025. // MOVING boxes now also fall through
  1026. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1027. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1028. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1029. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1030. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1031. // LQ_DEBRIS should have fallen through all but the floor
  1032. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1033. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1034. }
  1035. TEST_CASE("TestMultiplePhysicsSystems")
  1036. {
  1037. PhysicsTestContext c1;
  1038. c1.ZeroGravity();
  1039. PhysicsTestContext c2;
  1040. c2.ZeroGravity();
  1041. const RVec3 cBox1Position(1.0f, 2.0f, 3.0f);
  1042. Body &box1 = c1.CreateBox(cBox1Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1043. const RVec3 cBox2Position(4.0f, 5.0f, 6.0f);
  1044. Body& box2 = c2.CreateBox(cBox2Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1045. const Vec3 cBox1Velocity(1.0f, 0, 0);
  1046. const Vec3 cBox2Velocity(2.0f, 0, 0);
  1047. {
  1048. // 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)
  1049. BodyLockWrite lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1050. BodyLockWrite lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1051. CHECK(lock1.GetBody().GetPosition() == cBox1Position);
  1052. CHECK(lock2.GetBody().GetPosition() == cBox2Position);
  1053. lock1.GetBody().SetLinearVelocity(cBox1Velocity);
  1054. lock2.GetBody().SetLinearVelocity(cBox2Velocity);
  1055. }
  1056. const float cTime = 1.0f;
  1057. c1.Simulate(cTime);
  1058. c2.Simulate(cTime);
  1059. {
  1060. BodyLockRead lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1061. BodyLockRead lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1062. // Check that the bodies in the different systems updated correctly
  1063. CHECK_APPROX_EQUAL(lock1.GetBody().GetPosition(), cBox1Position + cBox1Velocity * cTime, 1.0e-5f);
  1064. CHECK_APPROX_EQUAL(lock2.GetBody().GetPosition(), cBox2Position + cBox2Velocity * cTime, 1.0e-5f);
  1065. }
  1066. }
  1067. TEST_CASE("TestOutOfBodies")
  1068. {
  1069. // Create a context with space for a single body
  1070. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1);
  1071. BodyInterface& bi = c.GetBodyInterface();
  1072. // First body
  1073. Body *b1 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1074. CHECK(b1 != nullptr);
  1075. // Second body should fail
  1076. Body *b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1077. CHECK(b2 == nullptr);
  1078. // Free first body
  1079. bi.DestroyBody(b1->GetID());
  1080. // Second body creation should succeed
  1081. b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1082. CHECK(b2 != nullptr);
  1083. // Clean up
  1084. bi.DestroyBody(b2->GetID());
  1085. }
  1086. TEST_CASE("TestOutOfContactConstraints")
  1087. {
  1088. // Create a context with space for 8 constraints
  1089. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1090. c.CreateFloor();
  1091. // The first 8 boxes should be fine
  1092. for (int i = 0; i < 8; ++i)
  1093. 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);
  1094. // Step
  1095. EPhysicsUpdateError errors = c.SimulateSingleStep();
  1096. CHECK(errors == EPhysicsUpdateError::None);
  1097. // Adding one more box should introduce an error
  1098. c.CreateBox(RVec3(24.0_r, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1099. // Step
  1100. {
  1101. JPH_IF_ENABLE_ASSERTS(ExpectAssert expect_assert(1);)
  1102. errors = c.SimulateSingleStep();
  1103. }
  1104. CHECK((errors & EPhysicsUpdateError::ContactConstraintsFull) != EPhysicsUpdateError::None);
  1105. }
  1106. TEST_CASE("TestFriction")
  1107. {
  1108. const float friction_floor = 0.9f;
  1109. const float friction_box = 0.8f;
  1110. const float combined_friction = sqrt(friction_floor * friction_box);
  1111. for (float angle = 0; angle < 360.0f; angle += 30.0f)
  1112. {
  1113. // Create a context with space for 8 constraints
  1114. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1115. // Create floor
  1116. Body &floor = c.CreateFloor();
  1117. floor.SetFriction(friction_floor);
  1118. // Create box with a velocity that will make it slide over the floor (making sure it intersects a little bit initially)
  1119. BodyCreationSettings box_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3(0, 0.999_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1120. box_settings.mFriction = friction_box;
  1121. box_settings.mLinearDamping = 0;
  1122. box_settings.mLinearVelocity = Vec3(Sin(DegreesToRadians(angle)), 0, Cos(DegreesToRadians(angle))) * 20.0f;
  1123. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1124. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1125. // We know that the friction force equals the normal force times the friction coefficient
  1126. float friction_acceleration = combined_friction * c.GetSystem()->GetGravity().Length();
  1127. // Simulate
  1128. Vec3 velocity = box_settings.mLinearVelocity;
  1129. RVec3 position = box_settings.mPosition;
  1130. for (int i = 0; i < 60; ++i)
  1131. {
  1132. c.SimulateSingleStep();
  1133. // Integrate our own simulation
  1134. velocity -= velocity.Normalized() * friction_acceleration * c.GetDeltaTime();
  1135. position += velocity * c.GetDeltaTime();
  1136. }
  1137. // Note that the result is not very accurate so we need quite a high tolerance
  1138. CHECK_APPROX_EQUAL(box.GetCenterOfMassPosition(), position, 1.0e-2f);
  1139. CHECK_APPROX_EQUAL(box.GetRotation(), box_settings.mRotation, 1.0e-2f);
  1140. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), velocity, 2.0e-2f);
  1141. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  1142. }
  1143. }
  1144. TEST_CASE("TestAllowedDOFs")
  1145. {
  1146. for (uint allowed_dofs = 1; allowed_dofs <= 0b111111; ++allowed_dofs)
  1147. {
  1148. // Create a context
  1149. PhysicsTestContext c;
  1150. c.ZeroGravity();
  1151. // Create box
  1152. RVec3 initial_position(1, 2, 3);
  1153. Quat initial_rotation = Quat::sRotation(Vec3::sReplicate(sqrt(1.0f / 3.0f)), DegreesToRadians(20.0f));
  1154. ShapeRefC box_shape = new BoxShape(Vec3(0.3f, 0.5f, 0.7f));
  1155. BodyCreationSettings box_settings(box_shape, initial_position, initial_rotation, EMotionType::Dynamic, Layers::MOVING);
  1156. box_settings.mLinearDamping = 0;
  1157. box_settings.mAngularDamping = 0;
  1158. box_settings.mAllowedDOFs = (EAllowedDOFs)allowed_dofs;
  1159. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1160. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1161. // Apply a force and torque in 3D
  1162. Vec3 force(100000, 110000, 120000);
  1163. box.AddForce(force);
  1164. Vec3 local_torque(13000, 14000, 15000);
  1165. box.AddTorque(initial_rotation * local_torque);
  1166. // Simulate
  1167. c.SimulateSingleStep();
  1168. // Cancel components that should not be allowed by the allowed DOFs
  1169. for (uint axis = 0; axis < 3; ++axis)
  1170. {
  1171. if ((allowed_dofs & (1 << axis)) == 0)
  1172. force.SetComponent(axis, 0.0f);
  1173. if ((allowed_dofs & (0b1000 << axis)) == 0)
  1174. local_torque.SetComponent(axis, 0.0f);
  1175. }
  1176. // Check resulting linear velocity
  1177. MassProperties mp = box_shape->GetMassProperties();
  1178. Vec3 expected_linear_velocity = force / mp.mMass * c.GetDeltaTime();
  1179. CHECK((force == Vec3::sZero() || expected_linear_velocity.Length() > 1.0f)); // Just to check that we applied a high enough force
  1180. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), expected_linear_velocity);
  1181. RVec3 expected_position = initial_position + expected_linear_velocity * c.GetDeltaTime();
  1182. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position);
  1183. // Check resulting angular velocity
  1184. Vec3 expected_angular_velocity = initial_rotation * (mp.mInertia.Inversed3x3() * local_torque) * c.GetDeltaTime();
  1185. CHECK((local_torque == Vec3::sZero() || expected_angular_velocity.Length() > 1.0f)); // Just to check that we applied a high enough torque
  1186. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), expected_angular_velocity);
  1187. float expected_angular_velocity_len = expected_angular_velocity.Length();
  1188. 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;
  1189. CHECK_APPROX_EQUAL(box.GetRotation(), expected_rotation);
  1190. }
  1191. }
  1192. TEST_CASE("TestSelectiveStateSaveAndRestore")
  1193. {
  1194. class MyFilter : public StateRecorderFilter
  1195. {
  1196. public:
  1197. bool ShouldSaveBody(const BodyID &inBodyID) const
  1198. {
  1199. return find(mIgnoreBodies.cbegin(), mIgnoreBodies.cend(), inBodyID) == mIgnoreBodies.cend();
  1200. }
  1201. virtual bool ShouldSaveBody(const Body &inBody) const override
  1202. {
  1203. return ShouldSaveBody(inBody.GetID());
  1204. }
  1205. virtual bool ShouldSaveContact(const BodyID &inBody1, const BodyID &inBody2) const override
  1206. {
  1207. return ShouldSaveBody(inBody1) && ShouldSaveBody(inBody2);
  1208. }
  1209. Array<BodyID> mIgnoreBodies;
  1210. };
  1211. for (int mode = 0; mode < 2; mode++)
  1212. {
  1213. PhysicsTestContext c;
  1214. Vec3 gravity = c.GetSystem()->GetGravity();
  1215. Vec3 upside_down_gravity = -gravity;
  1216. // Create the ground.
  1217. Body &ground = c.CreateFloor();
  1218. // Create two sets of bodies that each overlap
  1219. Body &box1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1220. Body &sphere1 = c.CreateSphere(RVec3(0, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1221. Body &box2 = c.CreateBox(RVec3(5, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1222. Body &sphere2 = c.CreateSphere(RVec3(5, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1223. // Store the absolute initial state, that will be used for the final test.
  1224. StateRecorderImpl absolute_initial_state;
  1225. c.GetSystem()->SaveState(absolute_initial_state);
  1226. EStateRecorderState state_to_save = EStateRecorderState::All;
  1227. MyFilter filter;
  1228. if (mode == 1)
  1229. {
  1230. // Don't save the global state
  1231. state_to_save = EStateRecorderState(uint(EStateRecorderState::All) ^ uint(EStateRecorderState::Global));
  1232. // Don't save some bodies
  1233. filter.mIgnoreBodies.push_back(ground.GetID());
  1234. filter.mIgnoreBodies.push_back(box2.GetID());
  1235. filter.mIgnoreBodies.push_back(sphere2.GetID());
  1236. }
  1237. // Store the initial transform.
  1238. const RMat44 initial_box1_transform = box1.GetWorldTransform();
  1239. const RMat44 initial_sphere1_transform = sphere1.GetWorldTransform();
  1240. const RMat44 initial_box2_transform = box2.GetWorldTransform();
  1241. const RMat44 initial_sphere2_transform = sphere2.GetWorldTransform();
  1242. // Save partial state
  1243. StateRecorderImpl initial_state;
  1244. c.GetSystem()->SaveState(initial_state, state_to_save, &filter);
  1245. // Simulate for 2 seconds
  1246. c.Simulate(2.0f);
  1247. // The bodies should have moved and come to rest
  1248. const RMat44 intermediate_box1_transform = box1.GetWorldTransform();
  1249. const RMat44 intermediate_sphere1_transform = sphere1.GetWorldTransform();
  1250. const RMat44 intermediate_box2_transform = box2.GetWorldTransform();
  1251. const RMat44 intermediate_sphere2_transform = sphere2.GetWorldTransform();
  1252. CHECK(intermediate_box1_transform != initial_box1_transform);
  1253. CHECK(intermediate_sphere1_transform != initial_sphere1_transform);
  1254. CHECK(intermediate_box2_transform != initial_box2_transform);
  1255. CHECK(intermediate_sphere2_transform != initial_sphere2_transform);
  1256. CHECK(!box1.IsActive());
  1257. CHECK(!sphere1.IsActive());
  1258. CHECK(!box2.IsActive());
  1259. CHECK(!sphere2.IsActive());
  1260. // Save the intermediate state.
  1261. StateRecorderImpl intermediate_state;
  1262. c.GetSystem()->SaveState(intermediate_state, state_to_save, &filter);
  1263. // Change the gravity.
  1264. c.GetSystem()->SetGravity(upside_down_gravity);
  1265. // Restore the initial state.
  1266. c.GetSystem()->RestoreState(initial_state);
  1267. // Make sure the state is properly set back to the initial state.
  1268. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1269. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1270. CHECK(box1.IsActive());
  1271. CHECK(sphere1.IsActive());
  1272. if (mode == 0)
  1273. {
  1274. // Make sure the gravity is restored.
  1275. CHECK(c.GetSystem()->GetGravity() == gravity);
  1276. // The second set of bodies should have been restored as well
  1277. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1278. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1279. CHECK(box2.IsActive());
  1280. CHECK(sphere2.IsActive());
  1281. }
  1282. else
  1283. {
  1284. // Make sure the gravity is NOT restored.
  1285. CHECK(c.GetSystem()->GetGravity() == upside_down_gravity);
  1286. c.GetSystem()->SetGravity(gravity);
  1287. // The second set of bodies should NOT have been restored
  1288. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1289. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1290. CHECK(!box2.IsActive());
  1291. CHECK(!sphere2.IsActive());
  1292. // Apply a velocity to the second set of bodies to make sure they are active again
  1293. c.GetBodyInterface().SetLinearVelocity(box2.GetID(), Vec3(0, 0, 0.1f));
  1294. c.GetBodyInterface().SetLinearVelocity(sphere2.GetID(), Vec3(0, 0, 0.1f));
  1295. }
  1296. // Simulate for 2 seconds - again
  1297. c.Simulate(2.0f);
  1298. // The first set of bodies have been saved and should have returned to the same positions again
  1299. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1300. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1301. CHECK(!box1.IsActive());
  1302. CHECK(!sphere1.IsActive());
  1303. if (mode == 0)
  1304. {
  1305. // The second set of bodies have been saved and should have returned to the same positions again
  1306. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1307. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1308. CHECK(!box2.IsActive());
  1309. CHECK(!sphere2.IsActive());
  1310. }
  1311. else
  1312. {
  1313. // The second set of bodies have not been saved and should have moved on
  1314. CHECK(box2.GetWorldTransform() != intermediate_box2_transform);
  1315. CHECK(sphere2.GetWorldTransform() != intermediate_sphere2_transform);
  1316. CHECK(!box2.IsActive());
  1317. CHECK(sphere2.IsActive()); // The sphere keeps rolling
  1318. }
  1319. // Save the final state
  1320. StateRecorderImpl final_state;
  1321. c.GetSystem()->SaveState(final_state, state_to_save, &filter);
  1322. // Compare the states to make sure they are the same
  1323. CHECK(final_state.IsEqual(intermediate_state));
  1324. // Now restore the absolute initial state and make sure all the
  1325. // bodies are being active and ready to be processed again
  1326. c.GetSystem()->RestoreState(absolute_initial_state);
  1327. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1328. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1329. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1330. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1331. CHECK(box1.IsActive());
  1332. CHECK(sphere1.IsActive());
  1333. CHECK(box2.IsActive());
  1334. CHECK(sphere2.IsActive());
  1335. // Save the state of a single body
  1336. StateRecorderImpl single_body;
  1337. c.GetSystem()->SaveBodyState(box2, single_body);
  1338. // Simulate for 2 seconds - again
  1339. c.Simulate(2.0f);
  1340. // We should have reached the same state as before
  1341. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1342. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1343. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1344. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1345. CHECK(!box1.IsActive());
  1346. CHECK(!sphere1.IsActive());
  1347. CHECK(!box2.IsActive());
  1348. CHECK(!sphere2.IsActive());
  1349. // Restore the single body
  1350. c.GetSystem()->RestoreBodyState(box2, single_body);
  1351. // Only that body should have been restored
  1352. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1353. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1354. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1355. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1356. CHECK(!box1.IsActive());
  1357. CHECK(!sphere1.IsActive());
  1358. CHECK(box2.IsActive());
  1359. CHECK(!sphere2.IsActive());
  1360. }
  1361. }
  1362. // This tests that when switching UseManifoldReduction on/off we get the correct contact callbacks
  1363. TEST_CASE("TestSwitchUseManifoldReduction")
  1364. {
  1365. PhysicsTestContext c;
  1366. // Install listener
  1367. LoggingContactListener contact_listener;
  1368. c.GetSystem()->SetContactListener(&contact_listener);
  1369. // Create floor
  1370. Body &floor = c.CreateFloor();
  1371. // Create a compound with 4 boxes
  1372. Ref<BoxShape> box_shape = new BoxShape(Vec3::sReplicate(2));
  1373. Ref<StaticCompoundShapeSettings> shape_settings = new StaticCompoundShapeSettings();
  1374. shape_settings->AddShape(Vec3(5, 0, 0), Quat::sIdentity(), box_shape);
  1375. shape_settings->AddShape(Vec3(-5, 0, 0), Quat::sIdentity(), box_shape);
  1376. shape_settings->AddShape(Vec3(0, 0, 5), Quat::sIdentity(), box_shape);
  1377. shape_settings->AddShape(Vec3(0, 0, -5), Quat::sIdentity(), box_shape);
  1378. RefConst<StaticCompoundShape> compound_shape = static_cast<const StaticCompoundShape *>(shape_settings->Create().Get().GetPtr());
  1379. SubShapeID sub_shape_ids[] = {
  1380. compound_shape->GetSubShapeIDFromIndex(0, SubShapeIDCreator()).GetID(),
  1381. compound_shape->GetSubShapeIDFromIndex(1, SubShapeIDCreator()).GetID(),
  1382. compound_shape->GetSubShapeIDFromIndex(2, SubShapeIDCreator()).GetID(),
  1383. compound_shape->GetSubShapeIDFromIndex(3, SubShapeIDCreator()).GetID()
  1384. };
  1385. // Embed body a little bit into the floor so we immediately get contact callbacks
  1386. BodyCreationSettings body_settings(compound_shape, RVec3(0, 1.99_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1387. body_settings.mUseManifoldReduction = true;
  1388. BodyID body_id = c.GetBodyInterface().CreateAndAddBody(body_settings, EActivation::Activate);
  1389. // Trigger contact callbacks
  1390. c.SimulateSingleStep();
  1391. // Since manifold reduction is on and the contacts will be coplanar we should only get 1 contact with the floor
  1392. // Note that which sub shape ID we get is deterministic but not guaranteed to be a particular value, sub_shape_ids[3] is the one it currently returns!!
  1393. CHECK(contact_listener.GetEntryCount() == 5); // 4x validate + 1x add
  1394. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1395. contact_listener.Clear();
  1396. // Now disable manifold reduction
  1397. c.GetBodyInterface().SetUseManifoldReduction(body_id, false);
  1398. // Trigger contact callbacks
  1399. c.SimulateSingleStep();
  1400. // Now manifold reduction is off so we should get collisions with each of the sub shapes
  1401. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x add
  1402. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1403. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1404. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1405. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1406. contact_listener.Clear();
  1407. // Now enable manifold reduction again
  1408. c.GetBodyInterface().SetUseManifoldReduction(body_id, true);
  1409. // Trigger contact callbacks
  1410. c.SimulateSingleStep();
  1411. // We should be back to the first state now where we only have 1 contact
  1412. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x remove
  1413. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1414. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1415. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1416. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1417. }
  1418. }