CharacterBaseTest.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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/CylinderShape.h>
  8. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  9. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  10. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  11. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  12. #include <Jolt/Physics/Constraints/HingeConstraint.h>
  13. #include <Jolt/Core/StringTools.h>
  14. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  15. #include <Application/DebugUI.h>
  16. #include <Layers.h>
  17. #include <Utils/Log.h>
  18. #include <Renderer/DebugRendererImp.h>
  19. JPH_IMPLEMENT_RTTI_ABSTRACT(CharacterBaseTest)
  20. {
  21. JPH_ADD_BASE_CLASS(CharacterBaseTest, Test)
  22. }
  23. const char *CharacterBaseTest::sScenes[] =
  24. {
  25. "PerlinMesh",
  26. "PerlinHeightField",
  27. "ObstacleCourse",
  28. "Terrain1",
  29. "Terrain2",
  30. };
  31. const char *CharacterBaseTest::sSceneName = "ObstacleCourse";
  32. // Scene constants
  33. static const RVec3 cRotatingPosition(-5, 0.15f, 15);
  34. static const Quat cRotatingOrientation = Quat::sIdentity();
  35. static const RVec3 cVerticallyMovingPosition(0, 2.0f, 15);
  36. static const Quat cVerticallyMovingOrientation = Quat::sIdentity();
  37. static const RVec3 cHorizontallyMovingPosition(5, 1, 15);
  38. static const Quat cHorizontallyMovingOrientation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);
  39. static const RVec3 cRampPosition(15, 2.2f, 15);
  40. static const Quat cRampOrientation = Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI);
  41. static const RVec3 cRampBlocksStart = cRampPosition + Vec3(-3.0f, 3.0f, 1.5f);
  42. static const Vec3 cRampBlocksDelta = Vec3(2.0f, 0, 0);
  43. static const float cRampBlocksTime = 5.0f;
  44. static const RVec3 cSmallBumpsPosition(-5.0f, 0, 2.5f);
  45. static const float cSmallBumpHeight = 0.05f;
  46. static const float cSmallBumpWidth = 0.01f;
  47. static const float cSmallBumpDelta = 0.5f;
  48. static const RVec3 cLargeBumpsPosition(-10.0f, 0, 2.5f);
  49. static const float cLargeBumpHeight = 0.3f;
  50. static const float cLargeBumpWidth = 0.1f;
  51. static const float cLargeBumpDelta = 2.0f;
  52. static const RVec3 cStairsPosition(-15.0f, 0, 2.5f);
  53. static const float cStairsStepHeight = 0.3f;
  54. static const RVec3 cMeshStairsPosition(-20.0f, 0, 2.5f);
  55. static const RVec3 cNoStairsPosition(-15.0f, 0, 10.0f);
  56. static const float cNoStairsStepHeight = 0.3f;
  57. static const float cNoStairsStepDelta = 0.05f;
  58. static const RVec3 cMeshNoStairsPosition(-20.0f, 0, 10.0f);
  59. static const RVec3 cMeshWallPosition(-25.0f, 0, -27.0f);
  60. static const float cMeshWallHeight = 3.0f;
  61. static const float cMeshWallWidth = 2.0f;
  62. static const float cMeshWallStepStart = 0.5f;
  63. static const float cMeshWallStepEnd = 4.0f;
  64. static const int cMeshWallSegments = 25;
  65. static const RVec3 cHalfCylinderPosition(5.0f, 0, 8.0f);
  66. static const RVec3 cMeshBoxPosition(30.0f, 1.5f, 5.0f);
  67. void CharacterBaseTest::Initialize()
  68. {
  69. if (strcmp(sSceneName, "PerlinMesh") == 0)
  70. {
  71. // Default terrain
  72. CreateMeshTerrain();
  73. }
  74. else if (strcmp(sSceneName, "PerlinHeightField") == 0)
  75. {
  76. // Default terrain
  77. CreateHeightFieldTerrain();
  78. }
  79. else if (strcmp(sSceneName, "ObstacleCourse") == 0)
  80. {
  81. // Default terrain
  82. CreateFloor(350.0f);
  83. {
  84. // Create ramps with different inclinations
  85. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  86. for (int angle = 0; angle < 18; ++angle)
  87. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp, RVec3(-15.0f + angle * 2.0f, 0, -10.0f), Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(10.0f * angle)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  88. }
  89. {
  90. // Create wall consisting of vertical pillars
  91. // Note: Convex radius 0 because otherwise it will be a bumpy wall
  92. Ref<Shape> wall = new BoxShape(Vec3(0.1f, 2.5f, 0.1f), 0.0f);
  93. for (int z = 0; z < 30; ++z)
  94. mBodyInterface->CreateAndAddBody(BodyCreationSettings(wall, RVec3(0.0f, 2.5f, 2.0f + 0.2f * z), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  95. }
  96. {
  97. // Kinematic blocks to test interacting with moving objects
  98. Ref<Shape> kinematic = new BoxShape(Vec3(1, 0.15f, 3.0f));
  99. mRotatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingPosition, cRotatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  100. mVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cVerticallyMovingPosition, cVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  101. mHorizontallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cHorizontallyMovingPosition, cHorizontallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  102. }
  103. {
  104. // A rolling sphere towards the player
  105. BodyCreationSettings bcs(new SphereShape(0.2f), RVec3(0.0f, 0.2f, -1.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  106. bcs.mLinearVelocity = Vec3(0, 0, 2.0f);
  107. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  108. bcs.mMassPropertiesOverride.mMass = 10.0f;
  109. mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  110. }
  111. {
  112. // Dynamic blocks to test player pushing blocks
  113. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  114. for (int y = 0; y < 3; ++y)
  115. {
  116. BodyCreationSettings bcs(block, RVec3(5.0f, 0.5f + float(y), 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  117. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  118. bcs.mMassPropertiesOverride.mMass = 10.0f;
  119. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  120. }
  121. }
  122. {
  123. // Dynamic block on a static step (to test pushing block on stairs)
  124. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 0.15f, 0.5f)), RVec3(10.0f, 0.15f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  125. BodyCreationSettings bcs(new BoxShape(Vec3::sReplicate(0.5f)), RVec3(10.0f, 0.8f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  126. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  127. bcs.mMassPropertiesOverride.mMass = 10.0f;
  128. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  129. }
  130. {
  131. // Dynamic spheres to test player pushing stuff you can step on
  132. float h = 0.0f;
  133. for (int y = 0; y < 3; ++y)
  134. {
  135. float r = 0.4f - 0.1f * y;
  136. h += r;
  137. BodyCreationSettings bcs(new SphereShape(r), RVec3(15.0f, h, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  138. h += r;
  139. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  140. bcs.mMassPropertiesOverride.mMass = 10.0f;
  141. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  142. }
  143. }
  144. {
  145. // A seesaw to test character gravity
  146. BodyID b1 = mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(1.0f, 0.2f, 0.05f)), RVec3(20.0f, 0.2f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  147. BodyCreationSettings bcs(new BoxShape(Vec3(1.0f, 0.05f, 5.0f)), RVec3(20.0f, 0.45f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  148. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  149. bcs.mMassPropertiesOverride.mMass = 10.0f;
  150. BodyID b2 = mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  151. // Connect the parts with a hinge
  152. HingeConstraintSettings hinge;
  153. hinge.mPoint1 = hinge.mPoint2 = RVec3(20.0f, 0.4f, 0.0f);
  154. hinge.mHingeAxis1 = hinge.mHingeAxis2 = Vec3::sAxisX();
  155. mPhysicsSystem->AddConstraint(mBodyInterface->CreateConstraint(&hinge, b1, b2));
  156. }
  157. {
  158. // A board above the character to crouch and jump up against
  159. float h = 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching + 0.1f;
  160. for (int x = 0; x < 2; ++x)
  161. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(1.0f, h, 0.05f)), RVec3(25.0f, h, x == 0? -0.95f : 0.95f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  162. BodyCreationSettings bcs(new BoxShape(Vec3(1.0f, 0.05f, 1.0f)), RVec3(25.0f, 2.0f * h + 0.05f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  163. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  164. bcs.mMassPropertiesOverride.mMass = 10.0f;
  165. mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  166. }
  167. {
  168. // A floating static block
  169. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3::sReplicate(0.5f)), RVec3(30.0f, 1.5f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  170. }
  171. {
  172. // Create ramp
  173. BodyCreationSettings ramp(new BoxShape(Vec3(4.0f, 0.1f, 3.0f)), cRampPosition, cRampOrientation, EMotionType::Static, Layers::NON_MOVING);
  174. mBodyInterface->CreateAndAddBody(ramp, EActivation::DontActivate);
  175. // Create blocks on ramp
  176. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  177. BodyCreationSettings bcs(block, cRampBlocksStart, cRampOrientation, EMotionType::Dynamic, Layers::MOVING);
  178. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  179. bcs.mMassPropertiesOverride.mMass = 10.0f;
  180. for (int i = 0; i < 4; ++i)
  181. {
  182. mRampBlocks.emplace_back(mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate));
  183. bcs.mPosition += cRampBlocksDelta;
  184. }
  185. }
  186. // Create three funnels with walls that are too steep to climb
  187. Ref<Shape> funnel = new BoxShape(Vec3(0.1f, 1.0f, 1.0f));
  188. for (int i = 0; i < 2; ++i)
  189. {
  190. Quat rotation = Quat::sRotation(Vec3::sAxisY(), JPH_PI * i);
  191. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, RVec3(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);
  192. }
  193. for (int i = 0; i < 3; ++i)
  194. {
  195. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 2.0f / 3.0f * JPH_PI * i);
  196. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, RVec3(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);
  197. }
  198. for (int i = 0; i < 4; ++i)
  199. {
  200. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 0.5f * JPH_PI * i);
  201. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, RVec3(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);
  202. }
  203. // Create small bumps
  204. {
  205. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cSmallBumpHeight, 0.5f * cSmallBumpWidth), 0.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  206. for (int i = 0; i < 10; ++i)
  207. {
  208. step.mPosition = cSmallBumpsPosition + Vec3(0, 0.5f * cSmallBumpHeight, cSmallBumpDelta * i);
  209. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  210. }
  211. }
  212. // Create large bumps
  213. {
  214. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cLargeBumpHeight, 0.5f * cLargeBumpWidth)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  215. for (int i = 0; i < 5; ++i)
  216. {
  217. step.mPosition = cLargeBumpsPosition + Vec3(0, 0.5f * cLargeBumpHeight, cLargeBumpDelta * i);
  218. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  219. }
  220. }
  221. // Create stairs
  222. {
  223. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cStairsStepHeight, 0.5f * cStairsStepHeight)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  224. for (int i = 0; i < 10; ++i)
  225. {
  226. step.mPosition = cStairsPosition + Vec3(0, cStairsStepHeight * (0.5f + i), cStairsStepHeight * i);
  227. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  228. }
  229. }
  230. // A wall beside the stairs
  231. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 2.0f, 5.0f * cStairsStepHeight)), cStairsPosition + Vec3(-2.5f, 2.0f, 5.0f * cStairsStepHeight), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  232. // Create stairs from triangles
  233. {
  234. TriangleList triangles;
  235. float rear_z = 10 * cStairsStepHeight;
  236. for (int i = 0; i < 10; ++i)
  237. {
  238. // Start of step
  239. Vec3 base(0, cStairsStepHeight * i, cStairsStepHeight * i);
  240. // Left side
  241. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  242. Vec3 s1 = b1 + Vec3(0, cStairsStepHeight, 0);
  243. Vec3 p1 = s1 + Vec3(0, 0, cStairsStepHeight);
  244. // Right side
  245. Vec3 width(-4.0f, 0, 0);
  246. Vec3 b2 = b1 + width;
  247. Vec3 s2 = s1 + width;
  248. Vec3 p2 = p1 + width;
  249. triangles.push_back(Triangle(s1, b1, s2));
  250. triangles.push_back(Triangle(b1, b2, s2));
  251. triangles.push_back(Triangle(s1, p2, p1));
  252. triangles.push_back(Triangle(s1, s2, p2));
  253. // Side of stairs
  254. Vec3 rb2 = b2; rb2.SetZ(rear_z);
  255. Vec3 rs2 = s2; rs2.SetZ(rear_z);
  256. triangles.push_back(Triangle(s2, b2, rs2));
  257. triangles.push_back(Triangle(rs2, b2, rb2));
  258. p1 = p2;
  259. }
  260. MeshShapeSettings mesh(triangles);
  261. mesh.SetEmbedded();
  262. BodyCreationSettings mesh_stairs(&mesh, cMeshStairsPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  263. mBodyInterface->CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  264. }
  265. // A wall to the side and behind the stairs
  266. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 2.0f, 0.25f)), cStairsPosition + Vec3(-7.5f, 2.0f, 10.0f * cStairsStepHeight + 0.25f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  267. // Create stairs with too little space between the steps
  268. {
  269. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cNoStairsStepHeight, 0.5f * cNoStairsStepHeight)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  270. for (int i = 0; i < 10; ++i)
  271. {
  272. step.mPosition = cNoStairsPosition + Vec3(0, cNoStairsStepHeight * (0.5f + i), cNoStairsStepDelta * i);
  273. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  274. }
  275. }
  276. // Create stairs with too little space between the steps consisting of triangles
  277. {
  278. TriangleList triangles;
  279. for (int i = 0; i < 10; ++i)
  280. {
  281. // Start of step
  282. Vec3 base(0, cStairsStepHeight * i, cNoStairsStepDelta * i);
  283. // Left side
  284. Vec3 b1 = base - Vec3(2.0f, 0, 0);
  285. Vec3 s1 = b1 + Vec3(0, cStairsStepHeight, 0);
  286. Vec3 p1 = s1 + Vec3(0, 0, cNoStairsStepDelta);
  287. // Right side
  288. Vec3 width(4.0f, 0, 0);
  289. Vec3 b2 = b1 + width;
  290. Vec3 s2 = s1 + width;
  291. Vec3 p2 = p1 + width;
  292. triangles.push_back(Triangle(s1, s2, b1));
  293. triangles.push_back(Triangle(b1, s2, b2));
  294. triangles.push_back(Triangle(s1, p1, p2));
  295. triangles.push_back(Triangle(s1, p2, s2));
  296. p1 = p2;
  297. }
  298. MeshShapeSettings mesh(triangles);
  299. mesh.SetEmbedded();
  300. BodyCreationSettings mesh_stairs(&mesh, cMeshNoStairsPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  301. mBodyInterface->CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  302. }
  303. // Create mesh with walls at varying angles
  304. {
  305. TriangleList triangles;
  306. Vec3 p1(0.5f * cMeshWallWidth, 0, 0);
  307. Vec3 h(0, cMeshWallHeight, 0);
  308. for (int i = 0; i < cMeshWallSegments; ++i)
  309. {
  310. float delta = cMeshWallStepStart + i * (cMeshWallStepEnd - cMeshWallStepStart) / (cMeshWallSegments - 1);
  311. Vec3 p2 = Vec3((i & 1)? 0.5f * cMeshWallWidth : -0.5f * cMeshWallWidth, 0, p1.GetZ() + delta);
  312. triangles.push_back(Triangle(p1, p1 + h, p2 + h));
  313. triangles.push_back(Triangle(p1, p2 + h, p2));
  314. p1 = p2;
  315. }
  316. MeshShapeSettings mesh(triangles);
  317. mesh.SetEmbedded();
  318. BodyCreationSettings wall(&mesh, cMeshWallPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  319. mBodyInterface->CreateAndAddBody(wall, EActivation::DontActivate);
  320. }
  321. // Create a half cylinder with caps for testing contact point limit
  322. {
  323. VertexList vertices;
  324. IndexedTriangleList triangles;
  325. // The half cylinder
  326. const int cPosSegments = 2;
  327. const int cAngleSegments = 512;
  328. const float cCylinderLength = 2.0f;
  329. for (int pos = 0; pos < cPosSegments; ++pos)
  330. for (int angle = 0; angle < cAngleSegments; ++angle)
  331. {
  332. uint32 start = (uint32)vertices.size();
  333. float radius = cCharacterRadiusStanding + 0.05f;
  334. float angle_rad = (-0.5f + float(angle) / cAngleSegments) * JPH_PI;
  335. float s = Sin(angle_rad);
  336. float c = Cos(angle_rad);
  337. float x = cCylinderLength * (-0.5f + float(pos) / (cPosSegments - 1));
  338. float y = angle == 0 || angle == cAngleSegments - 1? 0.5f : (1.0f - c) * radius;
  339. float z = s * radius;
  340. vertices.push_back(Float3(x, y, z));
  341. if (pos > 0 && angle > 0)
  342. {
  343. triangles.push_back(IndexedTriangle(start, start - 1, start - cAngleSegments));
  344. triangles.push_back(IndexedTriangle(start - 1, start - cAngleSegments - 1, start - cAngleSegments));
  345. }
  346. }
  347. // Add end caps
  348. uint32 end = cAngleSegments * (cPosSegments - 1);
  349. for (int angle = 0; angle < cAngleSegments - 1; ++angle)
  350. {
  351. triangles.push_back(IndexedTriangle(0, angle + 1, angle));
  352. triangles.push_back(IndexedTriangle(end, end + angle, end + angle + 1));
  353. }
  354. MeshShapeSettings mesh(vertices, triangles);
  355. mesh.SetEmbedded();
  356. BodyCreationSettings mesh_cylinder(&mesh, cHalfCylinderPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  357. mBodyInterface->CreateAndAddBody(mesh_cylinder, EActivation::DontActivate);
  358. }
  359. // Create a box made out of polygons (character should not get stuck behind back facing side)
  360. {
  361. VertexList vertices = {
  362. Float3(-1, 1, -1),
  363. Float3( 1, 1, -1),
  364. Float3( 1, 1, 1),
  365. Float3(-1, 1, 1),
  366. Float3(-1, -1, -1),
  367. Float3( 1, -1, -1),
  368. Float3( 1, -1, 1),
  369. Float3(-1, -1, 1)
  370. };
  371. IndexedTriangleList triangles = {
  372. IndexedTriangle(0, 3, 2),
  373. IndexedTriangle(0, 2, 1),
  374. IndexedTriangle(4, 5, 6),
  375. IndexedTriangle(4, 6, 7),
  376. IndexedTriangle(0, 4, 3),
  377. IndexedTriangle(3, 4, 7),
  378. IndexedTriangle(2, 6, 5),
  379. IndexedTriangle(2, 5, 1),
  380. IndexedTriangle(3, 7, 6),
  381. IndexedTriangle(3, 6, 2),
  382. IndexedTriangle(0, 1, 5),
  383. IndexedTriangle(0, 5, 4)
  384. };
  385. MeshShapeSettings mesh(vertices, triangles);
  386. mesh.SetEmbedded();
  387. BodyCreationSettings box(&mesh, cMeshBoxPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  388. mBodyInterface->CreateAndAddBody(box, EActivation::DontActivate);
  389. }
  390. }
  391. else
  392. {
  393. // Load scene
  394. Ref<PhysicsScene> scene;
  395. if (!ObjectStreamIn::sReadObject((String("Assets/") + sSceneName + ".bof").c_str(), scene))
  396. FatalError("Failed to load scene");
  397. scene->FixInvalidScales();
  398. for (BodyCreationSettings &settings : scene->GetBodies())
  399. {
  400. settings.mObjectLayer = Layers::NON_MOVING;
  401. settings.mFriction = 0.5f;
  402. }
  403. scene->CreateBodies(mPhysicsSystem);
  404. }
  405. // Create capsule shapes for all stances
  406. switch (sShapeType)
  407. {
  408. case EType::Capsule:
  409. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  410. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching)).Create().Get();
  411. break;
  412. case EType::Cylinder:
  413. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CylinderShape(0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding)).Create().Get();
  414. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CylinderShape(0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching)).Create().Get();
  415. break;
  416. case EType::Box:
  417. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding))).Create().Get();
  418. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching))).Create().Get();
  419. break;
  420. }
  421. }
  422. void CharacterBaseTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  423. {
  424. // Update scene time
  425. mTime += inParams.mDeltaTime;
  426. // Determine controller input
  427. Vec3 control_input = Vec3::sZero();
  428. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT)) control_input.SetZ(-1);
  429. if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT)) control_input.SetZ(1);
  430. if (inParams.mKeyboard->IsKeyPressed(DIK_UP)) control_input.SetX(1);
  431. if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN)) control_input.SetX(-1);
  432. if (control_input != Vec3::sZero())
  433. control_input = control_input.Normalized();
  434. // Rotate controls to align with the camera
  435. Vec3 cam_fwd = inParams.mCameraState.mForward;
  436. cam_fwd.SetY(0.0f);
  437. cam_fwd = cam_fwd.NormalizedOr(Vec3::sAxisX());
  438. Quat rotation = Quat::sFromTo(Vec3::sAxisX(), cam_fwd);
  439. control_input = rotation * control_input;
  440. // Check actions
  441. bool jump = false;
  442. bool switch_stance = false;
  443. for (int key = inParams.mKeyboard->GetFirstKey(); key != 0; key = inParams.mKeyboard->GetNextKey())
  444. {
  445. if (key == DIK_RSHIFT)
  446. switch_stance = true;
  447. else if (key == DIK_RCONTROL)
  448. jump = true;
  449. }
  450. HandleInput(control_input, jump, switch_stance, inParams.mDeltaTime);
  451. // Animate bodies
  452. if (!mRotatingBody.IsInvalid())
  453. mBodyInterface->MoveKinematic(mRotatingBody, cRotatingPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * Sin(mTime)), inParams.mDeltaTime);
  454. if (!mHorizontallyMovingBody.IsInvalid())
  455. mBodyInterface->MoveKinematic(mHorizontallyMovingBody, cHorizontallyMovingPosition + Vec3(3.0f * Sin(mTime), 0, 0), cHorizontallyMovingOrientation, inParams.mDeltaTime);
  456. if (!mVerticallyMovingBody.IsInvalid())
  457. mBodyInterface->MoveKinematic(mVerticallyMovingBody, cVerticallyMovingPosition + Vec3(0, 1.75f * Sin(mTime), 0), cVerticallyMovingOrientation, inParams.mDeltaTime);
  458. // Reset ramp blocks
  459. mRampBlocksTimeLeft -= inParams.mDeltaTime;
  460. if (mRampBlocksTimeLeft < 0.0f)
  461. {
  462. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  463. {
  464. mBodyInterface->SetPositionAndRotation(mRampBlocks[i], cRampBlocksStart + float(i) * cRampBlocksDelta, cRampOrientation, EActivation::Activate);
  465. mBodyInterface->SetLinearAndAngularVelocity(mRampBlocks[i], Vec3::sZero(), Vec3::sZero());
  466. }
  467. mRampBlocksTimeLeft = cRampBlocksTime;
  468. }
  469. }
  470. void CharacterBaseTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  471. {
  472. inUI->CreateTextButton(inSubMenu, "Select Scene", [this, inUI]() {
  473. UIElement *scene_name = inUI->CreateMenu();
  474. for (uint i = 0; i < size(sScenes); ++i)
  475. inUI->CreateTextButton(scene_name, sScenes[i], [this, i]() { sSceneName = sScenes[i]; RestartTest(); });
  476. inUI->ShowMenu(scene_name);
  477. });
  478. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [=]() {
  479. UIElement *configuration_settings = inUI->CreateMenu();
  480. inUI->CreateComboBox(configuration_settings, "Shape Type", { "Capsule", "Cylinder", "Box" }, (int)sShapeType, [](int inItem) { sShapeType = (EType)inItem; });
  481. AddConfigurationSettings(inUI, configuration_settings);
  482. inUI->CreateTextButton(configuration_settings, "Accept Changes", [=]() { RestartTest(); });
  483. inUI->ShowMenu(configuration_settings);
  484. });
  485. }
  486. void CharacterBaseTest::GetInitialCamera(CameraState& ioState) const
  487. {
  488. // This will become the local space offset, look down the x axis and slightly down
  489. ioState.mPos = RVec3::sZero();
  490. ioState.mForward = Vec3(10.0f, -2.0f, 0).Normalized();
  491. }
  492. RMat44 CharacterBaseTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  493. {
  494. // Pivot is center of character + distance behind based on the heading and pitch of the camera
  495. Vec3 fwd = Vec3(Cos(inCameraPitch) * Cos(inCameraHeading), Sin(inCameraPitch), Cos(inCameraPitch) * Sin(inCameraHeading));
  496. return RMat44::sTranslation(GetCharacterPosition() + Vec3(0, cCharacterHeightStanding + cCharacterRadiusStanding, 0) - 5.0f * fwd);
  497. }
  498. void CharacterBaseTest::SaveState(StateRecorder &inStream) const
  499. {
  500. inStream.Write(mTime);
  501. inStream.Write(mRampBlocksTimeLeft);
  502. }
  503. void CharacterBaseTest::RestoreState(StateRecorder &inStream)
  504. {
  505. inStream.Read(mTime);
  506. inStream.Read(mRampBlocksTimeLeft);
  507. }
  508. void CharacterBaseTest::DrawCharacterState(const CharacterBase *inCharacter, RMat44Arg inCharacterTransform, Vec3Arg inCharacterVelocity)
  509. {
  510. // Draw current location
  511. // 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)
  512. mDebugRenderer->DrawCoordinateSystem(inCharacterTransform, 0.1f);
  513. // Determine color
  514. CharacterBase::EGroundState ground_state = inCharacter->GetGroundState();
  515. Color color;
  516. switch (ground_state)
  517. {
  518. case CharacterBase::EGroundState::OnGround:
  519. color = Color::sGreen;
  520. break;
  521. case CharacterBase::EGroundState::OnSteepGround:
  522. color = Color::sYellow;
  523. break;
  524. case CharacterBase::EGroundState::NotSupported:
  525. color = Color::sOrange;
  526. break;
  527. case CharacterBase::EGroundState::InAir:
  528. default:
  529. color = Color::sRed;
  530. break;
  531. }
  532. // Draw the state of the ground contact
  533. if (ground_state != CharacterBase::EGroundState::InAir)
  534. {
  535. RVec3 ground_position = inCharacter->GetGroundPosition();
  536. Vec3 ground_normal = inCharacter->GetGroundNormal();
  537. Vec3 ground_velocity = inCharacter->GetGroundVelocity();
  538. // Draw ground position
  539. mDebugRenderer->DrawMarker(ground_position, Color::sRed, 0.1f);
  540. mDebugRenderer->DrawArrow(ground_position, ground_position + 2.0f * ground_normal, Color::sGreen, 0.1f);
  541. // Draw ground velocity
  542. if (!ground_velocity.IsNearZero())
  543. mDebugRenderer->DrawArrow(ground_position, ground_position + ground_velocity, Color::sBlue, 0.1f);
  544. }
  545. // Draw provided character velocity
  546. if (!inCharacterVelocity.IsNearZero())
  547. mDebugRenderer->DrawArrow(inCharacterTransform.GetTranslation(), inCharacterTransform.GetTranslation() + inCharacterVelocity, Color::sYellow, 0.1f);
  548. // Draw text info
  549. const PhysicsMaterial *ground_material = inCharacter->GetGroundMaterial();
  550. Vec3 horizontal_velocity = inCharacterVelocity;
  551. horizontal_velocity.SetY(0);
  552. 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);
  553. }