CharacterVirtualTest.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. // Update the character position (instant, do not have to wait for physics update)
  48. mCharacter->Update(inParams.mDeltaTime, mPhysicsSystem->GetGravity(), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  49. // Allow user to turn off walk stairs algorithm
  50. if (sEnableWalkStairs)
  51. {
  52. // Calculate how much we wanted to move horizontally
  53. Vec3 desired_horizontal_step = mCharacter->GetLinearVelocity() * inParams.mDeltaTime;
  54. desired_horizontal_step.SetY(0);
  55. float desired_horizontal_step_len = desired_horizontal_step.Length();
  56. // Calculate how much we moved horizontally
  57. Vec3 achieved_horizontal_step = mCharacter->GetPosition() - old_position;
  58. achieved_horizontal_step.SetY(0);
  59. float achieved_horizontal_step_len = achieved_horizontal_step.Length();
  60. // If we didn't move as far as we wanted and we're against a slope that's too steep
  61. if (achieved_horizontal_step_len + 1.0e-4f < desired_horizontal_step_len
  62. && mCharacter->CanWalkStairs())
  63. {
  64. // Calculate how much we should step forward
  65. Vec3 step_forward_normalized = desired_horizontal_step / desired_horizontal_step_len;
  66. Vec3 step_forward = step_forward_normalized * (desired_horizontal_step_len - achieved_horizontal_step_len);
  67. // Calculate how far to scan ahead for a floor
  68. Vec3 step_forward_test = step_forward_normalized * cMinStepForward;
  69. mCharacter->WalkStairs(inParams.mDeltaTime, mPhysicsSystem->GetGravity(), cStepUpHeight, step_forward, step_forward_test, Vec3::sZero(), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  70. }
  71. }
  72. // Calculate effective velocity
  73. Vec3 new_position = mCharacter->GetPosition();
  74. Vec3 velocity = (new_position - old_position) / inParams.mDeltaTime;
  75. // Draw state of character
  76. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), velocity);
  77. // Draw labels on ramp blocks
  78. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  79. 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);
  80. }
  81. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  82. {
  83. // Cancel movement in opposite direction of normal when sliding
  84. CharacterVirtual::EGroundState ground_state = mCharacter->GetGroundState();
  85. if (ground_state == CharacterVirtual::EGroundState::Sliding)
  86. {
  87. Vec3 normal = mCharacter->GetGroundNormal();
  88. normal.SetY(0.0f);
  89. float dot = normal.Dot(inMovementDirection);
  90. if (dot < 0.0f)
  91. inMovementDirection -= (dot * normal) / normal.LengthSq();
  92. }
  93. // Smooth the player input
  94. mSmoothMovementDirection = 0.25f * inMovementDirection + 0.75f * mSmoothMovementDirection;
  95. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  96. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  97. Vec3 new_velocity;
  98. if (ground_state == CharacterVirtual::EGroundState::OnGround // If on ground
  99. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  100. {
  101. // Assume velocity of ground when on ground
  102. new_velocity = ground_velocity;
  103. // Jump
  104. if (inJump)
  105. new_velocity += Vec3(0, cJumpSpeed, 0);
  106. }
  107. else
  108. new_velocity = current_vertical_velocity;
  109. // Gravity
  110. new_velocity += mPhysicsSystem->GetGravity() * inDeltaTime;
  111. // Player input
  112. new_velocity += mSmoothMovementDirection * cCharacterSpeed;
  113. // Update the velocity
  114. mCharacter->SetLinearVelocity(new_velocity);
  115. // Stance switch
  116. if (inSwitchStance)
  117. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  118. }
  119. void CharacterVirtualTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  120. {
  121. CharacterBaseTest::CreateSettingsMenu(inUI, inSubMenu);
  122. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [=]() {
  123. UIElement *configuration_settings = inUI->CreateMenu();
  124. inUI->CreateSlider(configuration_settings, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  125. inUI->CreateSlider(configuration_settings, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  126. inUI->CreateSlider(configuration_settings, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  127. inUI->CreateSlider(configuration_settings, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  128. inUI->CreateSlider(configuration_settings, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  129. inUI->CreateCheckBox(configuration_settings, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  130. inUI->CreateTextButton(configuration_settings, "Accept Changes", [=]() { RestartTest(); });
  131. inUI->ShowMenu(configuration_settings);
  132. });
  133. }
  134. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  135. {
  136. CharacterBaseTest::SaveState(inStream);
  137. mCharacter->SaveState(inStream);
  138. bool is_standing = mCharacter->GetShape() == mStandingShape;
  139. inStream.Write(is_standing);
  140. inStream.Write(mSmoothMovementDirection);
  141. }
  142. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  143. {
  144. CharacterBaseTest::RestoreState(inStream);
  145. mCharacter->RestoreState(inStream);
  146. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  147. inStream.Read(is_standing);
  148. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, *mTempAllocator);
  149. inStream.Read(mSmoothMovementDirection);
  150. }
  151. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  152. {
  153. // Dynamic boxes on the ramp go through all permutations
  154. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  155. if (i != mRampBlocks.end())
  156. {
  157. size_t index = i - mRampBlocks.begin();
  158. ioSettings.mCanPushCharacter = (index & 1) != 0;
  159. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  160. }
  161. }