CharacterVirtualTest.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 cStickToFloorStepDown(0, -0.5f, 0);
  15. static const Vec3 cWalkStairsStepUp = Vec3(0.0f, 0.4f, 0.0f);
  16. static const float cWalkStairsMinStepForward = 0.02f;
  17. static const float cWalkStairsStepForwardTest = 0.15f;
  18. static const Vec3 cWalkStairsStepDownExtra = Vec3::sZero();
  19. void CharacterVirtualTest::Initialize()
  20. {
  21. CharacterBaseTest::Initialize();
  22. // Create 'player' character
  23. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  24. settings->mMaxSlopeAngle = sMaxSlopeAngle;
  25. settings->mMaxStrength = sMaxStrength;
  26. settings->mShape = mStandingShape;
  27. settings->mCharacterPadding = sCharacterPadding;
  28. settings->mPenetrationRecoverySpeed = sPenetrationRecoverySpeed;
  29. settings->mPredictiveContactDistance = sPredictiveContactDistance;
  30. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  31. mCharacter = new CharacterVirtual(settings, Vec3::sZero(), Quat::sIdentity(), mPhysicsSystem);
  32. mCharacter->SetListener(this);
  33. }
  34. void CharacterVirtualTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  35. {
  36. CharacterBaseTest::PrePhysicsUpdate(inParams);
  37. // Draw character pre update (the sim is also drawn pre update)
  38. Mat44 com = mCharacter->GetCenterOfMassTransform();
  39. if (mCharacter->GetShape() == mStandingShape)
  40. {
  41. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding, Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  42. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  43. }
  44. else
  45. {
  46. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching, Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  47. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  48. }
  49. // Remember old position
  50. Vec3 old_position = mCharacter->GetPosition();
  51. // Update the character position
  52. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  53. mPhysicsSystem->GetGravity(),
  54. sEnableStickToFloor? cStickToFloorStepDown : Vec3::sZero(),
  55. sEnableWalkStairs? cWalkStairsStepUp : Vec3::sZero(),
  56. cWalkStairsMinStepForward,
  57. cWalkStairsStepForwardTest,
  58. cWalkStairsStepDownExtra,
  59. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  60. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  61. { },
  62. *mTempAllocator);
  63. // Calculate effective velocity
  64. Vec3 new_position = mCharacter->GetPosition();
  65. Vec3 velocity = (new_position - old_position) / inParams.mDeltaTime;
  66. // Draw state of character
  67. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), velocity);
  68. // Draw labels on ramp blocks
  69. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  70. 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);
  71. }
  72. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  73. {
  74. // Smooth the player input
  75. mDesiredVelocity = 0.25f * inMovementDirection * cCharacterSpeed + 0.75f * mDesiredVelocity;
  76. // True if the player intended to move
  77. mAllowSliding = !inMovementDirection.IsNearZero();
  78. // Determine new basic velocity
  79. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  80. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  81. Vec3 new_velocity;
  82. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  83. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  84. {
  85. // Assume velocity of ground when on ground
  86. new_velocity = ground_velocity;
  87. // Jump
  88. if (inJump)
  89. new_velocity += Vec3(0, cJumpSpeed, 0);
  90. }
  91. else
  92. new_velocity = current_vertical_velocity;
  93. // Gravity
  94. new_velocity += mPhysicsSystem->GetGravity() * inDeltaTime;
  95. // Player input
  96. new_velocity += mDesiredVelocity;
  97. // Update character velocity
  98. mCharacter->SetLinearVelocity(new_velocity);
  99. // Stance switch
  100. if (inSwitchStance)
  101. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  102. }
  103. void CharacterVirtualTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  104. {
  105. CharacterBaseTest::CreateSettingsMenu(inUI, inSubMenu);
  106. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [=]() {
  107. UIElement *configuration_settings = inUI->CreateMenu();
  108. inUI->CreateSlider(configuration_settings, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  109. inUI->CreateSlider(configuration_settings, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  110. inUI->CreateSlider(configuration_settings, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  111. inUI->CreateSlider(configuration_settings, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  112. inUI->CreateSlider(configuration_settings, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  113. inUI->CreateCheckBox(configuration_settings, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  114. inUI->CreateCheckBox(configuration_settings, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  115. inUI->CreateTextButton(configuration_settings, "Accept Changes", [=]() { RestartTest(); });
  116. inUI->ShowMenu(configuration_settings);
  117. });
  118. }
  119. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  120. {
  121. CharacterBaseTest::SaveState(inStream);
  122. mCharacter->SaveState(inStream);
  123. bool is_standing = mCharacter->GetShape() == mStandingShape;
  124. inStream.Write(is_standing);
  125. inStream.Write(mDesiredVelocity);
  126. }
  127. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  128. {
  129. CharacterBaseTest::RestoreState(inStream);
  130. mCharacter->RestoreState(inStream);
  131. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  132. inStream.Read(is_standing);
  133. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, *mTempAllocator);
  134. inStream.Read(mDesiredVelocity);
  135. }
  136. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  137. {
  138. // Dynamic boxes on the ramp go through all permutations
  139. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  140. if (i != mRampBlocks.end())
  141. {
  142. size_t index = i - mRampBlocks.begin();
  143. ioSettings.mCanPushCharacter = (index & 1) != 0;
  144. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  145. }
  146. // If we encounter an object that can push us, enable sliding
  147. if (ioSettings.mCanPushCharacter && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  148. mAllowSliding = true;
  149. }
  150. 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)
  151. {
  152. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  153. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  154. ioNewCharacterVelocity = Vec3::sZero();
  155. }