2
0

SamplesApp.cpp 88 KB

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