CharacterVirtualTest.cpp 11 KB

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