SamplesApp.cpp 105 KB

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