PhysicsTests.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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. // Scale the mass and check that the mass and inertia are correct
  288. const float cNewMass = 2.0f;
  289. b1.GetMotionProperties()->ScaleToMass(cNewMass);
  290. const Vec3 cNewExpectedInertiaDiagonal = cNewMass / 12.0f * cSquaredExtents;
  291. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseMass(), 1.0f / cNewMass);
  292. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  293. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseInertiaDiagonal(), cNewExpectedInertiaDiagonal.Reciprocal());
  294. // Override only the mass
  295. const float cOverriddenMass = 13.0f;
  296. const Vec3 cOverriddenMassInertiaDiagonal = cOverriddenMass / 12.0f * cSquaredExtents;
  297. body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  298. body_settings.mMassPropertiesOverride.mMass = cOverriddenMass;
  299. Body &b2 = *bi.CreateBody(body_settings);
  300. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  301. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  302. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenMassInertiaDiagonal.Reciprocal());
  303. // Override both the mass and inertia
  304. 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
  305. const Quat cOverriddenInertiaRotation = Quat::sRotation(Vec3(1, 1, 1).Normalized(), 0.1f * JPH_PI);
  306. body_settings.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  307. body_settings.mMassPropertiesOverride.mInertia = Mat44::sRotation(cOverriddenInertiaRotation) * Mat44::sScale(cOverriddenInertiaDiagonal) * Mat44::sRotation(cOverriddenInertiaRotation.Inversed());
  308. Body &b3 = *bi.CreateBody(body_settings);
  309. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  310. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInertiaRotation(), cOverriddenInertiaRotation);
  311. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenInertiaDiagonal.Reciprocal());
  312. }
  313. // Test a box free falling under gravity
  314. static void TestPhysicsFreeFall(PhysicsTestContext &ioContext)
  315. {
  316. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  317. const float cSimulationTime = 2.0f;
  318. // Create box
  319. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  320. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  321. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  322. ioContext.Simulate(cSimulationTime);
  323. // Test resulting velocity (due to gravity)
  324. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  325. // Test resulting position
  326. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  327. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  328. }
  329. TEST_CASE("TestPhysicsFreeFall")
  330. {
  331. PhysicsTestContext c1(1.0f / 60.0f, 1);
  332. TestPhysicsFreeFall(c1);
  333. PhysicsTestContext c2(2.0f / 60.0f, 2);
  334. TestPhysicsFreeFall(c2);
  335. PhysicsTestContext c4(4.0f / 60.0f, 4);
  336. TestPhysicsFreeFall(c4);
  337. }
  338. // Test acceleration of a box with force applied
  339. static void TestPhysicsApplyForce(PhysicsTestContext &ioContext)
  340. {
  341. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  342. const Vec3 cAcceleration(2.0f, 0.0f, 0.0f);
  343. const float cSimulationTime = 2.0f;
  344. // Create box
  345. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  346. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  347. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  348. // Validate mass
  349. float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  350. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  351. // Simulate while applying force
  352. ioContext.Simulate(cSimulationTime, [&]() { body.AddForce(mass * cAcceleration); });
  353. // Test resulting velocity (due to gravity and applied force)
  354. CHECK_APPROX_EQUAL(cSimulationTime * (cGravity + cAcceleration), body.GetLinearVelocity(), 1.0e-4f);
  355. // Test resulting position
  356. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity + cAcceleration, cSimulationTime);
  357. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  358. }
  359. TEST_CASE("TestPhysicsApplyForce")
  360. {
  361. PhysicsTestContext c1(1.0f / 60.0f, 1);
  362. TestPhysicsApplyForce(c1);
  363. PhysicsTestContext c2(2.0f / 60.0f, 2);
  364. TestPhysicsApplyForce(c2);
  365. PhysicsTestContext c4(4.0f / 60.0f, 4);
  366. TestPhysicsApplyForce(c4);
  367. }
  368. // Test angular acceleration for a box by applying torque every frame
  369. static void TestPhysicsApplyTorque(PhysicsTestContext &ioContext)
  370. {
  371. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  372. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  373. const float cSimulationTime = 2.0f;
  374. // Create box
  375. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  376. CHECK_APPROX_EQUAL(Quat::sIdentity(), body.GetRotation());
  377. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  378. // Validate mass and inertia
  379. constexpr float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  380. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  381. constexpr float inertia = mass * 8.0f / 12.0f; // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  382. CHECK_APPROX_EQUAL(Mat44::sScale(1.0f / inertia), body.GetMotionProperties()->GetLocalSpaceInverseInertia());
  383. // Simulate while applying torque
  384. ioContext.Simulate(cSimulationTime, [&]() { body.AddTorque(inertia * cAngularAcceleration); });
  385. // Get resulting angular velocity
  386. CHECK_APPROX_EQUAL(cSimulationTime * cAngularAcceleration, body.GetAngularVelocity(), 1.0e-4f);
  387. // Test resulting rotation
  388. Quat expected_rot = ioContext.PredictOrientation(Quat::sIdentity(), Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  389. CHECK_APPROX_EQUAL(expected_rot, body.GetRotation(), 1.0e-4f);
  390. }
  391. TEST_CASE("TestPhysicsApplyTorque")
  392. {
  393. PhysicsTestContext c1(1.0f / 60.0f, 1);
  394. TestPhysicsApplyTorque(c1);
  395. PhysicsTestContext c2(2.0f / 60.0f, 2);
  396. TestPhysicsApplyTorque(c2);
  397. PhysicsTestContext c4(4.0f / 60.0f, 4);
  398. TestPhysicsApplyTorque(c4);
  399. }
  400. // Let a sphere bounce on the floor with restitution = 1
  401. static void TestPhysicsCollisionElastic(PhysicsTestContext &ioContext)
  402. {
  403. const float cSimulationTime = 1.0f;
  404. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  405. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  406. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  407. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  408. // Create sphere
  409. ioContext.CreateFloor();
  410. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  411. body.SetRestitution(1.0f);
  412. // Simulate until at floor
  413. ioContext.Simulate(cSimulationTime);
  414. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  415. // Assert collision not yet processed
  416. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  417. // Simulate one more step to process the collision
  418. ioContext.SimulateSingleStep();
  419. // Assert that collision is processed and velocity is reversed (which is required for a fully elastic collision).
  420. float sub_step_delta_time = ioContext.GetStepDeltaTime();
  421. float remaining_step_time = ioContext.GetDeltaTime() - ioContext.GetStepDeltaTime();
  422. Vec3 reflected_velocity_after_sub_step = -cSimulationTime * cGravity;
  423. Vec3 reflected_velocity_after_full_step = reflected_velocity_after_sub_step + remaining_step_time * cGravity;
  424. CHECK_APPROX_EQUAL(reflected_velocity_after_full_step, body.GetLinearVelocity(), 1.0e-4f);
  425. // Body should have bounced back
  426. RVec3 pos_after_bounce_sub_step = cFloorHitPos + reflected_velocity_after_sub_step * sub_step_delta_time;
  427. RVec3 pos_after_bounce_full_step = ioContext.PredictPosition(pos_after_bounce_sub_step, reflected_velocity_after_sub_step, cGravity, remaining_step_time);
  428. CHECK_APPROX_EQUAL(pos_after_bounce_full_step, body.GetPosition());
  429. // Simulate same time minus one step, with a fully elastic body we should reach the initial position again
  430. RVec3 expected_pos = ioContext.PredictPosition(pos_after_bounce_full_step, reflected_velocity_after_full_step, cGravity, cSimulationTime - ioContext.GetDeltaTime());
  431. ioContext.Simulate(cSimulationTime - ioContext.GetDeltaTime());
  432. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition(), 1.0e-5f);
  433. CHECK_APPROX_EQUAL(expected_pos, cInitialPos, 1.0e-5f);
  434. // If we do one more step, we should be going down again
  435. RVec3 pre_step_pos = body.GetPosition();
  436. CHECK(body.GetLinearVelocity().GetY() > 0.0f);
  437. ioContext.SimulateSingleStep();
  438. CHECK(body.GetLinearVelocity().GetY() < 1.0e-6f);
  439. CHECK(body.GetPosition().GetY() < pre_step_pos.GetY() + 1.0e-6f);
  440. }
  441. TEST_CASE("TestPhysicsCollisionElastic")
  442. {
  443. PhysicsTestContext c1(1.0f / 60.0f, 1);
  444. TestPhysicsCollisionElastic(c1);
  445. PhysicsTestContext c2(2.0f / 60.0f, 2);
  446. TestPhysicsCollisionElastic(c2);
  447. PhysicsTestContext c4(4.0f / 60.0f, 4);
  448. TestPhysicsCollisionElastic(c4);
  449. }
  450. // Let a sphere with restitution 0.9 bounce on the floor
  451. TEST_CASE("TestPhysicsCollisionPartiallyElastic")
  452. {
  453. PhysicsTestContext c;
  454. c.CreateFloor();
  455. // Create sphere
  456. const RVec3 cInitialPos(0, 10, 0);
  457. constexpr float cRestitution = 0.9f;
  458. constexpr float cRadius = 2.0f;
  459. Body &body = c.CreateSphere(cInitialPos, cRadius, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  460. body.SetRestitution(cRestitution);
  461. // Simple simulation to compare with the actual simulation
  462. RVec3 pos = cInitialPos;
  463. Vec3 vel = Vec3::sZero();
  464. float dt = c.GetDeltaTime();
  465. float penetration_slop = c.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  466. for (int i = 0; i < 1000; ++i)
  467. {
  468. // Simple simulation
  469. Real penetration = cRadius - pos.GetY();
  470. if (penetration > -penetration_slop && vel.GetY() < 0.0f)
  471. vel = -cRestitution * vel;
  472. else
  473. vel += cGravity * dt;
  474. pos += vel * dt;
  475. // Actual step
  476. c.SimulateSingleStep();
  477. // Compare simulations
  478. CHECK_APPROX_EQUAL(pos, body.GetPosition(), 1.0e-5f);
  479. CHECK_APPROX_EQUAL(vel, body.GetLinearVelocity(), 1.0e-5f);
  480. }
  481. }
  482. // 2 spheres bounce with restitution = 1, tests we don't correct for gravity in a perpendicular direction to gravity
  483. static void TestPhysicsCollisionElasticDynamic(PhysicsTestContext &ioContext)
  484. {
  485. // Create spheres
  486. Body &sphere1 = ioContext.CreateSphere(RVec3(-2, 0, 0), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  487. sphere1.SetRestitution(1.0f);
  488. sphere1.SetLinearVelocity(Vec3(5, 0, 0));
  489. Body &sphere2 = ioContext.CreateSphere(RVec3(2, 0, 0), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  490. sphere2.SetRestitution(1.0f);
  491. sphere2.SetLinearVelocity(Vec3(-10, 0, 0));
  492. // Simulate
  493. constexpr float cSimulationTime = 1.0f;
  494. ioContext.Simulate(cSimulationTime);
  495. // Check that velocities match that of a fully elastic collision
  496. CHECK_APPROX_EQUAL(Vec3(-10, 0, 0) + cSimulationTime * cGravity, sphere1.GetLinearVelocity(), 1.0e-5f);
  497. CHECK_APPROX_EQUAL(Vec3(5, 0, 0) + cSimulationTime * cGravity, sphere2.GetLinearVelocity(), 1.0e-5f);
  498. }
  499. TEST_CASE("TestPhysicsCollisionElasticDynamic")
  500. {
  501. PhysicsTestContext c1(1.0f / 60.0f, 1);
  502. TestPhysicsCollisionElasticDynamic(c1);
  503. PhysicsTestContext c2(2.0f / 60.0f, 2);
  504. TestPhysicsCollisionElasticDynamic(c2);
  505. PhysicsTestContext c4(4.0f / 60.0f, 4);
  506. TestPhysicsCollisionElasticDynamic(c4);
  507. }
  508. // Let a sphere bounce on the floor with restitution = 0
  509. static void TestPhysicsCollisionInelastic(PhysicsTestContext &ioContext)
  510. {
  511. const float cSimulationTime = 1.0f;
  512. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  513. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  514. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  515. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  516. // Create sphere
  517. ioContext.CreateFloor();
  518. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  519. body.SetRestitution(0.0f);
  520. // Simulate until at floor
  521. ioContext.Simulate(cSimulationTime);
  522. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  523. // Assert collision not yet processed
  524. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  525. // Simulate one more step to process the collision
  526. ioContext.SimulateSingleStep();
  527. // Assert that all velocity was lost in the collision
  528. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  529. // Assert that we're on the floor
  530. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  531. // Simulate some more to validate that we remain on the floor
  532. ioContext.Simulate(cSimulationTime);
  533. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  534. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  535. }
  536. TEST_CASE("TestPhysicsCollisionInelastic")
  537. {
  538. PhysicsTestContext c1(1.0f / 60.0f, 1);
  539. TestPhysicsCollisionInelastic(c1);
  540. PhysicsTestContext c2(2.0f / 60.0f, 2);
  541. TestPhysicsCollisionInelastic(c2);
  542. PhysicsTestContext c4(4.0f / 60.0f, 4);
  543. TestPhysicsCollisionInelastic(c4);
  544. }
  545. // Let box intersect with floor by cPenetrationSlop. It should not move, this is the maximum penetration allowed.
  546. static void TestPhysicsPenetrationSlop1(PhysicsTestContext &ioContext)
  547. {
  548. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  549. const float cSimulationTime = 1.0f;
  550. const RVec3 cInitialPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  551. // Create box, penetrating with floor
  552. ioContext.CreateFloor();
  553. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  554. // Simulate
  555. ioContext.Simulate(cSimulationTime);
  556. // Test slop not resolved
  557. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  558. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  559. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  560. }
  561. TEST_CASE("TestPhysicsPenetrationSlop1")
  562. {
  563. PhysicsTestContext c1(1.0f / 60.0f, 1);
  564. TestPhysicsPenetrationSlop1(c1);
  565. PhysicsTestContext c2(2.0f / 60.0f, 2);
  566. TestPhysicsPenetrationSlop1(c2);
  567. PhysicsTestContext c4(4.0f / 60.0f, 4);
  568. TestPhysicsPenetrationSlop1(c4);
  569. }
  570. // Let box intersect with floor with more than cPenetrationSlop. It should be resolved by SolvePositionConstraint until interpenetration is cPenetrationSlop.
  571. static void TestPhysicsPenetrationSlop2(PhysicsTestContext &ioContext)
  572. {
  573. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  574. const float cSimulationTime = 1.0f;
  575. const RVec3 cInitialPos(0.0f, 1.0f - 2.0f * cPenetrationSlop, 0.0f);
  576. const RVec3 cFinalPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  577. // Create box, penetrating with floor
  578. ioContext.CreateFloor();
  579. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  580. // Simulate
  581. ioContext.Simulate(cSimulationTime);
  582. // Test resolved until slop
  583. CHECK_APPROX_EQUAL(cFinalPos, body.GetPosition(), 1.0e-5f);
  584. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  585. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  586. }
  587. TEST_CASE("TestPhysicsPenetrationSlop2")
  588. {
  589. PhysicsTestContext c1(1.0f / 60.0f, 1);
  590. TestPhysicsPenetrationSlop2(c1);
  591. PhysicsTestContext c2(2.0f / 60.0f, 2);
  592. TestPhysicsPenetrationSlop2(c2);
  593. PhysicsTestContext c4(4.0f / 60.0f, 4);
  594. TestPhysicsPenetrationSlop2(c4);
  595. }
  596. // Let box intersect with floor with less than cPenetrationSlop. Body should not move because SolveVelocityConstraint should reset velocity.
  597. static void TestPhysicsPenetrationSlop3(PhysicsTestContext &ioContext)
  598. {
  599. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  600. const float cSimulationTime = 1.0f;
  601. const RVec3 cInitialPos(0.0f, 1.0f - 0.1f * cPenetrationSlop, 0.0f);
  602. // Create box, penetrating with floor
  603. ioContext.CreateFloor();
  604. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  605. // Simulate
  606. ioContext.Simulate(cSimulationTime);
  607. // Test body remained static
  608. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  609. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  610. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  611. }
  612. TEST_CASE("TestPhysicsPenetrationSlop3")
  613. {
  614. PhysicsTestContext c1(1.0f / 60.0f, 1);
  615. TestPhysicsPenetrationSlop3(c1);
  616. PhysicsTestContext c2(2.0f / 60.0f, 2);
  617. TestPhysicsPenetrationSlop3(c2);
  618. PhysicsTestContext c4(4.0f / 60.0f, 4);
  619. TestPhysicsPenetrationSlop3(c4);
  620. }
  621. TEST_CASE("TestPhysicsOutsideOfSpeculativeContactDistance")
  622. {
  623. PhysicsTestContext c;
  624. Body &floor = c.CreateFloor();
  625. c.ZeroGravity();
  626. LoggingContactListener contact_listener;
  627. c.GetSystem()->SetContactListener(&contact_listener);
  628. // Create a box and a sphere just outside the speculative contact distance
  629. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  630. const float cDistanceAboveFloor = 1.1f * cSpeculativeContactDistance;
  631. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  632. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  633. // Make it move 1 m per step down
  634. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  635. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  636. box.SetLinearVelocity(cVelocity);
  637. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  638. sphere.SetLinearVelocity(cVelocity);
  639. // Simulate a step
  640. c.SimulateSingleStep();
  641. // 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)
  642. CHECK(contact_listener.GetEntryCount() == 0);
  643. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  644. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  645. // Simulate a step
  646. c.SimulateSingleStep();
  647. // Check that the contacts are detected now
  648. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  649. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  650. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  651. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  652. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  653. }
  654. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoRestitution")
  655. {
  656. PhysicsTestContext c;
  657. Body &floor = c.CreateFloor();
  658. c.ZeroGravity();
  659. LoggingContactListener contact_listener;
  660. c.GetSystem()->SetContactListener(&contact_listener);
  661. // Create a box and a sphere just inside the speculative contact distance
  662. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  663. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  664. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  665. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  666. // Make it move 1 m per step down
  667. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  668. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  669. box.SetLinearVelocity(cVelocity);
  670. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  671. sphere.SetLinearVelocity(cVelocity);
  672. // Simulate a step
  673. c.SimulateSingleStep();
  674. // Check that it is now on the floor and that 2 collisions have been detected
  675. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  676. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  677. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  678. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  679. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  680. contact_listener.Clear();
  681. // Velocity should have been reduced to exactly hit the floor in this step
  682. const Vec3 cExpectedVelocity(0, -cDistanceAboveFloor / c.GetDeltaTime(), 0);
  683. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  684. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  685. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cExpectedVelocity, 0.05f);
  686. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  687. // Sphere has only 1 contact point so is much more accurate
  688. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0));
  689. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cExpectedVelocity, 1.0e-4f);
  690. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  691. // Simulate a step
  692. c.SimulateSingleStep();
  693. // Check that the contacts persisted
  694. CHECK(contact_listener.GetEntryCount() >= 2); // 2 persist and possibly 2 validates depending on if the cache got reused
  695. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, box.GetID(), floor.GetID()));
  696. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  697. // Box should have come to rest
  698. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  699. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero(), 0.05f);
  700. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  701. // Sphere should have come to rest
  702. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0), 1.0e-4f);
  703. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), Vec3::sZero(), 1.0e-4f);
  704. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  705. }
  706. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceWithRestitution")
  707. {
  708. PhysicsTestContext c;
  709. Body &floor = c.CreateFloor();
  710. c.ZeroGravity();
  711. LoggingContactListener contact_listener;
  712. c.GetSystem()->SetContactListener(&contact_listener);
  713. // Create a box and a sphere just inside the speculative contact distance
  714. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  715. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  716. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  717. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  718. // Make it move 1 m per step down
  719. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  720. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  721. box.SetLinearVelocity(cVelocity);
  722. box.SetRestitution(1.0f);
  723. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  724. sphere.SetLinearVelocity(cVelocity);
  725. sphere.SetRestitution(1.0f);
  726. // Simulate a step
  727. c.SimulateSingleStep();
  728. // Check that it has triggered contact points and has bounced from it's initial position (effectively traveling the extra distance to the floor and back for free)
  729. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  730. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  731. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  732. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  733. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  734. contact_listener.Clear();
  735. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  736. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox - cVelocity * c.GetDeltaTime(), 0.01f);
  737. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), -cVelocity, 0.1f);
  738. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 0.02f);
  739. // Sphere has only 1 contact point so is much more accurate
  740. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere - cVelocity * c.GetDeltaTime(), 1.0e-5f);
  741. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), -cVelocity, 2.0e-4f);
  742. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 2.0e-4f);
  743. // Simulate a step
  744. c.SimulateSingleStep();
  745. // Check that all contact points are removed
  746. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  747. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  748. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  749. }
  750. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoHit")
  751. {
  752. PhysicsTestContext c;
  753. Body &floor = c.CreateFloor();
  754. floor.SetRestitution(1.0f);
  755. c.ZeroGravity();
  756. // Turn off the minimum velocity for restitution, our velocity is lower than the default
  757. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  758. settings.mMinVelocityForRestitution = 0.0f;
  759. c.GetSystem()->SetPhysicsSettings(settings);
  760. LoggingContactListener contact_listener;
  761. c.GetSystem()->SetContactListener(&contact_listener);
  762. // Create a sphere inside speculative contact distance from the ground
  763. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  764. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  765. const RVec3 cInitialPosSphere(0, 1.0f + cDistanceAboveFloor, 0.0f);
  766. // Make it move slow enough so that it will not touch the floor in 1 time step
  767. const Vec3 cVelocity(0, -0.9f * cDistanceAboveFloor / c.GetDeltaTime(), 0);
  768. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  769. sphere.SetLinearVelocity(cVelocity);
  770. sphere.SetRestitution(1.0f);
  771. sphere.GetMotionProperties()->SetLinearDamping(0.0f);
  772. // Simulate a step
  773. c.SimulateSingleStep();
  774. // Check that it has triggered contact points from the speculative contacts
  775. CHECK(contact_listener.GetEntryCount() == 2);
  776. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  777. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  778. contact_listener.Clear();
  779. // Check that sphere didn't actually change velocity (it hasn't actually interacted with the floor, the speculative contact was not an actual contact)
  780. CHECK(sphere.GetLinearVelocity() == cVelocity);
  781. // Simulate a step
  782. c.SimulateSingleStep();
  783. // Check again that it triggered contact points
  784. CHECK(contact_listener.GetEntryCount() == 2);
  785. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  786. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  787. contact_listener.Clear();
  788. // It should have bounced back up and inverted velocity due to restitution being 1
  789. CHECK_APPROX_EQUAL(-sphere.GetLinearVelocity(), cVelocity);
  790. }
  791. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceSensor")
  792. {
  793. PhysicsTestContext c;
  794. Body &floor = c.CreateFloor();
  795. c.ZeroGravity();
  796. LoggingContactListener contact_listener;
  797. c.GetSystem()->SetContactListener(&contact_listener);
  798. // Create a sphere sensor just inside the speculative contact distance
  799. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  800. const float cRadius = 1.0f;
  801. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  802. const RVec3 cInitialPosSphere(5, cRadius + cDistanceAboveFloor, 0);
  803. // Make it move 1 m per step down
  804. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  805. Body &sphere = c.CreateSphere(cInitialPosSphere, cRadius, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  806. sphere.SetIsSensor(true);
  807. sphere.SetLinearVelocity(cVelocity);
  808. // Simulate a step
  809. c.SimulateSingleStep();
  810. CHECK(contact_listener.GetEntryCount() == 0); // We're inside the speculative contact distance but we're a sensor so we shouldn't trigger any contacts
  811. // Simulate a step
  812. c.SimulateSingleStep();
  813. // Check that we're now actually intersecting
  814. CHECK(contact_listener.GetEntryCount() == 2); // 1 validates and 1 contact
  815. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  816. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  817. contact_listener.Clear();
  818. // Sensor should not be affected by the floor
  819. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + 2.0f * c.GetDeltaTime() * cVelocity);
  820. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  821. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  822. }
  823. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  824. {
  825. PhysicsTestContext c;
  826. Body &floor = c.CreateFloor();
  827. c.ZeroGravity();
  828. LoggingContactListener contact_listener;
  829. c.GetSystem()->SetContactListener(&contact_listener);
  830. // Create a box and a sphere just inside the speculative contact distance
  831. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  832. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  833. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  834. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  835. // Make it move 1 m per step up
  836. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  837. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  838. box.SetLinearVelocity(cVelocity);
  839. box.SetRestitution(1.0f);
  840. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  841. sphere.SetLinearVelocity(cVelocity);
  842. sphere.SetRestitution(1.0f);
  843. // Simulate a step
  844. c.SimulateSingleStep();
  845. // 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)
  846. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  847. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  848. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  849. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  850. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  851. contact_listener.Clear();
  852. // Box should have moved unimpeded
  853. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  854. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  855. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  856. // Sphere should have moved unimpeded
  857. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  858. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  859. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  860. // Simulate a step
  861. c.SimulateSingleStep();
  862. // Check that all contact points are removed
  863. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  864. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  865. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  866. }
  867. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  868. {
  869. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  870. // Install activation listener
  871. LoggingBodyActivationListener activation_listener;
  872. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  873. // Create floor
  874. Body &floor = ioContext.CreateBox(RVec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  875. CHECK(!floor.IsActive());
  876. // Create inactive box
  877. Body &box = ioContext.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  878. CHECK(!box.IsActive());
  879. CHECK(activation_listener.GetEntryCount() == 0);
  880. // Box should not activate by itself
  881. ioContext.Simulate(1.0f);
  882. CHECK(box.GetPosition() == RVec3(0, 5, 0));
  883. CHECK(!box.IsActive());
  884. CHECK(activation_listener.GetEntryCount() == 0);
  885. // Activate the body and validate it is active now
  886. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  887. CHECK(box.IsActive());
  888. CHECK(box.GetLinearVelocity().IsNearZero());
  889. CHECK(activation_listener.GetEntryCount() == 1);
  890. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  891. activation_listener.Clear();
  892. // Do a single step and check that the body is still active and has gained some velocity
  893. ioContext.SimulateSingleStep();
  894. CHECK(box.IsActive());
  895. CHECK(activation_listener.GetEntryCount() == 0);
  896. CHECK(!box.GetLinearVelocity().IsNearZero());
  897. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  898. ioContext.Simulate(5.0f);
  899. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  900. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  901. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  902. CHECK(!box.IsActive());
  903. CHECK(activation_listener.GetEntryCount() == 1);
  904. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  905. }
  906. TEST_CASE("TestPhysicsActivationDeactivation")
  907. {
  908. PhysicsTestContext c1(1.0f / 60.0f, 1);
  909. TestPhysicsActivationDeactivation(c1);
  910. PhysicsTestContext c2(2.0f / 60.0f, 2);
  911. TestPhysicsActivationDeactivation(c2);
  912. PhysicsTestContext c4(4.0f / 60.0f, 4);
  913. TestPhysicsActivationDeactivation(c4);
  914. }
  915. // 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
  916. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  917. {
  918. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  919. const int cNumBodies = 10;
  920. const float cBoxExtent = 0.5f;
  921. PhysicsSystem *system = ioContext.GetSystem();
  922. BodyInterface &bi = ioContext.GetBodyInterface();
  923. LoggingBodyActivationListener activation_listener;
  924. system->SetBodyActivationListener(&activation_listener);
  925. LoggingContactListener contact_listener;
  926. system->SetContactListener(&contact_listener);
  927. // 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
  928. BodyIDVector body_ids;
  929. if (inReverseCreate)
  930. for (int i = cNumBodies - 1; i >= 0; --i)
  931. 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());
  932. else
  933. for (int i = 0; i < cNumBodies; ++i)
  934. 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());
  935. // Test that nothing is active yet
  936. CHECK(activation_listener.GetEntryCount() == 0);
  937. CHECK(contact_listener.GetEntryCount() == 0);
  938. for (BodyID id : body_ids)
  939. CHECK(!bi.IsActive(id));
  940. // 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
  941. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  942. // Test that only the left most box is active
  943. CHECK(activation_listener.GetEntryCount() == 1);
  944. CHECK(contact_listener.GetEntryCount() == 0);
  945. CHECK(bi.IsActive(body_ids.front()));
  946. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  947. for (int i = 1; i < cNumBodies; ++i)
  948. CHECK(!bi.IsActive(body_ids[i]));
  949. activation_listener.Clear();
  950. // Step the world
  951. ioContext.SimulateSingleStep();
  952. // Other bodies should now be awake and each body should only collide with its neighbor
  953. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  954. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  955. for (int i = 0; i < cNumBodies; ++i)
  956. {
  957. BodyID id = body_ids[i];
  958. // Check body is active
  959. CHECK(bi.IsActive(id));
  960. // Check that body moved to the right
  961. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  962. }
  963. for (int i = 1; i < cNumBodies; ++i)
  964. {
  965. BodyID id1 = body_ids[i - 1];
  966. BodyID id2 = body_ids[i];
  967. // Check that we received activation events for each body
  968. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  969. // Check that we received a validate and an add for each body pair
  970. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  971. CHECK(validate >= 0);
  972. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  973. CHECK(add >= 0);
  974. CHECK(add > validate);
  975. // Check that bodies did not tunnel through each other
  976. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  977. }
  978. }
  979. TEST_CASE("TestPhysicsActivateDuringStep")
  980. {
  981. PhysicsTestContext c;
  982. TestPhysicsActivateDuringStep(c, false);
  983. PhysicsTestContext c2;
  984. TestPhysicsActivateDuringStep(c2, true);
  985. }
  986. TEST_CASE("TestPhysicsBroadPhaseLayers")
  987. {
  988. PhysicsTestContext c;
  989. BodyInterface &bi = c.GetBodyInterface();
  990. // Reduce slop
  991. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  992. settings.mPenetrationSlop = 0.0f;
  993. c.GetSystem()->SetPhysicsSettings(settings);
  994. // Create static floor
  995. c.CreateFloor();
  996. // Create MOVING boxes
  997. Body &moving1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  998. Body &moving2 = c.CreateBox(RVec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  999. // Create HQ_DEBRIS boxes
  1000. Body &hq_debris1 = c.CreateBox(RVec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1001. Body &hq_debris2 = c.CreateBox(RVec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1002. // Create LQ_DEBRIS boxes
  1003. Body &lq_debris1 = c.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1004. Body &lq_debris2 = c.CreateBox(RVec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1005. // Check layers
  1006. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  1007. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  1008. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1009. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1010. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1011. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1012. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1013. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1014. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1015. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1016. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1017. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1018. // Simulate the boxes falling
  1019. c.Simulate(5.0f);
  1020. // Everything should sleep
  1021. CHECK_FALSE(moving1.IsActive());
  1022. CHECK_FALSE(moving2.IsActive());
  1023. CHECK_FALSE(hq_debris1.IsActive());
  1024. CHECK_FALSE(hq_debris2.IsActive());
  1025. CHECK_FALSE(lq_debris1.IsActive());
  1026. CHECK_FALSE(lq_debris2.IsActive());
  1027. // MOVING boxes should have stacked
  1028. float slop = 0.02f;
  1029. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1030. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  1031. // HQ_DEBRIS boxes should have stacked on MOVING boxes but don't collide with each other
  1032. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 2.5f, 0), slop);
  1033. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 2.5f, 0), slop);
  1034. // LQ_DEBRIS should have fallen through all but the floor
  1035. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1036. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1037. // Now change HQ_DEBRIS to LQ_DEBRIS
  1038. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  1039. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  1040. bi.ActivateBody(hq_debris1.GetID());
  1041. bi.ActivateBody(hq_debris2.GetID());
  1042. // Check layers
  1043. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  1044. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  1045. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1046. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1047. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1048. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1049. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1050. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1051. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1052. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1053. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1054. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1055. // Simulate again
  1056. c.Simulate(5.0f);
  1057. // Everything should sleep
  1058. CHECK_FALSE(moving1.IsActive());
  1059. CHECK_FALSE(moving2.IsActive());
  1060. CHECK_FALSE(hq_debris1.IsActive());
  1061. CHECK_FALSE(hq_debris2.IsActive());
  1062. CHECK_FALSE(lq_debris1.IsActive());
  1063. CHECK_FALSE(lq_debris2.IsActive());
  1064. // MOVING boxes should have stacked
  1065. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1066. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  1067. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1068. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1069. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1070. // LQ_DEBRIS should have fallen through all but the floor
  1071. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1072. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1073. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  1074. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  1075. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  1076. bi.ActivateBody(moving1.GetID());
  1077. bi.ActivateBody(moving2.GetID());
  1078. // Check layers
  1079. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1080. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1081. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1082. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1083. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1084. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1085. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  1086. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1087. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1088. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1089. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1090. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1091. // Simulate again
  1092. c.Simulate(5.0f);
  1093. // Everything should sleep
  1094. CHECK_FALSE(moving1.IsActive());
  1095. CHECK_FALSE(moving2.IsActive());
  1096. CHECK_FALSE(hq_debris1.IsActive());
  1097. CHECK_FALSE(hq_debris2.IsActive());
  1098. CHECK_FALSE(lq_debris1.IsActive());
  1099. CHECK_FALSE(lq_debris2.IsActive());
  1100. // MOVING boxes now also fall through
  1101. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1102. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1103. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1104. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1105. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1106. // LQ_DEBRIS should have fallen through all but the floor
  1107. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1108. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1109. }
  1110. TEST_CASE("TestMultiplePhysicsSystems")
  1111. {
  1112. PhysicsTestContext c1;
  1113. c1.ZeroGravity();
  1114. PhysicsTestContext c2;
  1115. c2.ZeroGravity();
  1116. const RVec3 cBox1Position(1.0f, 2.0f, 3.0f);
  1117. Body &box1 = c1.CreateBox(cBox1Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1118. const RVec3 cBox2Position(4.0f, 5.0f, 6.0f);
  1119. Body& box2 = c2.CreateBox(cBox2Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1120. const Vec3 cBox1Velocity(1.0f, 0, 0);
  1121. const Vec3 cBox2Velocity(2.0f, 0, 0);
  1122. {
  1123. // 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)
  1124. BodyLockWrite lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1125. BodyLockWrite lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1126. CHECK(lock1.GetBody().GetPosition() == cBox1Position);
  1127. CHECK(lock2.GetBody().GetPosition() == cBox2Position);
  1128. lock1.GetBody().SetLinearVelocity(cBox1Velocity);
  1129. lock2.GetBody().SetLinearVelocity(cBox2Velocity);
  1130. }
  1131. const float cTime = 1.0f;
  1132. c1.Simulate(cTime);
  1133. c2.Simulate(cTime);
  1134. {
  1135. BodyLockRead lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1136. BodyLockRead lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1137. // Check that the bodies in the different systems updated correctly
  1138. CHECK_APPROX_EQUAL(lock1.GetBody().GetPosition(), cBox1Position + cBox1Velocity * cTime, 1.0e-5f);
  1139. CHECK_APPROX_EQUAL(lock2.GetBody().GetPosition(), cBox2Position + cBox2Velocity * cTime, 1.0e-5f);
  1140. }
  1141. }
  1142. TEST_CASE("TestOutOfBodies")
  1143. {
  1144. // Create a context with space for a single body
  1145. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1);
  1146. BodyInterface& bi = c.GetBodyInterface();
  1147. // First body
  1148. Body *b1 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1149. CHECK(b1 != nullptr);
  1150. // Second body should fail
  1151. Body *b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1152. CHECK(b2 == nullptr);
  1153. // Free first body
  1154. bi.DestroyBody(b1->GetID());
  1155. // Second body creation should succeed
  1156. b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1157. CHECK(b2 != nullptr);
  1158. // Clean up
  1159. bi.DestroyBody(b2->GetID());
  1160. }
  1161. TEST_CASE("TestOutOfContactConstraints")
  1162. {
  1163. // Create a context with space for 8 constraints
  1164. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1165. c.CreateFloor();
  1166. // The first 8 boxes should be fine
  1167. for (int i = 0; i < 8; ++i)
  1168. 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);
  1169. // Step
  1170. EPhysicsUpdateError errors = c.SimulateSingleStep();
  1171. CHECK(errors == EPhysicsUpdateError::None);
  1172. // Adding one more box should introduce an error
  1173. c.CreateBox(RVec3(24.0_r, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1174. // Step
  1175. {
  1176. JPH_IF_ENABLE_ASSERTS(ExpectAssert expect_assert(1);)
  1177. errors = c.SimulateSingleStep();
  1178. }
  1179. CHECK((errors & EPhysicsUpdateError::ContactConstraintsFull) != EPhysicsUpdateError::None);
  1180. }
  1181. TEST_CASE("TestFriction")
  1182. {
  1183. const float friction_floor = 0.9f;
  1184. const float friction_box = 0.8f;
  1185. const float combined_friction = sqrt(friction_floor * friction_box);
  1186. for (float angle = 0; angle < 360.0f; angle += 30.0f)
  1187. {
  1188. // Create a context with space for 8 constraints
  1189. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1190. // Create floor
  1191. Body &floor = c.CreateFloor();
  1192. floor.SetFriction(friction_floor);
  1193. // Create box with a velocity that will make it slide over the floor (making sure it intersects a little bit initially)
  1194. BodyCreationSettings box_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3(0, 0.999_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1195. box_settings.mFriction = friction_box;
  1196. box_settings.mLinearDamping = 0;
  1197. box_settings.mLinearVelocity = Vec3(Sin(DegreesToRadians(angle)), 0, Cos(DegreesToRadians(angle))) * 20.0f;
  1198. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1199. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1200. // We know that the friction force equals the normal force times the friction coefficient
  1201. float friction_acceleration = combined_friction * c.GetSystem()->GetGravity().Length();
  1202. // Simulate
  1203. Vec3 velocity = box_settings.mLinearVelocity;
  1204. RVec3 position = box_settings.mPosition;
  1205. for (int i = 0; i < 60; ++i)
  1206. {
  1207. c.SimulateSingleStep();
  1208. // Integrate our own simulation
  1209. velocity -= velocity.Normalized() * friction_acceleration * c.GetDeltaTime();
  1210. position += velocity * c.GetDeltaTime();
  1211. }
  1212. // Note that the result is not very accurate so we need quite a high tolerance
  1213. CHECK_APPROX_EQUAL(box.GetCenterOfMassPosition(), position, 1.0e-2f);
  1214. CHECK_APPROX_EQUAL(box.GetRotation(), box_settings.mRotation, 1.0e-2f);
  1215. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), velocity, 2.0e-2f);
  1216. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  1217. }
  1218. }
  1219. TEST_CASE("TestAllowedDOFs")
  1220. {
  1221. for (uint allowed_dofs = 1; allowed_dofs <= 0b111111; ++allowed_dofs)
  1222. {
  1223. // Create a context
  1224. PhysicsTestContext c;
  1225. c.ZeroGravity();
  1226. // Create box
  1227. RVec3 initial_position(1, 2, 3);
  1228. Quat initial_rotation = Quat::sRotation(Vec3::sReplicate(sqrt(1.0f / 3.0f)), DegreesToRadians(20.0f));
  1229. ShapeRefC box_shape = new BoxShape(Vec3(0.3f, 0.5f, 0.7f));
  1230. BodyCreationSettings box_settings(box_shape, initial_position, initial_rotation, EMotionType::Dynamic, Layers::MOVING);
  1231. box_settings.mLinearDamping = 0;
  1232. box_settings.mAngularDamping = 0;
  1233. box_settings.mAllowedDOFs = (EAllowedDOFs)allowed_dofs;
  1234. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1235. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1236. // Apply a force and torque in 3D
  1237. Vec3 force(100000, 110000, 120000);
  1238. box.AddForce(force);
  1239. Vec3 torque(13000, 14000, 15000);
  1240. box.AddTorque(torque);
  1241. // Simulate
  1242. c.SimulateSingleStep();
  1243. // Cancel components that should not be allowed by the allowed DOFs
  1244. Vec3 linear_lock = Vec3::sReplicate(1.0f), angular_lock = Vec3::sReplicate(1.0f);
  1245. for (uint axis = 0; axis < 3; ++axis)
  1246. {
  1247. if ((allowed_dofs & (1 << axis)) == 0)
  1248. linear_lock.SetComponent(axis, 0.0f);
  1249. if ((allowed_dofs & (0b1000 << axis)) == 0)
  1250. angular_lock.SetComponent(axis, 0.0f);
  1251. }
  1252. // Check resulting linear velocity
  1253. MassProperties mp = box_shape->GetMassProperties();
  1254. Vec3 expected_linear_velocity = linear_lock * (force / mp.mMass * c.GetDeltaTime());
  1255. CHECK((linear_lock == Vec3::sZero() || expected_linear_velocity.Length() > 1.0f)); // Just to check that we applied a high enough force
  1256. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), expected_linear_velocity);
  1257. RVec3 expected_position = initial_position + expected_linear_velocity * c.GetDeltaTime();
  1258. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position);
  1259. // Check resulting angular velocity
  1260. Mat44 inv_inertia = Mat44::sRotation(initial_rotation) * mp.mInertia.Inversed3x3() * Mat44::sRotation(initial_rotation.Conjugated());
  1261. inv_inertia = Mat44::sScale(angular_lock) * inv_inertia * Mat44::sScale(angular_lock); // Clear row and column for locked axes
  1262. Vec3 expected_angular_velocity = inv_inertia * torque * c.GetDeltaTime();
  1263. CHECK((angular_lock == Vec3::sZero() || expected_angular_velocity.Length() > 1.0f)); // Just to check that we applied a high enough torque
  1264. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), expected_angular_velocity);
  1265. float expected_angular_velocity_len = expected_angular_velocity.Length();
  1266. 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;
  1267. CHECK_APPROX_EQUAL(box.GetRotation(), expected_rotation);
  1268. }
  1269. }
  1270. TEST_CASE("TestAllowedDOFsVsCollision")
  1271. {
  1272. PhysicsTestContext c;
  1273. Body &floor = c.CreateFloor();
  1274. floor.SetFriction(1.0f);
  1275. LoggingContactListener contact_listener;
  1276. c.GetSystem()->SetContactListener(&contact_listener);
  1277. // Create box that can only rotate around Y that intersects with the floor
  1278. RVec3 initial_position(0, 0.99f, 0);
  1279. BodyCreationSettings box_settings(new BoxShape(Vec3::sReplicate(1.0f)), initial_position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1280. box_settings.mAllowedDOFs = EAllowedDOFs::RotationY;
  1281. box_settings.mAngularDamping = 0.0f; // No damping to make the calculation for expected angular velocity simple
  1282. box_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  1283. box_settings.mMassPropertiesOverride.mMass = 1.0f;
  1284. box_settings.mFriction = 1.0f; // High friction so that if the collision is processed, we'll slow down the rotation
  1285. Body *body = c.GetBodyInterface().CreateBody(box_settings);
  1286. c.GetBodyInterface().AddBody(body->GetID(), EActivation::Activate);
  1287. // Make the box rotate around Y
  1288. const Vec3 torque(0, 100.0f, 0);
  1289. body->AddTorque(torque);
  1290. // Simulate a step, this will make the box collide with the floor but should not result in the floor stopping the body
  1291. // 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
  1292. c.SimulateSingleStep();
  1293. // Check that we did detect the collision
  1294. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), body->GetID()));
  1295. // Check that we have the correct angular velocity
  1296. Vec3 expected_angular_velocity = torque * c.GetDeltaTime() * body->GetInverseInertia()(1, 1);
  1297. CHECK_APPROX_EQUAL(body->GetAngularVelocity(), expected_angular_velocity);
  1298. CHECK(body->GetLinearVelocity() == Vec3::sZero());
  1299. CHECK(body->GetPosition() == initial_position);
  1300. }
  1301. TEST_CASE("TestSelectiveStateSaveAndRestore")
  1302. {
  1303. class MyFilter : public StateRecorderFilter
  1304. {
  1305. public:
  1306. bool ShouldSaveBody(const BodyID &inBodyID) const
  1307. {
  1308. return std::find(mIgnoreBodies.cbegin(), mIgnoreBodies.cend(), inBodyID) == mIgnoreBodies.cend();
  1309. }
  1310. virtual bool ShouldSaveBody(const Body &inBody) const override
  1311. {
  1312. return ShouldSaveBody(inBody.GetID());
  1313. }
  1314. virtual bool ShouldSaveContact(const BodyID &inBody1, const BodyID &inBody2) const override
  1315. {
  1316. return ShouldSaveBody(inBody1) && ShouldSaveBody(inBody2);
  1317. }
  1318. Array<BodyID> mIgnoreBodies;
  1319. };
  1320. for (int mode = 0; mode < 2; mode++)
  1321. {
  1322. PhysicsTestContext c;
  1323. Vec3 gravity = c.GetSystem()->GetGravity();
  1324. Vec3 upside_down_gravity = -gravity;
  1325. // Create the ground.
  1326. Body &ground = c.CreateFloor();
  1327. // Create two sets of bodies that each overlap
  1328. Body &box1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1329. Body &sphere1 = c.CreateSphere(RVec3(0, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1330. Body &box2 = c.CreateBox(RVec3(5, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1331. Body &sphere2 = c.CreateSphere(RVec3(5, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1332. // Store the absolute initial state, that will be used for the final test.
  1333. StateRecorderImpl absolute_initial_state;
  1334. c.GetSystem()->SaveState(absolute_initial_state);
  1335. EStateRecorderState state_to_save = EStateRecorderState::All;
  1336. MyFilter filter;
  1337. if (mode == 1)
  1338. {
  1339. // Don't save the global state
  1340. state_to_save = EStateRecorderState::All ^ EStateRecorderState::Global;
  1341. // Don't save some bodies
  1342. filter.mIgnoreBodies.push_back(ground.GetID());
  1343. filter.mIgnoreBodies.push_back(box2.GetID());
  1344. filter.mIgnoreBodies.push_back(sphere2.GetID());
  1345. }
  1346. // Store the initial transform.
  1347. const RMat44 initial_box1_transform = box1.GetWorldTransform();
  1348. const RMat44 initial_sphere1_transform = sphere1.GetWorldTransform();
  1349. const RMat44 initial_box2_transform = box2.GetWorldTransform();
  1350. const RMat44 initial_sphere2_transform = sphere2.GetWorldTransform();
  1351. // Save partial state
  1352. StateRecorderImpl initial_state;
  1353. c.GetSystem()->SaveState(initial_state, state_to_save, &filter);
  1354. // Simulate for 2 seconds
  1355. c.Simulate(2.0f);
  1356. // The bodies should have moved and come to rest
  1357. const RMat44 intermediate_box1_transform = box1.GetWorldTransform();
  1358. const RMat44 intermediate_sphere1_transform = sphere1.GetWorldTransform();
  1359. const RMat44 intermediate_box2_transform = box2.GetWorldTransform();
  1360. const RMat44 intermediate_sphere2_transform = sphere2.GetWorldTransform();
  1361. CHECK(intermediate_box1_transform != initial_box1_transform);
  1362. CHECK(intermediate_sphere1_transform != initial_sphere1_transform);
  1363. CHECK(intermediate_box2_transform != initial_box2_transform);
  1364. CHECK(intermediate_sphere2_transform != initial_sphere2_transform);
  1365. CHECK(!box1.IsActive());
  1366. CHECK(!sphere1.IsActive());
  1367. CHECK(!box2.IsActive());
  1368. CHECK(!sphere2.IsActive());
  1369. // Save the intermediate state.
  1370. StateRecorderImpl intermediate_state;
  1371. c.GetSystem()->SaveState(intermediate_state, state_to_save, &filter);
  1372. // Change the gravity.
  1373. c.GetSystem()->SetGravity(upside_down_gravity);
  1374. // Restore the initial state.
  1375. c.GetSystem()->RestoreState(initial_state);
  1376. // Make sure the state is properly set back to the initial state.
  1377. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1378. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1379. CHECK(box1.IsActive());
  1380. CHECK(sphere1.IsActive());
  1381. if (mode == 0)
  1382. {
  1383. // Make sure the gravity is restored.
  1384. CHECK(c.GetSystem()->GetGravity() == gravity);
  1385. // The second set of bodies should have been restored as well
  1386. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1387. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1388. CHECK(box2.IsActive());
  1389. CHECK(sphere2.IsActive());
  1390. }
  1391. else
  1392. {
  1393. // Make sure the gravity is NOT restored.
  1394. CHECK(c.GetSystem()->GetGravity() == upside_down_gravity);
  1395. c.GetSystem()->SetGravity(gravity);
  1396. // The second set of bodies should NOT have been restored
  1397. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1398. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1399. CHECK(!box2.IsActive());
  1400. CHECK(!sphere2.IsActive());
  1401. // Apply a velocity to the second set of bodies to make sure they are active again
  1402. c.GetBodyInterface().SetLinearVelocity(box2.GetID(), Vec3(0, 0, 0.1f));
  1403. c.GetBodyInterface().SetLinearVelocity(sphere2.GetID(), Vec3(0, 0, 0.1f));
  1404. }
  1405. // Simulate for 2 seconds - again
  1406. c.Simulate(2.0f);
  1407. // The first set of bodies have been saved and should have returned to the same positions again
  1408. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1409. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1410. CHECK(!box1.IsActive());
  1411. CHECK(!sphere1.IsActive());
  1412. if (mode == 0)
  1413. {
  1414. // The second set of bodies have been saved and should have returned to the same positions again
  1415. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1416. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1417. CHECK(!box2.IsActive());
  1418. CHECK(!sphere2.IsActive());
  1419. }
  1420. else
  1421. {
  1422. // The second set of bodies have not been saved and should have moved on
  1423. CHECK(box2.GetWorldTransform() != intermediate_box2_transform);
  1424. CHECK(sphere2.GetWorldTransform() != intermediate_sphere2_transform);
  1425. CHECK(!box2.IsActive());
  1426. CHECK(sphere2.IsActive()); // The sphere keeps rolling
  1427. }
  1428. // Save the final state
  1429. StateRecorderImpl final_state;
  1430. c.GetSystem()->SaveState(final_state, state_to_save, &filter);
  1431. // Compare the states to make sure they are the same
  1432. CHECK(final_state.IsEqual(intermediate_state));
  1433. // Now restore the absolute initial state and make sure all the
  1434. // bodies are being active and ready to be processed again
  1435. c.GetSystem()->RestoreState(absolute_initial_state);
  1436. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1437. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1438. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1439. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1440. CHECK(box1.IsActive());
  1441. CHECK(sphere1.IsActive());
  1442. CHECK(box2.IsActive());
  1443. CHECK(sphere2.IsActive());
  1444. // Save the state of a single body
  1445. StateRecorderImpl single_body;
  1446. c.GetSystem()->SaveBodyState(box2, single_body);
  1447. // Simulate for 2 seconds - again
  1448. c.Simulate(2.0f);
  1449. // We should have reached the same state as before
  1450. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1451. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1452. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1453. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1454. CHECK(!box1.IsActive());
  1455. CHECK(!sphere1.IsActive());
  1456. CHECK(!box2.IsActive());
  1457. CHECK(!sphere2.IsActive());
  1458. // Restore the single body
  1459. c.GetSystem()->RestoreBodyState(box2, single_body);
  1460. // Only that body should have been restored
  1461. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1462. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1463. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1464. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1465. CHECK(!box1.IsActive());
  1466. CHECK(!sphere1.IsActive());
  1467. CHECK(box2.IsActive());
  1468. CHECK(!sphere2.IsActive());
  1469. }
  1470. }
  1471. TEST_CASE("TestMultiPartRestoreState")
  1472. {
  1473. class MyFilter : public StateRecorderFilter
  1474. {
  1475. public:
  1476. MyFilter(const Array<BodyID> &inStoredBodies) : mStoredBodies(inStoredBodies) { }
  1477. bool ShouldSaveBody(const BodyID &inBodyID) const
  1478. {
  1479. return std::find(mStoredBodies.cbegin(), mStoredBodies.cend(), inBodyID) != mStoredBodies.cend();
  1480. }
  1481. virtual bool ShouldSaveBody(const Body &inBody) const override
  1482. {
  1483. if (ShouldSaveBody(inBody.GetID()))
  1484. {
  1485. ++mNumBodies;
  1486. return true;
  1487. }
  1488. return false;
  1489. }
  1490. virtual bool ShouldSaveContact(const BodyID &inBody1, const BodyID &inBody2) const override
  1491. {
  1492. if (ShouldSaveBody(inBody1) || ShouldSaveBody(inBody2))
  1493. {
  1494. ++mNumContacts;
  1495. return true;
  1496. }
  1497. return false;
  1498. }
  1499. const Array<BodyID> & mStoredBodies;
  1500. mutable int mNumBodies = 0;
  1501. mutable int mNumContacts = 0;
  1502. };
  1503. PhysicsTestContext c;
  1504. c.CreateFloor();
  1505. // Create 1st set of moving bodies
  1506. constexpr int cNumMoving1 = 10;
  1507. Array<BodyID> moving1;
  1508. for (int i = 0; i < cNumMoving1; ++i)
  1509. moving1.push_back(c.CreateSphere(RVec3(0, 2.0f + 2.0f * i, 0.01f * i), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate).GetID());
  1510. // Create 2nd set of moving bodies, note that although the bodies overlap with the 1st set, they don't collide because of their layer.
  1511. // We need to create disjoint sets for restoring in parts to work.
  1512. constexpr int cNumMoving2 = 12;
  1513. Array<BodyID> moving2;
  1514. for (int i = 0; i < cNumMoving2; ++i)
  1515. moving2.push_back(c.CreateSphere(RVec3(1.0f, 2.0f + 2.0f * i, 0.01f * i), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING2, EActivation::Activate).GetID());
  1516. // Simulate for a short while to get some contacts
  1517. c.Simulate(2.0f);
  1518. // Save full snapshot
  1519. StateRecorderImpl initial_state;
  1520. c.GetSystem()->SaveState(initial_state);
  1521. // Save everything relating to 1st set of bodies
  1522. MyFilter filter1(moving1);
  1523. StateRecorderImpl state1;
  1524. c.GetSystem()->SaveState(state1, EStateRecorderState::All, &filter1);
  1525. CHECK(filter1.mNumBodies == cNumMoving1);
  1526. CHECK(filter1.mNumContacts > cNumMoving1 / 2); // Many bodies should be in contact now, if not we're not testing contact restoring
  1527. CHECK(state1.GetDataSize() < initial_state.GetDataSize()); // Should be smaller than the full state
  1528. // Save everything relating to 2nd set of bodies
  1529. MyFilter filter2(moving2);
  1530. StateRecorderImpl state2;
  1531. c.GetSystem()->SaveState(state2, EStateRecorderState::Bodies | EStateRecorderState::Contacts, &filter2);
  1532. CHECK(filter2.mNumBodies == cNumMoving2);
  1533. CHECK(filter2.mNumContacts > cNumMoving2 / 2);
  1534. CHECK(state2.GetDataSize() < initial_state.GetDataSize());
  1535. // Simulate for 2 seconds
  1536. c.Simulate(2.0f);
  1537. // Save result
  1538. StateRecorderImpl final_state;
  1539. c.GetSystem()->SaveState(final_state);
  1540. // Restore the initial state in parts
  1541. state1.SetIsLastPart(false);
  1542. c.GetSystem()->RestoreState(state1);
  1543. c.GetSystem()->RestoreState(state2);
  1544. // Verify we're back to the first state
  1545. StateRecorderImpl verify1;
  1546. c.GetSystem()->SaveState(verify1);
  1547. CHECK(initial_state.IsEqual(verify1));
  1548. // Simulate for 2 seconds again
  1549. c.Simulate(2.0f);
  1550. // Check we end up in the final state again
  1551. StateRecorderImpl verify2;
  1552. c.GetSystem()->SaveState(verify2);
  1553. CHECK(final_state.IsEqual(verify2));
  1554. }
  1555. // This tests that when switching UseManifoldReduction on/off we get the correct contact callbacks
  1556. TEST_CASE("TestSwitchUseManifoldReduction")
  1557. {
  1558. PhysicsTestContext c;
  1559. // Install listener
  1560. LoggingContactListener contact_listener;
  1561. c.GetSystem()->SetContactListener(&contact_listener);
  1562. // Create floor
  1563. Body &floor = c.CreateFloor();
  1564. // Create a compound with 4 boxes
  1565. Ref<BoxShape> box_shape = new BoxShape(Vec3::sReplicate(2));
  1566. Ref<StaticCompoundShapeSettings> shape_settings = new StaticCompoundShapeSettings();
  1567. shape_settings->AddShape(Vec3(5, 0, 0), Quat::sIdentity(), box_shape);
  1568. shape_settings->AddShape(Vec3(-5, 0, 0), Quat::sIdentity(), box_shape);
  1569. shape_settings->AddShape(Vec3(0, 0, 5), Quat::sIdentity(), box_shape);
  1570. shape_settings->AddShape(Vec3(0, 0, -5), Quat::sIdentity(), box_shape);
  1571. RefConst<StaticCompoundShape> compound_shape = StaticCast<StaticCompoundShape>(shape_settings->Create().Get());
  1572. SubShapeID sub_shape_ids[] = {
  1573. compound_shape->GetSubShapeIDFromIndex(0, SubShapeIDCreator()).GetID(),
  1574. compound_shape->GetSubShapeIDFromIndex(1, SubShapeIDCreator()).GetID(),
  1575. compound_shape->GetSubShapeIDFromIndex(2, SubShapeIDCreator()).GetID(),
  1576. compound_shape->GetSubShapeIDFromIndex(3, SubShapeIDCreator()).GetID()
  1577. };
  1578. // Embed body a little bit into the floor so we immediately get contact callbacks
  1579. BodyCreationSettings body_settings(compound_shape, RVec3(0, 1.99_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1580. body_settings.mUseManifoldReduction = true;
  1581. BodyID body_id = c.GetBodyInterface().CreateAndAddBody(body_settings, EActivation::Activate);
  1582. // Trigger contact callbacks
  1583. c.SimulateSingleStep();
  1584. // Since manifold reduction is on and the contacts will be coplanar we should only get 1 contact with the floor
  1585. // 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!!
  1586. CHECK(contact_listener.GetEntryCount() == 5); // 4x validate + 1x add
  1587. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1588. contact_listener.Clear();
  1589. // Now disable manifold reduction
  1590. c.GetBodyInterface().SetUseManifoldReduction(body_id, false);
  1591. // Trigger contact callbacks
  1592. c.SimulateSingleStep();
  1593. // Now manifold reduction is off so we should get collisions with each of the sub shapes
  1594. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x add
  1595. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1596. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1597. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1598. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1599. contact_listener.Clear();
  1600. // Now enable manifold reduction again
  1601. c.GetBodyInterface().SetUseManifoldReduction(body_id, true);
  1602. // Trigger contact callbacks
  1603. c.SimulateSingleStep();
  1604. // We should be back to the first state now where we only have 1 contact
  1605. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x remove
  1606. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1607. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1608. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1609. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1610. }
  1611. }