SamplesApp.cpp 83 KB

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