SamplesApp.cpp 108 KB

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