SamplesApp.cpp 88 KB

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