SamplesApp.h 11 KB

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