SamplesApp.cpp 105 KB

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