SamplesApp.cpp 83 KB

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