PhysicsSystem.h 14 KB

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