SamplesApp.cpp 89 KB

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