PhysicsSystem.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/Body/BodyInterface.h>
  5. #include <Jolt/Physics/Collision/NarrowPhaseQuery.h>
  6. #include <Jolt/Physics/Collision/ContactListener.h>
  7. #include <Jolt/Physics/Constraints/ContactConstraintManager.h>
  8. #include <Jolt/Physics/Constraints/ConstraintManager.h>
  9. #include <Jolt/Physics/IslandBuilder.h>
  10. #include <Jolt/Physics/PhysicsUpdateContext.h>
  11. #include <Jolt/Physics/PhysicsSettings.h>
  12. JPH_NAMESPACE_BEGIN
  13. class JobSystem;
  14. class StateRecorder;
  15. class TempAllocator;
  16. class PhysicsStepListener;
  17. /// The main class for the physics system. It contains all rigid bodies and simulates them.
  18. ///
  19. /// The main simulation is performed by the Update() call on multiple threads (if the JobSystem is configured to use them). Please refer to the general architecture overview in the Docs folder for more information.
  20. class PhysicsSystem : public NonCopyable
  21. {
  22. public:
  23. /// Constructor / Destructor
  24. PhysicsSystem() : mContactManager(mPhysicsSettings) { }
  25. ~PhysicsSystem();
  26. /// Initialize the system.
  27. /// @param inMaxBodies Maximum number of bodies to support.
  28. /// @param inNumBodyMutexes Number of body mutexes to use. Should be a power of 2 in the range [1, 64], use 0 to auto detect.
  29. /// @param inMaxBodyPairs Maximum amount of body pairs to process (anything else will fall through the world), this number should generally be much higher than the max amount of contact points as there will be lots of bodies close that are not actually touching
  30. /// @param inMaxContactConstraints Maximum amount of contact constraints to process (anything else will fall through the world)
  31. /// @param inBroadPhaseLayerInterface Information on the mapping of object layers to broad phase layers, note since this is a virtual interface, the instance needs to stay alive during the lifetime of the PhysicsSystem
  32. /// @param inObjectVsBroadPhaseLayerFilter Filter callback function that is used to determine if an object layer collides with a broad phase layer.
  33. /// @param inObjectLayerPairFilter Filter callback function that is used to determine if two object layers collide.
  34. void Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, ObjectVsBroadPhaseLayerFilter inObjectVsBroadPhaseLayerFilter, ObjectLayerPairFilter inObjectLayerPairFilter);
  35. /// Listener that is notified whenever a body is activated/deactivated
  36. void SetBodyActivationListener(BodyActivationListener *inListener) { mBodyManager.SetBodyActivationListener(inListener); }
  37. BodyActivationListener * GetBodyActivationListener() const { return mBodyManager.GetBodyActivationListener(); }
  38. /// Listener that is notified whenever a contact point between two bodies is added/updated/removed
  39. void SetContactListener(ContactListener *inListener) { mContactManager.SetContactListener(inListener); }
  40. ContactListener * GetContactListener() const { return mContactManager.GetContactListener(); }
  41. /// Set the function that combines the friction of two bodies and returns it
  42. /// Default method is the geometric mean: sqrt(friction1 * friction2).
  43. void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction) { mContactManager.SetCombineFriction(inCombineFriction); }
  44. /// Set the function that combines the restitution of two bodies and returns it
  45. /// Default method is max(restitution1, restitution1)
  46. void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition) { mContactManager.SetCombineRestitution(inCombineRestition); }
  47. /// Control the main constants of the physics simulation
  48. void SetPhysicsSettings(const PhysicsSettings &inSettings) { mPhysicsSettings = inSettings; }
  49. const PhysicsSettings & GetPhysicsSettings() const { return mPhysicsSettings; }
  50. /// Access to the body interface. This interface allows to to create / remove bodies and to change their properties.
  51. const BodyInterface & GetBodyInterface() const { return mBodyInterfaceLocking; }
  52. BodyInterface & GetBodyInterface() { return mBodyInterfaceLocking; }
  53. const BodyInterface & GetBodyInterfaceNoLock() const { return mBodyInterfaceNoLock; } ///< Version that does not lock the bodies, use with great care!
  54. BodyInterface & GetBodyInterfaceNoLock() { return mBodyInterfaceNoLock; } ///< Version that does not lock the bodies, use with great care!
  55. /// Access to the broadphase interface that allows coarse collision queries
  56. const BroadPhaseQuery & GetBroadPhaseQuery() const { return *mBroadPhase; }
  57. /// Interface that allows fine collision queries against first the broad phase and then the narrow phase.
  58. const NarrowPhaseQuery & GetNarrowPhaseQuery() const { return mNarrowPhaseQueryLocking; }
  59. const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const { return mNarrowPhaseQueryNoLock; } ///< Version that does not lock the bodies, use with great care!
  60. /// Add constraint to the world
  61. void AddConstraint(Constraint *inConstraint) { mConstraintManager.Add(&inConstraint, 1); }
  62. /// Remove constraint from the world
  63. void RemoveConstraint(Constraint *inConstraint) { mConstraintManager.Remove(&inConstraint, 1); }
  64. /// Batch add constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
  65. void AddConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Add(inConstraints, inNumber); }
  66. /// Batch remove constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
  67. void RemoveConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Remove(inConstraints, inNumber); }
  68. /// Get a list of all constraints
  69. Constraints GetConstraints() const { return mConstraintManager.GetConstraints(); }
  70. /// Optimize the broadphase, needed only if you've added many bodies prior to calling Update() for the first time.
  71. void OptimizeBroadPhase();
  72. /// Adds a new step listener
  73. void AddStepListener(PhysicsStepListener *inListener);
  74. /// Removes a step listener
  75. void RemoveStepListener(PhysicsStepListener *inListener);
  76. /// Simulate the system.
  77. /// The world steps for a total of inDeltaTime seconds. This is divided in inCollisionSteps iterations. Each iteration
  78. /// consists of collision detection followed by inIntegrationSubSteps integration steps.
  79. void Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem);
  80. /// Saving state for replay
  81. void SaveState(StateRecorder &inStream) const;
  82. /// Restoring state for replay. Returns false if failed.
  83. bool RestoreState(StateRecorder &inStream);
  84. #ifdef JPH_DEBUG_RENDERER
  85. // Drawing properties
  86. static bool sDrawMotionQualityLinearCast; ///< Draw debug info for objects that perform continuous collision detection through the linear cast motion quality
  87. /// Draw the state of the bodies (debugging purposes)
  88. void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer) { mBodyManager.Draw(inSettings, mPhysicsSettings, inRenderer); }
  89. /// Draw the constraints only (debugging purposes)
  90. void DrawConstraints(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraints(inRenderer); }
  91. /// Draw the constraint limits only (debugging purposes)
  92. void DrawConstraintLimits(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintLimits(inRenderer); }
  93. /// Draw the constraint reference frames only (debugging purposes)
  94. void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintReferenceFrame(inRenderer); }
  95. #endif // JPH_DEBUG_RENDERER
  96. /// Set gravity value
  97. void SetGravity(Vec3Arg inGravity) { mGravity = inGravity; }
  98. Vec3 GetGravity() const { return mGravity; }
  99. /// Returns a locking interface that won't actually lock the body. Use with great care!
  100. inline const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const { return mBodyLockInterfaceNoLock; }
  101. /// Returns a locking interface that locks the body so other threads cannot modify it.
  102. inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }
  103. /// Get an broadphase layer filter that uses the default pair filter and a specified object layer to determine if broadphase layers collide
  104. DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const { return DefaultBroadPhaseLayerFilter(mObjectVsBroadPhaseLayerFilter, inLayer); }
  105. /// Get an object layer filter that uses the default pair filter and a specified layer to determine if layers collide
  106. DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const { return DefaultObjectLayerFilter(mObjectLayerPairFilter, inLayer); }
  107. /// Gets the current amount of bodies that are in the body manager
  108. uint GetNumBodies() const { return mBodyManager.GetNumBodies(); }
  109. /// Gets the current amount of active bodies that are in the body manager
  110. uint32 GetNumActiveBodies() const { return mBodyManager.GetNumActiveBodies(); }
  111. /// Get the maximum amount of bodies that this physics system supports
  112. uint GetMaxBodies() const { return mBodyManager.GetMaxBodies(); }
  113. /// Helper struct that counts the number of bodies of each type
  114. using BodyStats = BodyManager::BodyStats;
  115. /// Get stats about the bodies in the body manager (slow, iterates through all bodies)
  116. BodyStats GetBodyStats() const { return mBodyManager.GetBodyStats(); }
  117. /// Get copy of the list of all bodies under protection of a lock.
  118. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  119. void GetBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetBodyIDs(outBodyIDs); }
  120. /// Get copy of the list of active bodies under protection of a lock.
  121. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  122. void GetActiveBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetActiveBodies(outBodyIDs); }
  123. #ifdef JPH_TRACK_BROADPHASE_STATS
  124. /// Trace the accumulated broadphase stats to the TTY
  125. void ReportBroadphaseStats() { mBroadPhase->ReportStats(); }
  126. #endif // JPH_TRACK_BROADPHASE_STATS
  127. private:
  128. using CCDBody = PhysicsUpdateContext::SubStep::CCDBody;
  129. // Various job entry points
  130. void JobStepListeners(PhysicsUpdateContext::Step *ioStep);
  131. void JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const;
  132. void JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  133. void JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const;
  134. void JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  135. void JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex);
  136. void JobFinalizeIslands(PhysicsUpdateContext *ioContext);
  137. void JobBodySetIslandIndex();
  138. void JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  139. void JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const;
  140. void JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  141. void JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const;
  142. void JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  143. void JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  144. void JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep);
  145. void JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  146. /// Tries to spawn a new FindCollisions job if max concurrency hasn't been reached yet
  147. void TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const;
  148. using ContactAllocator = ContactConstraintManager::ContactAllocator;
  149. /// Process narrow phase for a single body pair
  150. void ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair);
  151. /// Number of constraints to process at once in JobDetermineActiveConstraints
  152. static constexpr int cDetermineActiveConstraintsBatchSize = 64;
  153. /// Number of bodies to process at once in JobApplyGravity
  154. static constexpr int cApplyGravityBatchSize = 64;
  155. /// Number of active bodies to test for collisions per batch
  156. static constexpr int cActiveBodiesBatchSize = 16;
  157. /// Number of active bodies to integrate velocities for
  158. static constexpr int cIntegrateVelocityBatchSize = 64;
  159. /// Number of contacts that need to be queued before another narrow phase job is started
  160. static constexpr int cNarrowPhaseBatchSize = 16;
  161. /// Number of continuous collision shape casts that need to be queued before another job is started
  162. static constexpr int cNumCCDBodiesPerJob = 4;
  163. /// Broadphase layer filter that decides if two objects can collide
  164. ObjectVsBroadPhaseLayerFilter mObjectVsBroadPhaseLayerFilter = nullptr;
  165. /// Object layer filter that decides if two objects can collide
  166. ObjectLayerPairFilter mObjectLayerPairFilter = nullptr;
  167. /// The body manager keeps track which bodies are in the simulation
  168. BodyManager mBodyManager;
  169. /// Body locking interfaces
  170. BodyLockInterfaceNoLock mBodyLockInterfaceNoLock { mBodyManager };
  171. BodyLockInterfaceLocking mBodyLockInterfaceLocking { mBodyManager };
  172. /// Body interfaces
  173. BodyInterface mBodyInterfaceNoLock;
  174. BodyInterface mBodyInterfaceLocking;
  175. /// Narrow phase query interface
  176. NarrowPhaseQuery mNarrowPhaseQueryNoLock;
  177. NarrowPhaseQuery mNarrowPhaseQueryLocking;
  178. /// The broadphase does quick collision detection between body pairs
  179. BroadPhase * mBroadPhase = nullptr;
  180. /// The contact manager resolves all contacts during a simulation step
  181. ContactConstraintManager mContactManager;
  182. /// All non-contact constraints
  183. ConstraintManager mConstraintManager;
  184. /// Keeps track of connected bodies and builds islands for multithreaded velocity/position update
  185. IslandBuilder mIslandBuilder;
  186. /// Mutex protecting mStepListeners
  187. Mutex mStepListenersMutex;
  188. /// List of physics step listeners
  189. using StepListeners = vector<PhysicsStepListener *>;
  190. StepListeners mStepListeners;
  191. /// This is the global gravity vector
  192. Vec3 mGravity = Vec3(0, -9.81f, 0);
  193. /// Previous frame's delta time of one sub step to allow scaling previous frame's constraint impulses
  194. float mPreviousSubStepDeltaTime = 0.0f;
  195. /// Simulation settings
  196. PhysicsSettings mPhysicsSettings;
  197. };
  198. JPH_NAMESPACE_END