QuadTree.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Core/FixedSizeFreeList.h>
  5. #include <Core/Atomics.h>
  6. #include <Core/NonCopyable.h>
  7. #include <Physics/Body/BodyManager.h>
  8. #include <Physics/Collision/BroadPhase/BroadPhase.h>
  9. #ifdef JPH_TRACK_BROADPHASE_STATS
  10. #include <map>
  11. #endif // JPH_TRACK_BROADPHASE_STATS
  12. namespace JPH {
  13. /// Internal tree structure in broadphase, is essentially a quad AABB tree.
  14. /// Tree is lockless (except for UpdatePrepare/Finalize() function), modifying objects in the tree will widen the aabbs of parent nodes to make the node fit.
  15. /// During the UpdatePrepare/Finalize() call the tree is rebuilt to achieve a tight fit again.
  16. class QuadTree : public NonCopyable
  17. {
  18. private:
  19. // Forward declare
  20. class AtomicNodeID;
  21. /// Class that points to either a body or a node in the tree
  22. class NodeID
  23. {
  24. public:
  25. /// Default constructor does not initialize
  26. inline NodeID() = default;
  27. /// Construct a node ID
  28. static inline NodeID sInvalid() { return NodeID(cInvalidNodeIndex); }
  29. static inline NodeID sFromBodyID(BodyID inID) { NodeID node_id(inID.GetIndexAndSequenceNumber()); JPH_ASSERT(node_id.IsBody()); return node_id; }
  30. static inline NodeID sFromNodeIndex(uint32 inIdx) { NodeID node_id(inIdx | cIsNode); JPH_ASSERT(node_id.IsNode()); return node_id; }
  31. /// Check what type of ID it is
  32. inline bool IsValid() const { return mID != cInvalidNodeIndex; }
  33. inline bool IsBody() const { return (mID & cIsNode) == 0; }
  34. inline bool IsNode() const { return (mID & cIsNode) != 0; }
  35. /// Get body or node index
  36. inline BodyID GetBodyID() const { JPH_ASSERT(IsBody()); return BodyID(mID); }
  37. inline uint32 GetNodeIndex() const { JPH_ASSERT(IsNode()); return mID & ~cIsNode; }
  38. /// Comparison
  39. inline bool operator == (const BodyID &inRHS) const { return mID == inRHS.GetIndexAndSequenceNumber(); }
  40. inline bool operator == (const NodeID &inRHS) const { return mID == inRHS.mID; }
  41. private:
  42. friend class AtomicNodeID;
  43. inline explicit NodeID(uint32 inID) : mID(inID) { }
  44. static const uint32 cIsNode = BodyID::cBroadPhaseBit; ///< If this bit is set it means that the ID refers to a node, otherwise it refers to a body
  45. uint32 mID;
  46. };
  47. static_assert(sizeof(NodeID) == sizeof(BodyID), "Body id's should have the same size as NodeIDs");
  48. /// A NodeID that uses atomics to store the value
  49. class AtomicNodeID
  50. {
  51. public:
  52. /// Constructor
  53. AtomicNodeID() = default;
  54. explicit AtomicNodeID(const NodeID &inRHS) : mID(inRHS.mID) { }
  55. /// Assignment
  56. inline void operator = (const NodeID &inRHS) { mID = inRHS.mID; }
  57. /// Getting the value
  58. inline operator const NodeID () const { return NodeID(mID); }
  59. /// Check if the ID is valid
  60. inline bool IsValid() const { return mID != cInvalidNodeIndex; }
  61. /// Comparison
  62. inline bool operator == (const BodyID &inRHS) const { return mID == inRHS.GetIndexAndSequenceNumber(); }
  63. inline bool operator == (const NodeID &inRHS) const { return mID == inRHS.mID; }
  64. /// Atomically compare and swap value. Expects inOld value, replaces with inNew value or returns false
  65. inline bool CompareExchange(NodeID inOld, NodeID inNew) { return mID.compare_exchange_strong(inOld.mID, inNew.mID); }
  66. private:
  67. atomic<uint32> mID;
  68. };
  69. /// Class that represents a node in the tree
  70. class Node
  71. {
  72. public:
  73. /// Construct node
  74. explicit Node(bool inLocked);
  75. /// Get bounding box encapsulating all children
  76. void GetNodeBounds(AABox &outBounds) const;
  77. /// Get bounding box in a consistent way with the functions below (check outBounds.IsValid() before using the box)
  78. void GetChildBounds(int inChildIndex, AABox &outBounds) const;
  79. /// Set the bounds in such a way that other threads will either see a fully correct bounding box or a bounding box with no volume
  80. void SetChildBounds(int inChildIndex, const AABox &inBounds);
  81. /// Invalidate bounding box in such a way that other threads will not temporarily see a very large bounding box
  82. void InvalidateChildBounds(int inChildIndex);
  83. /// Encapsulate inBounds in node bounds, returns true if there were changes
  84. bool EncapsulateChildBounds(int inChildIndex, const AABox &inBounds);
  85. /// Bounding box for child nodes or bodies (all initially set to invalid so no collision test will ever traverse to the leaf)
  86. atomic<float> mBoundsMinX[4];
  87. atomic<float> mBoundsMinY[4];
  88. atomic<float> mBoundsMinZ[4];
  89. atomic<float> mBoundsMaxX[4];
  90. atomic<float> mBoundsMaxY[4];
  91. atomic<float> mBoundsMaxZ[4];
  92. /// Index of child node or body ID.
  93. AtomicNodeID mChildNodeID[4];
  94. /// Index of the parent node.
  95. /// Note: This value is unreliable during the UpdatePrepare/Finalize() function as a node may be relinked to the newly built tree.
  96. atomic<uint32> mParentNodeIndex;
  97. /// If this part of the tree is locked, meaning we will treat this sub tree as a single body during the UpdatePrepare/Finalize().
  98. /// If any changes are made to an object inside this sub tree then the direct path from the body to the top of the tree will become unlocked.
  99. atomic<uint32> mIsLocked;
  100. // Padding to align to 124 bytes
  101. uint32 mPadding = 0;
  102. };
  103. // Maximum size of the stack during tree walk
  104. static constexpr int cStackSize = 128;
  105. static_assert(sizeof(atomic<float>) == 4, "Assuming that an atomic doesn't add any additional storage");
  106. static_assert(sizeof(atomic<uint32>) == 4, "Assuming that an atomic doesn't add any additional storage");
  107. static_assert(is_trivially_destructible<Node>(), "Assuming that we don't have a destructor");
  108. public:
  109. /// Class that allocates tree nodes, can be shared between multiple trees
  110. using Allocator = FixedSizeFreeList<Node>;
  111. static_assert(Allocator::ObjectStorageSize == 128, "Node should be 128 bytes");
  112. /// Data to track location of a Body in the tree
  113. struct Tracking
  114. {
  115. /// Constructor to satisfy the vector class
  116. Tracking() = default;
  117. Tracking(const Tracking &inRHS) : mBroadPhaseLayer(inRHS.mBroadPhaseLayer.load()), mObjectLayer(inRHS.mObjectLayer.load()), mBodyLocation(inRHS.mBodyLocation.load()) { }
  118. /// Invalid body location identifier
  119. static const uint32 cInvalidBodyLocation = 0xffffffff;
  120. atomic<BroadPhaseLayer::Type> mBroadPhaseLayer = (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid;
  121. atomic<ObjectLayer> mObjectLayer = cObjectLayerInvalid;
  122. atomic<uint32> mBodyLocation { cInvalidBodyLocation };
  123. };
  124. using TrackingVector = vector<Tracking>;
  125. /// Destructor
  126. ~QuadTree();
  127. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  128. /// Name of the tree for debugging purposes
  129. void SetName(const char *inName) { mName = inName; }
  130. inline const char * GetName() const { return mName; }
  131. #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
  132. /// Check if there is anything in the tree
  133. inline bool HasBodies() const { return mNumBodies != 0; }
  134. /// Check if the tree needs an UpdatePrepare/Finalize()
  135. inline bool IsDirty() const { return mIsDirty; }
  136. /// Check if this tree can get an UpdatePrepare/Finalize() or if it needs a DiscardOldTree() first
  137. inline bool CanBeUpdated() const { return mFreeNodeBatch.mNumObjects == 0; }
  138. /// Initialization
  139. void Init(Allocator &inAllocator);
  140. struct UpdateState
  141. {
  142. NodeID * mAllNodeIDs; ///< Temporary storage for all leaf node ID's in the tree that must be grouped into a new tree
  143. NodeID mRootNodeID; ///< This will be the new root node id
  144. };
  145. /// Will throw away the previous frame's nodes so that we can start building a new tree in the background
  146. void DiscardOldTree();
  147. /// Update the broadphase, needs to be called regularly to achieve a tight fit of the tree when bodies have been modified.
  148. /// UpdatePrepare() will build the tree, UpdateFinalize() will lock the root of the tree shortly and swap the trees and afterwards clean up temporary data structures.
  149. void UpdatePrepare(const BodyVector &inBodies, TrackingVector &ioTracking, UpdateState &outUpdateState);
  150. void UpdateFinalize(const BodyVector &inBodies, TrackingVector &ioTracking, UpdateState &inUpdateState);
  151. /// Temporary data structure to pass information between AddBodiesPrepare and AddBodiesFinalize/Abort
  152. struct AddState
  153. {
  154. NodeID mLeafID = NodeID::sInvalid();
  155. AABox mLeafBounds;
  156. };
  157. /// Prepare adding inNumber bodies at ioBodyIDs to the quad tree, returns the state in outState that should be used in AddBodiesFinalize.
  158. /// This can be done on a background thread without influencing the broadphase.
  159. /// ioBodyIDs may be shuffled around by this function.
  160. void AddBodiesPrepare(const BodyVector &inBodies, TrackingVector &ioTracking, BodyID *ioBodyIDs, int inNumber, AddState &outState);
  161. /// Finalize adding bodies to the quadtree, supply the same number of bodies as in AddBodiesPrepare.
  162. void AddBodiesFinalize(TrackingVector &ioTracking, int inNumberBodies, const AddState &inState);
  163. /// Abort adding bodies to the quadtree, supply the same bodies and state as in AddBodiesPrepare.
  164. /// This can be done on a background thread without influencing the broadphase.
  165. void AddBodiesAbort(TrackingVector &ioTracking, const AddState &inState);
  166. /// Remove inNumber bodies in ioBodyIDs from the quadtree.
  167. /// ioBodyIDs may be shuffled around by this function.
  168. void RemoveBodies(const BodyVector &inBodies, TrackingVector &ioTracking, BodyID *ioBodyIDs, int inNumber);
  169. /// Call whenever the aabb of a body changes (can change order of ioBodyIDs array).
  170. void NotifyBodiesAABBChanged(const BodyVector &inBodies, const TrackingVector &inTracking, BodyID *ioBodyIDs, int inNumber);
  171. /// Cast a ray and get the intersecting bodies in ioCollector.
  172. void CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  173. /// Get bodies intersecting with inBox in ioCollector
  174. void CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  175. /// Get bodies intersecting with a sphere in ioCollector
  176. void CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  177. /// Get bodies intersecting with a point and any hits to ioCollector
  178. void CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  179. /// Get bodies intersecting with an oriented box and any hits to ioCollector
  180. void CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  181. /// Cast a box and get intersecting bodies in ioCollector
  182. void CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  183. /// Find all colliding pairs between dynamic bodies, calls ioPairCollector for every pair found
  184. void FindCollidingPairs(const BodyVector &inBodies, const BodyID *inActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, BodyPairCollector &ioPairCollector, ObjectLayerPairFilter inObjectLayerPairFilter) const;
  185. #ifdef JPH_TRACK_BROADPHASE_STATS
  186. /// Trace the stats of this tree to the TTY
  187. void ReportStats() const;
  188. #endif // JPH_TRACK_BROADPHASE_STATS
  189. private:
  190. /// Constants
  191. static const uint32 cInvalidNodeIndex = 0xffffffff; ///< Value used to indicate node index is invalid
  192. static const float cLargeFloat; ///< A large floating point number that is small enough to not cause any overflows
  193. static const AABox cInvalidBounds; ///< Invalid bounding box using cLargeFloat
  194. /// We alternate between two trees in order to let collision queries complete in parallel to adding/removing objects to the tree
  195. struct RootNode
  196. {
  197. /// Get the ID of the root node
  198. inline NodeID GetNodeID() const { return NodeID::sFromNodeIndex(mIndex); }
  199. /// Index of the root node of the tree (this is always a node, never a body id)
  200. atomic<uint32> mIndex { cInvalidNodeIndex };
  201. };
  202. /// Caches location of body inBodyID in the tracker, body can be found in mNodes[inNodeIdx].mChildNodeID[inChildIdx]
  203. void GetBodyLocation(const TrackingVector &inTracking, BodyID inBodyID, uint32 &outNodeIdx, uint32 &outChildIdx) const;
  204. void SetBodyLocation(TrackingVector &ioTracking, BodyID inBodyID, uint32 inNodeIdx, uint32 inChildIdx) const;
  205. void InvalidateBodyLocation(TrackingVector &ioTracking, BodyID inBodyID);
  206. /// Get the current root of the tree
  207. JPH_INLINE const RootNode & GetCurrentRoot() const { return mRootNode[mRootNodeIndex]; }
  208. JPH_INLINE RootNode & GetCurrentRoot() { return mRootNode[mRootNodeIndex]; }
  209. /// Depending on if inNodeID is a body or tree node return the bounding box
  210. inline AABox GetNodeOrBodyBounds(const BodyVector &inBodies, NodeID inNodeID) const;
  211. /// Unlock node and all of its parents
  212. inline void UnlockNodeAndParents(uint32 inNodeIndex);
  213. /// Widen parent bounds of node inNodeIndex to encapsulate inNewBounds, also unlock the node and its parents
  214. inline void WidenAndUnlockNodeAndParents(uint32 inNodeIndex, const AABox &inNewBounds);
  215. /// Allocate a new node
  216. inline uint32 AllocateNode(bool inLocked);
  217. /// Try to insert a new leaf to the tree at inNodeIndex
  218. inline bool TryInsertLeaf(TrackingVector &ioTracking, int inNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies);
  219. /// Try to replace the existing root with a new root that contains both the existing root and the new leaf
  220. inline bool TryCreateNewRoot(TrackingVector &ioTracking, atomic<uint32> &ioRootNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies);
  221. /// Build a tree for ioBodyIDs, returns the NodeID of the root (which will be the ID of a single body if inNumber = 1)
  222. NodeID BuildTree(const BodyVector &inBodies, TrackingVector &ioTracking, NodeID *ioNodeIDs, int inNumber, uint32 inParentNodeIndex, bool inLocked, AABox &outBounds);
  223. /// Sorts ioNodeIDs spatially into 2 groups. Second groups starts at ioNodeIDs + outMidPoint.
  224. /// After the function returns ioNodeIDs and ioNodeCenters will be shuffled
  225. static void sPartition(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inNumber, int &outMidPoint);
  226. /// Sorts ioNodeIDs from inBegin to (but excluding) inEnd spatially into 4 groups.
  227. /// outSplit needs to be 5 ints long, when the function returns each group runs from outSplit[i] to (but excluding) outSplit[i + 1]
  228. /// After the function returns ioNodeIDs and ioNodeCenters will be shuffled
  229. static void sPartition4(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inBegin, int inEnd, int *outSplit);
  230. #ifdef _DEBUG
  231. /// Validate that the tree is consistent.
  232. /// Note: This function only works if the tree is not modified while we're traversing it.
  233. void ValidateTree(const BodyVector &inBodies, const TrackingVector &inTracking, uint32 inNodeIndex, uint32 inNumExpectedBodies) const;
  234. #endif
  235. #ifdef JPH_TRACK_BROADPHASE_STATS
  236. /// Mutex protecting the various LayerToStats members
  237. mutable Mutex mStatsMutex;
  238. struct Stat
  239. {
  240. uint64 mNumQueries = 0;
  241. uint64 mNodesVisited = 0;
  242. uint64 mBodiesVisited = 0;
  243. uint64 mHitsReported = 0;
  244. uint64 mTotalTicks = 0;
  245. uint64 mCollectorTicks = 0;
  246. };
  247. using LayerToStats = map<string, Stat>;
  248. /// Trace the stats of a single query type to the TTY
  249. void ReportStats(const char *inName, const LayerToStats &inLayer) const;
  250. mutable LayerToStats mCastRayStats;
  251. mutable LayerToStats mCollideAABoxStats;
  252. mutable LayerToStats mCollideSphereStats;
  253. mutable LayerToStats mCollidePointStats;
  254. mutable LayerToStats mCollideOrientedBoxStats;
  255. mutable LayerToStats mCastAABoxStats;
  256. #endif // JPH_TRACK_BROADPHASE_STATS
  257. /// Walk the node tree calling the Visitor::VisitNodes for each node encountered and Visitor::VisitBody for each body encountered
  258. template <class Visitor>
  259. JPH_INLINE void WalkTree(const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking, Visitor &ioVisitor JPH_IF_TRACK_BROADPHASE_STATS(, LayerToStats &ioStats)) const;
  260. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  261. /// Name of this tree for debugging purposes
  262. const char * mName = "Layer";
  263. #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
  264. /// Number of bodies currently in the tree
  265. atomic<uint32> mNumBodies { 0 };
  266. /// We alternate between two tree root nodes. When updating, we activate the new tree and we keep the old tree alive.
  267. /// for queries that are in progress until the next time DiscardOldTree() is called.
  268. RootNode mRootNode[2];
  269. atomic<uint32> mRootNodeIndex { 0 };
  270. /// Allocator that controls adding / freeing nodes
  271. Allocator * mAllocator = nullptr;
  272. /// This is a list of nodes that must be deleted after the trees are swapped and the old tree is no longer in use
  273. Allocator::Batch mFreeNodeBatch;
  274. /// Flag to keep track of changes to the broadphase, if false, we don't need to UpdatePrepare/Finalize()
  275. atomic<bool> mIsDirty = false;
  276. };
  277. } // JPH