CharacterVirtualTest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Character/CharacterVirtualTest.h>
  6. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Layers.h>
  9. #include <Renderer/DebugRendererImp.h>
  10. #include <Application/DebugUI.h>
  11. JPH_IMPLEMENT_RTTI_VIRTUAL(CharacterVirtualTest)
  12. {
  13. JPH_ADD_BASE_CLASS(CharacterVirtualTest, CharacterBaseTest)
  14. }
  15. void CharacterVirtualTest::Initialize()
  16. {
  17. CharacterBaseTest::Initialize();
  18. // Create 'player' character
  19. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  20. settings->mMaxSlopeAngle = sMaxSlopeAngle;
  21. settings->mMaxStrength = sMaxStrength;
  22. settings->mShape = mStandingShape;
  23. settings->mBackFaceMode = sBackFaceMode;
  24. settings->mCharacterPadding = sCharacterPadding;
  25. settings->mPenetrationRecoverySpeed = sPenetrationRecoverySpeed;
  26. settings->mPredictiveContactDistance = sPredictiveContactDistance;
  27. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  28. settings->mEnhancedInternalEdgeRemoval = sEnhancedInternalEdgeRemoval;
  29. mCharacter = new CharacterVirtual(settings, RVec3::sZero(), Quat::sIdentity(), 0, mPhysicsSystem);
  30. mCharacter->SetCharacterVsCharacterCollision(&mCharacterVsCharacterCollision);
  31. mCharacterVsCharacterCollision.Add(mCharacter);
  32. // Install contact listener for all characters
  33. for (CharacterVirtual *character : mCharacterVsCharacterCollision.mCharacters)
  34. character->SetListener(this);
  35. }
  36. void CharacterVirtualTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  37. {
  38. CharacterBaseTest::PrePhysicsUpdate(inParams);
  39. // Draw character pre update (the sim is also drawn pre update)
  40. RMat44 com = mCharacter->GetCenterOfMassTransform();
  41. RMat44 world_transform = mCharacter->GetWorldTransform();
  42. #ifdef JPH_DEBUG_RENDERER
  43. mCharacter->GetShape()->Draw(mDebugRenderer, com, Vec3::sReplicate(1.0f), Color::sGreen, false, true);
  44. #endif // JPH_DEBUG_RENDERER
  45. // Draw shape including padding (only implemented for capsules right now)
  46. if (static_cast<const RotatedTranslatedShape *>(mCharacter->GetShape())->GetInnerShape()->GetSubType() == EShapeSubType::Capsule)
  47. {
  48. if (mCharacter->GetShape() == mStandingShape)
  49. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  50. else
  51. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  52. }
  53. // Remember old position
  54. RVec3 old_position = mCharacter->GetPosition();
  55. // Settings for our update function
  56. CharacterVirtual::ExtendedUpdateSettings update_settings;
  57. if (!sEnableStickToFloor)
  58. update_settings.mStickToFloorStepDown = Vec3::sZero();
  59. else
  60. update_settings.mStickToFloorStepDown = -mCharacter->GetUp() * update_settings.mStickToFloorStepDown.Length();
  61. if (!sEnableWalkStairs)
  62. update_settings.mWalkStairsStepUp = Vec3::sZero();
  63. else
  64. update_settings.mWalkStairsStepUp = mCharacter->GetUp() * update_settings.mWalkStairsStepUp.Length();
  65. // Update the character position
  66. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  67. -mCharacter->GetUp() * mPhysicsSystem->GetGravity().Length(),
  68. update_settings,
  69. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  70. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  71. { },
  72. { },
  73. *mTempAllocator);
  74. // Calculate effective velocity
  75. RVec3 new_position = mCharacter->GetPosition();
  76. Vec3 velocity = Vec3(new_position - old_position) / inParams.mDeltaTime;
  77. // Draw state of character
  78. DrawCharacterState(mCharacter, world_transform, velocity);
  79. // Draw labels on ramp blocks
  80. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  81. 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);
  82. }
  83. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  84. {
  85. bool player_controls_horizontal_velocity = sControlMovementDuringJump || mCharacter->IsSupported();
  86. if (player_controls_horizontal_velocity)
  87. {
  88. // Smooth the player input
  89. mDesiredVelocity = sEnableCharacterInertia? 0.25f * inMovementDirection * sCharacterSpeed + 0.75f * mDesiredVelocity : inMovementDirection * sCharacterSpeed;
  90. // True if the player intended to move
  91. mAllowSliding = !inMovementDirection.IsNearZero();
  92. }
  93. else
  94. {
  95. // While in air we allow sliding
  96. mAllowSliding = true;
  97. }
  98. // Update the character rotation and its up vector to match the up vector set by the user settings
  99. Quat character_up_rotation = Quat::sEulerAngles(Vec3(sUpRotationX, 0, sUpRotationZ));
  100. mCharacter->SetUp(character_up_rotation.RotateAxisY());
  101. mCharacter->SetRotation(character_up_rotation);
  102. // A cheaper way to update the character's ground velocity,
  103. // the platforms that the character is standing on may have changed velocity
  104. mCharacter->UpdateGroundVelocity();
  105. // Determine new basic velocity
  106. Vec3 current_vertical_velocity = mCharacter->GetLinearVelocity().Dot(mCharacter->GetUp()) * mCharacter->GetUp();
  107. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  108. Vec3 new_velocity;
  109. bool moving_towards_ground = (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f;
  110. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  111. && (sEnableCharacterInertia?
  112. moving_towards_ground // Inertia enabled: And not moving away from ground
  113. : !mCharacter->IsSlopeTooSteep(mCharacter->GetGroundNormal()))) // Inertia disabled: And not on a slope that is too steep
  114. {
  115. // Assume velocity of ground when on ground
  116. new_velocity = ground_velocity;
  117. // Jump
  118. if (inJump && moving_towards_ground)
  119. new_velocity += sJumpSpeed * mCharacter->GetUp();
  120. }
  121. else
  122. new_velocity = current_vertical_velocity;
  123. // Gravity
  124. new_velocity += (character_up_rotation * mPhysicsSystem->GetGravity()) * inDeltaTime;
  125. if (player_controls_horizontal_velocity)
  126. {
  127. // Player input
  128. new_velocity += character_up_rotation * mDesiredVelocity;
  129. }
  130. else
  131. {
  132. // Preserve horizontal velocity
  133. Vec3 current_horizontal_velocity = mCharacter->GetLinearVelocity() - current_vertical_velocity;
  134. new_velocity += current_horizontal_velocity;
  135. }
  136. // Update character velocity
  137. mCharacter->SetLinearVelocity(new_velocity);
  138. // Stance switch
  139. if (inSwitchStance)
  140. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, { }, *mTempAllocator);
  141. }
  142. void CharacterVirtualTest::AddCharacterMovementSettings(DebugUI* inUI, UIElement* inSubMenu)
  143. {
  144. inUI->CreateCheckBox(inSubMenu, "Enable Character Inertia", sEnableCharacterInertia, [](UICheckBox::EState inState) { sEnableCharacterInertia = inState == UICheckBox::STATE_CHECKED; });
  145. inUI->CreateCheckBox(inSubMenu, "Player Can Push Other Virtual Characters", sPlayerCanPushOtherCharacters, [](UICheckBox::EState inState) { sPlayerCanPushOtherCharacters = inState == UICheckBox::STATE_CHECKED; });
  146. inUI->CreateCheckBox(inSubMenu, "Other Virtual Characters Can Push Player", sOtherCharactersCanPushPlayer, [](UICheckBox::EState inState) { sOtherCharactersCanPushPlayer = inState == UICheckBox::STATE_CHECKED; });
  147. }
  148. void CharacterVirtualTest::AddConfigurationSettings(DebugUI *inUI, UIElement *inSubMenu)
  149. {
  150. inUI->CreateComboBox(inSubMenu, "Back Face Mode", { "Ignore", "Collide" }, (int)sBackFaceMode, [=](int inItem) { sBackFaceMode = (EBackFaceMode)inItem; });
  151. inUI->CreateSlider(inSubMenu, "Up Rotation X (degrees)", RadiansToDegrees(sUpRotationX), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationX = DegreesToRadians(inValue); });
  152. inUI->CreateSlider(inSubMenu, "Up Rotation Z (degrees)", RadiansToDegrees(sUpRotationZ), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationZ = DegreesToRadians(inValue); });
  153. inUI->CreateSlider(inSubMenu, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  154. inUI->CreateSlider(inSubMenu, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  155. inUI->CreateSlider(inSubMenu, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  156. inUI->CreateSlider(inSubMenu, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  157. inUI->CreateSlider(inSubMenu, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  158. inUI->CreateCheckBox(inSubMenu, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  159. inUI->CreateCheckBox(inSubMenu, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  160. inUI->CreateCheckBox(inSubMenu, "Enhanced Internal Edge Removal", sEnhancedInternalEdgeRemoval, [](UICheckBox::EState inState) { sEnhancedInternalEdgeRemoval = inState == UICheckBox::STATE_CHECKED; });
  161. }
  162. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  163. {
  164. CharacterBaseTest::SaveState(inStream);
  165. mCharacter->SaveState(inStream);
  166. bool is_standing = mCharacter->GetShape() == mStandingShape;
  167. inStream.Write(is_standing);
  168. inStream.Write(mAllowSliding);
  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(mAllowSliding);
  179. inStream.Read(mDesiredVelocity);
  180. }
  181. void CharacterVirtualTest::OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity)
  182. {
  183. // Apply artificial velocity to the character when standing on the conveyor belt
  184. if (inBody2.GetID() == mConveyorBeltBody)
  185. ioLinearVelocity += Vec3(0, 0, 2);
  186. }
  187. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  188. {
  189. // Draw a box around the character when it enters the sensor
  190. if (inBodyID2 == mSensorBody)
  191. {
  192. AABox box = inCharacter->GetShape()->GetWorldSpaceBounds(inCharacter->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f));
  193. mDebugRenderer->DrawBox(box, Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  194. }
  195. // Dynamic boxes on the ramp go through all permutations
  196. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  197. if (i != mRampBlocks.end())
  198. {
  199. size_t index = i - mRampBlocks.begin();
  200. ioSettings.mCanPushCharacter = (index & 1) != 0;
  201. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  202. }
  203. // If we encounter an object that can push the player, enable sliding
  204. if (inCharacter == mCharacter
  205. && ioSettings.mCanPushCharacter
  206. && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  207. mAllowSliding = true;
  208. }
  209. void CharacterVirtualTest::OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  210. {
  211. // Characters can only be pushed in their own update
  212. if (sPlayerCanPushOtherCharacters)
  213. ioSettings.mCanPushCharacter = sOtherCharactersCanPushPlayer || inOtherCharacter == mCharacter;
  214. else if (sOtherCharactersCanPushPlayer)
  215. ioSettings.mCanPushCharacter = inCharacter == mCharacter;
  216. else
  217. ioSettings.mCanPushCharacter = false;
  218. // If the player can be pushed by the other virtual character, we allow sliding
  219. if (inCharacter == mCharacter && ioSettings.mCanPushCharacter)
  220. mAllowSliding = true;
  221. }
  222. 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)
  223. {
  224. // Ignore callbacks for other characters than the player
  225. if (inCharacter != mCharacter)
  226. return;
  227. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  228. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  229. ioNewCharacterVelocity = Vec3::sZero();
  230. }