PhysicsSystem.h 18 KB

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