CharacterBaseTest.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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/StaticCompoundShape.h>
  13. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  14. #include <Jolt/Physics/Constraints/HingeConstraint.h>
  15. #include <Jolt/Core/StringTools.h>
  16. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  17. #include <Application/DebugUI.h>
  18. #include <Layers.h>
  19. #include <Utils/Log.h>
  20. #include <Utils/AssetStream.h>
  21. #include <Renderer/DebugRendererImp.h>
  22. JPH_IMPLEMENT_RTTI_ABSTRACT(CharacterBaseTest)
  23. {
  24. JPH_ADD_BASE_CLASS(CharacterBaseTest, Test)
  25. }
  26. const char *CharacterBaseTest::sScenes[] =
  27. {
  28. "PerlinMesh",
  29. "PerlinHeightField",
  30. "ObstacleCourse",
  31. "InitiallyIntersecting",
  32. #ifdef JPH_OBJECT_STREAM
  33. "Terrain1",
  34. "Terrain2",
  35. #endif // JPH_OBJECT_STREAM
  36. };
  37. const char *CharacterBaseTest::sSceneName = "ObstacleCourse";
  38. // Scene constants
  39. static const RVec3 cRotatingPosition(-5, 0.15f, 15);
  40. static const Quat cRotatingOrientation = Quat::sIdentity();
  41. static const RVec3 cRotatingWallPosition(5, 1.0f, 25.0f);
  42. static const Quat cRotatingWallOrientation = Quat::sIdentity();
  43. static const RVec3 cRotatingAndTranslatingPosition(-10, 0.15f, 27.5f);
  44. static const Quat cRotatingAndTranslatingOrientation = Quat::sIdentity();
  45. static const RVec3 cSmoothVerticallyMovingPosition(0, 2.0f, 15);
  46. static const Quat cSmoothVerticallyMovingOrientation = Quat::sIdentity();
  47. static const RVec3 cReversingVerticallyMovingPosition(0, 0.15f, 25);
  48. static const Quat cReversingVerticallyMovingOrientation = Quat::sIdentity();
  49. static const RVec3 cHorizontallyMovingPosition(5, 1, 15);
  50. static const Quat cHorizontallyMovingOrientation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);
  51. static const RVec3 cConveyorBeltPosition(-10, 0.15f, 15);
  52. static const RVec3 cRampPosition(15, 2.2f, 15);
  53. static const Quat cRampOrientation = Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI);
  54. static const RVec3 cRampBlocksStart = cRampPosition + Vec3(-3.0f, 3.0f, 1.5f);
  55. static const Vec3 cRampBlocksDelta = Vec3(2.0f, 0, 0);
  56. static const float cRampBlocksTime = 5.0f;
  57. static const RVec3 cSmallBumpsPosition(-5.0f, 0, 2.5f);
  58. static const float cSmallBumpHeight = 0.05f;
  59. static const float cSmallBumpWidth = 0.01f;
  60. static const float cSmallBumpDelta = 0.5f;
  61. static const RVec3 cLargeBumpsPosition(-10.0f, 0, 2.5f);
  62. static const float cLargeBumpHeight = 0.3f;
  63. static const float cLargeBumpWidth = 0.1f;
  64. static const float cLargeBumpDelta = 2.0f;
  65. static const RVec3 cStairsPosition(-15.0f, 0, 2.5f);
  66. static const float cStairsStepHeight = 0.3f;
  67. static const RVec3 cMeshStairsPosition(-20.0f, 0, 2.5f);
  68. static const RVec3 cNoStairsPosition(-15.0f, 0, 10.0f);
  69. static const float cNoStairsStepHeight = 0.3f;
  70. static const float cNoStairsStepDelta = 0.05f;
  71. static const RVec3 cMeshNoStairsPosition(-20.0f, 0, 10.0f);
  72. static const RVec3 cMeshWallPosition(-25.0f, 0, -27.0f);
  73. static const float cMeshWallHeight = 3.0f;
  74. static const float cMeshWallWidth = 2.0f;
  75. static const float cMeshWallStepStart = 0.5f;
  76. static const float cMeshWallStepEnd = 4.0f;
  77. static const int cMeshWallSegments = 25;
  78. static const RVec3 cHalfCylinderPosition(5.0f, 0, 8.0f);
  79. static const RVec3 cMeshBoxPosition(30.0f, 1.5f, 5.0f);
  80. static const RVec3 cSensorPosition(30, 0.9f, -5);
  81. static const RVec3 cCharacterPosition(-3.5f, 0, 3.0f);
  82. static const RVec3 cCharacterVirtualPosition(-5.0f, 0, 3.0f);
  83. static const RVec3 cCharacterVirtualWithInnerBodyPosition(-6.5f, 0, 3.0f);
  84. static const Vec3 cCharacterVelocity(0, 0, 2);
  85. CharacterBaseTest::~CharacterBaseTest()
  86. {
  87. if (mAnimatedCharacter != nullptr)
  88. mAnimatedCharacter->RemoveFromPhysicsSystem();
  89. }
  90. void CharacterBaseTest::Initialize()
  91. {
  92. // Create capsule shapes for all stances
  93. switch (sShapeType)
  94. {
  95. case EType::Capsule:
  96. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  97. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching)).Create().Get();
  98. mInnerStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightStanding, cInnerShapeFraction * cCharacterRadiusStanding)).Create().Get();
  99. mInnerCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightCrouching, cInnerShapeFraction * cCharacterRadiusCrouching)).Create().Get();
  100. break;
  101. case EType::Cylinder:
  102. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CylinderShape(0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding)).Create().Get();
  103. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CylinderShape(0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching)).Create().Get();
  104. mInnerStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CylinderShape(cInnerShapeFraction * (0.5f * cCharacterHeightStanding + cCharacterRadiusStanding), cInnerShapeFraction * cCharacterRadiusStanding)).Create().Get();
  105. mInnerCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CylinderShape(cInnerShapeFraction * (0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching), cInnerShapeFraction * cCharacterRadiusCrouching)).Create().Get();
  106. break;
  107. case EType::Box:
  108. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding))).Create().Get();
  109. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching))).Create().Get();
  110. mInnerStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding))).Create().Get();
  111. mInnerCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching))).Create().Get();
  112. break;
  113. case EType::Compound:
  114. {
  115. StaticCompoundShapeSettings standing_compound;
  116. standing_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding));
  117. standing_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding)));
  118. mStandingShape = standing_compound.Create().Get();
  119. StaticCompoundShapeSettings crouching_compound;
  120. crouching_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching));
  121. crouching_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching)));
  122. mCrouchingShape = crouching_compound.Create().Get();
  123. StaticCompoundShapeSettings inner_standing_compound;
  124. inner_standing_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightStanding, cInnerShapeFraction * cCharacterRadiusStanding));
  125. inner_standing_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding)));
  126. mInnerStandingShape = inner_standing_compound.Create().Get();
  127. StaticCompoundShapeSettings inner_crouching_compound;
  128. inner_crouching_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightCrouching, cInnerShapeFraction * cCharacterRadiusCrouching));
  129. inner_crouching_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching)));
  130. mInnerCrouchingShape = inner_crouching_compound.Create().Get();
  131. }
  132. break;
  133. }
  134. if (strcmp(sSceneName, "PerlinMesh") == 0)
  135. {
  136. // Default terrain
  137. CreateMeshTerrain();
  138. }
  139. else if (strcmp(sSceneName, "PerlinHeightField") == 0)
  140. {
  141. // Default terrain
  142. CreateHeightFieldTerrain();
  143. }
  144. else if (strcmp(sSceneName, "InitiallyIntersecting") == 0)
  145. {
  146. CreateFloor();
  147. // Create a grid of boxes that are initially intersecting with the character
  148. RefConst<Shape> box = new BoxShape(Vec3(0.1f, 0.1f, 0.1f));
  149. BodyCreationSettings settings(box, RVec3(0, 0.5f, 0), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  150. for (int x = 0; x < 4; ++x)
  151. for (int y = 0; y <= 10; ++y)
  152. for (int z = 0; z <= 10; ++z)
  153. {
  154. settings.mPosition = RVec3(-0.5f + 0.1f * x, 0.1f + 0.1f * y, -0.5f + 0.1f * z);
  155. mBodyInterface->CreateAndAddBody(settings, EActivation::DontActivate);
  156. }
  157. }
  158. else if (strcmp(sSceneName, "ObstacleCourse") == 0)
  159. {
  160. // Default terrain
  161. CreateFloor(350.0f);
  162. {
  163. // Create ramps with different inclinations
  164. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  165. for (int angle = 0; angle < 18; ++angle)
  166. 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);
  167. }
  168. {
  169. // Create ramps with different inclinations intersecting with a steep slope
  170. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  171. Ref<Shape> ramp2 = RotatedTranslatedShapeSettings(Vec3(0, 2.0f, 0), Quat::sIdentity(), new BoxShape(Vec3(0.05f, 2.0f, 1.0f))).Create().Get();
  172. for (int angle = 0; angle < 9; ++angle)
  173. {
  174. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp, RVec3(-15.0f + angle * 2.0f, 0, -20.0f - angle * 0.1f), Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(10.0f * angle)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  175. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp2, RVec3(-15.0f + angle * 2.0f, 0, -21.0f), Quat::sRotation(Vec3::sAxisZ(), DegreesToRadians(20.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  176. }
  177. }
  178. {
  179. // Create wall consisting of vertical pillars
  180. // Note: Convex radius 0 because otherwise it will be a bumpy wall
  181. Ref<Shape> wall = new BoxShape(Vec3(0.1f, 2.5f, 0.1f), 0.0f);
  182. for (int z = 0; z < 30; ++z)
  183. mBodyInterface->CreateAndAddBody(BodyCreationSettings(wall, RVec3(0.0f, 2.5f, 2.0f + 0.2f * z), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  184. }
  185. {
  186. // Kinematic blocks to test interacting with moving objects
  187. Ref<Shape> kinematic = new BoxShape(Vec3(1, 0.15f, 3.0f));
  188. mRotatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingPosition, cRotatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  189. mRotatingWallBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(3.0f, 1, 0.15f)), cRotatingWallPosition, cRotatingWallOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  190. mRotatingAndTranslatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingAndTranslatingPosition, cRotatingAndTranslatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  191. mSmoothVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cSmoothVerticallyMovingPosition, cSmoothVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  192. mReversingVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cReversingVerticallyMovingPosition, cReversingVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  193. mHorizontallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cHorizontallyMovingPosition, cHorizontallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  194. }
  195. {
  196. // Conveyor belt (only works with virtual character)
  197. mConveyorBeltBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(1, 0.15f, 3.0f)), cConveyorBeltPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::Activate);
  198. }
  199. {
  200. // A rolling sphere towards the player
  201. BodyCreationSettings bcs(new SphereShape(0.2f), RVec3(0.0f, 0.2f, -1.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  202. bcs.mLinearVelocity = Vec3(0, 0, 2.0f);
  203. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  204. bcs.mMassPropertiesOverride.mMass = 10.0f;
  205. mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  206. }
  207. {
  208. // Dynamic blocks to test player pushing blocks
  209. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  210. for (int y = 0; y < 3; ++y)
  211. {
  212. BodyCreationSettings bcs(block, RVec3(5.0f, 0.5f + float(y), 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  213. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  214. bcs.mMassPropertiesOverride.mMass = 10.0f;
  215. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  216. }
  217. }
  218. {
  219. // Dynamic block on a static step (to test pushing block on stairs)
  220. 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);
  221. BodyCreationSettings bcs(new BoxShape(Vec3::sReplicate(0.5f)), RVec3(10.0f, 0.8f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  222. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  223. bcs.mMassPropertiesOverride.mMass = 10.0f;
  224. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  225. }
  226. {
  227. // Dynamic spheres to test player pushing stuff you can step on
  228. float h = 0.0f;
  229. for (int y = 0; y < 3; ++y)
  230. {
  231. float r = 0.4f - 0.1f * y;
  232. h += r;
  233. BodyCreationSettings bcs(new SphereShape(r), RVec3(15.0f, h, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  234. h += r;
  235. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  236. bcs.mMassPropertiesOverride.mMass = 10.0f;
  237. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  238. }
  239. }
  240. {
  241. // A seesaw to test character gravity
  242. 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);
  243. BodyCreationSettings bcs(new BoxShape(Vec3(1.0f, 0.05f, 5.0f)), RVec3(20.0f, 0.45f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  244. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  245. bcs.mMassPropertiesOverride.mMass = 10.0f;
  246. BodyID b2 = mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  247. // Connect the parts with a hinge
  248. HingeConstraintSettings hinge;
  249. hinge.mPoint1 = hinge.mPoint2 = RVec3(20.0f, 0.4f, 0.0f);
  250. hinge.mHingeAxis1 = hinge.mHingeAxis2 = Vec3::sAxisX();
  251. mPhysicsSystem->AddConstraint(mBodyInterface->CreateConstraint(&hinge, b1, b2));
  252. }
  253. {
  254. // A board above the character to crouch and jump up against
  255. float h = 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching + 0.1f;
  256. for (int x = 0; x < 2; ++x)
  257. 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);
  258. 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);
  259. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  260. bcs.mMassPropertiesOverride.mMass = 10.0f;
  261. mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  262. }
  263. {
  264. // A floating static block
  265. 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);
  266. }
  267. {
  268. // Create ramp
  269. BodyCreationSettings ramp(new BoxShape(Vec3(4.0f, 0.1f, 3.0f)), cRampPosition, cRampOrientation, EMotionType::Static, Layers::NON_MOVING);
  270. mBodyInterface->CreateAndAddBody(ramp, EActivation::DontActivate);
  271. // Create blocks on ramp
  272. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  273. BodyCreationSettings bcs(block, cRampBlocksStart, cRampOrientation, EMotionType::Dynamic, Layers::MOVING);
  274. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  275. bcs.mMassPropertiesOverride.mMass = 10.0f;
  276. for (int i = 0; i < 4; ++i)
  277. {
  278. mRampBlocks.emplace_back(mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate));
  279. bcs.mPosition += cRampBlocksDelta;
  280. }
  281. }
  282. // Create three funnels with walls that are too steep to climb
  283. Ref<Shape> funnel = new BoxShape(Vec3(0.1f, 1.0f, 1.0f));
  284. for (int i = 0; i < 2; ++i)
  285. {
  286. Quat rotation = Quat::sRotation(Vec3::sAxisY(), JPH_PI * i);
  287. 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);
  288. }
  289. for (int i = 0; i < 3; ++i)
  290. {
  291. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 2.0f / 3.0f * JPH_PI * i);
  292. 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);
  293. }
  294. for (int i = 0; i < 4; ++i)
  295. {
  296. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 0.5f * JPH_PI * i);
  297. 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);
  298. }
  299. // Create small bumps
  300. {
  301. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cSmallBumpHeight, 0.5f * cSmallBumpWidth), 0.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  302. for (int i = 0; i < 10; ++i)
  303. {
  304. step.mPosition = cSmallBumpsPosition + Vec3(0, 0.5f * cSmallBumpHeight, cSmallBumpDelta * i);
  305. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  306. }
  307. }
  308. // Create large bumps
  309. {
  310. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cLargeBumpHeight, 0.5f * cLargeBumpWidth)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  311. for (int i = 0; i < 5; ++i)
  312. {
  313. step.mPosition = cLargeBumpsPosition + Vec3(0, 0.5f * cLargeBumpHeight, cLargeBumpDelta * i);
  314. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  315. }
  316. }
  317. // Create stairs
  318. {
  319. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cStairsStepHeight, 0.5f * cStairsStepHeight)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  320. for (int i = 0; i < 10; ++i)
  321. {
  322. step.mPosition = cStairsPosition + Vec3(0, cStairsStepHeight * (0.5f + i), cStairsStepHeight * i);
  323. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  324. }
  325. }
  326. // A wall beside the stairs
  327. 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);
  328. // Create stairs from triangles
  329. {
  330. TriangleList triangles;
  331. float rear_z = 10 * cStairsStepHeight;
  332. for (int i = 0; i < 10; ++i)
  333. {
  334. // Start of step
  335. Vec3 base(0, cStairsStepHeight * i, cStairsStepHeight * i);
  336. // Left side
  337. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  338. Vec3 s1 = b1 + Vec3(0, cStairsStepHeight, 0);
  339. Vec3 p1 = s1 + Vec3(0, 0, cStairsStepHeight);
  340. // Right side
  341. Vec3 width(-4.0f, 0, 0);
  342. Vec3 b2 = b1 + width;
  343. Vec3 s2 = s1 + width;
  344. Vec3 p2 = p1 + width;
  345. triangles.push_back(Triangle(s1, b1, s2));
  346. triangles.push_back(Triangle(b1, b2, s2));
  347. triangles.push_back(Triangle(s1, p2, p1));
  348. triangles.push_back(Triangle(s1, s2, p2));
  349. // Side of stairs
  350. Vec3 rb2 = b2; rb2.SetZ(rear_z);
  351. Vec3 rs2 = s2; rs2.SetZ(rear_z);
  352. triangles.push_back(Triangle(s2, b2, rs2));
  353. triangles.push_back(Triangle(rs2, b2, rb2));
  354. }
  355. MeshShapeSettings mesh(triangles);
  356. mesh.SetEmbedded();
  357. BodyCreationSettings mesh_stairs(&mesh, cMeshStairsPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  358. mBodyInterface->CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  359. }
  360. // A wall to the side and behind the stairs
  361. 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);
  362. // Create stairs with too little space between the steps
  363. {
  364. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cNoStairsStepHeight, 0.5f * cNoStairsStepHeight)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  365. for (int i = 0; i < 10; ++i)
  366. {
  367. step.mPosition = cNoStairsPosition + Vec3(0, cNoStairsStepHeight * (0.5f + i), cNoStairsStepDelta * i);
  368. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  369. }
  370. }
  371. // Create stairs with too little space between the steps consisting of triangles
  372. {
  373. TriangleList triangles;
  374. for (int i = 0; i < 10; ++i)
  375. {
  376. // Start of step
  377. Vec3 base(0, cStairsStepHeight * i, cNoStairsStepDelta * i);
  378. // Left side
  379. Vec3 b1 = base - Vec3(2.0f, 0, 0);
  380. Vec3 s1 = b1 + Vec3(0, cStairsStepHeight, 0);
  381. Vec3 p1 = s1 + Vec3(0, 0, cNoStairsStepDelta);
  382. // Right side
  383. Vec3 width(4.0f, 0, 0);
  384. Vec3 b2 = b1 + width;
  385. Vec3 s2 = s1 + width;
  386. Vec3 p2 = p1 + width;
  387. triangles.push_back(Triangle(s1, s2, b1));
  388. triangles.push_back(Triangle(b1, s2, b2));
  389. triangles.push_back(Triangle(s1, p1, p2));
  390. triangles.push_back(Triangle(s1, p2, s2));
  391. }
  392. MeshShapeSettings mesh(triangles);
  393. mesh.SetEmbedded();
  394. BodyCreationSettings mesh_stairs(&mesh, cMeshNoStairsPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  395. mBodyInterface->CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  396. }
  397. // Create mesh with walls at varying angles
  398. {
  399. TriangleList triangles;
  400. Vec3 p1(0.5f * cMeshWallWidth, 0, 0);
  401. Vec3 h(0, cMeshWallHeight, 0);
  402. for (int i = 0; i < cMeshWallSegments; ++i)
  403. {
  404. float delta = cMeshWallStepStart + i * (cMeshWallStepEnd - cMeshWallStepStart) / (cMeshWallSegments - 1);
  405. Vec3 p2 = Vec3((i & 1)? 0.5f * cMeshWallWidth : -0.5f * cMeshWallWidth, 0, p1.GetZ() + delta);
  406. triangles.push_back(Triangle(p1, p1 + h, p2 + h));
  407. triangles.push_back(Triangle(p1, p2 + h, p2));
  408. p1 = p2;
  409. }
  410. MeshShapeSettings mesh(triangles);
  411. mesh.SetEmbedded();
  412. BodyCreationSettings wall(&mesh, cMeshWallPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  413. mBodyInterface->CreateAndAddBody(wall, EActivation::DontActivate);
  414. }
  415. // Create a half cylinder with caps for testing contact point limit
  416. {
  417. VertexList vertices;
  418. IndexedTriangleList triangles;
  419. // The half cylinder
  420. const int cPosSegments = 2;
  421. const int cAngleSegments = 512;
  422. const float cCylinderLength = 2.0f;
  423. for (int pos = 0; pos < cPosSegments; ++pos)
  424. for (int angle = 0; angle < cAngleSegments; ++angle)
  425. {
  426. uint32 start = (uint32)vertices.size();
  427. float radius = cCharacterRadiusStanding + 0.05f;
  428. float angle_rad = (-0.5f + float(angle) / cAngleSegments) * JPH_PI;
  429. float s = Sin(angle_rad);
  430. float c = Cos(angle_rad);
  431. float x = cCylinderLength * (-0.5f + float(pos) / (cPosSegments - 1));
  432. float y = angle == 0 || angle == cAngleSegments - 1? 0.5f : (1.0f - c) * radius;
  433. float z = s * radius;
  434. vertices.push_back(Float3(x, y, z));
  435. if (pos > 0 && angle > 0)
  436. {
  437. triangles.push_back(IndexedTriangle(start, start - 1, start - cAngleSegments));
  438. triangles.push_back(IndexedTriangle(start - 1, start - cAngleSegments - 1, start - cAngleSegments));
  439. }
  440. }
  441. // Add end caps
  442. uint32 end = cAngleSegments * (cPosSegments - 1);
  443. for (int angle = 0; angle < cAngleSegments - 1; ++angle)
  444. {
  445. triangles.push_back(IndexedTriangle(0, angle + 1, angle));
  446. triangles.push_back(IndexedTriangle(end, end + angle, end + angle + 1));
  447. }
  448. MeshShapeSettings mesh(std::move(vertices), std::move(triangles));
  449. mesh.SetEmbedded();
  450. BodyCreationSettings mesh_cylinder(&mesh, cHalfCylinderPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  451. mBodyInterface->CreateAndAddBody(mesh_cylinder, EActivation::DontActivate);
  452. }
  453. // Create a box made out of polygons (character should not get stuck behind back facing side)
  454. {
  455. VertexList vertices = {
  456. Float3(-1, 1, -1),
  457. Float3( 1, 1, -1),
  458. Float3( 1, 1, 1),
  459. Float3(-1, 1, 1),
  460. Float3(-1, -1, -1),
  461. Float3( 1, -1, -1),
  462. Float3( 1, -1, 1),
  463. Float3(-1, -1, 1)
  464. };
  465. IndexedTriangleList triangles = {
  466. IndexedTriangle(0, 3, 2),
  467. IndexedTriangle(0, 2, 1),
  468. IndexedTriangle(4, 5, 6),
  469. IndexedTriangle(4, 6, 7),
  470. IndexedTriangle(0, 4, 3),
  471. IndexedTriangle(3, 4, 7),
  472. IndexedTriangle(2, 6, 5),
  473. IndexedTriangle(2, 5, 1),
  474. IndexedTriangle(3, 7, 6),
  475. IndexedTriangle(3, 6, 2),
  476. IndexedTriangle(0, 1, 5),
  477. IndexedTriangle(0, 5, 4)
  478. };
  479. MeshShapeSettings mesh(std::move(vertices), std::move(triangles));
  480. mesh.SetEmbedded();
  481. BodyCreationSettings box(&mesh, cMeshBoxPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  482. mBodyInterface->CreateAndAddBody(box, EActivation::DontActivate);
  483. }
  484. // Create a sensor
  485. {
  486. BodyCreationSettings sensor(new BoxShape(Vec3::sOne()), cSensorPosition, Quat::sIdentity(), EMotionType::Kinematic, Layers::SENSOR);
  487. sensor.mIsSensor = true;
  488. mSensorBody = mBodyInterface->CreateAndAddBody(sensor, EActivation::Activate);
  489. }
  490. // Create Character
  491. {
  492. CharacterSettings settings;
  493. settings.mLayer = Layers::MOVING;
  494. settings.mShape = mStandingShape;
  495. settings.mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  496. mAnimatedCharacter = new Character(&settings, cCharacterPosition, Quat::sIdentity(), 0, mPhysicsSystem);
  497. mAnimatedCharacter->AddToPhysicsSystem();
  498. }
  499. // Create CharacterVirtual
  500. {
  501. CharacterVirtualSettings settings;
  502. settings.mShape = mStandingShape;
  503. settings.mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  504. mAnimatedCharacterVirtual = new CharacterVirtual(&settings, cCharacterVirtualPosition, Quat::sIdentity(), 0, mPhysicsSystem);
  505. mAnimatedCharacterVirtual->SetCharacterVsCharacterCollision(&mCharacterVsCharacterCollision);
  506. mCharacterVsCharacterCollision.Add(mAnimatedCharacterVirtual);
  507. }
  508. // Create CharacterVirtual with inner rigid body
  509. {
  510. CharacterVirtualSettings settings;
  511. settings.mShape = mStandingShape;
  512. settings.mInnerBodyShape = mInnerStandingShape;
  513. settings.mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  514. mAnimatedCharacterVirtualWithInnerBody = new CharacterVirtual(&settings, cCharacterVirtualWithInnerBodyPosition, Quat::sIdentity(), 0, mPhysicsSystem);
  515. mAnimatedCharacterVirtualWithInnerBody->SetCharacterVsCharacterCollision(&mCharacterVsCharacterCollision);
  516. mCharacterVsCharacterCollision.Add(mAnimatedCharacterVirtualWithInnerBody);
  517. }
  518. }
  519. #ifdef JPH_OBJECT_STREAM
  520. else
  521. {
  522. // Load scene
  523. Ref<PhysicsScene> scene;
  524. AssetStream stream(String(sSceneName) + ".bof", std::ios::in | std::ios::binary);
  525. if (!ObjectStreamIn::sReadObject(stream.Get(), scene))
  526. FatalError("Failed to load scene");
  527. scene->FixInvalidScales();
  528. for (BodyCreationSettings &settings : scene->GetBodies())
  529. {
  530. settings.mObjectLayer = Layers::NON_MOVING;
  531. settings.mFriction = 0.5f;
  532. }
  533. scene->CreateBodies(mPhysicsSystem);
  534. }
  535. #endif // JPH_OBJECT_STREAM
  536. }
  537. void CharacterBaseTest::ProcessInput(const ProcessInputParams &inParams)
  538. {
  539. // Determine controller input
  540. mControlInput = Vec3::sZero();
  541. if (inParams.mKeyboard->IsKeyPressed(EKey::Left)) mControlInput.SetZ(-1);
  542. if (inParams.mKeyboard->IsKeyPressed(EKey::Right)) mControlInput.SetZ(1);
  543. if (inParams.mKeyboard->IsKeyPressed(EKey::Up)) mControlInput.SetX(1);
  544. if (inParams.mKeyboard->IsKeyPressed(EKey::Down)) mControlInput.SetX(-1);
  545. if (mControlInput != Vec3::sZero())
  546. mControlInput = mControlInput.Normalized();
  547. // Rotate controls to align with the camera
  548. Vec3 cam_fwd = inParams.mCameraState.mForward;
  549. cam_fwd.SetY(0.0f);
  550. cam_fwd = cam_fwd.NormalizedOr(Vec3::sAxisX());
  551. Quat rotation = Quat::sFromTo(Vec3::sAxisX(), cam_fwd);
  552. mControlInput = rotation * mControlInput;
  553. // Check actions
  554. mJump = inParams.mKeyboard->IsKeyPressedAndTriggered(EKey::RControl, mWasJump);
  555. mSwitchStance = inParams.mKeyboard->IsKeyPressedAndTriggered(EKey::RShift, mWasSwitchStance);
  556. }
  557. void CharacterBaseTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  558. {
  559. // Update scene time
  560. mTime += inParams.mDeltaTime;
  561. // Update camera pivot
  562. mCameraPivot = GetCharacterPosition();
  563. // Animate bodies
  564. if (!mRotatingBody.IsInvalid())
  565. mBodyInterface->MoveKinematic(mRotatingBody, cRotatingPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * Sin(mTime)), inParams.mDeltaTime);
  566. if (!mRotatingWallBody.IsInvalid())
  567. mBodyInterface->MoveKinematic(mRotatingWallBody, cRotatingWallPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * Sin(mTime)), inParams.mDeltaTime);
  568. if (!mRotatingAndTranslatingBody.IsInvalid())
  569. 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);
  570. if (!mHorizontallyMovingBody.IsInvalid())
  571. mBodyInterface->MoveKinematic(mHorizontallyMovingBody, cHorizontallyMovingPosition + Vec3(3.0f * Sin(mTime), 0, 0), cHorizontallyMovingOrientation, inParams.mDeltaTime);
  572. if (!mSmoothVerticallyMovingBody.IsInvalid())
  573. mBodyInterface->MoveKinematic(mSmoothVerticallyMovingBody, cSmoothVerticallyMovingPosition + Vec3(0, 1.75f * Sin(mTime), 0), cSmoothVerticallyMovingOrientation, inParams.mDeltaTime);
  574. if (!mReversingVerticallyMovingBody.IsInvalid())
  575. {
  576. RVec3 pos = mBodyInterface->GetPosition(mReversingVerticallyMovingBody);
  577. if (pos.GetY() < cReversingVerticallyMovingPosition.GetY())
  578. mReversingVerticallyMovingVelocity = 1.0f;
  579. else if (pos.GetY() > cReversingVerticallyMovingPosition.GetY() + 5.0f)
  580. mReversingVerticallyMovingVelocity = -1.0f;
  581. mBodyInterface->MoveKinematic(mReversingVerticallyMovingBody, pos + Vec3(0, mReversingVerticallyMovingVelocity * 3.0f * inParams.mDeltaTime, 0), cReversingVerticallyMovingOrientation, inParams.mDeltaTime);
  582. }
  583. // Animate character
  584. if (mAnimatedCharacter != nullptr)
  585. mAnimatedCharacter->SetLinearVelocity(Sin(mTime) * cCharacterVelocity);
  586. // Animate character virtual
  587. for (CharacterVirtual *character : { mAnimatedCharacterVirtual, mAnimatedCharacterVirtualWithInnerBody })
  588. if (character != nullptr)
  589. {
  590. // Draw the character
  591. DrawPaddedCharacter(character->GetShape(), character->GetCharacterPadding(), character->GetCenterOfMassTransform());
  592. // Update velocity and apply gravity
  593. Vec3 velocity;
  594. if (character->GetGroundState() == CharacterVirtual::EGroundState::OnGround)
  595. velocity = Vec3::sZero();
  596. else
  597. velocity = character->GetLinearVelocity() * mAnimatedCharacter->GetUp() + mPhysicsSystem->GetGravity() * inParams.mDeltaTime;
  598. velocity += Sin(mTime) * cCharacterVelocity;
  599. character->SetLinearVelocity(velocity);
  600. // Move character
  601. CharacterVirtual::ExtendedUpdateSettings update_settings;
  602. character->ExtendedUpdate(inParams.mDeltaTime,
  603. mPhysicsSystem->GetGravity(),
  604. update_settings,
  605. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  606. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  607. { },
  608. { },
  609. *mTempAllocator);
  610. }
  611. // Reset ramp blocks
  612. mRampBlocksTimeLeft -= inParams.mDeltaTime;
  613. if (mRampBlocksTimeLeft < 0.0f)
  614. {
  615. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  616. {
  617. mBodyInterface->SetPositionAndRotation(mRampBlocks[i], cRampBlocksStart + float(i) * cRampBlocksDelta, cRampOrientation, EActivation::Activate);
  618. mBodyInterface->SetLinearAndAngularVelocity(mRampBlocks[i], Vec3::sZero(), Vec3::sZero());
  619. }
  620. mRampBlocksTimeLeft = cRampBlocksTime;
  621. }
  622. // Call handle input after new velocities have been set to avoid frame delay
  623. HandleInput(mControlInput, mJump, mSwitchStance, inParams.mDeltaTime);
  624. }
  625. void CharacterBaseTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  626. {
  627. inUI->CreateTextButton(inSubMenu, "Select Scene", [this, inUI]() {
  628. UIElement *scene_name = inUI->CreateMenu();
  629. for (uint i = 0; i < size(sScenes); ++i)
  630. inUI->CreateTextButton(scene_name, sScenes[i], [this, i]() { sSceneName = sScenes[i]; RestartTest(); });
  631. inUI->ShowMenu(scene_name);
  632. });
  633. inUI->CreateTextButton(inSubMenu, "Character Movement Settings", [this, inUI]() {
  634. UIElement *movement_settings = inUI->CreateMenu();
  635. inUI->CreateCheckBox(movement_settings, "Control Movement During Jump", sControlMovementDuringJump, [](UICheckBox::EState inState) { sControlMovementDuringJump = inState == UICheckBox::STATE_CHECKED; });
  636. inUI->CreateSlider(movement_settings, "Character Speed", sCharacterSpeed, 0.1f, 10.0f, 0.1f, [](float inValue) { sCharacterSpeed = inValue; });
  637. inUI->CreateSlider(movement_settings, "Character Jump Speed", sJumpSpeed, 0.1f, 10.0f, 0.1f, [](float inValue) { sJumpSpeed = inValue; });
  638. AddCharacterMovementSettings(inUI, movement_settings);
  639. inUI->ShowMenu(movement_settings);
  640. });
  641. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [this, inUI]() {
  642. UIElement *configuration_settings = inUI->CreateMenu();
  643. inUI->CreateComboBox(configuration_settings, "Shape Type", { "Capsule", "Cylinder", "Box", "Compound" }, (int)sShapeType, [](int inItem) { sShapeType = (EType)inItem; });
  644. AddConfigurationSettings(inUI, configuration_settings);
  645. inUI->CreateTextButton(configuration_settings, "Accept Changes", [this]() { RestartTest(); });
  646. inUI->ShowMenu(configuration_settings);
  647. });
  648. }
  649. void CharacterBaseTest::GetInitialCamera(CameraState& ioState) const
  650. {
  651. // This will become the local space offset, look down the x axis and slightly down
  652. ioState.mPos = RVec3::sZero();
  653. ioState.mForward = Vec3(10.0f, -2.0f, 0).Normalized();
  654. }
  655. RMat44 CharacterBaseTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  656. {
  657. // Pivot is center of character + distance behind based on the heading and pitch of the camera
  658. Vec3 fwd = Vec3(Cos(inCameraPitch) * Cos(inCameraHeading), Sin(inCameraPitch), Cos(inCameraPitch) * Sin(inCameraHeading));
  659. return RMat44::sTranslation(mCameraPivot + Vec3(0, cCharacterHeightStanding + cCharacterRadiusStanding, 0) - 5.0f * fwd);
  660. }
  661. void CharacterBaseTest::SaveState(StateRecorder &inStream) const
  662. {
  663. inStream.Write(mTime);
  664. inStream.Write(mRampBlocksTimeLeft);
  665. inStream.Write(mReversingVerticallyMovingVelocity);
  666. if (mAnimatedCharacterVirtual != nullptr)
  667. mAnimatedCharacterVirtual->SaveState(inStream);
  668. if (mAnimatedCharacterVirtualWithInnerBody != nullptr)
  669. mAnimatedCharacterVirtualWithInnerBody->SaveState(inStream);
  670. }
  671. void CharacterBaseTest::RestoreState(StateRecorder &inStream)
  672. {
  673. inStream.Read(mTime);
  674. inStream.Read(mRampBlocksTimeLeft);
  675. inStream.Read(mReversingVerticallyMovingVelocity);
  676. if (mAnimatedCharacterVirtual != nullptr)
  677. mAnimatedCharacterVirtual->RestoreState(inStream);
  678. if (mAnimatedCharacterVirtualWithInnerBody != nullptr)
  679. mAnimatedCharacterVirtualWithInnerBody->RestoreState(inStream);
  680. }
  681. void CharacterBaseTest::SaveInputState(StateRecorder &inStream) const
  682. {
  683. inStream.Write(mControlInput);
  684. inStream.Write(mJump);
  685. inStream.Write(mSwitchStance);
  686. }
  687. void CharacterBaseTest::RestoreInputState(StateRecorder &inStream)
  688. {
  689. inStream.Read(mControlInput);
  690. inStream.Read(mJump);
  691. inStream.Read(mSwitchStance);
  692. }
  693. void CharacterBaseTest::DrawCharacterState(const CharacterBase *inCharacter, RMat44Arg inCharacterTransform, Vec3Arg inCharacterVelocity)
  694. {
  695. // Draw current location
  696. // 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)
  697. mDebugRenderer->DrawCoordinateSystem(inCharacterTransform, 0.1f);
  698. // Draw the state of the ground contact
  699. CharacterBase::EGroundState ground_state = inCharacter->GetGroundState();
  700. if (ground_state != CharacterBase::EGroundState::InAir)
  701. {
  702. RVec3 ground_position = inCharacter->GetGroundPosition();
  703. Vec3 ground_normal = inCharacter->GetGroundNormal();
  704. Vec3 ground_velocity = inCharacter->GetGroundVelocity();
  705. // Draw ground position
  706. mDebugRenderer->DrawMarker(ground_position, Color::sRed, 0.1f);
  707. mDebugRenderer->DrawArrow(ground_position, ground_position + 2.0f * ground_normal, Color::sGreen, 0.1f);
  708. // Draw ground velocity
  709. if (!ground_velocity.IsNearZero())
  710. mDebugRenderer->DrawArrow(ground_position, ground_position + ground_velocity, Color::sBlue, 0.1f);
  711. }
  712. // Draw provided character velocity
  713. if (!inCharacterVelocity.IsNearZero())
  714. mDebugRenderer->DrawArrow(inCharacterTransform.GetTranslation(), inCharacterTransform.GetTranslation() + inCharacterVelocity, Color::sYellow, 0.1f);
  715. // Draw text info
  716. const PhysicsMaterial *ground_material = inCharacter->GetGroundMaterial();
  717. Vec3 horizontal_velocity = inCharacterVelocity;
  718. horizontal_velocity.SetY(0);
  719. mDebugRenderer->DrawText3D(inCharacterTransform.GetTranslation(), StringFormat("State: %s\nMat: %s\nHorizontal Vel: %.1f m/s\nVertical Vel: %.1f m/s", CharacterBase::sToString(ground_state), ground_material->GetDebugName(), (double)horizontal_velocity.Length(), (double)inCharacterVelocity.GetY()), Color::sWhite, 0.25f);
  720. }
  721. void CharacterBaseTest::DrawPaddedCharacter(const Shape *inShape, float inPadding, RMat44Arg inCenterOfMass)
  722. {
  723. if (inShape->GetSubType() == EShapeSubType::Capsule)
  724. {
  725. const CapsuleShape *capsule = static_cast<const CapsuleShape *>(inShape);
  726. mDebugRenderer->DrawCapsule(inCenterOfMass, capsule->GetHalfHeightOfCylinder(), capsule->GetRadius() + inPadding, Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  727. }
  728. else if (inShape->GetSubType() == EShapeSubType::Cylinder)
  729. {
  730. // Not correct as the edges should be rounded
  731. const CylinderShape *cylinder = static_cast<const CylinderShape *>(inShape);
  732. mDebugRenderer->DrawCylinder(inCenterOfMass, cylinder->GetHalfHeight() + inPadding, cylinder->GetRadius() + inPadding, Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  733. }
  734. else if (inShape->GetSubType() == EShapeSubType::Box)
  735. {
  736. // Not correct as the edges should be rounded
  737. const BoxShape *box = static_cast<const BoxShape *>(inShape);
  738. AABox bounds = box->GetLocalBounds();
  739. bounds.ExpandBy(Vec3::sReplicate(inPadding));
  740. mDebugRenderer->DrawWireBox(inCenterOfMass, bounds, Color::sGrey);
  741. }
  742. else if (inShape->GetSubType() == EShapeSubType::RotatedTranslated)
  743. {
  744. const RotatedTranslatedShape *rt = static_cast<const RotatedTranslatedShape *>(inShape);
  745. DrawPaddedCharacter(rt->GetInnerShape(), inPadding, inCenterOfMass);
  746. }
  747. else if (inShape->GetType() == EShapeType::Compound)
  748. {
  749. const CompoundShape *compound = static_cast<const CompoundShape *>(inShape);
  750. for (const CompoundShape::SubShape &sub_shape : compound->GetSubShapes())
  751. DrawPaddedCharacter(sub_shape.mShape, inPadding, inCenterOfMass * sub_shape.GetLocalTransformNoScale(Vec3::sOne()));
  752. }
  753. }