CharacterVirtualTest.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. void CharacterVirtualTest::Initialize()
  15. {
  16. CharacterBaseTest::Initialize();
  17. // Create 'player' character
  18. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  19. settings->mMaxSlopeAngle = sMaxSlopeAngle;
  20. settings->mMaxStrength = sMaxStrength;
  21. settings->mShape = mStandingShape;
  22. settings->mCharacterPadding = sCharacterPadding;
  23. settings->mPenetrationRecoverySpeed = sPenetrationRecoverySpeed;
  24. settings->mPredictiveContactDistance = sPredictiveContactDistance;
  25. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  26. mCharacter = new CharacterVirtual(settings, RVec3::sZero(), Quat::sIdentity(), mPhysicsSystem);
  27. mCharacter->SetListener(this);
  28. }
  29. void CharacterVirtualTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  30. {
  31. CharacterBaseTest::PrePhysicsUpdate(inParams);
  32. // Draw character pre update (the sim is also drawn pre update)
  33. RMat44 com = mCharacter->GetCenterOfMassTransform();
  34. #ifdef JPH_DEBUG_RENDERER
  35. mCharacter->GetShape()->Draw(mDebugRenderer, com, Vec3::sReplicate(1.0f), Color::sGreen, false, true);
  36. #endif // JPH_DEBUG_RENDERER
  37. // Draw shape including padding (only implemented for capsules right now)
  38. if (static_cast<const RotatedTranslatedShape *>(mCharacter->GetShape())->GetInnerShape()->GetSubType() == EShapeSubType::Capsule)
  39. {
  40. if (mCharacter->GetShape() == mStandingShape)
  41. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  42. else
  43. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  44. }
  45. // Remember old position
  46. RVec3 old_position = mCharacter->GetPosition();
  47. // Settings for our update function
  48. CharacterVirtual::ExtendedUpdateSettings update_settings;
  49. if (!sEnableStickToFloor)
  50. update_settings.mStickToFloorStepDown = Vec3::sZero();
  51. else
  52. update_settings.mStickToFloorStepDown = -mCharacter->GetUp() * update_settings.mStickToFloorStepDown.Length();
  53. if (!sEnableWalkStairs)
  54. update_settings.mWalkStairsStepUp = Vec3::sZero();
  55. else
  56. update_settings.mWalkStairsStepUp = mCharacter->GetUp() * update_settings.mWalkStairsStepUp.Length();
  57. // Update the character position
  58. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  59. -mCharacter->GetUp() * mPhysicsSystem->GetGravity().Length(),
  60. update_settings,
  61. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  62. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  63. { },
  64. { },
  65. *mTempAllocator);
  66. // Calculate effective velocity
  67. RVec3 new_position = mCharacter->GetPosition();
  68. Vec3 velocity = Vec3(new_position - old_position) / inParams.mDeltaTime;
  69. // Draw state of character
  70. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), velocity);
  71. // Draw labels on ramp blocks
  72. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  73. 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);
  74. }
  75. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  76. {
  77. bool player_controls_horizontal_velocity = sControlMovementDuringJump || mCharacter->IsSupported();
  78. if (player_controls_horizontal_velocity)
  79. {
  80. // Smooth the player input
  81. mDesiredVelocity = 0.25f * inMovementDirection * sCharacterSpeed + 0.75f * mDesiredVelocity;
  82. // True if the player intended to move
  83. mAllowSliding = !inMovementDirection.IsNearZero();
  84. }
  85. else
  86. {
  87. // While in air we allow sliding
  88. mAllowSliding = true;
  89. }
  90. // Update the character rotation and its up vector to match the up vector set by the user settings
  91. Quat character_up_rotation = Quat::sEulerAngles(Vec3(sUpRotationX, 0, sUpRotationZ));
  92. mCharacter->SetUp(character_up_rotation.RotateAxisY());
  93. mCharacter->SetRotation(character_up_rotation);
  94. // Determine new basic velocity
  95. Vec3 current_vertical_velocity = mCharacter->GetLinearVelocity().Dot(mCharacter->GetUp()) * mCharacter->GetUp();
  96. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  97. Vec3 new_velocity;
  98. if (mCharacter->GetGroundState() == 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 += sJumpSpeed * mCharacter->GetUp();
  106. }
  107. else
  108. new_velocity = current_vertical_velocity;
  109. // Gravity
  110. new_velocity += (character_up_rotation * mPhysicsSystem->GetGravity()) * inDeltaTime;
  111. if (player_controls_horizontal_velocity)
  112. {
  113. // Player input
  114. new_velocity += character_up_rotation * mDesiredVelocity;
  115. }
  116. else
  117. {
  118. // Preserve horizontal velocity
  119. Vec3 current_horizontal_velocity = mCharacter->GetLinearVelocity() - current_vertical_velocity;
  120. new_velocity += current_horizontal_velocity;
  121. }
  122. // Update character velocity
  123. mCharacter->SetLinearVelocity(new_velocity);
  124. // Stance switch
  125. if (inSwitchStance)
  126. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, { }, *mTempAllocator);
  127. }
  128. void CharacterVirtualTest::AddConfigurationSettings(DebugUI *inUI, UIElement *inSubMenu)
  129. {
  130. inUI->CreateSlider(inSubMenu, "Up Rotation X (degrees)", RadiansToDegrees(sUpRotationX), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationX = DegreesToRadians(inValue); });
  131. inUI->CreateSlider(inSubMenu, "Up Rotation Z (degrees)", RadiansToDegrees(sUpRotationZ), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationZ = DegreesToRadians(inValue); });
  132. inUI->CreateSlider(inSubMenu, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  133. inUI->CreateSlider(inSubMenu, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  134. inUI->CreateSlider(inSubMenu, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  135. inUI->CreateSlider(inSubMenu, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  136. inUI->CreateSlider(inSubMenu, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  137. inUI->CreateCheckBox(inSubMenu, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  138. inUI->CreateCheckBox(inSubMenu, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  139. }
  140. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  141. {
  142. CharacterBaseTest::SaveState(inStream);
  143. mCharacter->SaveState(inStream);
  144. bool is_standing = mCharacter->GetShape() == mStandingShape;
  145. inStream.Write(is_standing);
  146. inStream.Write(mAllowSliding);
  147. inStream.Write(mDesiredVelocity);
  148. }
  149. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  150. {
  151. CharacterBaseTest::RestoreState(inStream);
  152. mCharacter->RestoreState(inStream);
  153. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  154. inStream.Read(is_standing);
  155. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, { }, *mTempAllocator);
  156. inStream.Read(mAllowSliding);
  157. inStream.Read(mDesiredVelocity);
  158. }
  159. void CharacterVirtualTest::OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity)
  160. {
  161. // Apply artificial velocity to the character when standing on the conveyor belt
  162. if (inBody2.GetID() == mConveyorBeltBody)
  163. ioLinearVelocity += Vec3(0, 0, 2);
  164. }
  165. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  166. {
  167. // Dynamic boxes on the ramp go through all permutations
  168. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  169. if (i != mRampBlocks.end())
  170. {
  171. size_t index = i - mRampBlocks.begin();
  172. ioSettings.mCanPushCharacter = (index & 1) != 0;
  173. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  174. }
  175. // If we encounter an object that can push us, enable sliding
  176. if (ioSettings.mCanPushCharacter && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  177. mAllowSliding = true;
  178. }
  179. void CharacterVirtualTest::OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity)
  180. {
  181. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  182. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  183. ioNewCharacterVelocity = Vec3::sZero();
  184. }