SamplesApp.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <SamplesApp.h>
  5. #include <Application/EntryPoint.h>
  6. #include <Jolt/Core/JobSystemThreadPool.h>
  7. #include <Jolt/Core/TempAllocator.h>
  8. #include <Jolt/Geometry/OrientedBox.h>
  9. #include <Jolt/Physics/PhysicsSystem.h>
  10. #include <Jolt/Physics/StateRecorderImpl.h>
  11. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  12. #include <Jolt/Physics/Collision/RayCast.h>
  13. #include <Jolt/Physics/Collision/ShapeCast.h>
  14. #include <Jolt/Physics/Collision/CastResult.h>
  15. #include <Jolt/Physics/Collision/CollidePointResult.h>
  16. #include <Jolt/Physics/Collision/AABoxCast.h>
  17. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  18. #include <Jolt/Physics/Collision/Shape/HeightFieldShape.h>
  19. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  20. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  21. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  22. #include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
  23. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  24. #include <Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h>
  25. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  26. #include <Jolt/Physics/Collision/Shape/TriangleShape.h>
  27. #include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
  28. #include <Jolt/Physics/Collision/Shape/MutableCompoundShape.h>
  29. #include <Jolt/Physics/Collision/Shape/ScaledShape.h>
  30. #include <Jolt/Physics/Collision/NarrowPhaseStats.h>
  31. #include <Jolt/Physics/Constraints/DistanceConstraint.h>
  32. #include <Jolt/Physics/Character/CharacterVirtual.h>
  33. #include <Utils/Log.h>
  34. #include <Renderer/DebugRendererImp.h>
  35. //-----------------------------------------------------------------------------
  36. // RTTI definitions
  37. //-----------------------------------------------------------------------------
  38. struct TestNameAndRTTI
  39. {
  40. const char * mName;
  41. const RTTI * mRTTI;
  42. };
  43. struct TestCategory
  44. {
  45. const char * mName;
  46. TestNameAndRTTI * mTests;
  47. size_t mNumTests;
  48. };
  49. JPH_DECLARE_RTTI_FOR_FACTORY(SimpleTest)
  50. JPH_DECLARE_RTTI_FOR_FACTORY(StackTest)
  51. JPH_DECLARE_RTTI_FOR_FACTORY(WallTest)
  52. JPH_DECLARE_RTTI_FOR_FACTORY(IslandTest)
  53. JPH_DECLARE_RTTI_FOR_FACTORY(FunnelTest)
  54. JPH_DECLARE_RTTI_FOR_FACTORY(FrictionTest)
  55. JPH_DECLARE_RTTI_FOR_FACTORY(FrictionPerTriangleTest)
  56. JPH_DECLARE_RTTI_FOR_FACTORY(GravityFactorTest)
  57. JPH_DECLARE_RTTI_FOR_FACTORY(RestitutionTest)
  58. JPH_DECLARE_RTTI_FOR_FACTORY(DampingTest)
  59. JPH_DECLARE_RTTI_FOR_FACTORY(KinematicTest)
  60. JPH_DECLARE_RTTI_FOR_FACTORY(ContactManifoldTest)
  61. JPH_DECLARE_RTTI_FOR_FACTORY(ManifoldReductionTest)
  62. JPH_DECLARE_RTTI_FOR_FACTORY(CenterOfMassTest)
  63. JPH_DECLARE_RTTI_FOR_FACTORY(HeavyOnLightTest)
  64. JPH_DECLARE_RTTI_FOR_FACTORY(HighSpeedTest)
  65. JPH_DECLARE_RTTI_FOR_FACTORY(ChangeMotionTypeTest)
  66. JPH_DECLARE_RTTI_FOR_FACTORY(ChangeShapeTest)
  67. JPH_DECLARE_RTTI_FOR_FACTORY(ChangeObjectLayerTest)
  68. JPH_DECLARE_RTTI_FOR_FACTORY(LoadSaveSceneTest)
  69. JPH_DECLARE_RTTI_FOR_FACTORY(LoadSaveBinaryTest)
  70. JPH_DECLARE_RTTI_FOR_FACTORY(BigVsSmallTest)
  71. JPH_DECLARE_RTTI_FOR_FACTORY(ActiveEdgesTest)
  72. JPH_DECLARE_RTTI_FOR_FACTORY(MultithreadedTest)
  73. JPH_DECLARE_RTTI_FOR_FACTORY(ContactListenerTest)
  74. JPH_DECLARE_RTTI_FOR_FACTORY(ActivateDuringUpdateTest)
  75. JPH_DECLARE_RTTI_FOR_FACTORY(SensorTest)
  76. static TestNameAndRTTI sGeneralTests[] =
  77. {
  78. { "Simple", JPH_RTTI(SimpleTest) },
  79. { "Stack", JPH_RTTI(StackTest) },
  80. { "Wall", JPH_RTTI(WallTest) },
  81. { "Island", JPH_RTTI(IslandTest) },
  82. { "Funnel", JPH_RTTI(FunnelTest) },
  83. { "Friction", JPH_RTTI(FrictionTest) },
  84. { "Friction (Per Triangle)", JPH_RTTI(FrictionPerTriangleTest) },
  85. { "Gravity Factor", JPH_RTTI(GravityFactorTest) },
  86. { "Restitution", JPH_RTTI(RestitutionTest) },
  87. { "Damping", JPH_RTTI(DampingTest) },
  88. { "Kinematic", JPH_RTTI(KinematicTest) },
  89. { "Contact Manifold", JPH_RTTI(ContactManifoldTest) },
  90. { "Manifold Reduction", JPH_RTTI(ManifoldReductionTest) },
  91. { "Center Of Mass", JPH_RTTI(CenterOfMassTest) },
  92. { "Heavy On Light", JPH_RTTI(HeavyOnLightTest) },
  93. { "High Speed", JPH_RTTI(HighSpeedTest) },
  94. { "Change Motion Type", JPH_RTTI(ChangeMotionTypeTest) },
  95. { "Change Shape", JPH_RTTI(ChangeShapeTest) },
  96. { "Change Object Layer", JPH_RTTI(ChangeObjectLayerTest) },
  97. { "Load/Save Scene", JPH_RTTI(LoadSaveSceneTest) },
  98. { "Load/Save Binary", JPH_RTTI(LoadSaveBinaryTest) },
  99. { "Big vs Small", JPH_RTTI(BigVsSmallTest) },
  100. { "Active Edges", JPH_RTTI(ActiveEdgesTest) },
  101. { "Multithreaded", JPH_RTTI(MultithreadedTest) },
  102. { "Contact Listener", JPH_RTTI(ContactListenerTest) },
  103. { "Activate During Update", JPH_RTTI(ActivateDuringUpdateTest) },
  104. { "Sensor", JPH_RTTI(SensorTest) },
  105. };
  106. JPH_DECLARE_RTTI_FOR_FACTORY(DistanceConstraintTest)
  107. JPH_DECLARE_RTTI_FOR_FACTORY(FixedConstraintTest)
  108. JPH_DECLARE_RTTI_FOR_FACTORY(ConeConstraintTest)
  109. JPH_DECLARE_RTTI_FOR_FACTORY(SwingTwistConstraintTest)
  110. JPH_DECLARE_RTTI_FOR_FACTORY(SixDOFConstraintTest)
  111. JPH_DECLARE_RTTI_FOR_FACTORY(HingeConstraintTest)
  112. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredHingeConstraintTest)
  113. JPH_DECLARE_RTTI_FOR_FACTORY(PointConstraintTest)
  114. JPH_DECLARE_RTTI_FOR_FACTORY(SliderConstraintTest)
  115. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredSliderConstraintTest)
  116. JPH_DECLARE_RTTI_FOR_FACTORY(SpringTest)
  117. JPH_DECLARE_RTTI_FOR_FACTORY(ConstraintSingularityTest)
  118. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredSwingTwistConstraintTest)
  119. JPH_DECLARE_RTTI_FOR_FACTORY(SwingTwistConstraintFrictionTest)
  120. JPH_DECLARE_RTTI_FOR_FACTORY(PathConstraintTest)
  121. static TestNameAndRTTI sConstraintTests[] =
  122. {
  123. { "Point Constraint", JPH_RTTI(PointConstraintTest) },
  124. { "Distance Constraint", JPH_RTTI(DistanceConstraintTest) },
  125. { "Hinge Constraint", JPH_RTTI(HingeConstraintTest) },
  126. { "Powered Hinge Constraint", JPH_RTTI(PoweredHingeConstraintTest) },
  127. { "Slider Constraint", JPH_RTTI(SliderConstraintTest) },
  128. { "Powered Slider Constraint", JPH_RTTI(PoweredSliderConstraintTest) },
  129. { "Fixed Constraint", JPH_RTTI(FixedConstraintTest) },
  130. { "Cone Constraint", JPH_RTTI(ConeConstraintTest) },
  131. { "Swing Twist Constraint", JPH_RTTI(SwingTwistConstraintTest) },
  132. { "Powered Swing Twist Constraint", JPH_RTTI(PoweredSwingTwistConstraintTest) },
  133. { "Swing Twist Constraint Friction", JPH_RTTI(SwingTwistConstraintFrictionTest) },
  134. { "Six DOF Constraint", JPH_RTTI(SixDOFConstraintTest) },
  135. { "Path Constraint", JPH_RTTI(PathConstraintTest) },
  136. { "Spring", JPH_RTTI(SpringTest) },
  137. { "Constraint Singularity", JPH_RTTI(ConstraintSingularityTest) },
  138. };
  139. JPH_DECLARE_RTTI_FOR_FACTORY(BoxShapeTest)
  140. JPH_DECLARE_RTTI_FOR_FACTORY(SphereShapeTest)
  141. JPH_DECLARE_RTTI_FOR_FACTORY(TaperedCapsuleShapeTest)
  142. JPH_DECLARE_RTTI_FOR_FACTORY(CapsuleShapeTest)
  143. JPH_DECLARE_RTTI_FOR_FACTORY(CylinderShapeTest)
  144. JPH_DECLARE_RTTI_FOR_FACTORY(StaticCompoundShapeTest)
  145. JPH_DECLARE_RTTI_FOR_FACTORY(MutableCompoundShapeTest)
  146. JPH_DECLARE_RTTI_FOR_FACTORY(TriangleShapeTest)
  147. JPH_DECLARE_RTTI_FOR_FACTORY(ConvexHullShapeTest)
  148. JPH_DECLARE_RTTI_FOR_FACTORY(MeshShapeTest)
  149. JPH_DECLARE_RTTI_FOR_FACTORY(HeightFieldShapeTest)
  150. JPH_DECLARE_RTTI_FOR_FACTORY(RotatedTranslatedShapeTest)
  151. JPH_DECLARE_RTTI_FOR_FACTORY(OffsetCenterOfMassShapeTest)
  152. static TestNameAndRTTI sShapeTests[] =
  153. {
  154. { "Sphere Shape", JPH_RTTI(SphereShapeTest) },
  155. { "Box Shape", JPH_RTTI(BoxShapeTest) },
  156. { "Capsule Shape", JPH_RTTI(CapsuleShapeTest) },
  157. { "Tapered Capsule Shape", JPH_RTTI(TaperedCapsuleShapeTest) },
  158. { "Cylinder Shape", JPH_RTTI(CylinderShapeTest) },
  159. { "Convex Hull Shape", JPH_RTTI(ConvexHullShapeTest) },
  160. { "Mesh Shape", JPH_RTTI(MeshShapeTest) },
  161. { "Height Field Shape", JPH_RTTI(HeightFieldShapeTest) },
  162. { "Static Compound Shape", JPH_RTTI(StaticCompoundShapeTest) },
  163. { "Mutable Compound Shape", JPH_RTTI(MutableCompoundShapeTest) },
  164. { "Triangle Shape", JPH_RTTI(TriangleShapeTest) },
  165. { "Rotated Translated Shape", JPH_RTTI(RotatedTranslatedShapeTest) },
  166. { "Offset Center Of Mass Shape", JPH_RTTI(OffsetCenterOfMassShapeTest) }
  167. };
  168. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledSphereShapeTest)
  169. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledBoxShapeTest)
  170. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledCapsuleShapeTest)
  171. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledTaperedCapsuleShapeTest)
  172. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledCylinderShapeTest)
  173. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledConvexHullShapeTest)
  174. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledMeshShapeTest)
  175. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledHeightFieldShapeTest)
  176. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledStaticCompoundShapeTest)
  177. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledMutableCompoundShapeTest)
  178. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledTriangleShapeTest)
  179. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledOffsetCenterOfMassShapeTest)
  180. static TestNameAndRTTI sScaledShapeTests[] =
  181. {
  182. { "Sphere Shape", JPH_RTTI(ScaledSphereShapeTest) },
  183. { "Box Shape", JPH_RTTI(ScaledBoxShapeTest) },
  184. { "Capsule Shape", JPH_RTTI(ScaledCapsuleShapeTest) },
  185. { "Tapered Capsule Shape", JPH_RTTI(ScaledTaperedCapsuleShapeTest) },
  186. { "Cylinder Shape", JPH_RTTI(ScaledCylinderShapeTest) },
  187. { "Convex Hull Shape", JPH_RTTI(ScaledConvexHullShapeTest) },
  188. { "Mesh Shape", JPH_RTTI(ScaledMeshShapeTest) },
  189. { "Height Field Shape", JPH_RTTI(ScaledHeightFieldShapeTest) },
  190. { "Static Compound Shape", JPH_RTTI(ScaledStaticCompoundShapeTest) },
  191. { "Mutable Compound Shape", JPH_RTTI(ScaledMutableCompoundShapeTest) },
  192. { "Triangle Shape", JPH_RTTI(ScaledTriangleShapeTest) },
  193. { "Offset Center Of Mass Shape", JPH_RTTI(ScaledOffsetCenterOfMassShapeTest) }
  194. };
  195. JPH_DECLARE_RTTI_FOR_FACTORY(CreateRigTest)
  196. JPH_DECLARE_RTTI_FOR_FACTORY(LoadRigTest)
  197. JPH_DECLARE_RTTI_FOR_FACTORY(KinematicRigTest)
  198. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredRigTest)
  199. JPH_DECLARE_RTTI_FOR_FACTORY(RigPileTest)
  200. JPH_DECLARE_RTTI_FOR_FACTORY(LoadSaveBinaryRigTest)
  201. static TestNameAndRTTI sRigTests[] =
  202. {
  203. { "Create Rig", JPH_RTTI(CreateRigTest) },
  204. { "Load Rig", JPH_RTTI(LoadRigTest) },
  205. { "Load / Save Binary Rig", JPH_RTTI(LoadSaveBinaryRigTest) },
  206. { "Kinematic Rig", JPH_RTTI(KinematicRigTest) },
  207. { "Powered Rig", JPH_RTTI(PoweredRigTest) },
  208. { "Rig Pile", JPH_RTTI(RigPileTest) }
  209. };
  210. JPH_DECLARE_RTTI_FOR_FACTORY(CharacterTest)
  211. JPH_DECLARE_RTTI_FOR_FACTORY(CharacterVirtualTest)
  212. static TestNameAndRTTI sCharacterTests[] =
  213. {
  214. { "Character", JPH_RTTI(CharacterTest) },
  215. { "Character Virtual", JPH_RTTI(CharacterVirtualTest) },
  216. };
  217. JPH_DECLARE_RTTI_FOR_FACTORY(WaterShapeTest)
  218. static TestNameAndRTTI sWaterTests[] =
  219. {
  220. { "Shapes", JPH_RTTI(WaterShapeTest) },
  221. };
  222. JPH_DECLARE_RTTI_FOR_FACTORY(VehicleSixDOFTest)
  223. JPH_DECLARE_RTTI_FOR_FACTORY(VehicleConstraintTest)
  224. JPH_DECLARE_RTTI_FOR_FACTORY(TankTest)
  225. static TestNameAndRTTI sVehicleTests[] =
  226. {
  227. { "Car (VehicleConstraint)", JPH_RTTI(VehicleConstraintTest) },
  228. { "Tank (VehicleConstraint)", JPH_RTTI(TankTest) },
  229. { "Car (SixDOFConstraint)", JPH_RTTI(VehicleSixDOFTest) },
  230. };
  231. JPH_DECLARE_RTTI_FOR_FACTORY(BroadPhaseCastRayTest)
  232. JPH_DECLARE_RTTI_FOR_FACTORY(BroadPhaseInsertionTest)
  233. static TestNameAndRTTI sBroadPhaseTests[] =
  234. {
  235. { "Cast Ray", JPH_RTTI(BroadPhaseCastRayTest) },
  236. { "Insertion", JPH_RTTI(BroadPhaseInsertionTest) }
  237. };
  238. JPH_DECLARE_RTTI_FOR_FACTORY(InteractivePairsTest)
  239. JPH_DECLARE_RTTI_FOR_FACTORY(EPATest)
  240. JPH_DECLARE_RTTI_FOR_FACTORY(ClosestPointTest)
  241. JPH_DECLARE_RTTI_FOR_FACTORY(ConvexHullTest)
  242. JPH_DECLARE_RTTI_FOR_FACTORY(ConvexHullShrinkTest)
  243. JPH_DECLARE_RTTI_FOR_FACTORY(RandomRayTest)
  244. JPH_DECLARE_RTTI_FOR_FACTORY(CapsuleVsBoxTest)
  245. static TestNameAndRTTI sConvexCollisionTests[] =
  246. {
  247. { "Interactive Pairs", JPH_RTTI(InteractivePairsTest) },
  248. { "EPA Test", JPH_RTTI(EPATest) },
  249. { "Closest Point", JPH_RTTI(ClosestPointTest) },
  250. { "Convex Hull", JPH_RTTI(ConvexHullTest) },
  251. { "Convex Hull Shrink", JPH_RTTI(ConvexHullShrinkTest) },
  252. { "Random Ray", JPH_RTTI(RandomRayTest) },
  253. { "Capsule Vs Box", JPH_RTTI(CapsuleVsBoxTest) }
  254. };
  255. static TestCategory sAllCategories[] =
  256. {
  257. { "General", sGeneralTests, size(sGeneralTests) },
  258. { "Shapes", sShapeTests, size(sShapeTests) },
  259. { "Scaled Shapes", sScaledShapeTests, size(sScaledShapeTests) },
  260. { "Constraints", sConstraintTests, size(sConstraintTests) },
  261. { "Rig", sRigTests, size(sRigTests) },
  262. { "Character", sCharacterTests, size(sCharacterTests) },
  263. { "Water", sWaterTests, size(sWaterTests) },
  264. { "Vehicle", sVehicleTests, size(sVehicleTests) },
  265. { "Broad Phase", sBroadPhaseTests, size(sBroadPhaseTests) },
  266. { "Convex Collision", sConvexCollisionTests, size(sConvexCollisionTests) }
  267. };
  268. //-----------------------------------------------------------------------------
  269. // Configuration
  270. //-----------------------------------------------------------------------------
  271. static constexpr uint cNumBodies = 10240;
  272. static constexpr uint cNumBodyMutexes = 0; // Autodetect
  273. static constexpr uint cMaxBodyPairs = 65536;
  274. static constexpr uint cMaxContactConstraints = 10240;
  275. SamplesApp::SamplesApp()
  276. {
  277. // Allocate temp memory
  278. #ifdef JPH_DISABLE_TEMP_ALLOCATOR
  279. mTempAllocator = new TempAllocatorMalloc();
  280. #else
  281. mTempAllocator = new TempAllocatorImpl(16 * 1024 * 1024);
  282. #endif
  283. // Create job system
  284. mJobSystem = new JobSystemThreadPool(cMaxPhysicsJobs, cMaxPhysicsBarriers, mMaxConcurrentJobs - 1);
  285. // Create job system without extra threads for validating
  286. mJobSystemValidating = new JobSystemThreadPool(cMaxPhysicsJobs, cMaxPhysicsBarriers, 0);
  287. // Create UI
  288. UIElement *main_menu = mDebugUI->CreateMenu();
  289. mDebugUI->CreateTextButton(main_menu, "Select Test", [this]() {
  290. UIElement *tests = mDebugUI->CreateMenu();
  291. for (TestCategory &c : sAllCategories)
  292. {
  293. mDebugUI->CreateTextButton(tests, c.mName, [=]() {
  294. UIElement *category = mDebugUI->CreateMenu();
  295. for (uint j = 0; j < c.mNumTests; ++j)
  296. mDebugUI->CreateTextButton(category, c.mTests[j].mName, [=]() { StartTest(c.mTests[j].mRTTI); });
  297. mDebugUI->ShowMenu(category);
  298. });
  299. }
  300. mDebugUI->ShowMenu(tests);
  301. });
  302. mTestSettingsButton = mDebugUI->CreateTextButton(main_menu, "Test Settings", [this](){
  303. UIElement *test_settings = mDebugUI->CreateMenu();
  304. mTest->CreateSettingsMenu(mDebugUI, test_settings);
  305. mDebugUI->ShowMenu(test_settings);
  306. });
  307. mDebugUI->CreateTextButton(main_menu, "Restart Test (R)", [this]() { StartTest(mTestClass); });
  308. mDebugUI->CreateTextButton(main_menu, "Run All Tests", [this]() { RunAllTests(); });
  309. mNextTestButton = mDebugUI->CreateTextButton(main_menu, "Next Test (N)", [this]() { NextTest(); });
  310. mNextTestButton->SetDisabled(true);
  311. mDebugUI->CreateTextButton(main_menu, "Physics Settings", [this]() {
  312. UIElement *phys_settings = mDebugUI->CreateMenu();
  313. mDebugUI->CreateSlider(phys_settings, "Max Concurrent Jobs", float(mMaxConcurrentJobs), 1, float(thread::hardware_concurrency()), 1, [this](float inValue) { mMaxConcurrentJobs = (int)inValue; });
  314. mDebugUI->CreateSlider(phys_settings, "Gravity (m/s^2)", -mPhysicsSystem->GetGravity().GetY(), 0.0f, 20.0f, 1.0f, [this](float inValue) { mPhysicsSystem->SetGravity(Vec3(0, -inValue, 0)); });
  315. mDebugUI->CreateSlider(phys_settings, "Update Frequency (Hz)", mUpdateFrequency, 7.5f, 120.0f, 2.5f, [this](float inValue) { mUpdateFrequency = inValue; });
  316. mDebugUI->CreateSlider(phys_settings, "Num Collision Steps", float(mCollisionSteps), 1.0f, 4.0f, 1.0f, [this](float inValue) { mCollisionSteps = int(inValue); });
  317. mDebugUI->CreateSlider(phys_settings, "Num Integration Sub Steps", float(mIntegrationSubSteps), 1.0f, 4.0f, 1.0f, [this](float inValue) { mIntegrationSubSteps = int(inValue); });
  318. mDebugUI->CreateSlider(phys_settings, "Num Velocity Steps", float(mPhysicsSettings.mNumVelocitySteps), 0, 30, 1, [this](float inValue) { mPhysicsSettings.mNumVelocitySteps = int(round(inValue)); mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  319. mDebugUI->CreateSlider(phys_settings, "Num Position Steps", float(mPhysicsSettings.mNumPositionSteps), 0, 30, 1, [this](float inValue) { mPhysicsSettings.mNumPositionSteps = int(round(inValue)); mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  320. mDebugUI->CreateSlider(phys_settings, "Baumgarte Stabilization Factor", mPhysicsSettings.mBaumgarte, 0.01f, 1.0f, 0.05f, [this](float inValue) { mPhysicsSettings.mBaumgarte = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  321. mDebugUI->CreateSlider(phys_settings, "Speculative Contact Distance (m)", mPhysicsSettings.mSpeculativeContactDistance, 0.0f, 0.1f, 0.005f, [this](float inValue) { mPhysicsSettings.mSpeculativeContactDistance = inValue; });
  322. mDebugUI->CreateSlider(phys_settings, "Penetration Slop (m)", mPhysicsSettings.mPenetrationSlop, 0.0f, 0.1f, 0.005f, [this](float inValue) { mPhysicsSettings.mPenetrationSlop = inValue; });
  323. mDebugUI->CreateSlider(phys_settings, "Min Velocity For Restitution (m/s)", mPhysicsSettings.mMinVelocityForRestitution, 0.0f, 10.0f, 0.1f, [this](float inValue) { mPhysicsSettings.mMinVelocityForRestitution = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  324. mDebugUI->CreateSlider(phys_settings, "Time Before Sleep (s)", mPhysicsSettings.mTimeBeforeSleep, 0.1f, 1.0f, 0.1f, [this](float inValue) { mPhysicsSettings.mTimeBeforeSleep = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  325. mDebugUI->CreateSlider(phys_settings, "Point Velocity Sleep Threshold (m/s)", mPhysicsSettings.mPointVelocitySleepThreshold, 0.01f, 1.0f, 0.01f, [this](float inValue) { mPhysicsSettings.mPointVelocitySleepThreshold = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  326. mDebugUI->CreateCheckBox(phys_settings, "Constraint Warm Starting", mPhysicsSettings.mConstraintWarmStart, [this](UICheckBox::EState inState) { mPhysicsSettings.mConstraintWarmStart = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  327. mDebugUI->CreateCheckBox(phys_settings, "Use Body Pair Contact Cache", mPhysicsSettings.mUseBodyPairContactCache, [this](UICheckBox::EState inState) { mPhysicsSettings.mUseBodyPairContactCache = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  328. mDebugUI->CreateCheckBox(phys_settings, "Contact Manifold Reduction", mPhysicsSettings.mUseManifoldReduction, [this](UICheckBox::EState inState) { mPhysicsSettings.mUseManifoldReduction = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  329. mDebugUI->CreateCheckBox(phys_settings, "Allow Sleeping", mPhysicsSettings.mAllowSleeping, [this](UICheckBox::EState inState) { mPhysicsSettings.mAllowSleeping = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  330. mDebugUI->CreateCheckBox(phys_settings, "Check Active Triangle Edges", mPhysicsSettings.mCheckActiveEdges, [this](UICheckBox::EState inState) { mPhysicsSettings.mCheckActiveEdges = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  331. mDebugUI->CreateCheckBox(phys_settings, "Record State For Playback", mRecordState, [this](UICheckBox::EState inState) { mRecordState = inState == UICheckBox::STATE_CHECKED; });
  332. mDebugUI->CreateCheckBox(phys_settings, "Check Determinism", mCheckDeterminism, [this](UICheckBox::EState inState) { mCheckDeterminism = inState == UICheckBox::STATE_CHECKED; });
  333. mDebugUI->CreateCheckBox(phys_settings, "Install Contact Listener", mInstallContactListener, [this](UICheckBox::EState inState) { mInstallContactListener = inState == UICheckBox::STATE_CHECKED; StartTest(mTestClass); });
  334. mDebugUI->ShowMenu(phys_settings);
  335. });
  336. #ifdef JPH_DEBUG_RENDERER
  337. mDebugUI->CreateTextButton(main_menu, "Drawing Options", [this]() {
  338. UIElement *drawing_options = mDebugUI->CreateMenu();
  339. mDebugUI->CreateCheckBox(drawing_options, "Draw Body Names", mBodyDrawSettings.mDrawNames, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawNames = inState == UICheckBox::STATE_CHECKED; });
  340. mDebugUI->CreateCheckBox(drawing_options, "Draw Shapes (H)", mBodyDrawSettings.mDrawShape, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawShape = inState == UICheckBox::STATE_CHECKED; });
  341. mDebugUI->CreateCheckBox(drawing_options, "Draw Shapes Wireframe (Alt+W)", mBodyDrawSettings.mDrawShapeWireframe, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawShapeWireframe = inState == UICheckBox::STATE_CHECKED; });
  342. mDebugUI->CreateComboBox(drawing_options, "Draw Shape Color", { "Instance", "Shape Type", "Motion Type", "Sleep", "Island", "Material" }, (int)mBodyDrawSettings.mDrawShapeColor, [this](int inItem) { mBodyDrawSettings.mDrawShapeColor = (BodyManager::EShapeColor)inItem; });
  343. mDebugUI->CreateCheckBox(drawing_options, "Draw GetSupport + Cvx Radius (Shift+H)", mBodyDrawSettings.mDrawGetSupportFunction, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawGetSupportFunction = inState == UICheckBox::STATE_CHECKED; });
  344. mDebugUI->CreateCheckBox(drawing_options, "Draw Shapes Using GetTrianglesStart/Next (Alt+H)", mDrawGetTriangles, [this](UICheckBox::EState inState) { mDrawGetTriangles = inState == UICheckBox::STATE_CHECKED; });
  345. mDebugUI->CreateCheckBox(drawing_options, "Draw GetSupport Direction", mBodyDrawSettings.mDrawSupportDirection, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawSupportDirection = inState == UICheckBox::STATE_CHECKED; mBodyDrawSettings.mDrawGetSupportFunction |= mBodyDrawSettings.mDrawSupportDirection; });
  346. mDebugUI->CreateCheckBox(drawing_options, "Draw GetSupportingFace (Shift+F)", mBodyDrawSettings.mDrawGetSupportingFace, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawGetSupportingFace = inState == UICheckBox::STATE_CHECKED; });
  347. mDebugUI->CreateCheckBox(drawing_options, "Draw Constraints (C)", mDrawConstraints, [this](UICheckBox::EState inState) { mDrawConstraints = inState == UICheckBox::STATE_CHECKED; });
  348. mDebugUI->CreateCheckBox(drawing_options, "Draw Constraint Limits (L)", mDrawConstraintLimits, [this](UICheckBox::EState inState) { mDrawConstraintLimits = inState == UICheckBox::STATE_CHECKED; });
  349. mDebugUI->CreateCheckBox(drawing_options, "Draw Constraint Reference Frame", mDrawConstraintReferenceFrame, [this](UICheckBox::EState inState) { mDrawConstraintReferenceFrame = inState == UICheckBox::STATE_CHECKED; });
  350. mDebugUI->CreateCheckBox(drawing_options, "Draw Contact Point (1)", ContactConstraintManager::sDrawContactPoint, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawContactPoint = inState == UICheckBox::STATE_CHECKED; });
  351. mDebugUI->CreateCheckBox(drawing_options, "Draw Supporting Faces (2)", ContactConstraintManager::sDrawSupportingFaces, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawSupportingFaces = inState == UICheckBox::STATE_CHECKED; });
  352. mDebugUI->CreateCheckBox(drawing_options, "Draw Contact Point Reduction (3)", ContactConstraintManager::sDrawContactPointReduction, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawContactPointReduction = inState == UICheckBox::STATE_CHECKED; });
  353. mDebugUI->CreateCheckBox(drawing_options, "Draw Contact Manifolds (M)", ContactConstraintManager::sDrawContactManifolds, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawContactManifolds = inState == UICheckBox::STATE_CHECKED; });
  354. mDebugUI->CreateCheckBox(drawing_options, "Draw Motion Quality Linear Cast", PhysicsSystem::sDrawMotionQualityLinearCast, [](UICheckBox::EState inState) { PhysicsSystem::sDrawMotionQualityLinearCast = inState == UICheckBox::STATE_CHECKED; });
  355. mDebugUI->CreateCheckBox(drawing_options, "Draw Bounding Boxes", mBodyDrawSettings.mDrawBoundingBox, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawBoundingBox = inState == UICheckBox::STATE_CHECKED; });
  356. mDebugUI->CreateCheckBox(drawing_options, "Draw Center of Mass Transforms", mBodyDrawSettings.mDrawCenterOfMassTransform, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawCenterOfMassTransform = inState == UICheckBox::STATE_CHECKED; });
  357. mDebugUI->CreateCheckBox(drawing_options, "Draw World Transforms", mBodyDrawSettings.mDrawWorldTransform, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawWorldTransform = inState == UICheckBox::STATE_CHECKED; });
  358. mDebugUI->CreateCheckBox(drawing_options, "Draw Velocity", mBodyDrawSettings.mDrawVelocity, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawVelocity = inState == UICheckBox::STATE_CHECKED; });
  359. mDebugUI->CreateCheckBox(drawing_options, "Draw Sleep Stats", mBodyDrawSettings.mDrawSleepStats, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawSleepStats = inState == UICheckBox::STATE_CHECKED; });
  360. mDebugUI->CreateCheckBox(drawing_options, "Draw Mass and Inertia (I)", mBodyDrawSettings.mDrawMassAndInertia, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawMassAndInertia = inState == UICheckBox::STATE_CHECKED; });
  361. mDebugUI->CreateCheckBox(drawing_options, "Draw Joints", mPoseDrawSettings.mDrawJoints, [this](UICheckBox::EState inState) { mPoseDrawSettings.mDrawJoints = inState == UICheckBox::STATE_CHECKED; });
  362. mDebugUI->CreateCheckBox(drawing_options, "Draw Joint Orientations", mPoseDrawSettings.mDrawJointOrientations, [this](UICheckBox::EState inState) { mPoseDrawSettings.mDrawJointOrientations = inState == UICheckBox::STATE_CHECKED; });
  363. mDebugUI->CreateCheckBox(drawing_options, "Draw Joint Names", mPoseDrawSettings.mDrawJointNames, [this](UICheckBox::EState inState) { mPoseDrawSettings.mDrawJointNames = inState == UICheckBox::STATE_CHECKED; });
  364. mDebugUI->CreateCheckBox(drawing_options, "Draw Mesh Shape Triangle Groups", MeshShape::sDrawTriangleGroups, [](UICheckBox::EState inState) { MeshShape::sDrawTriangleGroups = inState == UICheckBox::STATE_CHECKED; });
  365. mDebugUI->CreateCheckBox(drawing_options, "Draw Mesh Shape Triangle Outlines", MeshShape::sDrawTriangleOutlines, [](UICheckBox::EState inState) { MeshShape::sDrawTriangleOutlines = inState == UICheckBox::STATE_CHECKED; });
  366. mDebugUI->CreateCheckBox(drawing_options, "Draw Height Field Shape Triangle Outlines", HeightFieldShape::sDrawTriangleOutlines, [](UICheckBox::EState inState) { HeightFieldShape::sDrawTriangleOutlines = inState == UICheckBox::STATE_CHECKED; });
  367. mDebugUI->CreateCheckBox(drawing_options, "Draw Submerged Volumes", Shape::sDrawSubmergedVolumes, [](UICheckBox::EState inState) { Shape::sDrawSubmergedVolumes = inState == UICheckBox::STATE_CHECKED; });
  368. mDebugUI->CreateCheckBox(drawing_options, "Draw Character Virtual Constraints", CharacterVirtual::sDrawConstraints, [](UICheckBox::EState inState) { CharacterVirtual::sDrawConstraints = inState == UICheckBox::STATE_CHECKED; });
  369. mDebugUI->ShowMenu(drawing_options);
  370. });
  371. #endif // JPH_DEBUG_RENDERER
  372. mDebugUI->CreateTextButton(main_menu, "Mouse Probe", [this]() {
  373. UIElement *probe_options = mDebugUI->CreateMenu();
  374. mDebugUI->CreateComboBox(probe_options, "Mode", { "Pick", "Ray", "RayCollector", "CollidePoint", "CollideShape", "CastShape", "TransfShape", "GetTriangles", "BP Ray", "BP Box", "BP Sphere", "BP Point", "BP OBox", "BP Cast Box" }, (int)mProbeMode, [this](int inItem) { mProbeMode = (EProbeMode)inItem; });
  375. mDebugUI->CreateComboBox(probe_options, "Shape", { "Sphere", "Box", "ConvexHull", "Capsule", "TaperedCapsule", "Cylinder", "Triangle", "StaticCompound", "StaticCompound2", "MutableCompound" }, (int)mProbeShape, [=](int inItem) { mProbeShape = (EProbeShape)inItem; });
  376. mDebugUI->CreateCheckBox(probe_options, "Scale Shape", mScaleShape, [this](UICheckBox::EState inState) { mScaleShape = inState == UICheckBox::STATE_CHECKED; });
  377. mDebugUI->CreateSlider(probe_options, "Scale X", mShapeScale.GetX(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShapeScale.SetX(inValue); });
  378. mDebugUI->CreateSlider(probe_options, "Scale Y", mShapeScale.GetY(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShapeScale.SetY(inValue); });
  379. mDebugUI->CreateSlider(probe_options, "Scale Z", mShapeScale.GetZ(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShapeScale.SetZ(inValue); });
  380. mDebugUI->CreateComboBox(probe_options, "Back Face Cull", { "On", "Off" }, (int)mBackFaceMode, [=](int inItem) { mBackFaceMode = (EBackFaceMode)inItem; });
  381. mDebugUI->CreateComboBox(probe_options, "Active Edge Mode", { "Only Active", "All" }, (int)mActiveEdgeMode, [=](int inItem) { mActiveEdgeMode = (EActiveEdgeMode)inItem; });
  382. mDebugUI->CreateComboBox(probe_options, "Collect Faces Mode", { "Collect Faces", "No Faces" }, (int)mCollectFacesMode, [=](int inItem) { mCollectFacesMode = (ECollectFacesMode)inItem; });
  383. mDebugUI->CreateSlider(probe_options, "Max Separation Distance", mMaxSeparationDistance, 0.0f, 5.0f, 0.1f, [this](float inValue) { mMaxSeparationDistance = inValue; });
  384. mDebugUI->CreateCheckBox(probe_options, "Treat Convex As Solid", mTreatConvexAsSolid, [this](UICheckBox::EState inState) { mTreatConvexAsSolid = inState == UICheckBox::STATE_CHECKED; });
  385. mDebugUI->CreateCheckBox(probe_options, "Return Deepest Point", mReturnDeepestPoint, [this](UICheckBox::EState inState) { mReturnDeepestPoint = inState == UICheckBox::STATE_CHECKED; });
  386. mDebugUI->CreateCheckBox(probe_options, "Shrunken Shape + Convex Radius", mUseShrunkenShapeAndConvexRadius, [this](UICheckBox::EState inState) { mUseShrunkenShapeAndConvexRadius = inState == UICheckBox::STATE_CHECKED; });
  387. mDebugUI->CreateSlider(probe_options, "Max Hits", float(mMaxHits), 0, 10, 1, [this](float inValue) { mMaxHits = (int)inValue; });
  388. mDebugUI->ShowMenu(probe_options);
  389. });
  390. mDebugUI->CreateTextButton(main_menu, "Shoot Object", [this]() {
  391. UIElement *shoot_options = mDebugUI->CreateMenu();
  392. mDebugUI->CreateTextButton(shoot_options, "Shoot Object (B)", [=]() { ShootObject(); });
  393. mDebugUI->CreateSlider(shoot_options, "Initial Velocity", mShootObjectVelocity, 0.0f, 500.0f, 10.0f, [this](float inValue) { mShootObjectVelocity = inValue; });
  394. mDebugUI->CreateComboBox(shoot_options, "Shape", { "Sphere", "ConvexHull", "Thin Bar" }, (int)mShootObjectShape, [=](int inItem) { mShootObjectShape = (EShootObjectShape)inItem; });
  395. mDebugUI->CreateComboBox(shoot_options, "Motion Quality", { "Discrete", "LinearCast" }, (int)mShootObjectMotionQuality, [=](int inItem) { mShootObjectMotionQuality = (EMotionQuality)inItem; });
  396. mDebugUI->CreateSlider(shoot_options, "Friction", mShootObjectFriction, 0.0f, 1.0f, 0.05f, [this](float inValue) { mShootObjectFriction = inValue; });
  397. mDebugUI->CreateSlider(shoot_options, "Restitution", mShootObjectRestitution, 0.0f, 1.0f, 0.05f, [this](float inValue) { mShootObjectRestitution = inValue; });
  398. mDebugUI->CreateCheckBox(shoot_options, "Scale Shape", mShootObjectScaleShape, [this](UICheckBox::EState inState) { mShootObjectScaleShape = inState == UICheckBox::STATE_CHECKED; });
  399. mDebugUI->CreateSlider(shoot_options, "Scale X", mShootObjectShapeScale.GetX(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShootObjectShapeScale.SetX(inValue); });
  400. mDebugUI->CreateSlider(shoot_options, "Scale Y", mShootObjectShapeScale.GetY(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShootObjectShapeScale.SetY(inValue); });
  401. mDebugUI->CreateSlider(shoot_options, "Scale Z", mShootObjectShapeScale.GetZ(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShootObjectShapeScale.SetZ(inValue); });
  402. mDebugUI->ShowMenu(shoot_options);
  403. });
  404. mDebugUI->CreateTextButton(main_menu, "Help", [this](){
  405. UIElement *help = mDebugUI->CreateMenu();
  406. mDebugUI->CreateStaticText(help,
  407. "ESC: Back to previous menu.\n"
  408. "WASD + Mouse: Fly around. Hold Shift to speed up, Ctrl to slow down.\n"
  409. "Space: Hold to pick up and drag a physics object under the crosshair.\n"
  410. "P: Pause / unpause simulation.\n"
  411. "O: Single step the simulation.\n"
  412. ",: Step back (only when Physics Settings / Record State for Playback is on).\n"
  413. ".: Step forward (only when Physics Settings / Record State for Playback is on).\n"
  414. "Shift + ,: Play reverse (only when Physics Settings / Record State for Playback is on).\n"
  415. "Shift + .: Replay forward (only when Physics Settings / Record State for Playback is on).\n"
  416. "T: Dump frame timing information to profile_*.html (when JPH_PROFILE_ENABLED defined)."
  417. );
  418. mDebugUI->ShowMenu(help);
  419. });
  420. mDebugUI->ShowMenu(main_menu);
  421. // Get test name from commandline
  422. string cmd_line = ToLower(GetCommandLineA());
  423. vector<string> args;
  424. StringToVector(cmd_line, args, " ");
  425. if (args.size() == 2)
  426. {
  427. string cmd = args[1];
  428. if (cmd == "alltests")
  429. {
  430. // Run all tests
  431. mCheckDeterminism = true;
  432. mExitAfterRunningTests = true;
  433. RunAllTests();
  434. }
  435. else
  436. {
  437. // Search for the test
  438. const RTTI *test = JPH_RTTI(LoadRigTest);
  439. for (TestCategory &c : sAllCategories)
  440. for (uint i = 0; i < c.mNumTests; ++i)
  441. {
  442. TestNameAndRTTI &t = c.mTests[i];
  443. string test_name = ToLower(t.mRTTI->GetName());
  444. if (test_name == cmd)
  445. {
  446. test = t.mRTTI;
  447. break;
  448. }
  449. }
  450. // Construct test
  451. StartTest(test);
  452. }
  453. }
  454. }
  455. SamplesApp::~SamplesApp()
  456. {
  457. // Clean up
  458. delete mTest;
  459. delete mContactListener;
  460. delete mPhysicsSystem;
  461. delete mJobSystemValidating;
  462. delete mJobSystem;
  463. delete mTempAllocator;
  464. }
  465. void SamplesApp::StartTest(const RTTI *inRTTI)
  466. {
  467. // Pop active menus, we might be in the settings menu for the test which will be dangling after restarting the test
  468. mDebugUI->BackToMain();
  469. // Store old gravity
  470. Vec3 old_gravity = mPhysicsSystem != nullptr? mPhysicsSystem->GetGravity() : Vec3(0, -9.81f, 0);
  471. // Discard old test
  472. delete mTest;
  473. delete mContactListener;
  474. delete mPhysicsSystem;
  475. // Create physics system
  476. mPhysicsSystem = new PhysicsSystem();
  477. mPhysicsSystem->Init(cNumBodies, cNumBodyMutexes, cMaxBodyPairs, cMaxContactConstraints, mBroadPhaseLayerInterface, BroadPhaseCanCollide, ObjectCanCollide);
  478. mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings);
  479. // Restore gravity
  480. mPhysicsSystem->SetGravity(old_gravity);
  481. // Reset dragging
  482. mDragAnchor = nullptr;
  483. mDragConstraint = nullptr;
  484. // Reset playback state
  485. mPlaybackFrames.clear();
  486. mPlaybackMode = EPlaybackMode::Play;
  487. mCurrentPlaybackFrame = -1;
  488. // Set new test
  489. mTestClass = inRTTI;
  490. mTest = static_cast<Test *>(inRTTI->CreateObject());
  491. mTest->SetPhysicsSystem(mPhysicsSystem);
  492. mTest->SetJobSystem(mJobSystem);
  493. mTest->SetDebugRenderer(mDebugRenderer);
  494. mTest->SetTempAllocator(mTempAllocator);
  495. if (mInstallContactListener)
  496. {
  497. mContactListener = new ContactListenerImpl;
  498. mContactListener->SetNextListener(mTest->GetContactListener());
  499. mPhysicsSystem->SetContactListener(mContactListener);
  500. }
  501. else
  502. {
  503. mContactListener = nullptr;
  504. mPhysicsSystem->SetContactListener(mTest->GetContactListener());
  505. }
  506. mTest->Initialize();
  507. // Optimize the broadphase to make the first update fast
  508. mPhysicsSystem->OptimizeBroadPhase();
  509. // Reset the camera to the original position
  510. ResetCamera();
  511. // Start paused
  512. Pause(true);
  513. SingleStep();
  514. // Check if test has settings menu
  515. mTestSettingsButton->SetDisabled(!mTest->HasSettingsMenu());
  516. }
  517. void SamplesApp::RunAllTests()
  518. {
  519. mTestsToRun.clear();
  520. for (const TestCategory &c : sAllCategories)
  521. for (uint i = 0; i < c.mNumTests; ++i)
  522. {
  523. TestNameAndRTTI &t = c.mTests[i];
  524. mTestsToRun.push_back(t.mRTTI);
  525. }
  526. NextTest();
  527. }
  528. bool SamplesApp::NextTest()
  529. {
  530. if (mTestsToRun.empty())
  531. {
  532. if (mExitAfterRunningTests)
  533. return false; // Exit the application now
  534. else
  535. MessageBoxA(nullptr, "Test run complete!", "Complete", MB_OK);
  536. }
  537. else
  538. {
  539. // Start the timer for 10 seconds
  540. mTestTimeLeft = 10.0f;
  541. // Take next test
  542. const RTTI *rtti = mTestsToRun.front();
  543. mTestsToRun.erase(mTestsToRun.begin());
  544. // Start it
  545. StartTest(rtti);
  546. // Unpause
  547. Pause(false);
  548. }
  549. mNextTestButton->SetDisabled(mTestsToRun.empty());
  550. return true;
  551. }
  552. bool SamplesApp::CheckNextTest()
  553. {
  554. if (mTestTimeLeft >= 0.0f)
  555. {
  556. // Update status string
  557. mStatusString = StringFormat("%s: Next test in %.1fs", mTestClass->GetName(), (double)mTestTimeLeft);
  558. // Use physics time
  559. mTestTimeLeft -= 1.0f / mUpdateFrequency;
  560. // If time's up then go to the next test
  561. if (mTestTimeLeft < 0.0f)
  562. return NextTest();
  563. }
  564. else
  565. mStatusString.clear();
  566. return true;
  567. }
  568. RefConst<Shape> SamplesApp::CreateProbeShape()
  569. {
  570. // Get the scale
  571. Vec3 scale = mScaleShape? mShapeScale : Vec3::sReplicate(1.0f);
  572. // Make it minimally -0.1 or 0.1 depending on the sign
  573. Vec3 clamped_value = Vec3::sSelect(Vec3::sReplicate(-0.1f), Vec3::sReplicate(0.1f), Vec3::sGreaterOrEqual(scale, Vec3::sZero()));
  574. scale = Vec3::sSelect(scale, clamped_value, Vec3::sLess(scale.Abs(), Vec3::sReplicate(0.1f)));
  575. RefConst<Shape> shape;
  576. switch (mProbeShape)
  577. {
  578. case EProbeShape::Sphere:
  579. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  580. shape = new SphereShape(0.2f);
  581. break;
  582. case EProbeShape::Box:
  583. shape = new BoxShape(Vec3(0.1f, 0.2f, 0.3f));
  584. break;
  585. case EProbeShape::ConvexHull:
  586. {
  587. // Create tetrahedron
  588. vector<Vec3> tetrahedron;
  589. tetrahedron.push_back(Vec3::sZero());
  590. tetrahedron.push_back(Vec3(0.2f, 0, 0.4f));
  591. tetrahedron.push_back(Vec3(0.4f, 0, 0));
  592. tetrahedron.push_back(Vec3(0.2f, -0.2f, 1.0f));
  593. shape = ConvexHullShapeSettings(tetrahedron, 0.01f).Create().Get();
  594. }
  595. break;
  596. case EProbeShape::Capsule:
  597. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  598. shape = new CapsuleShape(0.2f, 0.1f);
  599. break;
  600. case EProbeShape::TaperedCapsule:
  601. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  602. shape = TaperedCapsuleShapeSettings(0.2f, 0.1f, 0.2f).Create().Get();
  603. break;
  604. case EProbeShape::Cylinder:
  605. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X>(); // Scale X must be same as Z
  606. shape = new CylinderShape(0.2f, 0.1f);
  607. break;
  608. case EProbeShape::Triangle:
  609. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  610. shape = new TriangleShape(Vec3(0.1f, 0.9f, 0.3f), Vec3(-0.9f, -0.5f, 0.2f), Vec3(0.7f, -0.3f, -0.1f));
  611. break;
  612. case EProbeShape::StaticCompound:
  613. {
  614. vector<Vec3> tetrahedron;
  615. tetrahedron.push_back(Vec3::sZero());
  616. tetrahedron.push_back(Vec3(-0.2f, 0, 0.4f));
  617. tetrahedron.push_back(Vec3(0, 0.2f, 0));
  618. tetrahedron.push_back(Vec3(0.2f, 0, 0.4f));
  619. RefConst<Shape> convex = ConvexHullShapeSettings(tetrahedron, 0.01f).Create().Get();
  620. StaticCompoundShapeSettings compound_settings;
  621. compound_settings.AddShape(Vec3(-0.5f, 0, 0), Quat::sIdentity(), convex);
  622. compound_settings.AddShape(Vec3(0.5f, 0, 0), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), convex);
  623. shape = compound_settings.Create().Get();
  624. }
  625. break;
  626. case EProbeShape::StaticCompound2:
  627. {
  628. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  629. Ref<StaticCompoundShapeSettings> compound = new StaticCompoundShapeSettings();
  630. compound->AddShape(Vec3(0, 0.5f, 0), Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI), new BoxShape(Vec3(0.5f, 0.15f, 0.1f)));
  631. compound->AddShape(Vec3(0.5f, 0, 0), Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI), new CylinderShape(0.5f, 0.1f));
  632. compound->AddShape(Vec3(0, 0, 0.5f), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), new TaperedCapsuleShapeSettings(0.5f, 0.15f, 0.1f));
  633. StaticCompoundShapeSettings compound2;
  634. compound2.AddShape(Vec3(0, 0, 0), Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI) * Quat::sRotation(Vec3::sAxisZ(), 0.25f * JPH_PI), compound);
  635. compound2.AddShape(Vec3(0, -0.4f, 0), Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI) * Quat::sRotation(Vec3::sAxisZ(), -0.75f * JPH_PI), compound);
  636. shape = compound2.Create().Get();
  637. }
  638. break;
  639. case EProbeShape::MutableCompound:
  640. {
  641. vector<Vec3> tetrahedron;
  642. tetrahedron.push_back(Vec3::sZero());
  643. tetrahedron.push_back(Vec3(-0.2f, 0, 0.4f));
  644. tetrahedron.push_back(Vec3(0, 0.2f, 0));
  645. tetrahedron.push_back(Vec3(0.2f, 0, 0.4f));
  646. RefConst<Shape> convex = ConvexHullShapeSettings(tetrahedron, 0.01f).Create().Get();
  647. MutableCompoundShapeSettings compound_settings;
  648. compound_settings.AddShape(Vec3(-0.5f, 0, 0), Quat::sIdentity(), convex);
  649. compound_settings.AddShape(Vec3(0.5f, 0, 0), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), convex);
  650. shape = compound_settings.Create().Get();
  651. }
  652. break;
  653. }
  654. JPH_ASSERT(shape != nullptr);
  655. // Scale the shape
  656. if (scale != Vec3::sReplicate(1.0f))
  657. shape = new ScaledShape(shape, scale);
  658. return shape;
  659. }
  660. RefConst<Shape> SamplesApp::CreateShootObjectShape()
  661. {
  662. // Get the scale
  663. Vec3 scale = mShootObjectScaleShape? mShootObjectShapeScale : Vec3::sReplicate(1.0f);
  664. // Make it minimally -0.1 or 0.1 depending on the sign
  665. Vec3 clamped_value = Vec3::sSelect(Vec3::sReplicate(-0.1f), Vec3::sReplicate(0.1f), Vec3::sGreaterOrEqual(scale, Vec3::sZero()));
  666. scale = Vec3::sSelect(scale, clamped_value, Vec3::sLess(scale.Abs(), Vec3::sReplicate(0.1f)));
  667. RefConst<Shape> shape;
  668. switch (mShootObjectShape)
  669. {
  670. case EShootObjectShape::Sphere:
  671. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  672. shape = new SphereShape(GetWorldScale());
  673. break;
  674. case EShootObjectShape::ConvexHull:
  675. {
  676. vector<Vec3> vertices = {
  677. Vec3(-0.044661f, 0.001230f, 0.003877f),
  678. Vec3(-0.024743f, -0.042562f, 0.003877f),
  679. Vec3(-0.012336f, -0.021073f, 0.048484f),
  680. Vec3(0.016066f, 0.028121f, -0.049904f),
  681. Vec3(-0.023734f, 0.043275f, -0.024153f),
  682. Vec3(0.020812f, 0.036341f, -0.019530f),
  683. Vec3(0.012495f, 0.021936f, 0.045288f),
  684. Vec3(0.026750f, 0.001230f, 0.049273f),
  685. Vec3(0.045495f, 0.001230f, -0.022077f),
  686. Vec3(0.022193f, -0.036274f, -0.021126f),
  687. Vec3(0.022781f, -0.037291f, 0.029558f),
  688. Vec3(0.014691f, -0.023280f, 0.052897f),
  689. Vec3(-0.012187f, -0.020815f, -0.040214f),
  690. Vec3(0.000541f, 0.001230f, -0.056224f),
  691. Vec3(-0.039882f, 0.001230f, -0.019461f),
  692. Vec3(0.000541f, 0.001230f, 0.056022f),
  693. Vec3(-0.020614f, -0.035411f, -0.020551f),
  694. Vec3(-0.019485f, 0.035916f, 0.027001f),
  695. Vec3(-0.023968f, 0.043680f, 0.003877f),
  696. Vec3(-0.020051f, 0.001230f, 0.039543f),
  697. Vec3(0.026213f, 0.001230f, -0.040589f),
  698. Vec3(-0.010797f, 0.020868f, 0.043152f),
  699. Vec3(-0.012378f, 0.023607f, -0.040876f)
  700. };
  701. // This shape was created at 0.2 world scale, rescale it to the current world scale
  702. float vert_scale = GetWorldScale() / 0.2f;
  703. for (Vec3 &v : vertices)
  704. v *= vert_scale;
  705. shape = ConvexHullShapeSettings(vertices).Create().Get();
  706. }
  707. break;
  708. case EShootObjectShape::ThinBar:
  709. shape = BoxShapeSettings(Vec3(0.05f, 0.8f, 0.03f), 0.015f).Create().Get();
  710. break;
  711. }
  712. // Scale shape if needed
  713. if (scale != Vec3::sReplicate(1.0f))
  714. shape = new ScaledShape(shape, scale);
  715. return shape;
  716. }
  717. void SamplesApp::ShootObject()
  718. {
  719. // Configure body
  720. BodyCreationSettings creation_settings(CreateShootObjectShape(), GetCamera().mPos, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  721. creation_settings.mMotionQuality = mShootObjectMotionQuality;
  722. creation_settings.mFriction = mShootObjectFriction;
  723. creation_settings.mRestitution = mShootObjectRestitution;
  724. // Create body
  725. BodyInterface &body_interface = mPhysicsSystem->GetBodyInterface();
  726. Body &body = *body_interface.CreateBody(creation_settings);
  727. body.SetLinearVelocity(mShootObjectVelocity * GetCamera().mForward);
  728. body_interface.AddBody(body.GetID(), EActivation::Activate);
  729. }
  730. bool SamplesApp::CastProbe(float inProbeLength, float &outFraction, Vec3 &outPosition, BodyID &outID)
  731. {
  732. const CameraState &camera = GetCamera();
  733. Vec3 start = camera.mPos;
  734. Vec3 direction = inProbeLength * camera.mForward;
  735. // Clear output
  736. outPosition = start + direction;
  737. outFraction = 1.0f;
  738. outID = BodyID();
  739. bool had_hit = false;
  740. switch (mProbeMode)
  741. {
  742. case EProbeMode::Pick:
  743. {
  744. // Create ray
  745. RayCast ray { start, direction };
  746. // Cast ray
  747. RayCastResult hit;
  748. had_hit = mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, hit, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::MOVING), SpecifiedObjectLayerFilter(Layers::MOVING));
  749. // Fill in results
  750. outPosition = start + hit.mFraction * direction;
  751. outFraction = hit.mFraction;
  752. outID = hit.mBodyID;
  753. if (had_hit)
  754. mDebugRenderer->DrawMarker(outPosition, Color::sYellow, 0.1f);
  755. else
  756. mDebugRenderer->DrawMarker(camera.mPos + 0.1f * camera.mForward, Color::sRed, 0.001f);
  757. }
  758. break;
  759. case EProbeMode::Ray:
  760. {
  761. // Create ray
  762. RayCast ray { start, direction };
  763. // Cast ray
  764. RayCastResult hit;
  765. had_hit = mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, hit);
  766. // Fill in results
  767. outPosition = ray.GetPointOnRay(hit.mFraction);
  768. outFraction = hit.mFraction;
  769. outID = hit.mBodyID;
  770. // Draw results
  771. if (had_hit)
  772. {
  773. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  774. if (lock.Succeeded())
  775. {
  776. const Body &hit_body = lock.GetBody();
  777. // Draw hit
  778. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  779. mDebugRenderer->DrawLine(start, outPosition, color);
  780. mDebugRenderer->DrawLine(outPosition, start + direction, Color::sRed);
  781. // Draw material
  782. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  783. mDebugRenderer->DrawText3D(outPosition, material2->GetDebugName());
  784. // Draw normal
  785. Vec3 normal = hit_body.GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, outPosition);
  786. mDebugRenderer->DrawArrow(outPosition, outPosition + normal, color, 0.01f);
  787. // Draw perpendicular axis to indicate hit position
  788. Vec3 perp1 = normal.GetNormalizedPerpendicular();
  789. Vec3 perp2 = normal.Cross(perp1);
  790. mDebugRenderer->DrawLine(outPosition - 0.1f * perp1, outPosition + 0.1f * perp1, color);
  791. mDebugRenderer->DrawLine(outPosition - 0.1f * perp2, outPosition + 0.1f * perp2, color);
  792. }
  793. }
  794. else
  795. {
  796. mDebugRenderer->DrawMarker(outPosition, Color::sRed, 0.1f);
  797. }
  798. }
  799. break;
  800. case EProbeMode::RayCollector:
  801. {
  802. // Create ray
  803. RayCast ray { start, direction };
  804. // Create settings
  805. RayCastSettings settings;
  806. settings.mBackFaceMode = mBackFaceMode;
  807. settings.mTreatConvexAsSolid = mTreatConvexAsSolid;
  808. // Cast ray
  809. vector<RayCastResult> hits;
  810. if (mMaxHits == 0)
  811. {
  812. AnyHitCollisionCollector<CastRayCollector> collector;
  813. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, settings, collector);
  814. if (collector.HadHit())
  815. hits.push_back(collector.mHit);
  816. }
  817. else if (mMaxHits == 1)
  818. {
  819. ClosestHitCollisionCollector<CastRayCollector> collector;
  820. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, settings, collector);
  821. if (collector.HadHit())
  822. hits.push_back(collector.mHit);
  823. }
  824. else
  825. {
  826. AllHitCollisionCollector<CastRayCollector> collector;
  827. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, settings, collector);
  828. collector.Sort();
  829. hits.insert(hits.end(), collector.mHits.begin(), collector.mHits.end());
  830. if ((int)hits.size() > mMaxHits)
  831. hits.resize(mMaxHits);
  832. }
  833. had_hit = !hits.empty();
  834. if (had_hit)
  835. {
  836. // Fill in results
  837. RayCastResult &first_hit = hits.front();
  838. outPosition = start + first_hit.mFraction * direction;
  839. outFraction = first_hit.mFraction;
  840. outID = first_hit.mBodyID;
  841. // Draw results
  842. Vec3 prev_position = start;
  843. bool c = false;
  844. for (const RayCastResult &hit : hits)
  845. {
  846. // Draw line
  847. Vec3 position = ray.GetPointOnRay(hit.mFraction);
  848. mDebugRenderer->DrawLine(prev_position, position, c? Color::sGrey : Color::sWhite);
  849. c = !c;
  850. prev_position = position;
  851. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  852. if (lock.Succeeded())
  853. {
  854. const Body &hit_body = lock.GetBody();
  855. // Draw material
  856. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  857. mDebugRenderer->DrawText3D(position, material2->GetDebugName());
  858. // Draw normal
  859. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  860. Vec3 normal = hit_body.GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, position);
  861. mDebugRenderer->DrawArrow(position, position + normal, color, 0.01f);
  862. // Draw perpendicular axis to indicate hit position
  863. Vec3 perp1 = normal.GetNormalizedPerpendicular();
  864. Vec3 perp2 = normal.Cross(perp1);
  865. mDebugRenderer->DrawLine(position - 0.1f * perp1, position + 0.1f * perp1, color);
  866. mDebugRenderer->DrawLine(position - 0.1f * perp2, position + 0.1f * perp2, color);
  867. }
  868. }
  869. // Draw remainder of line
  870. mDebugRenderer->DrawLine(start + hits.back().mFraction * direction, start + direction, Color::sRed);
  871. }
  872. else
  873. {
  874. // Draw 'miss'
  875. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  876. mDebugRenderer->DrawMarker(start + direction, Color::sRed, 0.1f);
  877. }
  878. }
  879. break;
  880. case EProbeMode::CollidePoint:
  881. {
  882. // Create point
  883. const float fraction = 0.1f;
  884. Vec3 point = start + fraction * direction;
  885. // Collide point
  886. AllHitCollisionCollector<CollidePointCollector> collector;
  887. mPhysicsSystem->GetNarrowPhaseQuery().CollidePoint(point, collector);
  888. had_hit = !collector.mHits.empty();
  889. if (had_hit)
  890. {
  891. // Draw results
  892. for (const CollidePointResult &hit : collector.mHits)
  893. {
  894. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  895. if (lock.Succeeded())
  896. {
  897. const Body &hit_body = lock.GetBody();
  898. // Draw bounding box
  899. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  900. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  901. }
  902. }
  903. }
  904. // Draw test location
  905. mDebugRenderer->DrawMarker(start + fraction * direction, had_hit? Color::sGreen : Color::sRed, 0.1f);
  906. }
  907. break;
  908. case EProbeMode::CollideShape:
  909. {
  910. // Create shape cast
  911. RefConst<Shape> shape = CreateProbeShape();
  912. Mat44 rotation = Mat44::sRotation(Vec3::sAxisX(), 0.1f * JPH_PI) * Mat44::sRotation(Vec3::sAxisY(), 0.2f * JPH_PI);
  913. Mat44 com = Mat44::sTranslation(shape->GetCenterOfMass());
  914. Mat44 shape_transform = Mat44::sTranslation(start + 5.0f * camera.mForward) * rotation * com;
  915. // Create settings
  916. CollideShapeSettings settings;
  917. settings.mActiveEdgeMode = mActiveEdgeMode;
  918. settings.mBackFaceMode = mBackFaceMode;
  919. settings.mCollectFacesMode = mCollectFacesMode;
  920. settings.mMaxSeparationDistance = mMaxSeparationDistance;
  921. vector<CollideShapeResult> hits;
  922. if (mMaxHits == 0)
  923. {
  924. AnyHitCollisionCollector<CollideShapeCollector> collector;
  925. mPhysicsSystem->GetNarrowPhaseQuery().CollideShape(shape, Vec3::sReplicate(1.0f), shape_transform, settings, collector);
  926. if (collector.HadHit())
  927. hits.push_back(collector.mHit);
  928. }
  929. else if (mMaxHits == 1)
  930. {
  931. ClosestHitCollisionCollector<CollideShapeCollector> collector;
  932. mPhysicsSystem->GetNarrowPhaseQuery().CollideShape(shape, Vec3::sReplicate(1.0f), shape_transform, settings, collector);
  933. if (collector.HadHit())
  934. hits.push_back(collector.mHit);
  935. }
  936. else
  937. {
  938. AllHitCollisionCollector<CollideShapeCollector> collector;
  939. mPhysicsSystem->GetNarrowPhaseQuery().CollideShape(shape, Vec3::sReplicate(1.0f), shape_transform, settings, collector);
  940. collector.Sort();
  941. hits.insert(hits.end(), collector.mHits.begin(), collector.mHits.end());
  942. if ((int)hits.size() > mMaxHits)
  943. hits.resize(mMaxHits);
  944. }
  945. had_hit = !hits.empty();
  946. if (had_hit)
  947. {
  948. // Draw results
  949. for (const CollideShapeResult &hit : hits)
  950. {
  951. // Draw 'hit'
  952. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID2);
  953. if (lock.Succeeded())
  954. {
  955. const Body &hit_body = lock.GetBody();
  956. // Draw contact
  957. mDebugRenderer->DrawMarker(hit.mContactPointOn1, Color::sGreen, 0.1f);
  958. mDebugRenderer->DrawMarker(hit.mContactPointOn2, Color::sRed, 0.1f);
  959. Vec3 pen_axis = hit.mPenetrationAxis;
  960. float pen_axis_len = pen_axis.Length();
  961. if (pen_axis_len > 0.0f)
  962. {
  963. pen_axis /= pen_axis_len;
  964. // Draw penetration axis with length of the penetration
  965. mDebugRenderer->DrawArrow(hit.mContactPointOn2, hit.mContactPointOn2 + pen_axis * hit.mPenetrationDepth, Color::sYellow, 0.01f);
  966. // Draw normal (flipped so it points towards body 1)
  967. mDebugRenderer->DrawArrow(hit.mContactPointOn2, hit.mContactPointOn2 - pen_axis, Color::sOrange, 0.01f);
  968. }
  969. // Draw material
  970. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  971. mDebugRenderer->DrawText3D(hit.mContactPointOn2, material2->GetDebugName());
  972. // Draw faces
  973. mDebugRenderer->DrawWirePolygon(hit.mShape1Face, Color::sYellow, 0.01f);
  974. mDebugRenderer->DrawWirePolygon(hit.mShape2Face, Color::sRed, 0.01f);
  975. }
  976. }
  977. }
  978. #ifdef JPH_DEBUG_RENDERER
  979. // Draw shape
  980. shape->Draw(mDebugRenderer, shape_transform, Vec3::sReplicate(1.0f), had_hit? Color::sGreen : Color::sGrey, false, false);
  981. #endif // JPH_DEBUG_RENDERER
  982. }
  983. break;
  984. case EProbeMode::CastShape:
  985. {
  986. // Create shape cast
  987. RefConst<Shape> shape = CreateProbeShape();
  988. Mat44 rotation = Mat44::sRotation(Vec3::sAxisX(), 0.1f * JPH_PI) * Mat44::sRotation(Vec3::sAxisY(), 0.2f * JPH_PI);
  989. ShapeCast shape_cast = ShapeCast::sFromWorldTransform(shape, Vec3::sReplicate(1.0f), Mat44::sTranslation(start) * rotation, direction);
  990. // Settings
  991. ShapeCastSettings settings;
  992. settings.mUseShrunkenShapeAndConvexRadius = mUseShrunkenShapeAndConvexRadius;
  993. settings.mActiveEdgeMode = mActiveEdgeMode;
  994. settings.mBackFaceModeTriangles = mBackFaceMode;
  995. settings.mBackFaceModeConvex = mBackFaceMode;
  996. settings.mReturnDeepestPoint = mReturnDeepestPoint;
  997. settings.mCollectFacesMode = mCollectFacesMode;
  998. // Cast shape
  999. vector<ShapeCastResult> hits;
  1000. if (mMaxHits == 0)
  1001. {
  1002. AnyHitCollisionCollector<CastShapeCollector> collector;
  1003. mPhysicsSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, collector);
  1004. if (collector.HadHit())
  1005. hits.push_back(collector.mHit);
  1006. }
  1007. else if (mMaxHits == 1)
  1008. {
  1009. ClosestHitCollisionCollector<CastShapeCollector> collector;
  1010. mPhysicsSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, collector);
  1011. if (collector.HadHit())
  1012. hits.push_back(collector.mHit);
  1013. }
  1014. else
  1015. {
  1016. AllHitCollisionCollector<CastShapeCollector> collector;
  1017. mPhysicsSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, collector);
  1018. collector.Sort();
  1019. hits.insert(hits.end(), collector.mHits.begin(), collector.mHits.end());
  1020. if ((int)hits.size() > mMaxHits)
  1021. hits.resize(mMaxHits);
  1022. }
  1023. had_hit = !hits.empty();
  1024. if (had_hit)
  1025. {
  1026. // Fill in results
  1027. ShapeCastResult &first_hit = hits.front();
  1028. outPosition = start + first_hit.mFraction * direction;
  1029. outFraction = first_hit.mFraction;
  1030. outID = first_hit.mBodyID2;
  1031. // Draw results
  1032. Vec3 prev_position = start;
  1033. bool c = false;
  1034. for (const ShapeCastResult &hit : hits)
  1035. {
  1036. // Draw line
  1037. Vec3 position = start + hit.mFraction * direction;
  1038. mDebugRenderer->DrawLine(prev_position, position, c? Color::sGrey : Color::sWhite);
  1039. c = !c;
  1040. prev_position = position;
  1041. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID2);
  1042. if (lock.Succeeded())
  1043. {
  1044. const Body &hit_body = lock.GetBody();
  1045. // Draw shape
  1046. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1047. #ifdef JPH_DEBUG_RENDERER
  1048. shape_cast.mShape->Draw(mDebugRenderer, shape_cast.mCenterOfMassStart.PostTranslated(hit.mFraction * shape_cast.mDirection), Vec3::sReplicate(1.0f), color, false, false);
  1049. #endif // JPH_DEBUG_RENDERER
  1050. // Draw normal
  1051. Vec3 contact_position1 = hit.mContactPointOn1;
  1052. Vec3 contact_position2 = hit.mContactPointOn2;
  1053. Vec3 normal = hit.mPenetrationAxis.Normalized();
  1054. mDebugRenderer->DrawArrow(contact_position2, contact_position2 - normal, color, 0.01f); // Flip to make it point towards the cast body
  1055. // Contact position 1
  1056. mDebugRenderer->DrawMarker(contact_position1, Color::sGreen, 0.1f);
  1057. // Draw perpendicular axis to indicate contact position 2
  1058. Vec3 perp1 = normal.GetNormalizedPerpendicular();
  1059. Vec3 perp2 = normal.Cross(perp1);
  1060. mDebugRenderer->DrawLine(contact_position2 - 0.1f * perp1, contact_position2 + 0.1f * perp1, color);
  1061. mDebugRenderer->DrawLine(contact_position2 - 0.1f * perp2, contact_position2 + 0.1f * perp2, color);
  1062. // Draw material
  1063. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  1064. mDebugRenderer->DrawText3D(position, material2->GetDebugName());
  1065. // Draw faces
  1066. mDebugRenderer->DrawWirePolygon(hit.mShape1Face, Color::sYellow, 0.01f);
  1067. mDebugRenderer->DrawWirePolygon(hit.mShape2Face, Color::sRed, 0.01f);
  1068. }
  1069. }
  1070. // Draw remainder of line
  1071. mDebugRenderer->DrawLine(start + hits.back().mFraction * direction, start + direction, Color::sRed);
  1072. }
  1073. else
  1074. {
  1075. // Draw 'miss'
  1076. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  1077. #ifdef JPH_DEBUG_RENDERER
  1078. shape_cast.mShape->Draw(mDebugRenderer, shape_cast.mCenterOfMassStart.PostTranslated(shape_cast.mDirection), Vec3::sReplicate(1.0f), Color::sRed, false, false);
  1079. #endif // JPH_DEBUG_RENDERER
  1080. }
  1081. }
  1082. break;
  1083. case EProbeMode::TransformedShape:
  1084. {
  1085. // Create box
  1086. const float fraction = 0.2f;
  1087. Vec3 center = start + fraction * direction;
  1088. Vec3 half_extent = 0.5f * mShapeScale;
  1089. AABox box(center - half_extent, center + half_extent);
  1090. // Get shapes
  1091. AllHitCollisionCollector<TransformedShapeCollector> collector;
  1092. mPhysicsSystem->GetNarrowPhaseQuery().CollectTransformedShapes(box, collector);
  1093. // Draw results
  1094. for (const TransformedShape &ts : collector.mHits)
  1095. mDebugRenderer->DrawWireBox(Mat44::sRotationTranslation(ts.mShapeRotation, ts.mShapePositionCOM) * Mat44::sScale(ts.GetShapeScale()), ts.mShape->GetLocalBounds(), Color::sYellow);
  1096. // Draw test location
  1097. mDebugRenderer->DrawWireBox(box, !collector.mHits.empty()? Color::sGreen : Color::sRed);
  1098. }
  1099. break;
  1100. case EProbeMode::GetTriangles:
  1101. {
  1102. // Create box
  1103. const float fraction = 0.2f;
  1104. Vec3 center = start + fraction * direction;
  1105. Vec3 half_extent = 2.0f * mShapeScale;
  1106. AABox box(center - half_extent, center + half_extent);
  1107. // Get shapes
  1108. AllHitCollisionCollector<TransformedShapeCollector> collector;
  1109. mPhysicsSystem->GetNarrowPhaseQuery().CollectTransformedShapes(box, collector);
  1110. // Loop over shapes
  1111. had_hit = false;
  1112. for (const TransformedShape &ts : collector.mHits)
  1113. {
  1114. const int cMaxTriangles = 32;
  1115. Float3 vertices[cMaxTriangles * 3];
  1116. const PhysicsMaterial *materials[cMaxTriangles];
  1117. // Start iterating triangles
  1118. Shape::GetTrianglesContext ctx;
  1119. ts.GetTrianglesStart(ctx, box);
  1120. for (;;)
  1121. {
  1122. // Fetch next triangles
  1123. int count = ts.GetTrianglesNext(ctx, cMaxTriangles, vertices, materials);
  1124. if (count == 0)
  1125. break;
  1126. // Draw triangles
  1127. const PhysicsMaterial **m = materials;
  1128. for (Float3 *v = vertices, *v_end = vertices + 3 * count; v < v_end; v += 3, ++m)
  1129. {
  1130. Vec3 v1(v[0]), v2(v[1]), v3(v[2]);
  1131. Vec3 triangle_center = (v1 + v2 + v3) / 3.0f;
  1132. Vec3 triangle_normal = (v2 - v1).Cross(v3 - v1).Normalized();
  1133. mDebugRenderer->DrawWireTriangle(v1, v2, v3, (*m)->GetDebugColor());
  1134. mDebugRenderer->DrawArrow(triangle_center, triangle_center + triangle_normal, Color::sGreen, 0.01f);
  1135. }
  1136. had_hit = true;
  1137. }
  1138. }
  1139. // Draw test location
  1140. mDebugRenderer->DrawWireBox(box, had_hit? Color::sGreen : Color::sRed);
  1141. }
  1142. break;
  1143. case EProbeMode::BroadPhaseRay:
  1144. {
  1145. // Create ray
  1146. RayCast ray { start, direction };
  1147. // Cast ray
  1148. AllHitCollisionCollector<RayCastBodyCollector> collector;
  1149. mPhysicsSystem->GetBroadPhaseQuery().CastRay(ray, collector);
  1150. collector.Sort();
  1151. had_hit = !collector.mHits.empty();
  1152. if (had_hit)
  1153. {
  1154. // Draw results
  1155. Vec3 prev_position = start;
  1156. bool c = false;
  1157. for (const BroadPhaseCastResult &hit : collector.mHits)
  1158. {
  1159. // Draw line
  1160. Vec3 position = start + hit.mFraction * direction;
  1161. Color cast_color = c? Color::sGrey : Color::sWhite;
  1162. mDebugRenderer->DrawLine(prev_position, position, cast_color);
  1163. mDebugRenderer->DrawMarker(position, cast_color, 0.1f);
  1164. c = !c;
  1165. prev_position = position;
  1166. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  1167. if (lock.Succeeded())
  1168. {
  1169. const Body &hit_body = lock.GetBody();
  1170. // Draw bounding box
  1171. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1172. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1173. }
  1174. }
  1175. // Draw remainder of line
  1176. mDebugRenderer->DrawLine(start + collector.mHits.back().mFraction * direction, start + direction, Color::sRed);
  1177. }
  1178. else
  1179. {
  1180. // Draw 'miss'
  1181. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  1182. mDebugRenderer->DrawMarker(start + direction, Color::sRed, 0.1f);
  1183. }
  1184. }
  1185. break;
  1186. case EProbeMode::BroadPhaseBox:
  1187. {
  1188. // Create box
  1189. const float fraction = 0.2f;
  1190. Vec3 center = start + fraction * direction;
  1191. Vec3 half_extent = 2.0f * mShapeScale;
  1192. AABox box(center - half_extent, center + half_extent);
  1193. // Collide box
  1194. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1195. mPhysicsSystem->GetBroadPhaseQuery().CollideAABox(box, collector);
  1196. had_hit = !collector.mHits.empty();
  1197. if (had_hit)
  1198. {
  1199. // Draw results
  1200. for (const BodyID &hit : collector.mHits)
  1201. {
  1202. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1203. if (lock.Succeeded())
  1204. {
  1205. const Body &hit_body = lock.GetBody();
  1206. // Draw bounding box
  1207. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1208. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1209. }
  1210. }
  1211. }
  1212. // Draw test location
  1213. mDebugRenderer->DrawWireBox(box, had_hit? Color::sGreen : Color::sRed);
  1214. }
  1215. break;
  1216. case EProbeMode::BroadPhaseSphere:
  1217. {
  1218. // Create sphere
  1219. const float fraction = 0.2f;
  1220. const float radius = mShapeScale.Length() * 2.0f;
  1221. Vec3 point = start + fraction * direction;
  1222. // Collide sphere
  1223. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1224. mPhysicsSystem->GetBroadPhaseQuery().CollideSphere(point, radius, collector);
  1225. had_hit = !collector.mHits.empty();
  1226. if (had_hit)
  1227. {
  1228. // Draw results
  1229. for (const BodyID &hit : collector.mHits)
  1230. {
  1231. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1232. if (lock.Succeeded())
  1233. {
  1234. const Body &hit_body = lock.GetBody();
  1235. // Draw bounding box
  1236. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1237. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1238. }
  1239. }
  1240. }
  1241. // Draw test location
  1242. mDebugRenderer->DrawWireSphere(start + fraction * direction, radius, had_hit? Color::sGreen : Color::sRed);
  1243. }
  1244. break;
  1245. case EProbeMode::BroadPhasePoint:
  1246. {
  1247. // Create point
  1248. const float fraction = 0.1f;
  1249. Vec3 point = start + fraction * direction;
  1250. // Collide point
  1251. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1252. mPhysicsSystem->GetBroadPhaseQuery().CollidePoint(point, collector);
  1253. had_hit = !collector.mHits.empty();
  1254. if (had_hit)
  1255. {
  1256. // Draw results
  1257. for (const BodyID &hit : collector.mHits)
  1258. {
  1259. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1260. if (lock.Succeeded())
  1261. {
  1262. const Body &hit_body = lock.GetBody();
  1263. // Draw bounding box
  1264. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1265. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1266. }
  1267. }
  1268. }
  1269. // Draw test location
  1270. mDebugRenderer->DrawMarker(start + fraction * direction, had_hit? Color::sGreen : Color::sRed, 0.1f);
  1271. }
  1272. break;
  1273. case EProbeMode::BroadPhaseOrientedBox:
  1274. {
  1275. // Create box
  1276. const float fraction = 0.2f;
  1277. Vec3 center = start + fraction * direction;
  1278. Vec3 half_extent = 2.0f * mShapeScale;
  1279. OrientedBox box(Mat44::sRotationTranslation(Quat::sRotation(Vec3::sAxisZ(), 0.2f * JPH_PI) * Quat::sRotation(Vec3::sAxisX(), 0.1f * JPH_PI), center), half_extent);
  1280. // Collide box
  1281. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1282. mPhysicsSystem->GetBroadPhaseQuery().CollideOrientedBox(box, collector);
  1283. had_hit = !collector.mHits.empty();
  1284. if (had_hit)
  1285. {
  1286. // Draw results
  1287. for (const BodyID &hit : collector.mHits)
  1288. {
  1289. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1290. if (lock.Succeeded())
  1291. {
  1292. const Body &hit_body = lock.GetBody();
  1293. // Draw bounding box
  1294. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1295. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1296. }
  1297. }
  1298. }
  1299. // Draw test location
  1300. mDebugRenderer->DrawWireBox(box, had_hit? Color::sGreen : Color::sRed);
  1301. }
  1302. break;
  1303. case EProbeMode::BroadPhaseCastBox:
  1304. {
  1305. // Create box
  1306. Vec3 half_extent = 2.0f * mShapeScale;
  1307. AABox box(start - half_extent, start + half_extent);
  1308. AABoxCast box_cast { box, direction };
  1309. // Cast box
  1310. AllHitCollisionCollector<CastShapeBodyCollector> collector;
  1311. mPhysicsSystem->GetBroadPhaseQuery().CastAABox(box_cast, collector);
  1312. collector.Sort();
  1313. had_hit = !collector.mHits.empty();
  1314. if (had_hit)
  1315. {
  1316. // Draw results
  1317. Vec3 prev_position = start;
  1318. bool c = false;
  1319. for (const BroadPhaseCastResult &hit : collector.mHits)
  1320. {
  1321. // Draw line
  1322. Vec3 position = start + hit.mFraction * direction;
  1323. Color cast_color = c? Color::sGrey : Color::sWhite;
  1324. mDebugRenderer->DrawLine(prev_position, position, cast_color);
  1325. mDebugRenderer->DrawWireBox(AABox(position - half_extent, position + half_extent), cast_color);
  1326. c = !c;
  1327. prev_position = position;
  1328. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  1329. if (lock.Succeeded())
  1330. {
  1331. const Body &hit_body = lock.GetBody();
  1332. // Draw bounding box
  1333. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1334. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1335. }
  1336. }
  1337. // Draw remainder of line
  1338. mDebugRenderer->DrawLine(start + collector.mHits.back().mFraction * direction, start + direction, Color::sRed);
  1339. }
  1340. else
  1341. {
  1342. // Draw 'miss'
  1343. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  1344. mDebugRenderer->DrawWireBox(AABox(start + direction - half_extent, start + direction + half_extent), Color::sRed);
  1345. }
  1346. }
  1347. break;
  1348. }
  1349. return had_hit;
  1350. }
  1351. void SamplesApp::UpdateDebug()
  1352. {
  1353. JPH_PROFILE_FUNCTION();
  1354. const float cDragRayLength = 40.0f;
  1355. BodyInterface &bi = mPhysicsSystem->GetBodyInterface();
  1356. // Handle keyboard input for which simulation needs to be running
  1357. for (int key = mKeyboard->GetFirstKey(); key != 0; key = mKeyboard->GetNextKey())
  1358. switch (key)
  1359. {
  1360. case DIK_B:
  1361. ShootObject();
  1362. break;
  1363. }
  1364. // Allow the user to drag rigid bodies around
  1365. if (mDragConstraint == nullptr)
  1366. {
  1367. // Not dragging yet
  1368. Vec3 hit_position;
  1369. float hit_fraction;
  1370. if (CastProbe(cDragRayLength, hit_fraction, hit_position, mDragBody))
  1371. {
  1372. // If key is pressed create constraint to start dragging
  1373. if (mKeyboard->IsKeyPressed(DIK_SPACE))
  1374. {
  1375. // Target body must be dynamic
  1376. BodyLockWrite lock(mPhysicsSystem->GetBodyLockInterface(), mDragBody);
  1377. if (lock.Succeeded())
  1378. {
  1379. Body &drag_body = lock.GetBody();
  1380. if (drag_body.IsDynamic())
  1381. {
  1382. // Create constraint to drag body
  1383. DistanceConstraintSettings settings;
  1384. settings.mPoint1 = settings.mPoint2 = hit_position;
  1385. settings.mFrequency = 2.0f / GetWorldScale();
  1386. settings.mDamping = 1.0f;
  1387. // Construct fixed body for the mouse constraint
  1388. // Note that we don't add it to the world since we don't want anything to collide with it, we just
  1389. // need an anchor for a constraint
  1390. Body *drag_anchor = bi.CreateBody(BodyCreationSettings(new SphereShape(0.01f), hit_position, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1391. #ifdef _DEBUG
  1392. drag_anchor->SetDebugName("DragAnchor");
  1393. #endif
  1394. mDragAnchor = drag_anchor;
  1395. // Construct constraint that connects the drag anchor with the body that we want to drag
  1396. mDragConstraint = settings.Create(*drag_anchor, drag_body);
  1397. mPhysicsSystem->AddConstraint(mDragConstraint);
  1398. mDragFraction = hit_fraction;
  1399. }
  1400. }
  1401. }
  1402. }
  1403. }
  1404. else
  1405. {
  1406. if (!mKeyboard->IsKeyPressed(DIK_SPACE))
  1407. {
  1408. // If key released, destroy constraint
  1409. if (mDragConstraint != nullptr)
  1410. mPhysicsSystem->RemoveConstraint(mDragConstraint);
  1411. mDragConstraint = nullptr;
  1412. // Destroy drag anchor
  1413. bi.DestroyBody(mDragAnchor->GetID());
  1414. mDragAnchor = nullptr;
  1415. // Forget the drag body
  1416. mDragBody = BodyID();
  1417. }
  1418. else
  1419. {
  1420. // Else update position of anchor
  1421. bi.SetPositionAndRotation(mDragAnchor->GetID(), GetCamera().mPos + cDragRayLength * mDragFraction * GetCamera().mForward, Quat::sIdentity(), EActivation::DontActivate);
  1422. // Activate other body
  1423. bi.ActivateBody(mDragBody);
  1424. }
  1425. }
  1426. }
  1427. bool SamplesApp::RenderFrame(float inDeltaTime)
  1428. {
  1429. // Reinitialize the job system if the concurrency setting changed
  1430. if (mMaxConcurrentJobs != mJobSystem->GetMaxConcurrency())
  1431. static_cast<JobSystemThreadPool *>(mJobSystem)->SetNumThreads(mMaxConcurrentJobs - 1);
  1432. // Restart the test if the test requests this
  1433. if (mTest->NeedsRestart())
  1434. {
  1435. StartTest(mTestClass);
  1436. return true;
  1437. }
  1438. // Select the next test if automatic testing times out
  1439. if (!CheckNextTest())
  1440. return false;
  1441. // Handle keyboard input
  1442. bool shift = mKeyboard->IsKeyPressed(DIK_LSHIFT) || mKeyboard->IsKeyPressed(DIK_RSHIFT);
  1443. #ifdef JPH_DEBUG_RENDERER
  1444. bool alt = mKeyboard->IsKeyPressed(DIK_LALT) || mKeyboard->IsKeyPressed(DIK_RALT);
  1445. #endif // JPH_DEBUG_RENDERER
  1446. for (int key = mKeyboard->GetFirstKey(); key != 0; key = mKeyboard->GetNextKey())
  1447. switch (key)
  1448. {
  1449. case DIK_R:
  1450. StartTest(mTestClass);
  1451. return true;
  1452. case DIK_N:
  1453. if (!mTestsToRun.empty())
  1454. NextTest();
  1455. break;
  1456. #ifdef JPH_DEBUG_RENDERER
  1457. case DIK_H:
  1458. if (shift)
  1459. mBodyDrawSettings.mDrawGetSupportFunction = !mBodyDrawSettings.mDrawGetSupportFunction;
  1460. else if (alt)
  1461. mDrawGetTriangles = !mDrawGetTriangles;
  1462. else
  1463. mBodyDrawSettings.mDrawShape = !mBodyDrawSettings.mDrawShape;
  1464. break;
  1465. case DIK_F:
  1466. if (shift)
  1467. mBodyDrawSettings.mDrawGetSupportingFace = !mBodyDrawSettings.mDrawGetSupportingFace;
  1468. break;
  1469. case DIK_I:
  1470. mBodyDrawSettings.mDrawMassAndInertia = !mBodyDrawSettings.mDrawMassAndInertia;
  1471. break;
  1472. case DIK_1:
  1473. ContactConstraintManager::sDrawContactPoint = !ContactConstraintManager::sDrawContactPoint;
  1474. break;
  1475. case DIK_2:
  1476. ContactConstraintManager::sDrawSupportingFaces = !ContactConstraintManager::sDrawSupportingFaces;
  1477. break;
  1478. case DIK_3:
  1479. ContactConstraintManager::sDrawContactPointReduction = !ContactConstraintManager::sDrawContactPointReduction;
  1480. break;
  1481. case DIK_C:
  1482. mDrawConstraints = !mDrawConstraints;
  1483. break;
  1484. case DIK_L:
  1485. mDrawConstraintLimits = !mDrawConstraintLimits;
  1486. break;
  1487. case DIK_M:
  1488. ContactConstraintManager::sDrawContactManifolds = !ContactConstraintManager::sDrawContactManifolds;
  1489. break;
  1490. case DIK_W:
  1491. if (alt)
  1492. mBodyDrawSettings.mDrawShapeWireframe = !mBodyDrawSettings.mDrawShapeWireframe;
  1493. break;
  1494. #endif // JPH_DEBUG_RENDERER
  1495. case DIK_COMMA:
  1496. // Back stepping
  1497. if (mPlaybackFrames.size() > 1)
  1498. {
  1499. if (mPlaybackMode == EPlaybackMode::Play)
  1500. {
  1501. JPH_ASSERT(mCurrentPlaybackFrame == -1);
  1502. mCurrentPlaybackFrame = (int)mPlaybackFrames.size() - 1;
  1503. }
  1504. mPlaybackMode = shift? EPlaybackMode::Rewind : EPlaybackMode::StepBack;
  1505. }
  1506. break;
  1507. case DIK_PERIOD:
  1508. // Forward stepping
  1509. if (mPlaybackMode != EPlaybackMode::Play)
  1510. {
  1511. JPH_ASSERT(mCurrentPlaybackFrame >= 0);
  1512. mPlaybackMode = shift? EPlaybackMode::FastForward : EPlaybackMode::StepForward;
  1513. }
  1514. break;
  1515. }
  1516. // Stop recording if record state is turned off
  1517. if (!mRecordState)
  1518. {
  1519. mPlaybackFrames.clear();
  1520. mPlaybackMode = EPlaybackMode::Play;
  1521. mCurrentPlaybackFrame = -1;
  1522. }
  1523. // Determine if we need to check deterministic simulation
  1524. bool check_determinism = mCheckDeterminism && mTest->IsDeterministic();
  1525. // Check if we've in replay mode
  1526. if (mPlaybackMode != EPlaybackMode::Play)
  1527. {
  1528. JPH_PROFILE("RestoreState");
  1529. // We're in replay mode
  1530. JPH_ASSERT(mCurrentPlaybackFrame >= 0);
  1531. // Ensure the simulation is paused
  1532. Pause(true);
  1533. // Always restore state when not paused, the debug drawing will be cleared
  1534. bool restore_state = inDeltaTime > 0.0f;
  1535. // Advance to the next frame when single stepping or unpausing
  1536. switch (mPlaybackMode)
  1537. {
  1538. case EPlaybackMode::StepBack:
  1539. mPlaybackMode = EPlaybackMode::Stop;
  1540. [[fallthrough]];
  1541. case EPlaybackMode::Rewind:
  1542. if (mCurrentPlaybackFrame > 0)
  1543. {
  1544. mCurrentPlaybackFrame--;
  1545. restore_state = true;
  1546. }
  1547. break;
  1548. case EPlaybackMode::StepForward:
  1549. mPlaybackMode = EPlaybackMode::Stop;
  1550. [[fallthrough]];
  1551. case EPlaybackMode::FastForward:
  1552. if (mCurrentPlaybackFrame < (int)mPlaybackFrames.size() - 1)
  1553. {
  1554. mCurrentPlaybackFrame++;
  1555. restore_state = true;
  1556. }
  1557. break;
  1558. case EPlaybackMode::Stop:
  1559. case EPlaybackMode::Play:
  1560. // Satisfy compiler
  1561. break;
  1562. }
  1563. // If the replay frame changed we need to update state
  1564. if (restore_state)
  1565. {
  1566. // Clear existing debug stuff so we can render this restored frame
  1567. // (if we're paused, we will otherwise not clear the debugging stuff)
  1568. ClearDebugRenderer();
  1569. // Restore state to what it was during that time
  1570. StateRecorderImpl &recorder = mPlaybackFrames[mCurrentPlaybackFrame];
  1571. RestoreState(recorder);
  1572. // Physics world is drawn using debug lines, when not paused
  1573. // Draw state prior to step so that debug lines are created from the same state
  1574. // (the constraints are solved on the current state and then the world is stepped)
  1575. DrawPhysics();
  1576. // Step the world (with fixed frequency)
  1577. StepPhysics(mJobSystem);
  1578. #ifdef JPH_DEBUG_RENDERER
  1579. // Draw any contacts that were collected through the contact listener
  1580. if (mContactListener)
  1581. mContactListener->DrawState();
  1582. #endif // JPH_DEBUG_RENDERER
  1583. // Validate that update result is the same as the previously recorded state
  1584. if (check_determinism && mCurrentPlaybackFrame < (int)mPlaybackFrames.size() - 1)
  1585. ValidateState(mPlaybackFrames[mCurrentPlaybackFrame + 1]);
  1586. }
  1587. // On the last frame go back to play mode
  1588. if (mCurrentPlaybackFrame >= (int)mPlaybackFrames.size() - 1)
  1589. {
  1590. mPlaybackMode = EPlaybackMode::Play;
  1591. mCurrentPlaybackFrame = -1;
  1592. }
  1593. // On the first frame go to stop mode
  1594. if (mCurrentPlaybackFrame == 0)
  1595. mPlaybackMode = EPlaybackMode::Stop;
  1596. }
  1597. else
  1598. {
  1599. // Normal update
  1600. JPH_ASSERT(mCurrentPlaybackFrame == -1);
  1601. if (inDeltaTime > 0.0f)
  1602. {
  1603. // Debugging functionality like shooting a ball and dragging objects
  1604. UpdateDebug();
  1605. if (mRecordState || check_determinism)
  1606. {
  1607. // Record the state prior to the step
  1608. mPlaybackFrames.push_back(StateRecorderImpl());
  1609. SaveState(mPlaybackFrames.back());
  1610. }
  1611. // Physics world is drawn using debug lines, when not paused
  1612. // Draw state prior to step so that debug lines are created from the same state
  1613. // (the constraints are solved on the current state and then the world is stepped)
  1614. DrawPhysics();
  1615. // Update the physics world
  1616. StepPhysics(mJobSystem);
  1617. #ifdef JPH_DEBUG_RENDERER
  1618. // Draw any contacts that were collected through the contact listener
  1619. if (mContactListener)
  1620. mContactListener->DrawState();
  1621. #endif // JPH_DEBUG_RENDERER
  1622. if (check_determinism)
  1623. {
  1624. // Save the current state
  1625. StateRecorderImpl post_step_state;
  1626. SaveState(post_step_state);
  1627. // Restore to the previous state
  1628. RestoreState(mPlaybackFrames.back());
  1629. // Step again
  1630. StepPhysics(mJobSystemValidating);
  1631. // Validate that the result is the same
  1632. ValidateState(post_step_state);
  1633. }
  1634. }
  1635. }
  1636. return true;
  1637. }
  1638. void SamplesApp::DrawPhysics()
  1639. {
  1640. #ifdef JPH_DEBUG_RENDERER
  1641. mPhysicsSystem->DrawBodies(mBodyDrawSettings, mDebugRenderer);
  1642. if (mDrawConstraints)
  1643. mPhysicsSystem->DrawConstraints(mDebugRenderer);
  1644. if (mDrawConstraintLimits)
  1645. mPhysicsSystem->DrawConstraintLimits(mDebugRenderer);
  1646. if (mDrawConstraintReferenceFrame)
  1647. mPhysicsSystem->DrawConstraintReferenceFrame(mDebugRenderer);
  1648. #endif // JPH_DEBUG_RENDERER
  1649. // This map collects the shapes that we used this frame
  1650. ShapeToGeometryMap shape_to_geometry;
  1651. #ifdef JPH_DEBUG_RENDERER
  1652. if (mDrawGetTriangles)
  1653. #endif // JPH_DEBUG_RENDERER
  1654. {
  1655. JPH_PROFILE("DrawGetTriangles");
  1656. // Iterate through all active bodies
  1657. BodyIDVector bodies;
  1658. mPhysicsSystem->GetBodies(bodies);
  1659. const BodyLockInterface &bli = mPhysicsSystem->GetBodyLockInterface();
  1660. for (BodyID b : bodies)
  1661. {
  1662. // Get the body
  1663. BodyLockRead lock(bli, b);
  1664. if (lock.SucceededAndIsInBroadPhase())
  1665. {
  1666. // Collect all leaf shapes for the body and their transforms
  1667. const Body &body = lock.GetBody();
  1668. AllHitCollisionCollector<TransformedShapeCollector> collector;
  1669. body.GetTransformedShape().CollectTransformedShapes(body.GetWorldSpaceBounds(), collector);
  1670. // Draw all leaf shapes
  1671. for (const TransformedShape &transformed_shape : collector.mHits)
  1672. {
  1673. DebugRenderer::GeometryRef geometry;
  1674. // Find geometry from previous frame
  1675. ShapeToGeometryMap::iterator map_iterator = mShapeToGeometry.find(transformed_shape.mShape);
  1676. if (map_iterator != mShapeToGeometry.end())
  1677. geometry = map_iterator->second;
  1678. if (geometry == nullptr)
  1679. {
  1680. // Find geometry from this frame
  1681. map_iterator = shape_to_geometry.find(transformed_shape.mShape);
  1682. if (map_iterator != shape_to_geometry.end())
  1683. geometry = map_iterator->second;
  1684. }
  1685. if (geometry == nullptr)
  1686. {
  1687. // Geometry not cached
  1688. vector<DebugRenderer::Triangle> triangles;
  1689. // Start iterating all triangles of the shape
  1690. Shape::GetTrianglesContext context;
  1691. transformed_shape.mShape->GetTrianglesStart(context, AABox::sBiggest(), Vec3::sZero(), Quat::sIdentity(), Vec3::sReplicate(1.0f));
  1692. for (;;)
  1693. {
  1694. // Get the next batch of vertices
  1695. constexpr int cMaxTriangles = 1000;
  1696. Float3 vertices[3 * cMaxTriangles];
  1697. int triangle_count = transformed_shape.mShape->GetTrianglesNext(context, cMaxTriangles, vertices);
  1698. if (triangle_count == 0)
  1699. break;
  1700. // Allocate space for triangles
  1701. size_t output_index = triangles.size();
  1702. triangles.resize(triangles.size() + triangle_count);
  1703. DebugRenderer::Triangle *triangle = &triangles[output_index];
  1704. // Convert to a renderable triangle
  1705. for (int vertex = 0, vertex_max = 3 * triangle_count; vertex < vertex_max; vertex += 3, ++triangle)
  1706. {
  1707. // Get the vertices
  1708. Vec3 v1(vertices[vertex + 0]);
  1709. Vec3 v2(vertices[vertex + 1]);
  1710. Vec3 v3(vertices[vertex + 2]);
  1711. // Calculate the normal
  1712. Float3 normal;
  1713. (v2 - v1).Cross(v3 - v1).NormalizedOr(Vec3::sZero()).StoreFloat3(&normal);
  1714. v1.StoreFloat3(&triangle->mV[0].mPosition);
  1715. triangle->mV[0].mNormal = normal;
  1716. triangle->mV[0].mColor = Color::sWhite;
  1717. triangle->mV[0].mUV = Float2(0, 0);
  1718. v2.StoreFloat3(&triangle->mV[1].mPosition);
  1719. triangle->mV[1].mNormal = normal;
  1720. triangle->mV[1].mColor = Color::sWhite;
  1721. triangle->mV[1].mUV = Float2(0, 0);
  1722. v3.StoreFloat3(&triangle->mV[2].mPosition);
  1723. triangle->mV[2].mNormal = normal;
  1724. triangle->mV[2].mColor = Color::sWhite;
  1725. triangle->mV[2].mUV = Float2(0, 0);
  1726. }
  1727. }
  1728. // Convert to geometry
  1729. geometry = new DebugRenderer::Geometry(mDebugRenderer->CreateTriangleBatch(triangles), transformed_shape.mShape->GetLocalBounds());
  1730. }
  1731. // Ensure that we cache the geometry for next frame
  1732. shape_to_geometry[transformed_shape.mShape] = geometry;
  1733. // Determine color
  1734. Color color;
  1735. switch (body.GetMotionType())
  1736. {
  1737. case EMotionType::Static:
  1738. color = Color::sGrey;
  1739. break;
  1740. case EMotionType::Kinematic:
  1741. color = Color::sGreen;
  1742. break;
  1743. case EMotionType::Dynamic:
  1744. color = Color::sGetDistinctColor(body.GetID().GetIndex());
  1745. break;
  1746. default:
  1747. JPH_ASSERT(false);
  1748. color = Color::sBlack;
  1749. break;
  1750. }
  1751. // Draw the geometry
  1752. Vec3 scale = transformed_shape.GetShapeScale();
  1753. bool inside_out = ScaleHelpers::IsInsideOut(scale);
  1754. Mat44 matrix = transformed_shape.GetCenterOfMassTransform() * Mat44::sScale(scale);
  1755. mDebugRenderer->DrawGeometry(matrix, color, geometry, inside_out? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace, DebugRenderer::ECastShadow::On, body.IsSensor()? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid);
  1756. }
  1757. }
  1758. }
  1759. }
  1760. // Replace the map with the newly created map so that shapes that we don't draw / were removed are released
  1761. mShapeToGeometry = move(shape_to_geometry);
  1762. }
  1763. void SamplesApp::StepPhysics(JobSystem *inJobSystem)
  1764. {
  1765. float delta_time = 1.0f / mUpdateFrequency;
  1766. {
  1767. // Pre update
  1768. JPH_PROFILE("PrePhysicsUpdate");
  1769. Test::PreUpdateParams pre_update;
  1770. pre_update.mDeltaTime = delta_time;
  1771. pre_update.mKeyboard = mKeyboard;
  1772. pre_update.mCameraState = GetCamera();
  1773. #ifdef JPH_DEBUG_RENDERER
  1774. pre_update.mPoseDrawSettings = &mPoseDrawSettings;
  1775. #endif // JPH_DEBUG_RENDERER
  1776. mTest->PrePhysicsUpdate(pre_update);
  1777. }
  1778. // Remember start tick
  1779. uint64 start_tick = GetProcessorTickCount();
  1780. // Step the world (with fixed frequency)
  1781. mPhysicsSystem->Update(delta_time, mCollisionSteps, mIntegrationSubSteps, mTempAllocator, inJobSystem);
  1782. // Accumulate time
  1783. mTotalTime += GetProcessorTickCount() - start_tick;
  1784. mStepNumber++;
  1785. // Print timing information
  1786. constexpr int cNumSteps = 60;
  1787. if (mStepNumber % cNumSteps == 0)
  1788. {
  1789. double us_per_step = double(mTotalTime / cNumSteps) / double(GetProcessorTicksPerSecond()) * 1.0e6;
  1790. Trace("Timing: %d, %.0f", mStepNumber / cNumSteps, us_per_step);
  1791. mTotalTime = 0;
  1792. }
  1793. #ifdef JPH_TRACK_BROADPHASE_STATS
  1794. if (mStepNumber % 600 == 0)
  1795. mPhysicsSystem->ReportBroadphaseStats();
  1796. #endif // JPH_TRACK_BROADPHASE_STATS
  1797. #ifdef JPH_TRACK_NARROWPHASE_STATS
  1798. if (mStepNumber % 600 == 0)
  1799. NarrowPhaseStat::sReportStats();
  1800. #endif // JPH_TRACK_NARROWPHASE_STATS
  1801. {
  1802. // Post update
  1803. JPH_PROFILE("PostPhysicsUpdate");
  1804. mTest->PostPhysicsUpdate(delta_time);
  1805. }
  1806. }
  1807. void SamplesApp::SaveState(StateRecorderImpl &inStream)
  1808. {
  1809. mTest->SaveState(inStream);
  1810. if (mContactListener)
  1811. mContactListener->SaveState(inStream);
  1812. mPhysicsSystem->SaveState(inStream);
  1813. }
  1814. void SamplesApp::RestoreState(StateRecorderImpl &inStream)
  1815. {
  1816. inStream.Rewind();
  1817. // Restore the state of the test first, this is needed because the test can make changes to
  1818. // the state of bodies that is not tracked by the PhysicsSystem::SaveState.
  1819. // E.g. in the ChangeShapeTest the shape is restored here, which needs to be done first
  1820. // because changing the shape changes Body::mPosition when the center of mass changes.
  1821. mTest->RestoreState(inStream);
  1822. if (mContactListener)
  1823. mContactListener->RestoreState(inStream);
  1824. if (!mPhysicsSystem->RestoreState(inStream))
  1825. FatalError("Failed to restore physics state");
  1826. }
  1827. void SamplesApp::ValidateState(StateRecorderImpl &inExpectedState)
  1828. {
  1829. // Save state
  1830. StateRecorderImpl current_state;
  1831. SaveState(current_state);
  1832. // Compare state with expected state
  1833. if (!current_state.IsEqual(inExpectedState))
  1834. {
  1835. // Mark this stream to break whenever it detects a memory change during reading
  1836. inExpectedState.SetValidating(true);
  1837. // Restore state. Anything that changes indicates a problem with the deterministic simulation.
  1838. RestoreState(inExpectedState);
  1839. // Turn change detection off again
  1840. inExpectedState.SetValidating(false);
  1841. }
  1842. }
  1843. void SamplesApp::GetInitialCamera(CameraState &ioState) const
  1844. {
  1845. // Default if the test doesn't override it
  1846. ioState.mPos = GetWorldScale() * Vec3(30, 10, 30);
  1847. ioState.mForward = -ioState.mPos.Normalized();
  1848. ioState.mFarPlane = 1000.0f;
  1849. mTest->GetInitialCamera(ioState);
  1850. }
  1851. Mat44 SamplesApp::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  1852. {
  1853. return mTest->GetCameraPivot(inCameraHeading, inCameraPitch);
  1854. }
  1855. float SamplesApp::GetWorldScale() const
  1856. {
  1857. return mTest != nullptr? mTest->GetWorldScale() : 1.0f;
  1858. }
  1859. ENTRY_POINT(SamplesApp)