SamplesApp.cpp 108 KB

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