CharacterBaseTest.cpp 14 KB

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