BodyManager.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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/Body.h>
  6. #include <Jolt/Core/Mutex.h>
  7. #include <Jolt/Core/MutexArray.h>
  8. JPH_NAMESPACE_BEGIN
  9. // Classes
  10. class BodyCreationSettings;
  11. class SoftBodyCreationSettings;
  12. class BodyActivationListener;
  13. class StateRecorderFilter;
  14. struct PhysicsSettings;
  15. #ifdef JPH_DEBUG_RENDERER
  16. class DebugRenderer;
  17. class BodyDrawFilter;
  18. #endif // JPH_DEBUG_RENDERER
  19. #ifdef JPH_DEBUG_RENDERER
  20. /// Defines how to color soft body constraints
  21. enum class ESoftBodyConstraintColor
  22. {
  23. ConstraintType, /// Draw different types of constraints in different colors
  24. ConstraintGroup, /// Draw constraints in the same group in the same color, non-parallel group will be red
  25. ConstraintOrder, /// Draw constraints in the same group in the same color, non-parallel group will be red, and order within each group will be indicated with gradient
  26. };
  27. #endif // JPH_DEBUG_RENDERER
  28. /// Array of bodies
  29. using BodyVector = Array<Body *>;
  30. /// Array of body ID's
  31. using BodyIDVector = Array<BodyID>;
  32. /// Class that contains all bodies
  33. ///
  34. /// WARNING: This class is an internal part of PhysicsSystem, it has no functions that can be called by users of the library.
  35. /// Its functionality is exposed through PhysicsSystem, BodyInterface, BodyLockRead and BodyLockWrite.
  36. class JPH_EXPORT BodyManager : public NonCopyable
  37. {
  38. public:
  39. JPH_OVERRIDE_NEW_DELETE
  40. /// Destructor
  41. ~BodyManager();
  42. /// Initialize the manager
  43. void Init(uint inMaxBodies, uint inNumBodyMutexes, const BroadPhaseLayerInterface &inLayerInterface);
  44. /// Gets the current amount of bodies that are in the body manager
  45. uint GetNumBodies() const;
  46. /// Gets the max bodies that we can support
  47. uint GetMaxBodies() const { return uint(mBodies.capacity()); }
  48. /// Helper struct that counts the number of bodies of each type
  49. struct BodyStats
  50. {
  51. uint mNumBodies = 0; ///< Total number of bodies in the body manager
  52. uint mMaxBodies = 0; ///< Max allowed number of bodies in the body manager (as configured in Init(...))
  53. uint mNumBodiesStatic = 0; ///< Number of static bodies
  54. uint mNumBodiesDynamic = 0; ///< Number of dynamic bodies
  55. uint mNumActiveBodiesDynamic = 0; ///< Number of dynamic bodies that are currently active
  56. uint mNumBodiesKinematic = 0; ///< Number of kinematic bodies
  57. uint mNumActiveBodiesKinematic = 0; ///< Number of kinematic bodies that are currently active
  58. uint mNumSoftBodies = 0; ///< Number of soft bodies
  59. uint mNumActiveSoftBodies = 0; ///< Number of soft bodies that are currently active
  60. };
  61. /// Get stats about the bodies in the body manager (slow, iterates through all bodies)
  62. BodyStats GetBodyStats() const;
  63. /// Create a body using creation settings. The returned body will not be part of the body manager yet.
  64. Body * AllocateBody(const BodyCreationSettings &inBodyCreationSettings) const;
  65. /// Create a soft body using creation settings. The returned body will not be part of the body manager yet.
  66. Body * AllocateSoftBody(const SoftBodyCreationSettings &inSoftBodyCreationSettings) const;
  67. /// Free a body that has not been added to the body manager yet (if it has, use DestroyBodies).
  68. void FreeBody(Body *inBody) const;
  69. /// Add a body to the body manager, assigning it the next available ID. Returns false if no more IDs are available.
  70. bool AddBody(Body *ioBody);
  71. /// Add a body to the body manager, assigning it a custom ID. Returns false if the ID is not valid.
  72. bool AddBodyWithCustomID(Body *ioBody, const BodyID &inBodyID);
  73. /// Remove a list of bodies from the body manager
  74. void RemoveBodies(const BodyID *inBodyIDs, int inNumber, Body **outBodies);
  75. /// Remove a set of bodies from the body manager and frees them.
  76. void DestroyBodies(const BodyID *inBodyIDs, int inNumber);
  77. /// Activate a list of bodies.
  78. /// This function should only be called when an exclusive lock for the bodies are held.
  79. void ActivateBodies(const BodyID *inBodyIDs, int inNumber);
  80. /// Deactivate a list of bodies.
  81. /// This function should only be called when an exclusive lock for the bodies are held.
  82. void DeactivateBodies(const BodyID *inBodyIDs, int inNumber);
  83. /// Update the motion quality for a body
  84. void SetMotionQuality(Body &ioBody, EMotionQuality inMotionQuality);
  85. /// Get copy of the list of active bodies under protection of a lock.
  86. void GetActiveBodies(EBodyType inType, BodyIDVector &outBodyIDs) const;
  87. /// Get the list of active bodies. Note: Not thread safe. The active bodies list can change at any moment.
  88. const BodyID * GetActiveBodiesUnsafe(EBodyType inType) const { return mActiveBodies[int(inType)]; }
  89. /// Get the number of active bodies.
  90. uint32 GetNumActiveBodies(EBodyType inType) const { return mNumActiveBodies[int(inType)].load(memory_order_acquire); }
  91. /// Get the number of active bodies that are using continuous collision detection
  92. uint32 GetNumActiveCCDBodies() const { return mNumActiveCCDBodies; }
  93. /// Listener that is notified whenever a body is activated/deactivated
  94. void SetBodyActivationListener(BodyActivationListener *inListener);
  95. BodyActivationListener * GetBodyActivationListener() const { return mActivationListener; }
  96. /// Check if this is a valid body pointer. When a body is freed the memory that the pointer occupies is reused to store a freelist.
  97. static inline bool sIsValidBodyPointer(const Body *inBody) { return (uintptr_t(inBody) & cIsFreedBody) == 0; }
  98. /// Get all bodies. Note that this can contain invalid body pointers, call sIsValidBodyPointer to check.
  99. const BodyVector & GetBodies() const { return mBodies; }
  100. /// Get all bodies. Note that this can contain invalid body pointers, call sIsValidBodyPointer to check.
  101. BodyVector & GetBodies() { return mBodies; }
  102. /// Get all body IDs under the protection of a lock
  103. void GetBodyIDs(BodyIDVector &outBodies) const;
  104. /// Access a body (not protected by lock)
  105. const Body & GetBody(const BodyID &inID) const { return *mBodies[inID.GetIndex()]; }
  106. /// Access a body (not protected by lock)
  107. Body & GetBody(const BodyID &inID) { return *mBodies[inID.GetIndex()]; }
  108. /// Access a body, will return a nullptr if the body ID is no longer valid (not protected by lock)
  109. const Body * TryGetBody(const BodyID &inID) const
  110. {
  111. uint32 idx = inID.GetIndex();
  112. if (idx >= mBodies.size())
  113. return nullptr;
  114. const Body *body = mBodies[idx];
  115. if (sIsValidBodyPointer(body) && body->GetID() == inID)
  116. return body;
  117. return nullptr;
  118. }
  119. /// Access a body, will return a nullptr if the body ID is no longer valid (not protected by lock)
  120. Body * TryGetBody(const BodyID &inID)
  121. {
  122. uint32 idx = inID.GetIndex();
  123. if (idx >= mBodies.size())
  124. return nullptr;
  125. Body *body = mBodies[idx];
  126. if (sIsValidBodyPointer(body) && body->GetID() == inID)
  127. return body;
  128. return nullptr;
  129. }
  130. /// Access the mutex for a single body
  131. SharedMutex & GetMutexForBody(const BodyID &inID) const { return mBodyMutexes.GetMutexByObjectIndex(inID.GetIndex()); }
  132. /// Bodies are protected using an array of mutexes (so a fixed number, not 1 per body). Each bit in this mask indicates a locked mutex.
  133. using MutexMask = uint64;
  134. ///@name Batch body mutex access (do not use directly)
  135. ///@{
  136. MutexMask GetAllBodiesMutexMask() const { return mBodyMutexes.GetNumMutexes() == sizeof(MutexMask) * 8? ~MutexMask(0) : (MutexMask(1) << mBodyMutexes.GetNumMutexes()) - 1; }
  137. MutexMask GetMutexMask(const BodyID *inBodies, int inNumber) const;
  138. void LockRead(MutexMask inMutexMask) const;
  139. void UnlockRead(MutexMask inMutexMask) const;
  140. void LockWrite(MutexMask inMutexMask) const;
  141. void UnlockWrite(MutexMask inMutexMask) const;
  142. ///@}
  143. /// Lock all bodies. This should only be done during PhysicsSystem::Update().
  144. void LockAllBodies() const;
  145. /// Unlock all bodies. This should only be done during PhysicsSystem::Update().
  146. void UnlockAllBodies() const;
  147. /// Function to update body's layer (should only be called by the BodyInterface since it also requires updating the broadphase)
  148. inline void SetBodyObjectLayerInternal(Body &ioBody, ObjectLayer inLayer) const { ioBody.mObjectLayer = inLayer; ioBody.mBroadPhaseLayer = mBroadPhaseLayerInterface->GetBroadPhaseLayer(inLayer); }
  149. /// Set the Body::EFlags::InvalidateContactCache flag for the specified body. This means that the collision cache is invalid for any body pair involving that body until the next physics step.
  150. void InvalidateContactCacheForBody(Body &ioBody);
  151. /// Reset the Body::EFlags::InvalidateContactCache flag for all bodies. All contact pairs in the contact cache will now by valid again.
  152. void ValidateContactCacheForAllBodies();
  153. /// Saving state for replay
  154. void SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;
  155. /// Restoring state for replay. Returns false if failed.
  156. bool RestoreState(StateRecorder &inStream);
  157. /// Save the state of a single body for replay
  158. void SaveBodyState(const Body &inBody, StateRecorder &inStream) const;
  159. /// Save the state of a single body for replay
  160. void RestoreBodyState(Body &inBody, StateRecorder &inStream);
  161. #ifdef JPH_DEBUG_RENDERER
  162. enum class EShapeColor
  163. {
  164. InstanceColor, ///< Random color per instance
  165. ShapeTypeColor, ///< Convex = green, scaled = yellow, compound = orange, mesh = red
  166. MotionTypeColor, ///< Static = grey, keyframed = green, dynamic = random color per instance
  167. SleepColor, ///< Static = grey, keyframed = green, dynamic = yellow, sleeping = red
  168. IslandColor, ///< Static = grey, active = random color per island, sleeping = light grey
  169. MaterialColor, ///< Color as defined by the PhysicsMaterial of the shape
  170. };
  171. /// Draw settings
  172. ///
  173. /// Note that there are several debug drawing features that are not exposed through this interface since they use information
  174. /// that is only available deep inside the simulation update and are mostly there to facilitate debugging Jolt. These options
  175. /// use DebugRenderer::sInstance to draw.
  176. ///
  177. /// E.g.:
  178. /// * To draw contact information, use ContactConstraintManager::sDrawContactManifolds.
  179. /// * To draw when continuous collision detection is used, use PhysicsSystem::sDrawMotionQualityLinearCast.
  180. /// * To draw what's going on in a CharacterVirtual update, use CharacterVirtual::sDrawConstraints, CharacterVirtual::sDrawWalkStairs and CharacterVirtual::sDrawStickToFloor.
  181. /// * To draw the volume of water that interacts with a shape, use Shape::sDrawSubmergedVolumes.
  182. struct DrawSettings
  183. {
  184. bool mDrawGetSupportFunction = false; ///< Draw the GetSupport() function, used for convex collision detection
  185. bool mDrawSupportDirection = false; ///< When drawing the support function, also draw which direction mapped to a specific support point
  186. bool mDrawGetSupportingFace = false; ///< Draw the faces that were found colliding during collision detection
  187. bool mDrawShape = true; ///< Draw the shapes of all bodies
  188. bool mDrawShapeWireframe = false; ///< When mDrawShape is true and this is true, the shapes will be drawn in wireframe instead of solid.
  189. EShapeColor mDrawShapeColor = EShapeColor::MotionTypeColor; ///< Coloring scheme to use for shapes
  190. bool mDrawBoundingBox = false; ///< Draw a bounding box per body
  191. bool mDrawCenterOfMassTransform = false; ///< Draw the center of mass for each body
  192. bool mDrawWorldTransform = false; ///< Draw the world transform (which can be different than the center of mass) for each body
  193. bool mDrawVelocity = false; ///< Draw the velocity vector for each body
  194. bool mDrawMassAndInertia = false; ///< Draw the mass and inertia (as the box equivalent) for each body
  195. bool mDrawSleepStats = false; ///< Draw stats regarding the sleeping algorithm of each body
  196. bool mDrawSoftBodyVertices = false; ///< Draw the vertices of soft bodies
  197. bool mDrawSoftBodyVertexVelocities = false; ///< Draw the velocities of the vertices of soft bodies
  198. bool mDrawSoftBodyEdgeConstraints = false; ///< Draw the edge constraints of soft bodies
  199. bool mDrawSoftBodyBendConstraints = false; ///< Draw the bend constraints of soft bodies
  200. bool mDrawSoftBodyVolumeConstraints = false; ///< Draw the volume constraints of soft bodies
  201. bool mDrawSoftBodySkinConstraints = false; ///< Draw the skin constraints of soft bodies
  202. bool mDrawSoftBodyLRAConstraints = false; ///< Draw the LRA constraints of soft bodies
  203. bool mDrawSoftBodyRods = false; ///< Draw the rods of soft bodies
  204. bool mDrawSoftBodyRodStates = false; ///< Draw the rod states (orientation and angular velocity) of soft bodies
  205. bool mDrawSoftBodyRodBendTwistConstraints = false; ///< Draw the rod bend twist constraints of soft bodies
  206. bool mDrawSoftBodyPredictedBounds = false; ///< Draw the predicted bounds of soft bodies
  207. ESoftBodyConstraintColor mDrawSoftBodyConstraintColor = ESoftBodyConstraintColor::ConstraintType; ///< Coloring scheme to use for soft body constraints
  208. };
  209. /// Draw the state of the bodies (debugging purposes)
  210. void Draw(const DrawSettings &inSettings, const PhysicsSettings &inPhysicsSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter = nullptr);
  211. #endif // JPH_DEBUG_RENDERER
  212. #ifdef JPH_ENABLE_ASSERTS
  213. /// Lock the active body list, asserts when Activate/DeactivateBody is called.
  214. void SetActiveBodiesLocked(bool inLocked) { mActiveBodiesLocked = inLocked; }
  215. /// Per thread override of the locked state, to be used by the PhysicsSystem only!
  216. class GrantActiveBodiesAccess
  217. {
  218. public:
  219. inline GrantActiveBodiesAccess(bool inAllowActivation, bool inAllowDeactivation)
  220. {
  221. JPH_ASSERT(!sGetOverrideAllowActivation());
  222. sSetOverrideAllowActivation(inAllowActivation);
  223. JPH_ASSERT(!sGetOverrideAllowDeactivation());
  224. sSetOverrideAllowDeactivation(inAllowDeactivation);
  225. }
  226. inline ~GrantActiveBodiesAccess()
  227. {
  228. sSetOverrideAllowActivation(false);
  229. sSetOverrideAllowDeactivation(false);
  230. }
  231. };
  232. #endif
  233. #ifdef JPH_DEBUG
  234. /// Validate if the cached bounding boxes are correct for all active bodies
  235. void ValidateActiveBodyBounds();
  236. #endif // JPH_DEBUG
  237. #ifdef JPH_TRACK_SIMULATION_STATS
  238. /// Resets the per body simulation stats
  239. void ResetSimulationStats();
  240. #ifdef JPH_PROFILE_ENABLED
  241. /// Dump the per body simulation stats to the TTY
  242. void ReportSimulationStats();
  243. #endif
  244. #endif
  245. private:
  246. /// Increment and get the sequence number of the body
  247. #ifdef JPH_COMPILER_CLANG
  248. __attribute__((no_sanitize("implicit-conversion"))) // We intentionally overflow the uint8 sequence number
  249. #endif
  250. inline uint8 GetNextSequenceNumber(int inBodyIndex) { return ++mBodySequenceNumbers[inBodyIndex]; }
  251. /// Add a single body to mActiveBodies, note doesn't lock the active body mutex!
  252. inline void AddBodyToActiveBodies(Body &ioBody);
  253. /// Remove a single body from mActiveBodies, note doesn't lock the active body mutex!
  254. inline void RemoveBodyFromActiveBodies(Body &ioBody);
  255. /// Helper function to remove a body from the manager
  256. JPH_INLINE Body * RemoveBodyInternal(const BodyID &inBodyID);
  257. /// Helper function to delete a body (which could actually be a BodyWithMotionProperties)
  258. inline static void sDeleteBody(Body *inBody);
  259. #if defined(JPH_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  260. /// Function to check that the free list is not corrupted
  261. void ValidateFreeList() const;
  262. #endif // defined(JPH_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  263. /// List of pointers to all bodies. Contains invalid pointers for deleted bodies, check with sIsValidBodyPointer. Note that this array is reserved to the max bodies that is passed in the Init function so that adding bodies will not reallocate the array.
  264. BodyVector mBodies;
  265. /// Current number of allocated bodies
  266. uint mNumBodies = 0;
  267. /// Indicates that there are no more freed body IDs
  268. static constexpr uintptr_t cBodyIDFreeListEnd = ~uintptr_t(0);
  269. /// Bit that indicates a pointer in mBodies is actually the index of the next freed body. We use the lowest bit because we know that Bodies need to be 16 byte aligned so addresses can never end in a 1 bit.
  270. static constexpr uintptr_t cIsFreedBody = uintptr_t(1);
  271. /// Amount of bits to shift to get an index to the next freed body
  272. static constexpr uint cFreedBodyIndexShift = 1;
  273. /// Index of first entry in mBodies that is unused
  274. uintptr_t mBodyIDFreeListStart = cBodyIDFreeListEnd;
  275. /// Protects mBodies array (but not the bodies it points to), mNumBodies and mBodyIDFreeListStart
  276. mutable Mutex mBodiesMutex;
  277. /// An array of mutexes protecting the bodies in the mBodies array
  278. using BodyMutexes = MutexArray<SharedMutex>;
  279. mutable BodyMutexes mBodyMutexes;
  280. /// List of next sequence number for a body ID
  281. Array<uint8> mBodySequenceNumbers;
  282. /// Mutex that protects the mActiveBodies array
  283. mutable Mutex mActiveBodiesMutex;
  284. /// List of all active dynamic bodies (size is equal to max amount of bodies)
  285. BodyID * mActiveBodies[cBodyTypeCount] = { };
  286. /// How many bodies there are in the list of active bodies
  287. atomic<uint32> mNumActiveBodies[cBodyTypeCount] = { };
  288. /// How many of the active bodies have continuous collision detection enabled
  289. uint32 mNumActiveCCDBodies = 0;
  290. /// Mutex that protects the mBodiesCacheInvalid array
  291. mutable Mutex mBodiesCacheInvalidMutex;
  292. /// List of all bodies that should have their cache invalidated
  293. BodyIDVector mBodiesCacheInvalid;
  294. /// Listener that is notified whenever a body is activated/deactivated
  295. BodyActivationListener * mActivationListener = nullptr;
  296. /// Cached broadphase layer interface
  297. const BroadPhaseLayerInterface *mBroadPhaseLayerInterface = nullptr;
  298. #ifdef JPH_ENABLE_ASSERTS
  299. static bool sGetOverrideAllowActivation();
  300. static void sSetOverrideAllowActivation(bool inValue);
  301. static bool sGetOverrideAllowDeactivation();
  302. static void sSetOverrideAllowDeactivation(bool inValue);
  303. /// Debug system that tries to limit changes to active bodies during the PhysicsSystem::Update()
  304. bool mActiveBodiesLocked = false;
  305. #endif
  306. };
  307. JPH_NAMESPACE_END