PhysicsSystem.h 15 KB

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