SamplesApp.cpp 89 KB

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