CharacterBaseTest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Character/CharacterBaseTest.h>
  5. #include <Jolt/Physics/PhysicsScene.h>
  6. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  9. #include <Jolt/Core/StringTools.h>
  10. #include <Application/DebugUI.h>
  11. #include <Layers.h>
  12. #include <Utils/Log.h>
  13. #include <Renderer/DebugRendererImp.h>
  14. JPH_IMPLEMENT_RTTI_ABSTRACT(CharacterBaseTest)
  15. {
  16. JPH_ADD_BASE_CLASS(CharacterBaseTest, Test)
  17. }
  18. const char *CharacterBaseTest::sScenes[] =
  19. {
  20. "PerlinMesh",
  21. "PerlinHeightField",
  22. "ObstacleCourse",
  23. "Terrain1",
  24. "Terrain2",
  25. };
  26. const char *CharacterBaseTest::sSceneName = "ObstacleCourse";
  27. // Scene constants
  28. static const Vec3 cRotatingPosition(-5, 0.15f, 15);
  29. static const Quat cRotatingOrientation = Quat::sIdentity();
  30. static const Vec3 cVerticallyMovingPosition(0, 2.0f, 15);
  31. static const Quat cVerticallyMovingOrientation = Quat::sIdentity();
  32. static const Vec3 cHorizontallyMovingPosition(5, 1, 15);
  33. static const Quat cHorizontallyMovingOrientation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);
  34. static const Vec3 cRampPosition(15, 2.2f, 15);
  35. static const Quat cRampOrientation = Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI);
  36. static const Vec3 cRampBlocksStart = cRampPosition + Vec3(-3.0f, 3.0f, 1.5f);
  37. static const Vec3 cRampBlocksDelta = Vec3(2.0f, 0, 0);
  38. static const float cRampBlocksTime = 5.0f;
  39. static const Vec3 cBumpsPosition = Vec3(-5.0f, 0, 2.5f);
  40. static const float cBumpHeight = 0.05f;
  41. static const float cBumpWidth = 0.01f;
  42. static const float cBumpDelta = 0.5f;
  43. static const Vec3 cStairsPosition = Vec3(-10.0f, 0, 2.5f);
  44. static const float cStairsStepHeight = 0.3f;
  45. void CharacterBaseTest::Initialize()
  46. {
  47. if (strcmp(sSceneName, "PerlinMesh") == 0)
  48. {
  49. // Default terrain
  50. CreateMeshTerrain();
  51. }
  52. else if (strcmp(sSceneName, "PerlinHeightField") == 0)
  53. {
  54. // Default terrain
  55. CreateHeightFieldTerrain();
  56. }
  57. else if (strcmp(sSceneName, "ObstacleCourse") == 0)
  58. {
  59. // Default terrain
  60. CreateFloor();
  61. {
  62. // Create ramps with different inclinations
  63. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  64. for (int angle = 0; angle < 18; ++angle)
  65. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp, Vec3(-15.0f + angle * 2.0f, 0, -10.0f), Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(10.0f * angle)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  66. }
  67. {
  68. // Create wall consisting of vertical pillars
  69. // Note: Convex radius 0 because otherwise it will be a bumpy wall
  70. Ref<Shape> wall = new BoxShape(Vec3(0.1f, 2.5f, 0.1f), 0.0f);
  71. for (int z = 0; z < 40; ++z)
  72. mBodyInterface->CreateAndAddBody(BodyCreationSettings(wall, Vec3(-10.0f, 2.5f, -10.0f + 0.2f * z), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  73. }
  74. {
  75. // Kinematic blocks to test interacting with moving objects
  76. Ref<Shape> kinematic = new BoxShape(Vec3(1, 0.15f, 3.0f));
  77. mRotatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingPosition, cRotatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  78. mVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cVerticallyMovingPosition, cVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  79. mHorizontallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cHorizontallyMovingPosition, cHorizontallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  80. }
  81. {
  82. // Dynamic blocks to test player pushing blocks
  83. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  84. for (int y = 0; y < 3; ++y)
  85. {
  86. BodyCreationSettings bcs(block, Vec3(5.0f, 0.5f + float(y), 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  87. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  88. bcs.mMassPropertiesOverride.mMass = 10.0f;
  89. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  90. }
  91. }
  92. {
  93. // Create ramp
  94. BodyCreationSettings ramp(new BoxShape(Vec3(4.0f, 0.1f, 3.0f)), cRampPosition, cRampOrientation, EMotionType::Static, Layers::NON_MOVING);
  95. mBodyInterface->CreateAndAddBody(ramp, EActivation::DontActivate);
  96. // Create blocks on ramp
  97. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  98. BodyCreationSettings bcs(block, cRampBlocksStart, cRampOrientation, EMotionType::Dynamic, Layers::MOVING);
  99. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  100. bcs.mMassPropertiesOverride.mMass = 10.0f;
  101. for (int i = 0; i < 4; ++i)
  102. {
  103. mRampBlocks.emplace_back(mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate));
  104. bcs.mPosition += cRampBlocksDelta;
  105. }
  106. }
  107. // Create three funnels with walls that are too steep to climb
  108. Ref<Shape> funnel = new BoxShape(Vec3(0.1f, 1.0f, 1.0f));
  109. for (int i = 0; i < 2; ++i)
  110. {
  111. Quat rotation = Quat::sRotation(Vec3::sAxisY(), JPH_PI * i);
  112. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, Vec3(5.0f, 0.1f, 5.0f) + rotation * Vec3(0.2f, 0, 0), rotation * Quat::sRotation(Vec3::sAxisZ(), -DegreesToRadians(40.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  113. }
  114. for (int i = 0; i < 3; ++i)
  115. {
  116. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 2.0f / 3.0f * JPH_PI * i);
  117. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, Vec3(7.5f, 0.1f, 5.0f) + rotation * Vec3(0.2f, 0, 0), rotation * Quat::sRotation(Vec3::sAxisZ(), -DegreesToRadians(40.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  118. }
  119. for (int i = 0; i < 4; ++i)
  120. {
  121. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 0.5f * JPH_PI * i);
  122. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, Vec3(10.0f, 0.1f, 5.0f) + rotation * Vec3(0.2f, 0, 0), rotation * Quat::sRotation(Vec3::sAxisZ(), -DegreesToRadians(40.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  123. }
  124. // Create small bumps
  125. {
  126. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cBumpHeight, 0.5f * cBumpWidth), 0.0f), Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  127. for (int i = 0; i < 10; ++i)
  128. {
  129. step.mPosition = cBumpsPosition + Vec3(0, 0.5f * cBumpHeight, cBumpDelta * i);
  130. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  131. }
  132. }
  133. // Create stairs
  134. {
  135. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cStairsStepHeight, 0.5f * cStairsStepHeight)), Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  136. for (int i = 0; i < 10; ++i)
  137. {
  138. step.mPosition = cStairsPosition + Vec3(0, cStairsStepHeight * (0.5f + i), cStairsStepHeight * i);
  139. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  140. }
  141. }
  142. }
  143. else
  144. {
  145. // Load scene
  146. Ref<PhysicsScene> scene;
  147. if (!ObjectStreamIn::sReadObject((string("Assets/") + sSceneName + ".bof").c_str(), scene))
  148. FatalError("Failed to load scene");
  149. scene->FixInvalidScales();
  150. for (BodyCreationSettings &settings : scene->GetBodies())
  151. {
  152. settings.mObjectLayer = Layers::NON_MOVING;
  153. settings.mFriction = 0.5f;
  154. }
  155. scene->CreateBodies(mPhysicsSystem);
  156. }
  157. // Create capsule shapes for all stances
  158. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  159. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching)).Create().Get();
  160. }
  161. void CharacterBaseTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  162. {
  163. // Update scene time
  164. mTime += inParams.mDeltaTime;
  165. // Determine controller input
  166. Vec3 control_input = Vec3::sZero();
  167. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT)) control_input.SetZ(-1);
  168. if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT)) control_input.SetZ(1);
  169. if (inParams.mKeyboard->IsKeyPressed(DIK_UP)) control_input.SetX(1);
  170. if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN)) control_input.SetX(-1);
  171. if (control_input != Vec3::sZero())
  172. control_input = control_input.Normalized();
  173. // Rotate controls to align with the camera
  174. Vec3 cam_fwd = inParams.mCameraState.mForward;
  175. cam_fwd.SetY(0.0f);
  176. cam_fwd = cam_fwd.NormalizedOr(Vec3::sAxisX());
  177. Quat rotation = Quat::sFromTo(Vec3::sAxisX(), cam_fwd);
  178. control_input = rotation * control_input;
  179. // Check actions
  180. bool jump = false;
  181. bool switch_stance = false;
  182. for (int key = inParams.mKeyboard->GetFirstKey(); key != 0; key = inParams.mKeyboard->GetNextKey())
  183. {
  184. if (key == DIK_RSHIFT)
  185. switch_stance = true;
  186. else if (key == DIK_RCONTROL)
  187. jump = true;
  188. }
  189. HandleInput(control_input, jump, switch_stance, inParams.mDeltaTime);
  190. // Animate bodies
  191. if (!mRotatingBody.IsInvalid())
  192. mBodyInterface->MoveKinematic(mRotatingBody, cRotatingPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * sin(mTime)), inParams.mDeltaTime);
  193. if (!mHorizontallyMovingBody.IsInvalid())
  194. mBodyInterface->MoveKinematic(mHorizontallyMovingBody, cHorizontallyMovingPosition + Vec3(3.0f * sin(mTime), 0, 0), cHorizontallyMovingOrientation, inParams.mDeltaTime);
  195. if (!mVerticallyMovingBody.IsInvalid())
  196. mBodyInterface->MoveKinematic(mVerticallyMovingBody, cVerticallyMovingPosition + Vec3(0, 1.75f * sin(mTime), 0), cVerticallyMovingOrientation, inParams.mDeltaTime);
  197. // Reset ramp blocks
  198. mRampBlocksTimeLeft -= inParams.mDeltaTime;
  199. if (mRampBlocksTimeLeft < 0.0f)
  200. {
  201. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  202. {
  203. mBodyInterface->SetPositionAndRotation(mRampBlocks[i], cRampBlocksStart + float(i) * cRampBlocksDelta, cRampOrientation, EActivation::Activate);
  204. mBodyInterface->SetLinearAndAngularVelocity(mRampBlocks[i], Vec3::sZero(), Vec3::sZero());
  205. }
  206. mRampBlocksTimeLeft = cRampBlocksTime;
  207. }
  208. }
  209. void CharacterBaseTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  210. {
  211. inUI->CreateTextButton(inSubMenu, "Select Scene", [this, inUI]() {
  212. UIElement *scene_name = inUI->CreateMenu();
  213. for (uint i = 0; i < size(sScenes); ++i)
  214. inUI->CreateTextButton(scene_name, sScenes[i], [this, i]() { sSceneName = sScenes[i]; RestartTest(); });
  215. inUI->ShowMenu(scene_name);
  216. });
  217. }
  218. void CharacterBaseTest::GetInitialCamera(CameraState& ioState) const
  219. {
  220. // This will become the local space offset, look down the x axis and slightly down
  221. ioState.mPos = Vec3::sZero();
  222. ioState.mForward = Vec3(10.0f, -2.0f, 0).Normalized();
  223. }
  224. Mat44 CharacterBaseTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  225. {
  226. // Pivot is center of character + distance behind based on the heading and pitch of the camera
  227. Vec3 fwd = Vec3(cos(inCameraPitch) * cos(inCameraHeading), sin(inCameraPitch), cos(inCameraPitch) * sin(inCameraHeading));
  228. return Mat44::sTranslation(GetCharacterPosition() + Vec3(0, cCharacterHeightStanding + cCharacterRadiusStanding, 0) - 5.0f * fwd);
  229. }
  230. void CharacterBaseTest::SaveState(StateRecorder &inStream) const
  231. {
  232. inStream.Write(mTime);
  233. inStream.Write(mRampBlocksTimeLeft);
  234. }
  235. void CharacterBaseTest::RestoreState(StateRecorder &inStream)
  236. {
  237. inStream.Read(mTime);
  238. inStream.Read(mRampBlocksTimeLeft);
  239. }
  240. void CharacterBaseTest::DrawCharacterState(const CharacterBase *inCharacter, Mat44Arg inCharacterTransform, Vec3Arg inCharacterVelocity)
  241. {
  242. // Draw current location
  243. // Drawing prior to update since the physics system state is also that prior to the simulation step (so that all detected collisions etc. make sense)
  244. mDebugRenderer->DrawCoordinateSystem(inCharacterTransform);
  245. // Determine color
  246. CharacterBase::EGroundState ground_state = inCharacter->GetGroundState();
  247. Color color;
  248. switch (ground_state)
  249. {
  250. case CharacterBase::EGroundState::OnGround:
  251. color = Color::sGreen;
  252. break;
  253. case CharacterBase::EGroundState::Sliding:
  254. color = Color::sOrange;
  255. break;
  256. case CharacterBase::EGroundState::InAir:
  257. default:
  258. color = Color::sRed;
  259. break;
  260. }
  261. // Draw the state of the ground contact
  262. if (ground_state != CharacterBase::EGroundState::InAir)
  263. {
  264. Vec3 ground_position = inCharacter->GetGroundPosition();
  265. Vec3 ground_normal = inCharacter->GetGroundNormal();
  266. Vec3 ground_velocity = inCharacter->GetGroundVelocity();
  267. // Draw ground position
  268. mDebugRenderer->DrawWireSphere(ground_position, 0.1f, Color::sRed);
  269. mDebugRenderer->DrawArrow(ground_position, ground_position + 2.0f * ground_normal, Color::sGreen, 0.1f);
  270. // Draw ground velocity
  271. if (!ground_velocity.IsNearZero())
  272. mDebugRenderer->DrawArrow(ground_position, ground_position + ground_velocity, Color::sBlue, 0.1f);
  273. }
  274. // Draw provided character velocity
  275. if (!inCharacterVelocity.IsNearZero())
  276. mDebugRenderer->DrawArrow(inCharacterTransform.GetTranslation(), inCharacterTransform.GetTranslation() + inCharacterVelocity, Color::sYellow, 0.1f);
  277. // Draw text info
  278. const PhysicsMaterial *ground_material = inCharacter->GetGroundMaterial();
  279. mDebugRenderer->DrawText3D(inCharacterTransform.GetTranslation(), StringFormat("Mat: %s\nVel: %.1f m/s", ground_material->GetDebugName(), (double)inCharacterVelocity.Length()), color, 0.25f);
  280. }