CharacterVirtualTests.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2022 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include "UnitTestFramework.h"
  5. #include "PhysicsTestContext.h"
  6. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  9. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  10. #include <Jolt/Physics/Character/CharacterVirtual.h>
  11. #include "Layers.h"
  12. TEST_SUITE("CharacterVirtualTests")
  13. {
  14. class Character : public CharacterContactListener
  15. {
  16. public:
  17. // Construct
  18. Character(PhysicsTestContext &ioContext) : mContext(ioContext) { }
  19. // Create the character
  20. void Create()
  21. {
  22. // Create capsule
  23. Ref<Shape> capsule = new CapsuleShape(0.5f * mHeightStanding, mRadiusStanding);
  24. mCharacterSettings.mShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * mHeightStanding + mRadiusStanding, 0), Quat::sIdentity(), capsule).Create().Get();
  25. // Configure supporting volume
  26. mCharacterSettings.mSupportingVolume = Plane(Vec3::sAxisY(), -mHeightStanding); // Accept contacts that touch the lower sphere of the capsule
  27. // Create character
  28. mCharacter = new CharacterVirtual(&mCharacterSettings, mInitialPosition, Quat::sIdentity(), 0, mContext.GetSystem());
  29. mCharacter->SetListener(this);
  30. mCharacter->SetCharacterVsCharacterCollision(&mCharacterVsCharacter);
  31. }
  32. // Step the character and the world
  33. void Step()
  34. {
  35. // Step the world
  36. mContext.SimulateSingleStep();
  37. // Determine new basic velocity
  38. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  39. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  40. Vec3 new_velocity;
  41. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  42. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  43. {
  44. // Assume velocity of ground when on ground
  45. new_velocity = ground_velocity;
  46. // Jump
  47. new_velocity += Vec3(0, mJumpSpeed, 0);
  48. mJumpSpeed = 0.0f;
  49. }
  50. else
  51. new_velocity = current_vertical_velocity;
  52. // Gravity
  53. PhysicsSystem *system = mContext.GetSystem();
  54. float delta_time = mContext.GetDeltaTime();
  55. new_velocity += system->GetGravity() * delta_time;
  56. // Player input
  57. new_velocity += mHorizontalSpeed;
  58. // Update character velocity
  59. mCharacter->SetLinearVelocity(new_velocity);
  60. RVec3 start_pos = GetPosition();
  61. // Update the character position
  62. TempAllocatorMalloc allocator;
  63. mCharacter->ExtendedUpdate(delta_time,
  64. system->GetGravity(),
  65. mUpdateSettings,
  66. system->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  67. system->GetDefaultLayerFilter(Layers::MOVING),
  68. { },
  69. { },
  70. allocator);
  71. // Calculate effective velocity in this step
  72. mEffectiveVelocity = Vec3(GetPosition() - start_pos) / delta_time;
  73. }
  74. // Simulate a longer period of time
  75. void Simulate(float inTime)
  76. {
  77. int num_steps = (int)round(inTime / mContext.GetDeltaTime());
  78. for (int step = 0; step < num_steps; ++step)
  79. Step();
  80. }
  81. // Get the number of active contacts
  82. size_t GetNumContacts() const
  83. {
  84. return mCharacter->GetActiveContacts().size();
  85. }
  86. // Check if the character is in contact with another body
  87. bool HasCollidedWith(const BodyID &inBody) const
  88. {
  89. return mCharacter->HasCollidedWith(inBody);
  90. }
  91. // Check if the character is in contact with another character
  92. bool HasCollidedWith(const CharacterVirtual *inCharacter) const
  93. {
  94. return mCharacter->HasCollidedWith(inCharacter);
  95. }
  96. // Get position of character
  97. RVec3 GetPosition() const
  98. {
  99. return mCharacter->GetPosition();
  100. }
  101. // Configuration
  102. RVec3 mInitialPosition = RVec3::sZero();
  103. float mHeightStanding = 1.35f;
  104. float mRadiusStanding = 0.3f;
  105. CharacterVirtualSettings mCharacterSettings;
  106. CharacterVirtual::ExtendedUpdateSettings mUpdateSettings;
  107. // Character movement settings (update to control the movement of the character)
  108. Vec3 mHorizontalSpeed = Vec3::sZero();
  109. float mJumpSpeed = 0.0f; // Character will jump when not 0, will auto reset
  110. // The character
  111. Ref<CharacterVirtual> mCharacter;
  112. // Character vs character
  113. CharacterVsCharacterCollisionSimple mCharacterVsCharacter;
  114. // Calculated effective velocity after a step
  115. Vec3 mEffectiveVelocity = Vec3::sZero();
  116. private:
  117. // CharacterContactListener callback
  118. virtual void OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) override
  119. {
  120. // Don't allow sliding if the character doesn't want to move
  121. if (mHorizontalSpeed.IsNearZero() && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  122. ioNewCharacterVelocity = Vec3::sZero();
  123. }
  124. PhysicsTestContext & mContext;
  125. };
  126. TEST_CASE("TestFallingAndJumping")
  127. {
  128. // Create floor
  129. PhysicsTestContext c;
  130. c.CreateFloor();
  131. // Create character
  132. Character character(c);
  133. character.mInitialPosition = RVec3(0, 2, 0);
  134. character.Create();
  135. // After 1 step we should still be in air
  136. character.Step();
  137. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  138. // After some time we should be on the floor
  139. character.Simulate(1.0f);
  140. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  141. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  142. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  143. // Jump
  144. character.mJumpSpeed = 1.0f;
  145. character.Step();
  146. Vec3 velocity(0, 1.0f + c.GetDeltaTime() * c.GetSystem()->GetGravity().GetY(), 0);
  147. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(velocity * c.GetDeltaTime()));
  148. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, velocity);
  149. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  150. // After some time we should be on the floor again
  151. character.Simulate(1.0f);
  152. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  153. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  154. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  155. }
  156. TEST_CASE("TestMovingOnSlope")
  157. {
  158. constexpr float cFloorHalfHeight = 1.0f;
  159. constexpr float cMovementTime = 1.5f;
  160. // Iterate various slope angles
  161. for (float slope_angle = DegreesToRadians(5.0f); slope_angle < DegreesToRadians(85.0f); slope_angle += DegreesToRadians(10.0f))
  162. {
  163. // Create sloped floor
  164. PhysicsTestContext c;
  165. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), slope_angle);
  166. c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  167. // Create character so that it is touching the slope
  168. Character character(c);
  169. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  170. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(slope_angle) - radius_and_padding, 0);
  171. character.Create();
  172. // Determine if the slope is too steep for the character
  173. bool too_steep = slope_angle > character.mCharacterSettings.mMaxSlopeAngle;
  174. CharacterBase::EGroundState expected_ground_state = (too_steep? CharacterBase::EGroundState::OnSteepGround : CharacterBase::EGroundState::OnGround);
  175. Vec3 gravity = c.GetSystem()->GetGravity();
  176. float time_step = c.GetDeltaTime();
  177. Vec3 slope_normal = slope_rotation.RotateAxisY();
  178. // Calculate expected position after 1 time step
  179. RVec3 position_after_1_step = character.mInitialPosition;
  180. if (too_steep)
  181. {
  182. // Apply 1 frame of gravity and cancel movement in the slope normal direction
  183. Vec3 velocity = gravity * time_step;
  184. velocity -= velocity.Dot(slope_normal) * slope_normal;
  185. position_after_1_step += velocity * time_step;
  186. }
  187. // After 1 step we should be on the slope
  188. character.Step();
  189. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  190. CHECK_APPROX_EQUAL(character.GetPosition(), position_after_1_step, 2.0e-6f);
  191. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  192. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  193. RVec3 start_pos = character.GetPosition();
  194. // Start moving in X direction
  195. character.mHorizontalSpeed = Vec3(2.0f, 0, 0);
  196. character.Simulate(cMovementTime);
  197. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  198. // Calculate resulting translation
  199. Vec3 translation = Vec3(character.GetPosition() - start_pos);
  200. // Calculate expected translation
  201. Vec3 expected_translation;
  202. if (too_steep)
  203. {
  204. // If too steep, we're just falling. Integrate using an Euler integrator.
  205. Vec3 velocity = Vec3::sZero();
  206. expected_translation = Vec3::sZero();
  207. int num_steps = (int)round(cMovementTime / time_step);
  208. for (int i = 0; i < num_steps; ++i)
  209. {
  210. velocity += gravity * time_step;
  211. expected_translation += velocity * time_step;
  212. }
  213. }
  214. else
  215. {
  216. // Every frame we apply 1 delta time * gravity which gets reset on the next update, add this to the horizontal speed
  217. expected_translation = (character.mHorizontalSpeed + gravity * time_step) * cMovementTime;
  218. }
  219. // Cancel movement in slope direction
  220. expected_translation -= expected_translation.Dot(slope_normal) * slope_normal;
  221. // Check that we traveled the right amount
  222. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  223. }
  224. }
  225. TEST_CASE("TestStickToFloor")
  226. {
  227. constexpr float cFloorHalfHeight = 1.0f;
  228. constexpr float cSlopeAngle = DegreesToRadians(45.0f);
  229. constexpr float cMovementTime = 1.5f;
  230. for (int mode = 0; mode < 2; ++mode)
  231. {
  232. // If this run is with 'stick to floor' enabled
  233. bool stick_to_floor = mode == 0;
  234. // Create sloped floor
  235. PhysicsTestContext c;
  236. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), cSlopeAngle);
  237. c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  238. // Create character so that it is touching the slope
  239. Character character(c);
  240. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  241. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(cSlopeAngle) - radius_and_padding, 0);
  242. character.mUpdateSettings.mStickToFloorStepDown = stick_to_floor? Vec3(0, -0.5f, 0) : Vec3::sZero();
  243. character.Create();
  244. // After 1 step we should be on the slope
  245. character.Step();
  246. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  247. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  248. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  249. RVec3 start_pos = character.GetPosition();
  250. // Start moving down the slope at a speed high enough so that gravity will not keep us on the floor
  251. character.mHorizontalSpeed = Vec3(-10.0f, 0, 0);
  252. character.Simulate(cMovementTime);
  253. CHECK(character.mCharacter->GetGroundState() == (stick_to_floor? CharacterBase::EGroundState::OnGround : CharacterBase::EGroundState::InAir));
  254. // Calculate resulting translation
  255. Vec3 translation = Vec3(character.GetPosition() - start_pos);
  256. // Calculate expected translation
  257. Vec3 expected_translation;
  258. if (stick_to_floor)
  259. {
  260. // We should stick to the floor, so the vertical translation follows the slope perfectly
  261. expected_translation = character.mHorizontalSpeed * cMovementTime;
  262. expected_translation.SetY(expected_translation.GetX() * Tan(cSlopeAngle));
  263. }
  264. else
  265. {
  266. Vec3 gravity = c.GetSystem()->GetGravity();
  267. float time_step = c.GetDeltaTime();
  268. // If too steep, we're just falling. Integrate using an Euler integrator.
  269. Vec3 velocity = character.mHorizontalSpeed;
  270. expected_translation = Vec3::sZero();
  271. int num_steps = (int)round(cMovementTime / time_step);
  272. for (int i = 0; i < num_steps; ++i)
  273. {
  274. velocity += gravity * time_step;
  275. expected_translation += velocity * time_step;
  276. }
  277. }
  278. // Check that we traveled the right amount
  279. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  280. }
  281. }
  282. TEST_CASE("TestWalkStairs")
  283. {
  284. const float cStepHeight = 0.3f;
  285. const int cNumSteps = 10;
  286. // Create stairs from triangles
  287. TriangleList triangles;
  288. for (int i = 0; i < cNumSteps; ++i)
  289. {
  290. // Start of step
  291. Vec3 base(0, cStepHeight * i, cStepHeight * i);
  292. // Left side
  293. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  294. Vec3 s1 = b1 + Vec3(0, cStepHeight, 0);
  295. Vec3 p1 = s1 + Vec3(0, 0, cStepHeight);
  296. // Right side
  297. Vec3 width(-4.0f, 0, 0);
  298. Vec3 b2 = b1 + width;
  299. Vec3 s2 = s1 + width;
  300. Vec3 p2 = p1 + width;
  301. triangles.push_back(Triangle(s1, b1, s2));
  302. triangles.push_back(Triangle(b1, b2, s2));
  303. triangles.push_back(Triangle(s1, p2, p1));
  304. triangles.push_back(Triangle(s1, s2, p2));
  305. }
  306. MeshShapeSettings mesh(triangles);
  307. mesh.SetEmbedded();
  308. BodyCreationSettings mesh_stairs(&mesh, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  309. // Stair stepping is very delta time sensitive, so test various update frequencies
  310. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  311. for (float frequency : frequencies)
  312. {
  313. float time_step = 1.0f / frequency;
  314. PhysicsTestContext c(time_step);
  315. c.CreateFloor();
  316. c.GetBodyInterface().CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  317. // Create character so that it is touching the slope
  318. Character character(c);
  319. character.mInitialPosition = RVec3(0, 0, -2.0f); // Start in front of the stairs
  320. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero(); // No stair walking
  321. character.Create();
  322. // Start moving towards the stairs
  323. character.mHorizontalSpeed = Vec3(0, 0, 4.0f);
  324. character.Simulate(1.0f);
  325. // We should have gotten stuck at the start of the stairs (can't move up)
  326. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  327. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  328. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(0, 0, -radius_and_padding), 1.1e-2f);
  329. // Enable stair walking
  330. character.mUpdateSettings.mWalkStairsStepUp = Vec3(0, 0.4f, 0);
  331. // Calculate time it should take to move up the stairs at constant speed
  332. float movement_time = (cNumSteps * cStepHeight + radius_and_padding) / character.mHorizontalSpeed.GetZ();
  333. int max_steps = int(1.5f * round(movement_time / time_step)); // In practice there is a bit of slowdown while stair stepping, so add a bit of slack
  334. // Step until we reach the top of the stairs
  335. RVec3 last_position = character.GetPosition();
  336. bool reached_goal = false;
  337. for (int i = 0; i < max_steps; ++i)
  338. {
  339. character.Step();
  340. // We should always be on the floor during stair stepping
  341. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  342. // Check position progression
  343. RVec3 position = character.GetPosition();
  344. CHECK_APPROX_EQUAL(position.GetX(), 0); // No movement in X
  345. CHECK(position.GetZ() > last_position.GetZ()); // Always moving forward
  346. CHECK(position.GetZ() < cNumSteps * cStepHeight); // No movement beyond stairs
  347. if (position.GetY() > cNumSteps * cStepHeight - 1.0e-3f)
  348. {
  349. reached_goal = true;
  350. break;
  351. }
  352. last_position = position;
  353. }
  354. CHECK(reached_goal);
  355. }
  356. }
  357. TEST_CASE("TestRotatingPlatform")
  358. {
  359. constexpr float cFloorHalfHeight = 1.0f;
  360. constexpr float cFloorHalfWidth = 10.0f;
  361. constexpr float cCharacterPosition = 0.9f * cFloorHalfWidth;
  362. constexpr float cAngularVelocity = 2.0f * JPH_PI;
  363. PhysicsTestContext c;
  364. // Create box
  365. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  366. box.SetAllowSleeping(false);
  367. // Create character so that it is touching the box at the
  368. Character character(c);
  369. character.mInitialPosition = RVec3(cCharacterPosition, cFloorHalfHeight, 0);
  370. character.Create();
  371. // Step to ensure the character is on the box
  372. character.Step();
  373. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  374. // Set the box to rotate a full circle per second
  375. box.SetAngularVelocity(Vec3(0, cAngularVelocity, 0));
  376. // Rotate and check that character stays on the box
  377. for (int t = 0; t < 60; ++t)
  378. {
  379. character.Step();
  380. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  381. // Note that the character moves according to the ground velocity and the ground velocity is updated at the end of the step
  382. // so the character is always 1 time step behind the platform. This is why we use t and not t + 1 to calculate the expected position.
  383. RVec3 expected_position = RMat44::sRotation(Quat::sRotation(Vec3::sAxisY(), float(t) * c.GetDeltaTime() * cAngularVelocity)) * character.mInitialPosition;
  384. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-4f);
  385. }
  386. }
  387. TEST_CASE("TestMovingPlatformUp")
  388. {
  389. constexpr float cFloorHalfHeight = 1.0f;
  390. constexpr float cFloorHalfWidth = 10.0f;
  391. constexpr float cLinearVelocity = 0.5f;
  392. PhysicsTestContext c;
  393. // Create box
  394. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  395. box.SetAllowSleeping(false);
  396. // Create character so that it is touching the box at the
  397. Character character(c);
  398. character.mInitialPosition = RVec3(0, cFloorHalfHeight, 0);
  399. character.Create();
  400. // Step to ensure the character is on the box
  401. character.Step();
  402. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  403. // Set the box to move up
  404. box.SetLinearVelocity(Vec3(0, cLinearVelocity, 0));
  405. // Check that character stays on the box
  406. for (int t = 0; t < 60; ++t)
  407. {
  408. character.Step();
  409. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  410. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  411. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-2f);
  412. }
  413. // Stop box
  414. box.SetLinearVelocity(Vec3::sZero());
  415. character.Simulate(0.5f);
  416. // Set the box to move down
  417. box.SetLinearVelocity(Vec3(0, -cLinearVelocity, 0));
  418. // Check that character stays on the box
  419. for (int t = 0; t < 60; ++t)
  420. {
  421. character.Step();
  422. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  423. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  424. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-2f);
  425. }
  426. }
  427. TEST_CASE("TestContactPointLimit")
  428. {
  429. PhysicsTestContext ctx;
  430. Body &floor = ctx.CreateFloor();
  431. // Create character at the origin
  432. Character character(ctx);
  433. character.mInitialPosition = RVec3(0, 1, 0);
  434. character.mUpdateSettings.mStickToFloorStepDown = Vec3::sZero();
  435. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero();
  436. character.Create();
  437. // Radius including padding
  438. const float character_radius = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  439. // Create a half cylinder with caps for testing contact point limit
  440. VertexList vertices;
  441. IndexedTriangleList triangles;
  442. // The half cylinder
  443. const int cPosSegments = 2;
  444. const int cAngleSegments = 768;
  445. const float cCylinderLength = 2.0f;
  446. for (int pos = 0; pos < cPosSegments; ++pos)
  447. for (int angle = 0; angle < cAngleSegments; ++angle)
  448. {
  449. uint32 start = (uint32)vertices.size();
  450. float radius = character_radius + 0.01f;
  451. float angle_rad = (-0.5f + float(angle) / cAngleSegments) * JPH_PI;
  452. float s = Sin(angle_rad);
  453. float c = Cos(angle_rad);
  454. float x = cCylinderLength * (-0.5f + float(pos) / (cPosSegments - 1));
  455. float y = angle == 0 || angle == cAngleSegments - 1? 0.5f : (1.0f - c) * radius;
  456. float z = s * radius;
  457. vertices.push_back(Float3(x, y, z));
  458. if (pos > 0 && angle > 0)
  459. {
  460. triangles.push_back(IndexedTriangle(start, start - 1, start - cAngleSegments));
  461. triangles.push_back(IndexedTriangle(start - 1, start - cAngleSegments - 1, start - cAngleSegments));
  462. }
  463. }
  464. // Add end caps
  465. uint32 end = cAngleSegments * (cPosSegments - 1);
  466. for (int angle = 0; angle < cAngleSegments - 1; ++angle)
  467. {
  468. triangles.push_back(IndexedTriangle(0, angle + 1, angle));
  469. triangles.push_back(IndexedTriangle(end, end + angle, end + angle + 1));
  470. }
  471. // Create test body
  472. MeshShapeSettings mesh(vertices, triangles);
  473. mesh.SetEmbedded();
  474. BodyCreationSettings mesh_cylinder(&mesh, character.mInitialPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  475. BodyID cylinder_id = ctx.GetBodyInterface().CreateAndAddBody(mesh_cylinder, EActivation::DontActivate);
  476. // End positions that can be reached by character
  477. RVec3 pos_end(0.5_r * cCylinderLength - character_radius, 1, 0);
  478. RVec3 neg_end(-0.5_r * cCylinderLength + character_radius, 1, 0);
  479. // Move towards positive cap and test if we hit the end
  480. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  481. for (int t = 0; t < 60; ++t)
  482. {
  483. character.Step();
  484. CHECK(character.mCharacter->GetMaxHitsExceeded());
  485. CHECK(character.GetNumContacts() <= character.mCharacter->GetMaxNumHits());
  486. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  487. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  488. }
  489. CHECK_APPROX_EQUAL(character.GetPosition(), pos_end, 1.0e-4f);
  490. // Move towards negative cap and test if we hit the end
  491. character.mHorizontalSpeed = Vec3(-cCylinderLength, 0, 0);
  492. for (int t = 0; t < 60; ++t)
  493. {
  494. character.Step();
  495. CHECK(character.mCharacter->GetMaxHitsExceeded());
  496. CHECK(character.GetNumContacts() <= character.mCharacter->GetMaxNumHits());
  497. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  498. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  499. }
  500. CHECK_APPROX_EQUAL(character.GetPosition(), neg_end, 1.0e-4f);
  501. // Turn off contact point reduction
  502. character.mCharacter->SetHitReductionCosMaxAngle(-1.0f);
  503. // Move towards positive cap and test that we did not reach the end
  504. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  505. for (int t = 0; t < 60; ++t)
  506. {
  507. character.Step();
  508. CHECK(character.mCharacter->GetMaxHitsExceeded());
  509. CHECK(character.GetNumContacts() == character.mCharacter->GetMaxNumHits());
  510. }
  511. RVec3 cur_pos = character.GetPosition();
  512. CHECK((pos_end - cur_pos).Length() > 0.01_r);
  513. // Move towards negative cap and test that we got stuck
  514. character.mHorizontalSpeed = Vec3(-cCylinderLength, 0, 0);
  515. for (int t = 0; t < 60; ++t)
  516. {
  517. character.Step();
  518. CHECK(character.mCharacter->GetMaxHitsExceeded());
  519. CHECK(character.GetNumContacts() == character.mCharacter->GetMaxNumHits());
  520. }
  521. CHECK(cur_pos.IsClose(character.GetPosition(), 1.0e-6f));
  522. // Now teleport the character next to the half cylinder
  523. character.mCharacter->SetPosition(RVec3(0, 0, 1));
  524. // Move in positive X and check that we did not exceed max hits and that we were able to move unimpeded
  525. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  526. for (int t = 0; t < 60; ++t)
  527. {
  528. character.Step();
  529. CHECK(!character.mCharacter->GetMaxHitsExceeded());
  530. CHECK(character.GetNumContacts() == 1); // We should only hit the floor
  531. CHECK(character.mCharacter->GetGroundBodyID() == floor.GetID());
  532. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  533. }
  534. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(cCylinderLength, 0, 1), 1.0e-4f);
  535. }
  536. TEST_CASE("TestStairWalkAlongWall")
  537. {
  538. // Stair stepping is very delta time sensitive, so test various update frequencies
  539. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  540. for (float frequency : frequencies)
  541. {
  542. float time_step = 1.0f / frequency;
  543. PhysicsTestContext c(time_step);
  544. c.CreateFloor();
  545. // Create character
  546. Character character(c);
  547. character.Create();
  548. // Create a wall
  549. const float cWallHalfThickness = 0.05f;
  550. c.GetBodyInterface().CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(50.0f, 1.0f, cWallHalfThickness)), RVec3(0, 1.0_r, Real(-character.mRadiusStanding - character.mCharacter->GetCharacterPadding() - cWallHalfThickness)), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  551. // Start moving along the wall, if the stair stepping algorithm is working correctly it should not trigger and not apply extra speed to the character
  552. character.mHorizontalSpeed = Vec3(5.0f, 0, -1.0f);
  553. character.Simulate(1.0f);
  554. // We should have moved along the wall at the desired speed
  555. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  556. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(5.0f, 0, 0), 1.0e-2f);
  557. }
  558. }
  559. TEST_CASE("TestInitiallyIntersecting")
  560. {
  561. PhysicsTestContext c;
  562. c.CreateFloor();
  563. // Create box that is intersecting with the character
  564. c.CreateBox(RVec3(-0.5f, 0.5f, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3::sReplicate(0.5f));
  565. // Try various penetration recovery values
  566. for (float penetration_recovery : { 0.0f, 0.5f, 0.75f, 1.0f })
  567. {
  568. // Create character
  569. Character character(c);
  570. character.mCharacterSettings.mPenetrationRecoverySpeed = penetration_recovery;
  571. character.Create();
  572. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  573. // Total radius of character
  574. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  575. float x = 0.0f;
  576. for (int step = 0; step < 3; ++step)
  577. {
  578. // Calculate expected position
  579. x += penetration_recovery * (radius_and_padding - x);
  580. // Step character and check that it matches expected recovery
  581. character.Step();
  582. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(x, 0, 0));
  583. }
  584. }
  585. }
  586. TEST_CASE("TestCharacterVsCharacter")
  587. {
  588. PhysicsTestContext c;
  589. BodyID floor_id = c.CreateFloor().GetID();
  590. // Create characters with different radii and padding
  591. Character character1(c);
  592. character1.mInitialPosition = RVec3::sZero();
  593. character1.mRadiusStanding = 0.2f;
  594. character1.mCharacterSettings.mCharacterPadding = 0.04f;
  595. character1.Create();
  596. Character character2(c);
  597. character2.mInitialPosition = RVec3(1, 0, 0);
  598. character2.mRadiusStanding = 0.3f;
  599. character2.mCharacterSettings.mCharacterPadding = 0.03f;
  600. character2.Create();
  601. // Make both collide
  602. character1.mCharacterVsCharacter.Add(character2.mCharacter);
  603. character2.mCharacterVsCharacter.Add(character1.mCharacter);
  604. // Add a box behind character 2, we should never hit this
  605. Vec3 box_extent(0.1f, 1.0f, 1.0f);
  606. c.CreateBox(RVec3(1.5f, 0, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, box_extent, EActivation::DontActivate);
  607. // Move character 1 towards character 2 so that in 1 step it will hit both character 2 and the box
  608. character1.mHorizontalSpeed = Vec3(600.0f, 0, 0);
  609. character1.Step();
  610. // Character 1 should have stopped at character 2
  611. float character1_radius = character1.mRadiusStanding + character1.mCharacterSettings.mCharacterPadding;
  612. float character2_radius = character2.mRadiusStanding + character2.mCharacterSettings.mCharacterPadding;
  613. float separation = character1_radius + character2_radius;
  614. RVec3 expected_colliding_with_character = character2.mInitialPosition - Vec3(separation, 0, 0);
  615. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_character, 1.0e-3f);
  616. CHECK(character1.GetNumContacts() == 2);
  617. CHECK(character1.HasCollidedWith(floor_id));
  618. CHECK(character1.HasCollidedWith(character2.mCharacter));
  619. // Move character 1 back to its initial position
  620. character1.mCharacter->SetPosition(character1.mInitialPosition);
  621. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  622. // Now move slowly so that we will detect the collision during the normal collide shape step
  623. character1.mHorizontalSpeed = Vec3(1.0f, 0, 0);
  624. character1.Step();
  625. CHECK(character1.GetNumContacts() == 1);
  626. CHECK(character1.HasCollidedWith(floor_id));
  627. character1.Simulate(1.0f);
  628. // Character 1 should have stopped at character 2
  629. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_character, 1.0e-3f);
  630. CHECK(character1.GetNumContacts() == 2);
  631. CHECK(character1.HasCollidedWith(floor_id));
  632. CHECK(character1.HasCollidedWith(character2.mCharacter));
  633. // Move character 1 back to its initial position
  634. character1.mCharacter->SetPosition(character1.mInitialPosition);
  635. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  636. // Add a box in between the characters
  637. RVec3 box_position(0.5f, 0, 0);
  638. BodyID box_id = c.CreateBox(box_position, Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, box_extent, EActivation::DontActivate).GetID();
  639. // Move character 1 so that it will step through both the box and the character in 1 time step
  640. character1.mHorizontalSpeed = Vec3(600.0f, 0, 0);
  641. character1.Step();
  642. // Expect that it ends up at the box
  643. RVec3 expected_colliding_with_box = box_position - Vec3(character1_radius + box_extent.GetX(), 0, 0);
  644. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_box, 1.0e-3f);
  645. CHECK(character1.GetNumContacts() == 2);
  646. CHECK(character1.HasCollidedWith(floor_id));
  647. CHECK(character1.HasCollidedWith(box_id));
  648. // Move character 1 back to its initial position
  649. character1.mCharacter->SetPosition(character1.mInitialPosition);
  650. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  651. // Now move slowly so that we will detect the collision during the normal collide shape step
  652. character1.mHorizontalSpeed = Vec3(1.0f, 0, 0);
  653. character1.Step();
  654. CHECK(character1.GetNumContacts() == 1);
  655. CHECK(character1.HasCollidedWith(floor_id));
  656. character1.Simulate(1.0f);
  657. // Expect that it ends up at the box
  658. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_box, 1.0e-3f);
  659. CHECK(character1.GetNumContacts() == 2);
  660. CHECK(character1.HasCollidedWith(floor_id));
  661. CHECK(character1.HasCollidedWith(box_id));
  662. }
  663. }