PhysicsTests.cpp 69 KB

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