SamplesApp.cpp 111 KB

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