PhysicsTests.cpp 57 KB

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