SamplesApp.cpp 99 KB

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