SamplesApp.cpp 104 KB

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