CharacterBaseTest.cpp 29 KB

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