SamplesApp.cpp 85 KB

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