CharacterBaseTest.cpp 28 KB

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