SamplesApp.cpp 91 KB

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