PhysicsTests.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  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("TestPhysicsInsideSpeculativeContactDistanceSensor")
  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 sphere sensor just inside the speculative contact distance
  756. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  757. const float cRadius = 1.0f;
  758. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  759. const RVec3 cInitialPosSphere(5, cRadius + cDistanceAboveFloor, 0);
  760. // Make it move 1 m per step down
  761. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  762. Body &sphere = c.CreateSphere(cInitialPosSphere, cRadius, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  763. sphere.SetIsSensor(true);
  764. sphere.SetLinearVelocity(cVelocity);
  765. // Simulate a step
  766. c.SimulateSingleStep();
  767. CHECK(contact_listener.GetEntryCount() == 0); // We're inside the speculative contact distance but we're a sensor so we shouldn't trigger any contacts
  768. // Simulate a step
  769. c.SimulateSingleStep();
  770. // Check that we're now actually intersecting
  771. CHECK(contact_listener.GetEntryCount() == 2); // 1 validates and 1 contact
  772. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  773. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  774. contact_listener.Clear();
  775. // Sensor should not be affected by the floor
  776. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + 2.0f * c.GetDeltaTime() * cVelocity);
  777. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  778. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  779. }
  780. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  781. {
  782. PhysicsTestContext c;
  783. Body &floor = c.CreateFloor();
  784. c.ZeroGravity();
  785. LoggingContactListener contact_listener;
  786. c.GetSystem()->SetContactListener(&contact_listener);
  787. // Create a box and a sphere just inside the speculative contact distance
  788. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  789. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  790. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  791. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  792. // Make it move 1 m per step up
  793. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  794. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  795. box.SetLinearVelocity(cVelocity);
  796. box.SetRestitution(1.0f);
  797. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  798. sphere.SetLinearVelocity(cVelocity);
  799. sphere.SetRestitution(1.0f);
  800. // Simulate a step
  801. c.SimulateSingleStep();
  802. // 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)
  803. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  804. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  805. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  806. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  807. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  808. contact_listener.Clear();
  809. // Box should have moved unimpeded
  810. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  811. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  812. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  813. // Sphere should have moved unimpeded
  814. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  815. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  816. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  817. // Simulate a step
  818. c.SimulateSingleStep();
  819. // Check that all contact points are removed
  820. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  821. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  822. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  823. }
  824. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  825. {
  826. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  827. // Install activation listener
  828. LoggingBodyActivationListener activation_listener;
  829. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  830. // Create floor
  831. Body &floor = ioContext.CreateBox(RVec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  832. CHECK(!floor.IsActive());
  833. // Create inactive box
  834. Body &box = ioContext.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  835. CHECK(!box.IsActive());
  836. CHECK(activation_listener.GetEntryCount() == 0);
  837. // Box should not activate by itself
  838. ioContext.Simulate(1.0f);
  839. CHECK(box.GetPosition() == RVec3(0, 5, 0));
  840. CHECK(!box.IsActive());
  841. CHECK(activation_listener.GetEntryCount() == 0);
  842. // Activate the body and validate it is active now
  843. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  844. CHECK(box.IsActive());
  845. CHECK(box.GetLinearVelocity().IsNearZero());
  846. CHECK(activation_listener.GetEntryCount() == 1);
  847. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  848. activation_listener.Clear();
  849. // Do a single step and check that the body is still active and has gained some velocity
  850. ioContext.SimulateSingleStep();
  851. CHECK(box.IsActive());
  852. CHECK(activation_listener.GetEntryCount() == 0);
  853. CHECK(!box.GetLinearVelocity().IsNearZero());
  854. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  855. ioContext.Simulate(5.0f);
  856. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  857. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  858. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  859. CHECK(!box.IsActive());
  860. CHECK(activation_listener.GetEntryCount() == 1);
  861. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  862. }
  863. TEST_CASE("TestPhysicsActivationDeactivation")
  864. {
  865. PhysicsTestContext c1(1.0f / 60.0f, 1);
  866. TestPhysicsActivationDeactivation(c1);
  867. PhysicsTestContext c2(2.0f / 60.0f, 2);
  868. TestPhysicsActivationDeactivation(c2);
  869. PhysicsTestContext c3(4.0f / 60.0f, 4);
  870. TestPhysicsActivationDeactivation(c3);
  871. }
  872. // 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
  873. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  874. {
  875. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  876. const int cNumBodies = 10;
  877. const float cBoxExtent = 0.5f;
  878. PhysicsSystem *system = ioContext.GetSystem();
  879. BodyInterface &bi = ioContext.GetBodyInterface();
  880. LoggingBodyActivationListener activation_listener;
  881. system->SetBodyActivationListener(&activation_listener);
  882. LoggingContactListener contact_listener;
  883. system->SetContactListener(&contact_listener);
  884. // 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
  885. BodyIDVector body_ids;
  886. if (inReverseCreate)
  887. for (int i = cNumBodies - 1; i >= 0; --i)
  888. 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());
  889. else
  890. for (int i = 0; i < cNumBodies; ++i)
  891. 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());
  892. // Test that nothing is active yet
  893. CHECK(activation_listener.GetEntryCount() == 0);
  894. CHECK(contact_listener.GetEntryCount() == 0);
  895. for (BodyID id : body_ids)
  896. CHECK(!bi.IsActive(id));
  897. // 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
  898. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  899. // Test that only the left most box is active
  900. CHECK(activation_listener.GetEntryCount() == 1);
  901. CHECK(contact_listener.GetEntryCount() == 0);
  902. CHECK(bi.IsActive(body_ids.front()));
  903. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  904. for (int i = 1; i < cNumBodies; ++i)
  905. CHECK(!bi.IsActive(body_ids[i]));
  906. activation_listener.Clear();
  907. // Step the world
  908. ioContext.SimulateSingleStep();
  909. // Other bodies should now be awake and each body should only collide with its neighbour
  910. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  911. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  912. for (int i = 0; i < cNumBodies; ++i)
  913. {
  914. BodyID id = body_ids[i];
  915. // Check body is active
  916. CHECK(bi.IsActive(id));
  917. // Check that body moved to the right
  918. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  919. }
  920. for (int i = 1; i < cNumBodies; ++i)
  921. {
  922. BodyID id1 = body_ids[i - 1];
  923. BodyID id2 = body_ids[i];
  924. // Check that we received activation events for each body
  925. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  926. // Check that we received a validate and an add for each body pair
  927. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  928. CHECK(validate >= 0);
  929. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  930. CHECK(add >= 0);
  931. CHECK(add > validate);
  932. // Check that bodies did not tunnel through each other
  933. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  934. }
  935. }
  936. TEST_CASE("TestPhysicsActivateDuringStep")
  937. {
  938. PhysicsTestContext c;
  939. TestPhysicsActivateDuringStep(c, false);
  940. PhysicsTestContext c2;
  941. TestPhysicsActivateDuringStep(c2, true);
  942. }
  943. TEST_CASE("TestPhysicsBroadPhaseLayers")
  944. {
  945. PhysicsTestContext c;
  946. BodyInterface &bi = c.GetBodyInterface();
  947. // Reduce slop
  948. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  949. settings.mPenetrationSlop = 0.0f;
  950. c.GetSystem()->SetPhysicsSettings(settings);
  951. // Create static floor
  952. c.CreateFloor();
  953. // Create MOVING boxes
  954. Body &moving1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  955. Body &moving2 = c.CreateBox(RVec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  956. // Create HQ_DEBRIS boxes
  957. Body &hq_debris1 = c.CreateBox(RVec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  958. Body &hq_debris2 = c.CreateBox(RVec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  959. // Create LQ_DEBRIS boxes
  960. Body &lq_debris1 = c.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  961. Body &lq_debris2 = c.CreateBox(RVec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  962. // Check layers
  963. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  964. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  965. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  966. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  967. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  968. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  969. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  970. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  971. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  972. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  973. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  974. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  975. // Simulate the boxes falling
  976. c.Simulate(5.0f);
  977. // Everything should sleep
  978. CHECK_FALSE(moving1.IsActive());
  979. CHECK_FALSE(moving2.IsActive());
  980. CHECK_FALSE(hq_debris1.IsActive());
  981. CHECK_FALSE(hq_debris2.IsActive());
  982. CHECK_FALSE(lq_debris1.IsActive());
  983. CHECK_FALSE(lq_debris2.IsActive());
  984. // MOVING boxes should have stacked
  985. float slop = 0.02f;
  986. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  987. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  988. // HQ_DEBRIS boxes should have stacked on MOVING boxes but don't collide with each other
  989. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 2.5f, 0), slop);
  990. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 2.5f, 0), slop);
  991. // LQ_DEBRIS should have fallen through all but the floor
  992. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  993. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  994. // Now change HQ_DEBRIS to LQ_DEBRIS
  995. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  996. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  997. bi.ActivateBody(hq_debris1.GetID());
  998. bi.ActivateBody(hq_debris2.GetID());
  999. // Check layers
  1000. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  1001. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  1002. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1003. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1004. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1005. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1006. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1007. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1008. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1009. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1010. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1011. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1012. // Simulate again
  1013. c.Simulate(5.0f);
  1014. // Everything should sleep
  1015. CHECK_FALSE(moving1.IsActive());
  1016. CHECK_FALSE(moving2.IsActive());
  1017. CHECK_FALSE(hq_debris1.IsActive());
  1018. CHECK_FALSE(hq_debris2.IsActive());
  1019. CHECK_FALSE(lq_debris1.IsActive());
  1020. CHECK_FALSE(lq_debris2.IsActive());
  1021. // MOVING boxes should have stacked
  1022. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1023. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  1024. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1025. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1026. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1027. // LQ_DEBRIS should have fallen through all but the floor
  1028. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1029. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1030. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  1031. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  1032. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  1033. bi.ActivateBody(moving1.GetID());
  1034. bi.ActivateBody(moving2.GetID());
  1035. // Check layers
  1036. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1037. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1038. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1039. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1040. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1041. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1042. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  1043. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1044. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1045. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1046. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1047. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1048. // Simulate again
  1049. c.Simulate(5.0f);
  1050. // Everything should sleep
  1051. CHECK_FALSE(moving1.IsActive());
  1052. CHECK_FALSE(moving2.IsActive());
  1053. CHECK_FALSE(hq_debris1.IsActive());
  1054. CHECK_FALSE(hq_debris2.IsActive());
  1055. CHECK_FALSE(lq_debris1.IsActive());
  1056. CHECK_FALSE(lq_debris2.IsActive());
  1057. // MOVING boxes now also fall through
  1058. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1059. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1060. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1061. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1062. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1063. // LQ_DEBRIS should have fallen through all but the floor
  1064. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1065. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1066. }
  1067. TEST_CASE("TestMultiplePhysicsSystems")
  1068. {
  1069. PhysicsTestContext c1;
  1070. c1.ZeroGravity();
  1071. PhysicsTestContext c2;
  1072. c2.ZeroGravity();
  1073. const RVec3 cBox1Position(1.0f, 2.0f, 3.0f);
  1074. Body &box1 = c1.CreateBox(cBox1Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1075. const RVec3 cBox2Position(4.0f, 5.0f, 6.0f);
  1076. Body& box2 = c2.CreateBox(cBox2Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1077. const Vec3 cBox1Velocity(1.0f, 0, 0);
  1078. const Vec3 cBox2Velocity(2.0f, 0, 0);
  1079. {
  1080. // 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)
  1081. BodyLockWrite lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1082. BodyLockWrite lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1083. CHECK(lock1.GetBody().GetPosition() == cBox1Position);
  1084. CHECK(lock2.GetBody().GetPosition() == cBox2Position);
  1085. lock1.GetBody().SetLinearVelocity(cBox1Velocity);
  1086. lock2.GetBody().SetLinearVelocity(cBox2Velocity);
  1087. }
  1088. const float cTime = 1.0f;
  1089. c1.Simulate(cTime);
  1090. c2.Simulate(cTime);
  1091. {
  1092. BodyLockRead lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1093. BodyLockRead lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1094. // Check that the bodies in the different systems updated correctly
  1095. CHECK_APPROX_EQUAL(lock1.GetBody().GetPosition(), cBox1Position + cBox1Velocity * cTime, 1.0e-5f);
  1096. CHECK_APPROX_EQUAL(lock2.GetBody().GetPosition(), cBox2Position + cBox2Velocity * cTime, 1.0e-5f);
  1097. }
  1098. }
  1099. TEST_CASE("TestOutOfBodies")
  1100. {
  1101. // Create a context with space for a single body
  1102. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1);
  1103. BodyInterface& bi = c.GetBodyInterface();
  1104. // First body
  1105. Body *b1 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1106. CHECK(b1 != nullptr);
  1107. // Second body should fail
  1108. Body *b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1109. CHECK(b2 == nullptr);
  1110. // Free first body
  1111. bi.DestroyBody(b1->GetID());
  1112. // Second body creation should succeed
  1113. b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1114. CHECK(b2 != nullptr);
  1115. // Clean up
  1116. bi.DestroyBody(b2->GetID());
  1117. }
  1118. TEST_CASE("TestOutOfContactConstraints")
  1119. {
  1120. // Create a context with space for 8 constraints
  1121. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1122. c.CreateFloor();
  1123. // The first 8 boxes should be fine
  1124. for (int i = 0; i < 8; ++i)
  1125. 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);
  1126. // Step
  1127. EPhysicsUpdateError errors = c.SimulateSingleStep();
  1128. CHECK(errors == EPhysicsUpdateError::None);
  1129. // Adding one more box should introduce an error
  1130. c.CreateBox(RVec3(24.0_r, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1131. // Step
  1132. {
  1133. JPH_IF_ENABLE_ASSERTS(ExpectAssert expect_assert(1);)
  1134. errors = c.SimulateSingleStep();
  1135. }
  1136. CHECK((errors & EPhysicsUpdateError::ContactConstraintsFull) != EPhysicsUpdateError::None);
  1137. }
  1138. TEST_CASE("TestFriction")
  1139. {
  1140. const float friction_floor = 0.9f;
  1141. const float friction_box = 0.8f;
  1142. const float combined_friction = sqrt(friction_floor * friction_box);
  1143. for (float angle = 0; angle < 360.0f; angle += 30.0f)
  1144. {
  1145. // Create a context with space for 8 constraints
  1146. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1147. // Create floor
  1148. Body &floor = c.CreateFloor();
  1149. floor.SetFriction(friction_floor);
  1150. // Create box with a velocity that will make it slide over the floor (making sure it intersects a little bit initially)
  1151. BodyCreationSettings box_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3(0, 0.999_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1152. box_settings.mFriction = friction_box;
  1153. box_settings.mLinearDamping = 0;
  1154. box_settings.mLinearVelocity = Vec3(Sin(DegreesToRadians(angle)), 0, Cos(DegreesToRadians(angle))) * 20.0f;
  1155. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1156. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1157. // We know that the friction force equals the normal force times the friction coefficient
  1158. float friction_acceleration = combined_friction * c.GetSystem()->GetGravity().Length();
  1159. // Simulate
  1160. Vec3 velocity = box_settings.mLinearVelocity;
  1161. RVec3 position = box_settings.mPosition;
  1162. for (int i = 0; i < 60; ++i)
  1163. {
  1164. c.SimulateSingleStep();
  1165. // Integrate our own simulation
  1166. velocity -= velocity.Normalized() * friction_acceleration * c.GetDeltaTime();
  1167. position += velocity * c.GetDeltaTime();
  1168. }
  1169. // Note that the result is not very accurate so we need quite a high tolerance
  1170. CHECK_APPROX_EQUAL(box.GetCenterOfMassPosition(), position, 1.0e-2f);
  1171. CHECK_APPROX_EQUAL(box.GetRotation(), box_settings.mRotation, 1.0e-2f);
  1172. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), velocity, 2.0e-2f);
  1173. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  1174. }
  1175. }
  1176. TEST_CASE("TestAllowedDOFs")
  1177. {
  1178. for (uint allowed_dofs = 1; allowed_dofs <= 0b111111; ++allowed_dofs)
  1179. {
  1180. // Create a context
  1181. PhysicsTestContext c;
  1182. c.ZeroGravity();
  1183. // Create box
  1184. RVec3 initial_position(1, 2, 3);
  1185. Quat initial_rotation = Quat::sRotation(Vec3::sReplicate(sqrt(1.0f / 3.0f)), DegreesToRadians(20.0f));
  1186. ShapeRefC box_shape = new BoxShape(Vec3(0.3f, 0.5f, 0.7f));
  1187. BodyCreationSettings box_settings(box_shape, initial_position, initial_rotation, EMotionType::Dynamic, Layers::MOVING);
  1188. box_settings.mLinearDamping = 0;
  1189. box_settings.mAngularDamping = 0;
  1190. box_settings.mAllowedDOFs = (EAllowedDOFs)allowed_dofs;
  1191. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1192. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1193. // Apply a force and torque in 3D
  1194. Vec3 force(100000, 110000, 120000);
  1195. box.AddForce(force);
  1196. Vec3 torque(13000, 14000, 15000);
  1197. box.AddTorque(torque);
  1198. // Simulate
  1199. c.SimulateSingleStep();
  1200. // Cancel components that should not be allowed by the allowed DOFs
  1201. Vec3 linear_lock = Vec3::sReplicate(1.0f), angular_lock = Vec3::sReplicate(1.0f);
  1202. for (uint axis = 0; axis < 3; ++axis)
  1203. {
  1204. if ((allowed_dofs & (1 << axis)) == 0)
  1205. linear_lock.SetComponent(axis, 0.0f);
  1206. if ((allowed_dofs & (0b1000 << axis)) == 0)
  1207. angular_lock.SetComponent(axis, 0.0f);
  1208. }
  1209. // Check resulting linear velocity
  1210. MassProperties mp = box_shape->GetMassProperties();
  1211. Vec3 expected_linear_velocity = linear_lock * (force / mp.mMass * c.GetDeltaTime());
  1212. CHECK((linear_lock == Vec3::sZero() || expected_linear_velocity.Length() > 1.0f)); // Just to check that we applied a high enough force
  1213. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), expected_linear_velocity);
  1214. RVec3 expected_position = initial_position + expected_linear_velocity * c.GetDeltaTime();
  1215. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position);
  1216. // Check resulting angular velocity
  1217. Mat44 inv_inertia = Mat44::sRotation(initial_rotation) * mp.mInertia.Inversed3x3() * Mat44::sRotation(initial_rotation.Conjugated());
  1218. inv_inertia = Mat44::sScale(angular_lock) * inv_inertia * Mat44::sScale(angular_lock); // Clear row and column for locked axes
  1219. Vec3 expected_angular_velocity = inv_inertia * torque * c.GetDeltaTime();
  1220. CHECK((angular_lock == Vec3::sZero() || expected_angular_velocity.Length() > 1.0f)); // Just to check that we applied a high enough torque
  1221. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), expected_angular_velocity);
  1222. float expected_angular_velocity_len = expected_angular_velocity.Length();
  1223. 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;
  1224. CHECK_APPROX_EQUAL(box.GetRotation(), expected_rotation);
  1225. }
  1226. }
  1227. TEST_CASE("TestAllowedDOFsVsCollision")
  1228. {
  1229. PhysicsTestContext c;
  1230. Body &floor = c.CreateFloor();
  1231. floor.SetFriction(1.0f);
  1232. LoggingContactListener contact_listener;
  1233. c.GetSystem()->SetContactListener(&contact_listener);
  1234. // Create box that can only rotate around Y that intersects with the floor
  1235. RVec3 initial_position(0, 0.99f, 0);
  1236. BodyCreationSettings box_settings(new BoxShape(Vec3::sReplicate(1.0f)), initial_position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1237. box_settings.mAllowedDOFs = EAllowedDOFs::RotationY;
  1238. box_settings.mAngularDamping = 0.0f; // No damping to make the calculation for expected angular velocity simple
  1239. box_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  1240. box_settings.mMassPropertiesOverride.mMass = 1.0f;
  1241. box_settings.mFriction = 1.0f; // High friction so that if the collision is processed, we'll slow down the rotation
  1242. Body *body = c.GetBodyInterface().CreateBody(box_settings);
  1243. c.GetBodyInterface().AddBody(body->GetID(), EActivation::Activate);
  1244. // Make the box rotate around Y
  1245. const Vec3 torque(0, 100.0f, 0);
  1246. body->AddTorque(torque);
  1247. // Simulate a step, this will make the box collide with the floor but should not result in the floor stopping the body
  1248. // but will cause the effective mass of the contact to become infinite so is a test if we are properly ignoring the contact in this case
  1249. c.SimulateSingleStep();
  1250. // Check that we did detect the collision
  1251. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), body->GetID()));
  1252. // Check that we have the correct angular velocity
  1253. Vec3 expected_angular_velocity = torque * c.GetDeltaTime() * body->GetInverseInertia()(1, 1);
  1254. CHECK_APPROX_EQUAL(body->GetAngularVelocity(), expected_angular_velocity);
  1255. CHECK(body->GetLinearVelocity() == Vec3::sZero());
  1256. CHECK(body->GetPosition() == initial_position);
  1257. }
  1258. TEST_CASE("TestSelectiveStateSaveAndRestore")
  1259. {
  1260. class MyFilter : public StateRecorderFilter
  1261. {
  1262. public:
  1263. bool ShouldSaveBody(const BodyID &inBodyID) const
  1264. {
  1265. return find(mIgnoreBodies.cbegin(), mIgnoreBodies.cend(), inBodyID) == mIgnoreBodies.cend();
  1266. }
  1267. virtual bool ShouldSaveBody(const Body &inBody) const override
  1268. {
  1269. return ShouldSaveBody(inBody.GetID());
  1270. }
  1271. virtual bool ShouldSaveContact(const BodyID &inBody1, const BodyID &inBody2) const override
  1272. {
  1273. return ShouldSaveBody(inBody1) && ShouldSaveBody(inBody2);
  1274. }
  1275. Array<BodyID> mIgnoreBodies;
  1276. };
  1277. for (int mode = 0; mode < 2; mode++)
  1278. {
  1279. PhysicsTestContext c;
  1280. Vec3 gravity = c.GetSystem()->GetGravity();
  1281. Vec3 upside_down_gravity = -gravity;
  1282. // Create the ground.
  1283. Body &ground = c.CreateFloor();
  1284. // Create two sets of bodies that each overlap
  1285. Body &box1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1286. Body &sphere1 = c.CreateSphere(RVec3(0, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1287. Body &box2 = c.CreateBox(RVec3(5, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1288. Body &sphere2 = c.CreateSphere(RVec3(5, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1289. // Store the absolute initial state, that will be used for the final test.
  1290. StateRecorderImpl absolute_initial_state;
  1291. c.GetSystem()->SaveState(absolute_initial_state);
  1292. EStateRecorderState state_to_save = EStateRecorderState::All;
  1293. MyFilter filter;
  1294. if (mode == 1)
  1295. {
  1296. // Don't save the global state
  1297. state_to_save = EStateRecorderState(uint(EStateRecorderState::All) ^ uint(EStateRecorderState::Global));
  1298. // Don't save some bodies
  1299. filter.mIgnoreBodies.push_back(ground.GetID());
  1300. filter.mIgnoreBodies.push_back(box2.GetID());
  1301. filter.mIgnoreBodies.push_back(sphere2.GetID());
  1302. }
  1303. // Store the initial transform.
  1304. const RMat44 initial_box1_transform = box1.GetWorldTransform();
  1305. const RMat44 initial_sphere1_transform = sphere1.GetWorldTransform();
  1306. const RMat44 initial_box2_transform = box2.GetWorldTransform();
  1307. const RMat44 initial_sphere2_transform = sphere2.GetWorldTransform();
  1308. // Save partial state
  1309. StateRecorderImpl initial_state;
  1310. c.GetSystem()->SaveState(initial_state, state_to_save, &filter);
  1311. // Simulate for 2 seconds
  1312. c.Simulate(2.0f);
  1313. // The bodies should have moved and come to rest
  1314. const RMat44 intermediate_box1_transform = box1.GetWorldTransform();
  1315. const RMat44 intermediate_sphere1_transform = sphere1.GetWorldTransform();
  1316. const RMat44 intermediate_box2_transform = box2.GetWorldTransform();
  1317. const RMat44 intermediate_sphere2_transform = sphere2.GetWorldTransform();
  1318. CHECK(intermediate_box1_transform != initial_box1_transform);
  1319. CHECK(intermediate_sphere1_transform != initial_sphere1_transform);
  1320. CHECK(intermediate_box2_transform != initial_box2_transform);
  1321. CHECK(intermediate_sphere2_transform != initial_sphere2_transform);
  1322. CHECK(!box1.IsActive());
  1323. CHECK(!sphere1.IsActive());
  1324. CHECK(!box2.IsActive());
  1325. CHECK(!sphere2.IsActive());
  1326. // Save the intermediate state.
  1327. StateRecorderImpl intermediate_state;
  1328. c.GetSystem()->SaveState(intermediate_state, state_to_save, &filter);
  1329. // Change the gravity.
  1330. c.GetSystem()->SetGravity(upside_down_gravity);
  1331. // Restore the initial state.
  1332. c.GetSystem()->RestoreState(initial_state);
  1333. // Make sure the state is properly set back to the initial state.
  1334. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1335. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1336. CHECK(box1.IsActive());
  1337. CHECK(sphere1.IsActive());
  1338. if (mode == 0)
  1339. {
  1340. // Make sure the gravity is restored.
  1341. CHECK(c.GetSystem()->GetGravity() == gravity);
  1342. // The second set of bodies should have been restored as well
  1343. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1344. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1345. CHECK(box2.IsActive());
  1346. CHECK(sphere2.IsActive());
  1347. }
  1348. else
  1349. {
  1350. // Make sure the gravity is NOT restored.
  1351. CHECK(c.GetSystem()->GetGravity() == upside_down_gravity);
  1352. c.GetSystem()->SetGravity(gravity);
  1353. // The second set of bodies should NOT have been restored
  1354. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1355. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1356. CHECK(!box2.IsActive());
  1357. CHECK(!sphere2.IsActive());
  1358. // Apply a velocity to the second set of bodies to make sure they are active again
  1359. c.GetBodyInterface().SetLinearVelocity(box2.GetID(), Vec3(0, 0, 0.1f));
  1360. c.GetBodyInterface().SetLinearVelocity(sphere2.GetID(), Vec3(0, 0, 0.1f));
  1361. }
  1362. // Simulate for 2 seconds - again
  1363. c.Simulate(2.0f);
  1364. // The first set of bodies have been saved and should have returned to the same positions again
  1365. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1366. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1367. CHECK(!box1.IsActive());
  1368. CHECK(!sphere1.IsActive());
  1369. if (mode == 0)
  1370. {
  1371. // The second set of bodies have been saved and should have returned to the same positions again
  1372. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1373. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1374. CHECK(!box2.IsActive());
  1375. CHECK(!sphere2.IsActive());
  1376. }
  1377. else
  1378. {
  1379. // The second set of bodies have not been saved and should have moved on
  1380. CHECK(box2.GetWorldTransform() != intermediate_box2_transform);
  1381. CHECK(sphere2.GetWorldTransform() != intermediate_sphere2_transform);
  1382. CHECK(!box2.IsActive());
  1383. CHECK(sphere2.IsActive()); // The sphere keeps rolling
  1384. }
  1385. // Save the final state
  1386. StateRecorderImpl final_state;
  1387. c.GetSystem()->SaveState(final_state, state_to_save, &filter);
  1388. // Compare the states to make sure they are the same
  1389. CHECK(final_state.IsEqual(intermediate_state));
  1390. // Now restore the absolute initial state and make sure all the
  1391. // bodies are being active and ready to be processed again
  1392. c.GetSystem()->RestoreState(absolute_initial_state);
  1393. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1394. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1395. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1396. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1397. CHECK(box1.IsActive());
  1398. CHECK(sphere1.IsActive());
  1399. CHECK(box2.IsActive());
  1400. CHECK(sphere2.IsActive());
  1401. // Save the state of a single body
  1402. StateRecorderImpl single_body;
  1403. c.GetSystem()->SaveBodyState(box2, single_body);
  1404. // Simulate for 2 seconds - again
  1405. c.Simulate(2.0f);
  1406. // We should have reached the same state as before
  1407. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1408. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1409. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1410. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1411. CHECK(!box1.IsActive());
  1412. CHECK(!sphere1.IsActive());
  1413. CHECK(!box2.IsActive());
  1414. CHECK(!sphere2.IsActive());
  1415. // Restore the single body
  1416. c.GetSystem()->RestoreBodyState(box2, single_body);
  1417. // Only that body should have been restored
  1418. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1419. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1420. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1421. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1422. CHECK(!box1.IsActive());
  1423. CHECK(!sphere1.IsActive());
  1424. CHECK(box2.IsActive());
  1425. CHECK(!sphere2.IsActive());
  1426. }
  1427. }
  1428. // This tests that when switching UseManifoldReduction on/off we get the correct contact callbacks
  1429. TEST_CASE("TestSwitchUseManifoldReduction")
  1430. {
  1431. PhysicsTestContext c;
  1432. // Install listener
  1433. LoggingContactListener contact_listener;
  1434. c.GetSystem()->SetContactListener(&contact_listener);
  1435. // Create floor
  1436. Body &floor = c.CreateFloor();
  1437. // Create a compound with 4 boxes
  1438. Ref<BoxShape> box_shape = new BoxShape(Vec3::sReplicate(2));
  1439. Ref<StaticCompoundShapeSettings> shape_settings = new StaticCompoundShapeSettings();
  1440. shape_settings->AddShape(Vec3(5, 0, 0), Quat::sIdentity(), box_shape);
  1441. shape_settings->AddShape(Vec3(-5, 0, 0), Quat::sIdentity(), box_shape);
  1442. shape_settings->AddShape(Vec3(0, 0, 5), Quat::sIdentity(), box_shape);
  1443. shape_settings->AddShape(Vec3(0, 0, -5), Quat::sIdentity(), box_shape);
  1444. RefConst<StaticCompoundShape> compound_shape = static_cast<const StaticCompoundShape *>(shape_settings->Create().Get().GetPtr());
  1445. SubShapeID sub_shape_ids[] = {
  1446. compound_shape->GetSubShapeIDFromIndex(0, SubShapeIDCreator()).GetID(),
  1447. compound_shape->GetSubShapeIDFromIndex(1, SubShapeIDCreator()).GetID(),
  1448. compound_shape->GetSubShapeIDFromIndex(2, SubShapeIDCreator()).GetID(),
  1449. compound_shape->GetSubShapeIDFromIndex(3, SubShapeIDCreator()).GetID()
  1450. };
  1451. // Embed body a little bit into the floor so we immediately get contact callbacks
  1452. BodyCreationSettings body_settings(compound_shape, RVec3(0, 1.99_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1453. body_settings.mUseManifoldReduction = true;
  1454. BodyID body_id = c.GetBodyInterface().CreateAndAddBody(body_settings, EActivation::Activate);
  1455. // Trigger contact callbacks
  1456. c.SimulateSingleStep();
  1457. // Since manifold reduction is on and the contacts will be coplanar we should only get 1 contact with the floor
  1458. // 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!!
  1459. CHECK(contact_listener.GetEntryCount() == 5); // 4x validate + 1x add
  1460. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1461. contact_listener.Clear();
  1462. // Now disable manifold reduction
  1463. c.GetBodyInterface().SetUseManifoldReduction(body_id, false);
  1464. // Trigger contact callbacks
  1465. c.SimulateSingleStep();
  1466. // Now manifold reduction is off so we should get collisions with each of the sub shapes
  1467. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x add
  1468. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1469. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1470. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1471. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1472. contact_listener.Clear();
  1473. // Now enable manifold reduction again
  1474. c.GetBodyInterface().SetUseManifoldReduction(body_id, true);
  1475. // Trigger contact callbacks
  1476. c.SimulateSingleStep();
  1477. // We should be back to the first state now where we only have 1 contact
  1478. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x remove
  1479. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1480. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1481. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1482. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1483. }
  1484. }