SamplesApp.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Application/Application.h>
  6. #include <UI/UIManager.h>
  7. #include <Application/DebugUI.h>
  8. #include <Jolt/Physics/Collision/CollideShape.h>
  9. #include <Jolt/Skeleton/SkeletonPose.h>
  10. #include <Tests/Test.h>
  11. #include <Utils/ContactListenerImpl.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. #include <Jolt/Physics/StateRecorderImpl.h>
  14. #include <Layers.h>
  15. namespace JPH {
  16. class JobSystem;
  17. class TempAllocator;
  18. };
  19. // Application class that runs the samples
  20. class SamplesApp : public Application
  21. {
  22. public:
  23. // Constructor / destructor
  24. SamplesApp(const String &inCommandLine);
  25. virtual ~SamplesApp() override;
  26. // Update the application
  27. virtual bool UpdateFrame(float inDeltaTime) override;
  28. // Override to specify the initial camera state (local to GetCameraPivot)
  29. virtual void GetInitialCamera(CameraState &ioState) const override;
  30. // Override to specify a camera pivot point and orientation (world space)
  31. virtual RMat44 GetCameraPivot(float inCameraHeading, float inCameraPitch) const override;
  32. // Get scale factor for this world, used to boost camera speed and to scale detail of the shadows
  33. virtual float GetWorldScale() const override;
  34. private:
  35. // Start running a new test
  36. void StartTest(const RTTI *inRTTI);
  37. // Run all tests one by one
  38. void RunAllTests();
  39. // Run the next test. Returns false when the application should exit.
  40. bool NextTest();
  41. // Check if we've got to start the next test. Returns false when the application should exit.
  42. bool CheckNextTest();
  43. // Create a snapshot of the physics system and save it to disc
  44. void TakeSnapshot();
  45. // Create a snapshot of the physics system, save it to disc and immediately reload it
  46. void TakeAndReloadSnapshot();
  47. // Probing the collision world
  48. RefConst<Shape> CreateProbeShape();
  49. bool CastProbe(float inProbeLength, float &outFraction, RVec3 &outPosition, BodyID &outID);
  50. // Shooting an object
  51. RefConst<Shape> CreateShootObjectShape();
  52. void ShootObject();
  53. // Debug functionality: firing a ball, mouse dragging
  54. void UpdateDebug(float inDeltaTime);
  55. // Draw the state of the physics system
  56. void DrawPhysics();
  57. // Update the physics system with a fixed delta time
  58. void StepPhysics(JobSystem *inJobSystem);
  59. // Save state of simulation
  60. void SaveState(StateRecorderImpl &inStream);
  61. // Restore state of simulation
  62. void RestoreState(StateRecorderImpl &inStream);
  63. // Compare current physics state with inExpectedState
  64. void ValidateState(StateRecorderImpl &inExpectedState);
  65. // Global settings
  66. int mMaxConcurrentJobs = thread::hardware_concurrency(); // How many jobs to run in parallel
  67. float mUpdateFrequency = 60.0f; // Physics update frequency, measured in Hz (cycles per second)
  68. int mCollisionSteps = 1; // How many collision detection steps per physics update
  69. TempAllocator * mTempAllocator = nullptr; // Allocator for temporary allocations
  70. JobSystem * mJobSystem = nullptr; // The job system that runs physics jobs
  71. JobSystem * mJobSystemValidating = nullptr; // The job system to use when validating determinism
  72. BPLayerInterfaceImpl mBroadPhaseLayerInterface; // The broadphase layer interface that maps object layers to broadphase layers
  73. ObjectVsBroadPhaseLayerFilterImpl mObjectVsBroadPhaseLayerFilter; // Class that filters object vs broadphase layers
  74. ObjectLayerPairFilterImpl mObjectVsObjectLayerFilter; // Class that filters object vs object layers
  75. PhysicsSystem * mPhysicsSystem = nullptr; // The physics system that simulates the world
  76. ContactListenerImpl * mContactListener = nullptr; // Contact listener implementation
  77. PhysicsSettings mPhysicsSettings; // Main physics simulation settings
  78. // Drawing settings
  79. #ifdef JPH_DEBUG_RENDERER
  80. bool mDrawGetTriangles = false; // Draw all shapes using Shape::GetTrianglesStart/Next
  81. bool mDrawConstraints = false; // If the constraints should be drawn
  82. bool mDrawConstraintLimits = false; // If the constraint limits should be drawn
  83. bool mDrawConstraintReferenceFrame = false; // If the constraint reference frames should be drawn
  84. bool mDrawPhysicsSystemBounds = false; // If the bounds of the physics system should be drawn
  85. BodyManager::DrawSettings mBodyDrawSettings; // Settings for how to draw bodies from the body manager
  86. SkeletonPose::DrawSettings mPoseDrawSettings; // Settings for drawing skeletal poses
  87. #endif // JPH_DEBUG_RENDERER
  88. // Drawing using GetTriangles interface
  89. using ShapeToGeometryMap = UnorderedMap<RefConst<Shape>, DebugRenderer::GeometryRef>;
  90. ShapeToGeometryMap mShapeToGeometry;
  91. // The test to run
  92. const RTTI * mTestClass = nullptr; // RTTI information for the test we're currently running
  93. Test * mTest = nullptr; // The test we're currently running
  94. UITextButton * mTestSettingsButton = nullptr; // Button that activates the menu that the test uses to configure additional settings
  95. int mShowDescription = 0; // If > 0, render the description of the test
  96. // Automatic cycling through tests
  97. bool mIsRunningAllTests = false; // If the user selected the 'Run All Tests' option
  98. float mTestTimeLeft = -1.0f; // How many seconds the test is still supposed to run
  99. bool mExitAfterRunningTests = false; // When true, the application will quit when mTestsToRun becomes empty
  100. // Test settings
  101. bool mInstallContactListener = false; // When true, the contact listener is installed the next time the test is reset
  102. // State recording and determinism checks
  103. bool mRecordState = false; // When true, the state of the physics system is recorded in mPlaybackFrames every physics update
  104. bool mCheckDeterminism = false; // When true, the physics state is rolled back after every update and run again to verify that the state is the same
  105. struct PlayBackFrame
  106. {
  107. StateRecorderImpl mInputState; // State of the player inputs at the beginning of the step
  108. StateRecorderImpl mState; // Main simulation state
  109. };
  110. Array<PlayBackFrame> mPlaybackFrames; // A list of recorded world states, one per physics simulation step
  111. enum class EPlaybackMode
  112. {
  113. Rewind,
  114. StepBack,
  115. Stop,
  116. StepForward,
  117. FastForward,
  118. Play
  119. };
  120. EPlaybackMode mPlaybackMode = EPlaybackMode::Play; // Current playback state. Indicates if we're playing or scrubbing back/forward.
  121. int mCurrentPlaybackFrame = -1; // Current playback frame
  122. // Which mode the probe is operating in.
  123. enum class EProbeMode
  124. {
  125. Pick,
  126. Ray,
  127. RayCollector,
  128. CollidePoint,
  129. CollideShape,
  130. CollideShapeWithInternalEdgeRemoval,
  131. CastShape,
  132. CollideSoftBody,
  133. TransformedShape,
  134. GetTriangles,
  135. BroadPhaseRay,
  136. BroadPhaseBox,
  137. BroadPhaseSphere,
  138. BroadPhasePoint,
  139. BroadPhaseOrientedBox,
  140. BroadPhaseCastBox,
  141. };
  142. // Which probe shape to use.
  143. enum class EProbeShape
  144. {
  145. Sphere,
  146. Box,
  147. ConvexHull,
  148. Capsule,
  149. TaperedCapsule,
  150. Cylinder,
  151. Triangle,
  152. RotatedTranslated,
  153. StaticCompound,
  154. StaticCompound2,
  155. MutableCompound,
  156. Mesh,
  157. };
  158. // Probe settings
  159. EProbeMode mProbeMode = EProbeMode::Pick; // Mouse probe mode. Determines what happens under the crosshair.
  160. EProbeShape mProbeShape = EProbeShape::Sphere; // Shape to use for the mouse probe.
  161. bool mScaleShape = false; // If the shape is scaled or not. When true mShapeScale is taken into account.
  162. Vec3 mShapeScale = Vec3::sOne(); // Scale in local space for the probe shape.
  163. EBackFaceMode mBackFaceModeTriangles = EBackFaceMode::CollideWithBackFaces; // How to handle back facing triangles when doing a collision probe check.
  164. EBackFaceMode mBackFaceModeConvex = EBackFaceMode::CollideWithBackFaces; // How to handle back facing convex shapes when doing a collision probe check.
  165. EActiveEdgeMode mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive; // How to handle active edges when doing a collision probe check.
  166. ECollectFacesMode mCollectFacesMode = ECollectFacesMode::NoFaces; // If we should collect colliding faces
  167. float mMaxSeparationDistance = 0.0f; // Max separation distance for collide shape test
  168. bool mTreatConvexAsSolid = true; // For ray casts if the shape should be treated as solid or if the ray should only collide with the surface
  169. bool mReturnDeepestPoint = true; // For shape casts, when true this will return the deepest point
  170. bool mUseShrunkenShapeAndConvexRadius = false; // Shrink then expand the shape by the convex radius
  171. bool mDrawSupportingFace = false; // Draw the result of GetSupportingFace
  172. int mMaxHits = 10; // The maximum number of hits to request for a collision probe.
  173. bool mClosestHitPerBody = false; // If we are only interested in the closest hit for every body
  174. // Which object to shoot
  175. enum class EShootObjectShape
  176. {
  177. Sphere,
  178. ConvexHull,
  179. ThinBar,
  180. SoftBodyCube,
  181. };
  182. // Shoot object settings
  183. EShootObjectShape mShootObjectShape = EShootObjectShape::Sphere; // Type of object to shoot
  184. float mShootObjectVelocity = 20.0f; // Speed at which objects are ejected
  185. EMotionQuality mShootObjectMotionQuality = EMotionQuality::Discrete; // Motion quality for the object that we're shooting
  186. float mShootObjectFriction = 0.2f; // Friction for the object that is shot
  187. float mShootObjectRestitution = 0.0f; // Restitution for the object that is shot
  188. bool mShootObjectScaleShape = false; // If the shape should be scaled
  189. Vec3 mShootObjectShapeScale = Vec3::sOne(); // Scale of the object to shoot
  190. bool mWasShootKeyPressed = false; // Remembers if the shoot key was pressed last frame
  191. // Mouse dragging
  192. Body * mDragAnchor = nullptr; // Rigid bodies only: A anchor point for the distance constraint. Corresponds to the current crosshair position.
  193. BodyID mDragBody; // The body ID of the body that the user is currently dragging.
  194. Ref<Constraint> mDragConstraint; // Rigid bodies only: The distance constraint that connects the body to be dragged and the anchor point.
  195. uint mDragVertexIndex = ~uint(0); // Soft bodies only: The vertex index of the body that the user is currently dragging.
  196. float mDragVertexPreviousInvMass = 0.0f; // Soft bodies only: The inverse mass of the vertex that the user is currently dragging.
  197. float mDragFraction; // Fraction along cDragRayLength (see cpp) where the hit occurred. This will be combined with the crosshair position to get a 3d anchor point.
  198. // Timing
  199. uint mStepNumber = 0; // Which step number we're accumulating
  200. chrono::microseconds mTotalTime { 0 }; // How many nano seconds we spent simulating
  201. };