SamplesApp.cpp 112 KB

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