CharacterVirtualTests.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. }
  31. // Step the character and the world
  32. void Step()
  33. {
  34. // Step the world
  35. mContext.SimulateSingleStep();
  36. // Determine new basic velocity
  37. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  38. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  39. Vec3 new_velocity;
  40. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  41. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  42. {
  43. // Assume velocity of ground when on ground
  44. new_velocity = ground_velocity;
  45. // Jump
  46. new_velocity += Vec3(0, mJumpSpeed, 0);
  47. mJumpSpeed = 0.0f;
  48. }
  49. else
  50. new_velocity = current_vertical_velocity;
  51. // Gravity
  52. PhysicsSystem *system = mContext.GetSystem();
  53. float delta_time = mContext.GetDeltaTime();
  54. new_velocity += system->GetGravity() * delta_time;
  55. // Player input
  56. new_velocity += mHorizontalSpeed;
  57. // Update character velocity
  58. mCharacter->SetLinearVelocity(new_velocity);
  59. RVec3 start_pos = mCharacter->GetPosition();
  60. // Update the character position
  61. TempAllocatorMalloc allocator;
  62. mCharacter->ExtendedUpdate(delta_time,
  63. system->GetGravity(),
  64. mUpdateSettings,
  65. system->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  66. system->GetDefaultLayerFilter(Layers::MOVING),
  67. { },
  68. { },
  69. allocator);
  70. // Calculate effective velocity in this step
  71. mEffectiveVelocity = Vec3(mCharacter->GetPosition() - start_pos) / delta_time;
  72. }
  73. // Simulate a longer period of time
  74. void Simulate(float inTime)
  75. {
  76. int num_steps = (int)round(inTime / mContext.GetDeltaTime());
  77. for (int step = 0; step < num_steps; ++step)
  78. Step();
  79. }
  80. // Configuration
  81. RVec3 mInitialPosition = RVec3::sZero();
  82. float mHeightStanding = 1.35f;
  83. float mRadiusStanding = 0.3f;
  84. CharacterVirtualSettings mCharacterSettings;
  85. CharacterVirtual::ExtendedUpdateSettings mUpdateSettings;
  86. // Character movement settings (update to control the movement of the character)
  87. Vec3 mHorizontalSpeed = Vec3::sZero();
  88. float mJumpSpeed = 0.0f; // Character will jump when not 0, will auto reset
  89. // The character
  90. Ref<CharacterVirtual> mCharacter;
  91. // Calculated effective velocity after a step
  92. Vec3 mEffectiveVelocity = Vec3::sZero();
  93. private:
  94. // CharacterContactListener callback
  95. 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
  96. {
  97. // Don't allow sliding if the character doesn't want to move
  98. if (mHorizontalSpeed.IsNearZero() && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  99. ioNewCharacterVelocity = Vec3::sZero();
  100. }
  101. PhysicsTestContext & mContext;
  102. };
  103. TEST_CASE("TestFallingAndJumping")
  104. {
  105. // Create floor
  106. PhysicsTestContext c;
  107. c.CreateFloor();
  108. // Create character
  109. Character character(c);
  110. character.mInitialPosition = RVec3(0, 2, 0);
  111. character.Create();
  112. // After 1 step we should still be in air
  113. character.Step();
  114. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  115. // After some time we should be on the floor
  116. character.Simulate(1.0f);
  117. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  118. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3::sZero());
  119. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  120. // Jump
  121. character.mJumpSpeed = 1.0f;
  122. character.Step();
  123. Vec3 velocity(0, 1.0f + c.GetDeltaTime() * c.GetSystem()->GetGravity().GetY(), 0);
  124. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3(velocity * c.GetDeltaTime()));
  125. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, velocity);
  126. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  127. // After some time we should be on the floor again
  128. character.Simulate(1.0f);
  129. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  130. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3::sZero());
  131. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  132. }
  133. TEST_CASE("TestMovingOnSlope")
  134. {
  135. constexpr float cFloorHalfHeight = 1.0f;
  136. constexpr float cMovementTime = 1.5f;
  137. // Iterate various slope angles
  138. for (float slope_angle = DegreesToRadians(5.0f); slope_angle < DegreesToRadians(85.0f); slope_angle += DegreesToRadians(10.0f))
  139. {
  140. // Create sloped floor
  141. PhysicsTestContext c;
  142. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), slope_angle);
  143. c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  144. // Create character so that it is touching the slope
  145. Character character(c);
  146. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  147. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(slope_angle) - radius_and_padding, 0);
  148. character.Create();
  149. // Determine if the slope is too steep for the character
  150. bool too_steep = slope_angle > character.mCharacterSettings.mMaxSlopeAngle;
  151. CharacterBase::EGroundState expected_ground_state = (too_steep? CharacterBase::EGroundState::OnSteepGround : CharacterBase::EGroundState::OnGround);
  152. Vec3 gravity = c.GetSystem()->GetGravity();
  153. float time_step = c.GetDeltaTime();
  154. Vec3 slope_normal = slope_rotation.RotateAxisY();
  155. // Calculate expected position after 1 time step
  156. RVec3 position_after_1_step = character.mInitialPosition;
  157. if (too_steep)
  158. {
  159. // Apply 1 frame of gravity and cancel movement in the slope normal direction
  160. Vec3 velocity = gravity * time_step;
  161. velocity -= velocity.Dot(slope_normal) * slope_normal;
  162. position_after_1_step += velocity * time_step;
  163. }
  164. // After 1 step we should be on the slope
  165. character.Step();
  166. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  167. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), position_after_1_step, 2.0e-6f);
  168. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  169. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  170. RVec3 start_pos = character.mCharacter->GetPosition();
  171. // Start moving in X direction
  172. character.mHorizontalSpeed = Vec3(2.0f, 0, 0);
  173. character.Simulate(cMovementTime);
  174. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  175. // Calculate resulting translation
  176. Vec3 translation = Vec3(character.mCharacter->GetPosition() - start_pos);
  177. // Calculate expected translation
  178. Vec3 expected_translation;
  179. if (too_steep)
  180. {
  181. // If too steep, we're just falling. Integrate using an Euler integrator.
  182. Vec3 velocity = Vec3::sZero();
  183. expected_translation = Vec3::sZero();
  184. int num_steps = (int)round(cMovementTime / time_step);
  185. for (int i = 0; i < num_steps; ++i)
  186. {
  187. velocity += gravity * time_step;
  188. expected_translation += velocity * time_step;
  189. }
  190. }
  191. else
  192. {
  193. // Every frame we apply 1 delta time * gravity which gets reset on the next update, add this to the horizontal speed
  194. expected_translation = (character.mHorizontalSpeed + gravity * time_step) * cMovementTime;
  195. }
  196. // Cancel movement in slope direction
  197. expected_translation -= expected_translation.Dot(slope_normal) * slope_normal;
  198. // Check that we traveled the right amount
  199. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  200. }
  201. }
  202. TEST_CASE("TestStickToFloor")
  203. {
  204. constexpr float cFloorHalfHeight = 1.0f;
  205. constexpr float cSlopeAngle = DegreesToRadians(45.0f);
  206. constexpr float cMovementTime = 1.5f;
  207. for (int mode = 0; mode < 2; ++mode)
  208. {
  209. // If this run is with 'stick to floor' enabled
  210. bool stick_to_floor = mode == 0;
  211. // Create sloped floor
  212. PhysicsTestContext c;
  213. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), cSlopeAngle);
  214. c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  215. // Create character so that it is touching the slope
  216. Character character(c);
  217. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  218. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(cSlopeAngle) - radius_and_padding, 0);
  219. character.mUpdateSettings.mStickToFloorStepDown = stick_to_floor? Vec3(0, -0.5f, 0) : Vec3::sZero();
  220. character.Create();
  221. // After 1 step we should be on the slope
  222. character.Step();
  223. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  224. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  225. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  226. RVec3 start_pos = character.mCharacter->GetPosition();
  227. // Start moving down the slope at a speed high enough so that gravity will not keep us on the floor
  228. character.mHorizontalSpeed = Vec3(-10.0f, 0, 0);
  229. character.Simulate(cMovementTime);
  230. CHECK(character.mCharacter->GetGroundState() == (stick_to_floor? CharacterBase::EGroundState::OnGround : CharacterBase::EGroundState::InAir));
  231. // Calculate resulting translation
  232. Vec3 translation = Vec3(character.mCharacter->GetPosition() - start_pos);
  233. // Calculate expected translation
  234. Vec3 expected_translation;
  235. if (stick_to_floor)
  236. {
  237. // We should stick to the floor, so the vertical translation follows the slope perfectly
  238. expected_translation = character.mHorizontalSpeed * cMovementTime;
  239. expected_translation.SetY(expected_translation.GetX() * Tan(cSlopeAngle));
  240. }
  241. else
  242. {
  243. Vec3 gravity = c.GetSystem()->GetGravity();
  244. float time_step = c.GetDeltaTime();
  245. // If too steep, we're just falling. Integrate using an Euler integrator.
  246. Vec3 velocity = character.mHorizontalSpeed;
  247. expected_translation = Vec3::sZero();
  248. int num_steps = (int)round(cMovementTime / time_step);
  249. for (int i = 0; i < num_steps; ++i)
  250. {
  251. velocity += gravity * time_step;
  252. expected_translation += velocity * time_step;
  253. }
  254. }
  255. // Check that we traveled the right amount
  256. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  257. }
  258. }
  259. TEST_CASE("TestWalkStairs")
  260. {
  261. const float cStepHeight = 0.3f;
  262. const int cNumSteps = 10;
  263. // Create stairs from triangles
  264. TriangleList triangles;
  265. for (int i = 0; i < cNumSteps; ++i)
  266. {
  267. // Start of step
  268. Vec3 base(0, cStepHeight * i, cStepHeight * i);
  269. // Left side
  270. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  271. Vec3 s1 = b1 + Vec3(0, cStepHeight, 0);
  272. Vec3 p1 = s1 + Vec3(0, 0, cStepHeight);
  273. // Right side
  274. Vec3 width(-4.0f, 0, 0);
  275. Vec3 b2 = b1 + width;
  276. Vec3 s2 = s1 + width;
  277. Vec3 p2 = p1 + width;
  278. triangles.push_back(Triangle(s1, b1, s2));
  279. triangles.push_back(Triangle(b1, b2, s2));
  280. triangles.push_back(Triangle(s1, p2, p1));
  281. triangles.push_back(Triangle(s1, s2, p2));
  282. }
  283. MeshShapeSettings mesh(triangles);
  284. mesh.SetEmbedded();
  285. BodyCreationSettings mesh_stairs(&mesh, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  286. // Stair stepping is very delta time sensitive, so test various update frequencies
  287. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  288. for (float frequency : frequencies)
  289. {
  290. float time_step = 1.0f / frequency;
  291. PhysicsTestContext c(time_step);
  292. c.CreateFloor();
  293. c.GetBodyInterface().CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  294. // Create character so that it is touching the slope
  295. Character character(c);
  296. character.mInitialPosition = RVec3(0, 0, -2.0f); // Start in front of the stairs
  297. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero(); // No stair walking
  298. character.Create();
  299. // Start moving towards the stairs
  300. character.mHorizontalSpeed = Vec3(0, 0, 4.0f);
  301. character.Simulate(1.0f);
  302. // We should have gotten stuck at the start of the stairs (can't move up)
  303. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  304. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  305. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3(0, 0, -radius_and_padding), 1.1e-2f);
  306. // Enable stair walking
  307. character.mUpdateSettings.mWalkStairsStepUp = Vec3(0, 0.4f, 0);
  308. // Calculate time it should take to move up the stairs at constant speed
  309. float movement_time = (cNumSteps * cStepHeight + radius_and_padding) / character.mHorizontalSpeed.GetZ();
  310. 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
  311. // Step until we reach the top of the stairs
  312. RVec3 last_position = character.mCharacter->GetPosition();
  313. bool reached_goal = false;
  314. for (int i = 0; i < max_steps; ++i)
  315. {
  316. character.Step();
  317. // We should always be on the floor during stair stepping
  318. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  319. // Check position progression
  320. RVec3 position = character.mCharacter->GetPosition();
  321. CHECK_APPROX_EQUAL(position.GetX(), 0); // No movement in X
  322. CHECK(position.GetZ() > last_position.GetZ()); // Always moving forward
  323. CHECK(position.GetZ() < cNumSteps * cStepHeight); // No movement beyond stairs
  324. if (position.GetY() > cNumSteps * cStepHeight - 1.0e-3f)
  325. {
  326. reached_goal = true;
  327. break;
  328. }
  329. last_position = position;
  330. }
  331. CHECK(reached_goal);
  332. }
  333. }
  334. TEST_CASE("TestRotatingPlatform")
  335. {
  336. constexpr float cFloorHalfHeight = 1.0f;
  337. constexpr float cFloorHalfWidth = 10.0f;
  338. constexpr float cCharacterPosition = 0.9f * cFloorHalfWidth;
  339. constexpr float cAngularVelocity = 2.0f * JPH_PI;
  340. PhysicsTestContext c;
  341. // Create box
  342. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  343. box.SetAllowSleeping(false);
  344. // Create character so that it is touching the box at the
  345. Character character(c);
  346. character.mInitialPosition = RVec3(cCharacterPosition, cFloorHalfHeight, 0);
  347. character.Create();
  348. // Step to ensure the character is on the box
  349. character.Step();
  350. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  351. // Set the box to rotate a full circle per second
  352. box.SetAngularVelocity(Vec3(0, cAngularVelocity, 0));
  353. // Rotate and check that character stays on the box
  354. for (int t = 0; t < 60; ++t)
  355. {
  356. character.Step();
  357. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  358. // Note that the character moves according to the ground velocity and the ground velocity is updated at the end of the step
  359. // 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.
  360. RVec3 expected_position = RMat44::sRotation(Quat::sRotation(Vec3::sAxisY(), float(t) * c.GetDeltaTime() * cAngularVelocity)) * character.mInitialPosition;
  361. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), expected_position, 1.0e-4f);
  362. }
  363. }
  364. TEST_CASE("TestMovingPlatformUp")
  365. {
  366. constexpr float cFloorHalfHeight = 1.0f;
  367. constexpr float cFloorHalfWidth = 10.0f;
  368. constexpr float cLinearVelocity = 0.5f;
  369. PhysicsTestContext c;
  370. // Create box
  371. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  372. box.SetAllowSleeping(false);
  373. // Create character so that it is touching the box at the
  374. Character character(c);
  375. character.mInitialPosition = RVec3(0, cFloorHalfHeight, 0);
  376. character.Create();
  377. // Step to ensure the character is on the box
  378. character.Step();
  379. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  380. // Set the box to move up
  381. box.SetLinearVelocity(Vec3(0, cLinearVelocity, 0));
  382. // Check that character stays on the box
  383. for (int t = 0; t < 60; ++t)
  384. {
  385. character.Step();
  386. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  387. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  388. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), expected_position, 1.0e-2f);
  389. }
  390. // Stop box
  391. box.SetLinearVelocity(Vec3::sZero());
  392. character.Simulate(0.5f);
  393. // Set the box to move down
  394. box.SetLinearVelocity(Vec3(0, -cLinearVelocity, 0));
  395. // Check that character stays on the box
  396. for (int t = 0; t < 60; ++t)
  397. {
  398. character.Step();
  399. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  400. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  401. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), expected_position, 1.0e-2f);
  402. }
  403. }
  404. TEST_CASE("TestContactPointLimit")
  405. {
  406. PhysicsTestContext ctx;
  407. Body &floor = ctx.CreateFloor();
  408. // Create character at the origin
  409. Character character(ctx);
  410. character.mInitialPosition = RVec3(0, 1, 0);
  411. character.mUpdateSettings.mStickToFloorStepDown = Vec3::sZero();
  412. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero();
  413. character.Create();
  414. // Radius including padding
  415. const float character_radius = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  416. // Create a half cylinder with caps for testing contact point limit
  417. VertexList vertices;
  418. IndexedTriangleList triangles;
  419. // The half cylinder
  420. const int cPosSegments = 2;
  421. const int cAngleSegments = 768;
  422. const float cCylinderLength = 2.0f;
  423. for (int pos = 0; pos < cPosSegments; ++pos)
  424. for (int angle = 0; angle < cAngleSegments; ++angle)
  425. {
  426. uint32 start = (uint32)vertices.size();
  427. float radius = character_radius + 0.01f;
  428. float angle_rad = (-0.5f + float(angle) / cAngleSegments) * JPH_PI;
  429. float s = Sin(angle_rad);
  430. float c = Cos(angle_rad);
  431. float x = cCylinderLength * (-0.5f + float(pos) / (cPosSegments - 1));
  432. float y = angle == 0 || angle == cAngleSegments - 1? 0.5f : (1.0f - c) * radius;
  433. float z = s * radius;
  434. vertices.push_back(Float3(x, y, z));
  435. if (pos > 0 && angle > 0)
  436. {
  437. triangles.push_back(IndexedTriangle(start, start - 1, start - cAngleSegments));
  438. triangles.push_back(IndexedTriangle(start - 1, start - cAngleSegments - 1, start - cAngleSegments));
  439. }
  440. }
  441. // Add end caps
  442. uint32 end = cAngleSegments * (cPosSegments - 1);
  443. for (int angle = 0; angle < cAngleSegments - 1; ++angle)
  444. {
  445. triangles.push_back(IndexedTriangle(0, angle + 1, angle));
  446. triangles.push_back(IndexedTriangle(end, end + angle, end + angle + 1));
  447. }
  448. // Create test body
  449. MeshShapeSettings mesh(vertices, triangles);
  450. mesh.SetEmbedded();
  451. BodyCreationSettings mesh_cylinder(&mesh, character.mInitialPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  452. BodyID cylinder_id = ctx.GetBodyInterface().CreateAndAddBody(mesh_cylinder, EActivation::DontActivate);
  453. // End positions that can be reached by character
  454. RVec3 pos_end(0.5_r * cCylinderLength - character_radius, 1, 0);
  455. RVec3 neg_end(-0.5_r * cCylinderLength + character_radius, 1, 0);
  456. // Move towards positive cap and test if we hit the end
  457. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  458. for (int t = 0; t < 60; ++t)
  459. {
  460. character.Step();
  461. CHECK(character.mCharacter->GetMaxHitsExceeded());
  462. CHECK(character.mCharacter->GetActiveContacts().size() <= character.mCharacter->GetMaxNumHits());
  463. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  464. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  465. }
  466. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), pos_end, 1.0e-4f);
  467. // Move towards negative cap and test if we hit the end
  468. character.mHorizontalSpeed = Vec3(-cCylinderLength, 0, 0);
  469. for (int t = 0; t < 60; ++t)
  470. {
  471. character.Step();
  472. CHECK(character.mCharacter->GetMaxHitsExceeded());
  473. CHECK(character.mCharacter->GetActiveContacts().size() <= character.mCharacter->GetMaxNumHits());
  474. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  475. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  476. }
  477. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), neg_end, 1.0e-4f);
  478. // Turn off contact point reduction
  479. character.mCharacter->SetHitReductionCosMaxAngle(-1.0f);
  480. // Move towards positive cap and test that we did not reach the end
  481. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  482. for (int t = 0; t < 60; ++t)
  483. {
  484. character.Step();
  485. CHECK(character.mCharacter->GetMaxHitsExceeded());
  486. CHECK(character.mCharacter->GetActiveContacts().size() == character.mCharacter->GetMaxNumHits());
  487. }
  488. RVec3 cur_pos = character.mCharacter->GetPosition();
  489. CHECK((pos_end - cur_pos).Length() > 0.01_r);
  490. // Move towards negative cap and test that we got stuck
  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.mCharacter->GetActiveContacts().size() == character.mCharacter->GetMaxNumHits());
  497. }
  498. CHECK(cur_pos.IsClose(character.mCharacter->GetPosition(), 1.0e-6f));
  499. // Now teleport the character next to the half cylinder
  500. character.mCharacter->SetPosition(RVec3(0, 0, 1));
  501. // Move in positive X and check that we did not exceed max hits and that we were able to move unimpeded
  502. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  503. for (int t = 0; t < 60; ++t)
  504. {
  505. character.Step();
  506. CHECK(!character.mCharacter->GetMaxHitsExceeded());
  507. CHECK(character.mCharacter->GetActiveContacts().size() == 1); // We should only hit the floor
  508. CHECK(character.mCharacter->GetGroundBodyID() == floor.GetID());
  509. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  510. }
  511. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3(cCylinderLength, 0, 1), 1.0e-4f);
  512. }
  513. TEST_CASE("TestStairWalkAlongWall")
  514. {
  515. // Stair stepping is very delta time sensitive, so test various update frequencies
  516. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  517. for (float frequency : frequencies)
  518. {
  519. float time_step = 1.0f / frequency;
  520. PhysicsTestContext c(time_step);
  521. c.CreateFloor();
  522. // Create character
  523. Character character(c);
  524. character.Create();
  525. // Create a wall
  526. const float cWallHalfThickness = 0.05f;
  527. 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);
  528. // 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
  529. character.mHorizontalSpeed = Vec3(5.0f, 0, -1.0f);
  530. character.Simulate(1.0f);
  531. // We should have moved along the wall at the desired speed
  532. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  533. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3(5.0f, 0, 0), 1.0e-2f);
  534. }
  535. }
  536. TEST_CASE("TestInitiallyIntersecting")
  537. {
  538. PhysicsTestContext c;
  539. c.CreateFloor();
  540. // Create box that is intersecting with the character
  541. c.CreateBox(RVec3(-0.5f, 0.5f, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3::sReplicate(0.5f));
  542. // Try various penetration recovery values
  543. for (float penetration_recovery : { 0.0f, 0.5f, 0.75f, 1.0f })
  544. {
  545. // Create character
  546. Character character(c);
  547. character.mCharacterSettings.mPenetrationRecoverySpeed = penetration_recovery;
  548. character.Create();
  549. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3::sZero());
  550. // Total radius of character
  551. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  552. float x = 0.0f;
  553. for (int step = 0; step < 3; ++step)
  554. {
  555. // Calculate expected position
  556. x += penetration_recovery * (radius_and_padding - x);
  557. // Step character and check that it matches expected recovery
  558. character.Step();
  559. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), RVec3(x, 0, 0));
  560. }
  561. }
  562. }
  563. }