SamplesApp.cpp 83 KB

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