2
0

SamplesApp.cpp 106 KB

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