SamplesApp.cpp 84 KB

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