SamplesApp.cpp 100 KB

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