SamplesApp.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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();
  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. // Automatic cycling through tests
  96. Array<const RTTI *> mTestsToRun; // The list of tests that are still waiting to be run
  97. float mTestTimeLeft = -1.0f; // How many seconds the test is still supposed to run
  98. bool mExitAfterRunningTests = false; // When true, the application will quit when mTestsToRun becomes empty
  99. UITextButton * mNextTestButton = nullptr; // Button that activates the next test when we're running all tests
  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. CastShape,
  131. CollideSoftBody,
  132. TransformedShape,
  133. GetTriangles,
  134. BroadPhaseRay,
  135. BroadPhaseBox,
  136. BroadPhaseSphere,
  137. BroadPhasePoint,
  138. BroadPhaseOrientedBox,
  139. BroadPhaseCastBox,
  140. };
  141. // Which probe shape to use.
  142. enum class EProbeShape
  143. {
  144. Sphere,
  145. Box,
  146. ConvexHull,
  147. Capsule,
  148. TaperedCapsule,
  149. Cylinder,
  150. Triangle,
  151. RotatedTranslated,
  152. StaticCompound,
  153. StaticCompound2,
  154. MutableCompound,
  155. Mesh,
  156. };
  157. // Probe settings
  158. EProbeMode mProbeMode = EProbeMode::Pick; // Mouse probe mode. Determines what happens under the crosshair.
  159. EProbeShape mProbeShape = EProbeShape::Sphere; // Shape to use for the mouse probe.
  160. bool mScaleShape = false; // If the shape is scaled or not. When true mShapeScale is taken into account.
  161. Vec3 mShapeScale = Vec3::sReplicate(1.0f); // Scale in local space for the probe shape.
  162. EBackFaceMode mBackFaceMode = EBackFaceMode::CollideWithBackFaces; // How to handle back facing triangles when doing a collision probe check.
  163. EActiveEdgeMode mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive; // How to handle active edges when doing a collision probe check.
  164. ECollectFacesMode mCollectFacesMode = ECollectFacesMode::NoFaces; // If we should collect colliding faces
  165. float mMaxSeparationDistance = 0.0f; // Max separation distance for collide shape test
  166. bool mTreatConvexAsSolid = true; // For ray casts if the shape should be treated as solid or if the ray should only collide with the surface
  167. bool mReturnDeepestPoint = true; // For shape casts, when true this will return the deepest point
  168. bool mUseShrunkenShapeAndConvexRadius = false; // Shrink then expand the shape by the convex radius
  169. bool mDrawSupportingFace = false; // Draw the result of GetSupportingFace
  170. int mMaxHits = 10; // The maximum number of hits to request for a collision probe.
  171. // Which object to shoot
  172. enum class EShootObjectShape
  173. {
  174. Sphere,
  175. ConvexHull,
  176. ThinBar,
  177. SoftBodyCube,
  178. };
  179. // Shoot object settings
  180. EShootObjectShape mShootObjectShape = EShootObjectShape::Sphere; // Type of object to shoot
  181. float mShootObjectVelocity = 20.0f; // Speed at which objects are ejected
  182. EMotionQuality mShootObjectMotionQuality = EMotionQuality::Discrete; // Motion quality for the object that we're shooting
  183. float mShootObjectFriction = 0.2f; // Friction for the object that is shot
  184. float mShootObjectRestitution = 0.0f; // Restitution for the object that is shot
  185. bool mShootObjectScaleShape = false; // If the shape should be scaled
  186. Vec3 mShootObjectShapeScale = Vec3::sReplicate(1.0f); // Scale of the object to shoot
  187. bool mWasShootKeyPressed = false; // Remembers if the shoot key was pressed last frame
  188. // Mouse dragging
  189. Body * mDragAnchor = nullptr; // Rigid bodies only: A anchor point for the distance constraint. Corresponds to the current crosshair position.
  190. BodyID mDragBody; // The body ID of the body that the user is currently dragging.
  191. Ref<Constraint> mDragConstraint; // Rigid bodies only: The distance constraint that connects the body to be dragged and the anchor point.
  192. uint mDragVertexIndex = ~uint(0); // Soft bodies only: The vertex index of the body that the user is currently dragging.
  193. float mDragVertexPreviousInvMass = 0.0f; // Soft bodies only: The inverse mass of the vertex that the user is currently dragging.
  194. 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.
  195. // Timing
  196. uint mStepNumber = 0; // Which step number we're accumulating
  197. chrono::microseconds mTotalTime { 0 }; // How many nano seconds we spent simulating
  198. };