SamplesApp.cpp 100 KB

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