CharacterVirtualTest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Character/CharacterVirtualTest.h>
  5. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  6. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  7. #include <Layers.h>
  8. #include <Renderer/DebugRendererImp.h>
  9. #include <Application/DebugUI.h>
  10. JPH_IMPLEMENT_RTTI_VIRTUAL(CharacterVirtualTest)
  11. {
  12. JPH_ADD_BASE_CLASS(CharacterVirtualTest, CharacterBaseTest)
  13. }
  14. static const Vec3 cStepUpHeight = Vec3(0.0f, 0.4f, 0.0f);
  15. static const float cMinStepForward = 0.02f;
  16. static const float cStepForwardTest = 0.15f;
  17. void CharacterVirtualTest::Initialize()
  18. {
  19. CharacterBaseTest::Initialize();
  20. // Create 'player' character
  21. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  22. settings->mMaxSlopeAngle = sMaxSlopeAngle;
  23. settings->mMaxStrength = sMaxStrength;
  24. settings->mShape = mStandingShape;
  25. settings->mCharacterPadding = sCharacterPadding;
  26. settings->mPenetrationRecoverySpeed = sPenetrationRecoverySpeed;
  27. settings->mPredictiveContactDistance = sPredictiveContactDistance;
  28. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  29. mCharacter = new CharacterVirtual(settings, Vec3::sZero(), Quat::sIdentity(), mPhysicsSystem);
  30. mCharacter->SetListener(this);
  31. }
  32. void CharacterVirtualTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  33. {
  34. CharacterBaseTest::PrePhysicsUpdate(inParams);
  35. // Draw character pre update (the sim is also drawn pre update)
  36. Mat44 com = mCharacter->GetCenterOfMassTransform();
  37. if (mCharacter->GetShape() == mStandingShape)
  38. {
  39. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding, Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  40. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  41. }
  42. else
  43. {
  44. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching, Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  45. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  46. }
  47. // Remember old position
  48. Vec3 old_position = mCharacter->GetPosition();
  49. // Track that on ground before the update
  50. bool ground_to_air = mCharacter->IsSupported();
  51. // Update the character position (instant, do not have to wait for physics update)
  52. mCharacter->Update(inParams.mDeltaTime, mPhysicsSystem->GetGravity(), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  53. // ... and that we got into air after
  54. if (mCharacter->IsSupported())
  55. ground_to_air = false;
  56. // If we're in air for the first frame and the user has enabled stick to floor
  57. if (sEnableStickToFloor && ground_to_air)
  58. {
  59. // If we're not moving up, stick to the floor
  60. float velocity = (mCharacter->GetPosition().GetY() - old_position.GetY()) / inParams.mDeltaTime;
  61. if (velocity <= 1.0e-6f)
  62. mCharacter->StickToFloor(Vec3(0, -0.5f, 0), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  63. }
  64. // Allow user to turn off walk stairs algorithm
  65. if (sEnableWalkStairs)
  66. {
  67. // Calculate how much we wanted to move horizontally
  68. Vec3 desired_horizontal_step = mDesiredVelocity * inParams.mDeltaTime;
  69. float desired_horizontal_step_len = desired_horizontal_step.Length();
  70. if (desired_horizontal_step_len > 0.0f)
  71. {
  72. // Calculate how much we moved horizontally
  73. Vec3 achieved_horizontal_step = mCharacter->GetPosition() - old_position;
  74. achieved_horizontal_step.SetY(0);
  75. // Only count movement in the direction of the desired movement
  76. // (otherwise we find it ok if we're sliding downhill while we're trying to climb uphill)
  77. Vec3 step_forward_normalized = desired_horizontal_step / desired_horizontal_step_len;
  78. achieved_horizontal_step = max(0.0f, achieved_horizontal_step.Dot(step_forward_normalized)) * step_forward_normalized;
  79. float achieved_horizontal_step_len = achieved_horizontal_step.Length();
  80. // If we didn't move as far as we wanted and we're against a slope that's too steep
  81. if (achieved_horizontal_step_len + 1.0e-4f < desired_horizontal_step_len
  82. && mCharacter->CanWalkStairs(mDesiredVelocity))
  83. {
  84. // Calculate how much we should step forward
  85. // Note that we clamp the step forward to a minimum distance. This is done because at very high frame rates the delta time
  86. // may be very small, causing a very small step forward. If the step becomes small enough, we may not move far enough
  87. // horizontally to actually end up at the top of the step.
  88. Vec3 step_forward = step_forward_normalized * max(cMinStepForward, desired_horizontal_step_len - achieved_horizontal_step_len);
  89. // Calculate how far to scan ahead for a floor. This is only used in case the floor normal at step_forward is too steep.
  90. // In that case an additional check will be performed at this distance to check if that normal is not too steep.
  91. Vec3 step_forward_test = step_forward_normalized * cStepForwardTest;
  92. mCharacter->WalkStairs(inParams.mDeltaTime, cStepUpHeight, step_forward, step_forward_test, Vec3::sZero(), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  93. }
  94. }
  95. }
  96. // Calculate effective velocity
  97. Vec3 new_position = mCharacter->GetPosition();
  98. Vec3 velocity = (new_position - old_position) / inParams.mDeltaTime;
  99. // Draw state of character
  100. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), velocity);
  101. // Draw labels on ramp blocks
  102. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  103. mDebugRenderer->DrawText3D(mBodyInterface->GetPosition(mRampBlocks[i]), StringFormat("PushesPlayer: %s\nPushable: %s", (i & 1) != 0? "True" : "False", (i & 2) != 0? "True" : "False"), Color::sWhite, 0.25f);
  104. }
  105. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  106. {
  107. // Smooth the player input
  108. mDesiredVelocity = 0.25f * inMovementDirection * cCharacterSpeed + 0.75f * mDesiredVelocity;
  109. // True if the player intended to move
  110. mAllowSliding = !inMovementDirection.IsNearZero();
  111. // Cancel movement in opposite direction of normal when touching something we can't walk up
  112. CharacterVirtual::EGroundState ground_state = mCharacter->GetGroundState();
  113. Vec3 desired_velocity = mDesiredVelocity;
  114. if (ground_state == CharacterVirtual::EGroundState::OnSteepGround
  115. || ground_state == CharacterVirtual::EGroundState::NotSupported)
  116. {
  117. Vec3 normal = mCharacter->GetGroundNormal();
  118. normal.SetY(0.0f);
  119. float dot = normal.Dot(desired_velocity);
  120. if (dot < 0.0f)
  121. desired_velocity -= (dot * normal) / normal.LengthSq();
  122. }
  123. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  124. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  125. Vec3 new_velocity;
  126. if (ground_state == CharacterVirtual::EGroundState::OnGround // If on ground
  127. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  128. {
  129. // Assume velocity of ground when on ground
  130. new_velocity = ground_velocity;
  131. // Jump
  132. if (inJump)
  133. new_velocity += Vec3(0, cJumpSpeed, 0);
  134. }
  135. else
  136. new_velocity = current_vertical_velocity;
  137. // Gravity
  138. new_velocity += mPhysicsSystem->GetGravity() * inDeltaTime;
  139. // Player input
  140. new_velocity += desired_velocity;
  141. // Update the velocity
  142. mCharacter->SetLinearVelocity(new_velocity);
  143. // Stance switch
  144. if (inSwitchStance)
  145. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  146. }
  147. void CharacterVirtualTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  148. {
  149. CharacterBaseTest::CreateSettingsMenu(inUI, inSubMenu);
  150. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [=]() {
  151. UIElement *configuration_settings = inUI->CreateMenu();
  152. inUI->CreateSlider(configuration_settings, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  153. inUI->CreateSlider(configuration_settings, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  154. inUI->CreateSlider(configuration_settings, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  155. inUI->CreateSlider(configuration_settings, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  156. inUI->CreateSlider(configuration_settings, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  157. inUI->CreateCheckBox(configuration_settings, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  158. inUI->CreateCheckBox(configuration_settings, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  159. inUI->CreateTextButton(configuration_settings, "Accept Changes", [=]() { RestartTest(); });
  160. inUI->ShowMenu(configuration_settings);
  161. });
  162. }
  163. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  164. {
  165. CharacterBaseTest::SaveState(inStream);
  166. mCharacter->SaveState(inStream);
  167. bool is_standing = mCharacter->GetShape() == mStandingShape;
  168. inStream.Write(is_standing);
  169. inStream.Write(mDesiredVelocity);
  170. }
  171. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  172. {
  173. CharacterBaseTest::RestoreState(inStream);
  174. mCharacter->RestoreState(inStream);
  175. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  176. inStream.Read(is_standing);
  177. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, *mTempAllocator);
  178. inStream.Read(mDesiredVelocity);
  179. }
  180. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  181. {
  182. // Dynamic boxes on the ramp go through all permutations
  183. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  184. if (i != mRampBlocks.end())
  185. {
  186. size_t index = i - mRampBlocks.begin();
  187. ioSettings.mCanPushCharacter = (index & 1) != 0;
  188. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  189. }
  190. // If we encounter an object that can push us, enable sliding
  191. if (ioSettings.mCanPushCharacter && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  192. mAllowSliding = true;
  193. }
  194. void CharacterVirtualTest::OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity)
  195. {
  196. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  197. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  198. ioNewCharacterVelocity = Vec3::sZero();
  199. }