QuadTree.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/BroadPhase/QuadTree.h>
  6. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuadTree.h>
  7. #include <Jolt/Physics/Collision/RayCast.h>
  8. #include <Jolt/Physics/Collision/AABoxCast.h>
  9. #include <Jolt/Physics/Collision/CastResult.h>
  10. #include <Jolt/Physics/Collision/SortReverseAndStore.h>
  11. #include <Jolt/Physics/Body/BodyPair.h>
  12. #include <Jolt/Physics/PhysicsLock.h>
  13. #include <Jolt/Geometry/AABox4.h>
  14. #include <Jolt/Geometry/RayAABox.h>
  15. #include <Jolt/Geometry/OrientedBox.h>
  16. #ifdef JPH_DUMP_BROADPHASE_TREE
  17. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  18. #include <fstream>
  19. JPH_SUPPRESS_WARNINGS_STD_END
  20. #endif // JPH_DUMP_BROADPHASE_TREE
  21. JPH_NAMESPACE_BEGIN
  22. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  23. // QuadTree::Node
  24. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  25. QuadTree::Node::Node(bool inIsChanged) :
  26. mIsChanged(inIsChanged)
  27. {
  28. // First reset bounds
  29. Vec4 val = Vec4::sReplicate(cLargeFloat);
  30. val.StoreFloat4((Float4 *)&mBoundsMinX);
  31. val.StoreFloat4((Float4 *)&mBoundsMinY);
  32. val.StoreFloat4((Float4 *)&mBoundsMinZ);
  33. val = Vec4::sReplicate(-cLargeFloat);
  34. val.StoreFloat4((Float4 *)&mBoundsMaxX);
  35. val.StoreFloat4((Float4 *)&mBoundsMaxY);
  36. val.StoreFloat4((Float4 *)&mBoundsMaxZ);
  37. // Reset child node ids
  38. mChildNodeID[0] = NodeID::sInvalid();
  39. mChildNodeID[1] = NodeID::sInvalid();
  40. mChildNodeID[2] = NodeID::sInvalid();
  41. mChildNodeID[3] = NodeID::sInvalid();
  42. }
  43. void QuadTree::Node::GetChildBounds(int inChildIndex, AABox &outBounds) const
  44. {
  45. // Read bounding box in order min -> max
  46. outBounds.mMin = Vec3(mBoundsMinX[inChildIndex], mBoundsMinY[inChildIndex], mBoundsMinZ[inChildIndex]);
  47. outBounds.mMax = Vec3(mBoundsMaxX[inChildIndex], mBoundsMaxY[inChildIndex], mBoundsMaxZ[inChildIndex]);
  48. }
  49. void QuadTree::Node::SetChildBounds(int inChildIndex, const AABox &inBounds)
  50. {
  51. // Set max first (this keeps the bounding box invalid for reading threads)
  52. mBoundsMaxZ[inChildIndex] = inBounds.mMax.GetZ();
  53. mBoundsMaxY[inChildIndex] = inBounds.mMax.GetY();
  54. mBoundsMaxX[inChildIndex] = inBounds.mMax.GetX();
  55. // Then set min (and make box valid)
  56. mBoundsMinZ[inChildIndex] = inBounds.mMin.GetZ();
  57. mBoundsMinY[inChildIndex] = inBounds.mMin.GetY();
  58. mBoundsMinX[inChildIndex] = inBounds.mMin.GetX(); // Min X becomes valid last
  59. }
  60. void QuadTree::Node::InvalidateChildBounds(int inChildIndex)
  61. {
  62. // First we make the box invalid by setting the min to cLargeFloat
  63. mBoundsMinX[inChildIndex] = cLargeFloat; // Min X becomes invalid first
  64. mBoundsMinY[inChildIndex] = cLargeFloat;
  65. mBoundsMinZ[inChildIndex] = cLargeFloat;
  66. // Then we reset the max values too
  67. mBoundsMaxX[inChildIndex] = -cLargeFloat;
  68. mBoundsMaxY[inChildIndex] = -cLargeFloat;
  69. mBoundsMaxZ[inChildIndex] = -cLargeFloat;
  70. }
  71. void QuadTree::Node::GetNodeBounds(AABox &outBounds) const
  72. {
  73. // Get first child bounds
  74. GetChildBounds(0, outBounds);
  75. // Encapsulate other child bounds
  76. for (int child_idx = 1; child_idx < 4; ++child_idx)
  77. {
  78. AABox tmp;
  79. GetChildBounds(child_idx, tmp);
  80. outBounds.Encapsulate(tmp);
  81. }
  82. }
  83. bool QuadTree::Node::EncapsulateChildBounds(int inChildIndex, const AABox &inBounds)
  84. {
  85. bool changed = AtomicMin(mBoundsMinX[inChildIndex], inBounds.mMin.GetX());
  86. changed |= AtomicMin(mBoundsMinY[inChildIndex], inBounds.mMin.GetY());
  87. changed |= AtomicMin(mBoundsMinZ[inChildIndex], inBounds.mMin.GetZ());
  88. changed |= AtomicMax(mBoundsMaxX[inChildIndex], inBounds.mMax.GetX());
  89. changed |= AtomicMax(mBoundsMaxY[inChildIndex], inBounds.mMax.GetY());
  90. changed |= AtomicMax(mBoundsMaxZ[inChildIndex], inBounds.mMax.GetZ());
  91. return changed;
  92. }
  93. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  94. // QuadTree
  95. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  96. const float QuadTree::cLargeFloat = 1.0e30f;
  97. const AABox QuadTree::cInvalidBounds(Vec3::sReplicate(cLargeFloat), Vec3::sReplicate(-cLargeFloat));
  98. void QuadTree::GetBodyLocation(const TrackingVector &inTracking, BodyID inBodyID, uint32 &outNodeIdx, uint32 &outChildIdx) const
  99. {
  100. uint32 body_location = inTracking[inBodyID.GetIndex()].mBodyLocation;
  101. JPH_ASSERT(body_location != Tracking::cInvalidBodyLocation);
  102. outNodeIdx = body_location & 0x3fffffff;
  103. outChildIdx = body_location >> 30;
  104. JPH_ASSERT(mAllocator->Get(outNodeIdx).mChildNodeID[outChildIdx] == inBodyID, "Make sure that the body is in the node where it should be");
  105. }
  106. void QuadTree::SetBodyLocation(TrackingVector &ioTracking, BodyID inBodyID, uint32 inNodeIdx, uint32 inChildIdx) const
  107. {
  108. JPH_ASSERT(inNodeIdx <= 0x3fffffff);
  109. JPH_ASSERT(inChildIdx < 4);
  110. JPH_ASSERT(mAllocator->Get(inNodeIdx).mChildNodeID[inChildIdx] == inBodyID, "Make sure that the body is in the node where it should be");
  111. ioTracking[inBodyID.GetIndex()].mBodyLocation = inNodeIdx + (inChildIdx << 30);
  112. #ifdef JPH_ENABLE_ASSERTS
  113. uint32 v1, v2;
  114. GetBodyLocation(ioTracking, inBodyID, v1, v2);
  115. JPH_ASSERT(v1 == inNodeIdx);
  116. JPH_ASSERT(v2 == inChildIdx);
  117. #endif
  118. }
  119. void QuadTree::sInvalidateBodyLocation(TrackingVector &ioTracking, BodyID inBodyID)
  120. {
  121. ioTracking[inBodyID.GetIndex()].mBodyLocation = Tracking::cInvalidBodyLocation;
  122. }
  123. QuadTree::~QuadTree()
  124. {
  125. // Get rid of any nodes that are still to be freed
  126. DiscardOldTree();
  127. // Get the current root node
  128. const RootNode &root_node = GetCurrentRoot();
  129. // Collect all bodies
  130. Allocator::Batch free_batch;
  131. NodeID node_stack[cStackSize];
  132. node_stack[0] = root_node.GetNodeID();
  133. JPH_ASSERT(node_stack[0].IsValid());
  134. if (node_stack[0].IsNode())
  135. {
  136. int top = 0;
  137. do
  138. {
  139. // Process node
  140. NodeID node_id = node_stack[top];
  141. JPH_ASSERT(!node_id.IsBody());
  142. uint32 node_idx = node_id.GetNodeIndex();
  143. const Node &node = mAllocator->Get(node_idx);
  144. // Recurse and get all child nodes
  145. for (NodeID child_node_id : node.mChildNodeID)
  146. if (child_node_id.IsValid() && child_node_id.IsNode())
  147. {
  148. JPH_ASSERT(top < cStackSize);
  149. node_stack[top] = child_node_id;
  150. top++;
  151. }
  152. // Mark node to be freed
  153. mAllocator->AddObjectToBatch(free_batch, node_idx);
  154. --top;
  155. }
  156. while (top >= 0);
  157. }
  158. // Now free all nodes
  159. mAllocator->DestructObjectBatch(free_batch);
  160. }
  161. uint32 QuadTree::AllocateNode(bool inIsChanged)
  162. {
  163. uint32 index = mAllocator->ConstructObject(inIsChanged);
  164. if (index == Allocator::cInvalidObjectIndex)
  165. {
  166. Trace("QuadTree: Out of nodes!");
  167. std::abort();
  168. }
  169. return index;
  170. }
  171. void QuadTree::Init(Allocator &inAllocator)
  172. {
  173. // Store allocator
  174. mAllocator = &inAllocator;
  175. // Allocate root node
  176. mRootNode[mRootNodeIndex].mIndex = AllocateNode(false);
  177. }
  178. void QuadTree::DiscardOldTree()
  179. {
  180. // Check if there is an old tree
  181. RootNode &old_root_node = mRootNode[mRootNodeIndex ^ 1];
  182. if (old_root_node.mIndex != cInvalidNodeIndex)
  183. {
  184. // Clear the root
  185. old_root_node.mIndex = cInvalidNodeIndex;
  186. // Now free all old nodes
  187. mAllocator->DestructObjectBatch(mFreeNodeBatch);
  188. // Clear the batch
  189. mFreeNodeBatch = Allocator::Batch();
  190. }
  191. }
  192. AABox QuadTree::GetBounds() const
  193. {
  194. uint32 node_idx = GetCurrentRoot().mIndex;
  195. JPH_ASSERT(node_idx != cInvalidNodeIndex);
  196. const Node &node = mAllocator->Get(node_idx);
  197. AABox bounds;
  198. node.GetNodeBounds(bounds);
  199. return bounds;
  200. }
  201. void QuadTree::UpdatePrepare(const BodyVector &inBodies, TrackingVector &ioTracking, UpdateState &outUpdateState, bool inFullRebuild)
  202. {
  203. #ifdef JPH_ENABLE_ASSERTS
  204. // We only read positions
  205. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  206. #endif
  207. // Assert we have no nodes pending deletion, this means DiscardOldTree wasn't called yet
  208. JPH_ASSERT(mFreeNodeBatch.mNumObjects == 0);
  209. // Mark tree non-dirty
  210. mIsDirty = false;
  211. // Get the current root node
  212. const RootNode &root_node = GetCurrentRoot();
  213. #ifdef JPH_DUMP_BROADPHASE_TREE
  214. DumpTree(root_node.GetNodeID(), StringFormat("%s_PRE", mName).c_str());
  215. #endif
  216. // Assert sane data
  217. #ifdef JPH_DEBUG
  218. ValidateTree(inBodies, ioTracking, root_node.mIndex, mNumBodies);
  219. #endif
  220. // Create space for all body ID's
  221. NodeID *node_ids = new NodeID [mNumBodies];
  222. NodeID *cur_node_id = node_ids;
  223. // Collect all bodies
  224. NodeID node_stack[cStackSize];
  225. node_stack[0] = root_node.GetNodeID();
  226. JPH_ASSERT(node_stack[0].IsValid());
  227. int top = 0;
  228. do
  229. {
  230. // Check if node is a body
  231. NodeID node_id = node_stack[top];
  232. if (node_id.IsBody())
  233. {
  234. // Validate that we're still in the right layer
  235. #ifdef JPH_ENABLE_ASSERTS
  236. uint32 body_index = node_id.GetBodyID().GetIndex();
  237. JPH_ASSERT(ioTracking[body_index].mObjectLayer == inBodies[body_index]->GetObjectLayer());
  238. #endif
  239. // Store body
  240. *cur_node_id = node_id;
  241. ++cur_node_id;
  242. }
  243. else
  244. {
  245. // Process normal node
  246. uint32 node_idx = node_id.GetNodeIndex();
  247. const Node &node = mAllocator->Get(node_idx);
  248. if (!node.mIsChanged && !inFullRebuild)
  249. {
  250. // Node is unchanged, treat it as a whole
  251. *cur_node_id = node_id;
  252. ++cur_node_id;
  253. }
  254. else
  255. {
  256. // Node is changed, recurse and get all children
  257. for (NodeID child_node_id : node.mChildNodeID)
  258. if (child_node_id.IsValid())
  259. {
  260. if (top < cStackSize)
  261. {
  262. node_stack[top] = child_node_id;
  263. top++;
  264. }
  265. else
  266. {
  267. JPH_ASSERT(false, "Stack full!\n"
  268. "This must be a very deep tree. Are you batch adding bodies through BodyInterface::AddBodiesPrepare/AddBodiesFinalize?\n"
  269. "If you add lots of bodies through BodyInterface::AddBody you may need to call PhysicsSystem::OptimizeBroadPhase to rebuild the tree.");
  270. // Falling back to adding the node as a whole
  271. *cur_node_id = child_node_id;
  272. ++cur_node_id;
  273. }
  274. }
  275. // Mark node to be freed
  276. mAllocator->AddObjectToBatch(mFreeNodeBatch, node_idx);
  277. }
  278. }
  279. --top;
  280. }
  281. while (top >= 0);
  282. // Check that our book keeping matches
  283. uint32 num_node_ids = uint32(cur_node_id - node_ids);
  284. JPH_ASSERT(inFullRebuild? num_node_ids == mNumBodies : num_node_ids <= mNumBodies);
  285. // This will be the new root node id
  286. NodeID root_node_id;
  287. if (num_node_ids > 0)
  288. {
  289. // We mark the first 5 levels (max 1024 nodes) of the newly built tree as 'changed' so that
  290. // those nodes get recreated every time when we rebuild the tree. This balances the amount of
  291. // time we spend on rebuilding the tree ('unchanged' nodes will be put in the new tree as a whole)
  292. // vs the quality of the built tree.
  293. constexpr uint cMaxDepthMarkChanged = 5;
  294. // Build new tree
  295. AABox root_bounds;
  296. root_node_id = BuildTree(inBodies, ioTracking, node_ids, num_node_ids, cMaxDepthMarkChanged, root_bounds);
  297. if (root_node_id.IsBody())
  298. {
  299. // For a single body we need to allocate a new root node
  300. uint32 root_idx = AllocateNode(false);
  301. Node &root = mAllocator->Get(root_idx);
  302. root.SetChildBounds(0, root_bounds);
  303. root.mChildNodeID[0] = root_node_id;
  304. SetBodyLocation(ioTracking, root_node_id.GetBodyID(), root_idx, 0);
  305. root_node_id = NodeID::sFromNodeIndex(root_idx);
  306. }
  307. }
  308. else
  309. {
  310. // Empty tree, create root node
  311. uint32 root_idx = AllocateNode(false);
  312. root_node_id = NodeID::sFromNodeIndex(root_idx);
  313. }
  314. // Delete temporary data
  315. delete [] node_ids;
  316. outUpdateState.mRootNodeID = root_node_id;
  317. }
  318. void QuadTree::UpdateFinalize([[maybe_unused]] const BodyVector &inBodies, [[maybe_unused]] const TrackingVector &inTracking, const UpdateState &inUpdateState)
  319. {
  320. // Tree building is complete, now we switch the old with the new tree
  321. uint32 new_root_idx = mRootNodeIndex ^ 1;
  322. RootNode &new_root_node = mRootNode[new_root_idx];
  323. {
  324. // Note: We don't need to lock here as the old tree stays available so any queries
  325. // that use it can continue using it until DiscardOldTree is called. This slot
  326. // should be empty and unused at this moment.
  327. JPH_ASSERT(new_root_node.mIndex == cInvalidNodeIndex);
  328. new_root_node.mIndex = inUpdateState.mRootNodeID.GetNodeIndex();
  329. }
  330. // All queries that start from now on will use this new tree
  331. mRootNodeIndex = new_root_idx;
  332. #ifdef JPH_DUMP_BROADPHASE_TREE
  333. DumpTree(new_root_node.GetNodeID(), StringFormat("%s_POST", mName).c_str());
  334. #endif
  335. #ifdef JPH_DEBUG
  336. ValidateTree(inBodies, inTracking, new_root_node.mIndex, mNumBodies);
  337. #endif
  338. }
  339. void QuadTree::sPartition(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inNumber, int &outMidPoint)
  340. {
  341. // Handle trivial case
  342. if (inNumber <= 4)
  343. {
  344. outMidPoint = inNumber / 2;
  345. return;
  346. }
  347. // Calculate bounding box of box centers
  348. Vec3 center_min = Vec3::sReplicate(cLargeFloat);
  349. Vec3 center_max = Vec3::sReplicate(-cLargeFloat);
  350. for (const Vec3 *c = ioNodeCenters, *c_end = ioNodeCenters + inNumber; c < c_end; ++c)
  351. {
  352. Vec3 center = *c;
  353. center_min = Vec3::sMin(center_min, center);
  354. center_max = Vec3::sMax(center_max, center);
  355. }
  356. // Calculate split plane
  357. int dimension = (center_max - center_min).GetHighestComponentIndex();
  358. float split = 0.5f * (center_min + center_max)[dimension];
  359. // Divide bodies
  360. int start = 0, end = inNumber;
  361. while (start < end)
  362. {
  363. // Search for first element that is on the right hand side of the split plane
  364. while (start < end && ioNodeCenters[start][dimension] < split)
  365. ++start;
  366. // Search for the first element that is on the left hand side of the split plane
  367. while (start < end && ioNodeCenters[end - 1][dimension] >= split)
  368. --end;
  369. if (start < end)
  370. {
  371. // Swap the two elements
  372. std::swap(ioNodeIDs[start], ioNodeIDs[end - 1]);
  373. std::swap(ioNodeCenters[start], ioNodeCenters[end - 1]);
  374. ++start;
  375. --end;
  376. }
  377. }
  378. JPH_ASSERT(start == end);
  379. if (start > 0 && start < inNumber)
  380. {
  381. // Success!
  382. outMidPoint = start;
  383. }
  384. else
  385. {
  386. // Failed to divide bodies
  387. outMidPoint = inNumber / 2;
  388. }
  389. }
  390. void QuadTree::sPartition4(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inBegin, int inEnd, int *outSplit)
  391. {
  392. NodeID *node_ids = ioNodeIDs + inBegin;
  393. Vec3 *node_centers = ioNodeCenters + inBegin;
  394. int number = inEnd - inBegin;
  395. // Partition entire range
  396. sPartition(node_ids, node_centers, number, outSplit[2]);
  397. // Partition lower half
  398. sPartition(node_ids, node_centers, outSplit[2], outSplit[1]);
  399. // Partition upper half
  400. sPartition(node_ids + outSplit[2], node_centers + outSplit[2], number - outSplit[2], outSplit[3]);
  401. // Convert to proper range
  402. outSplit[0] = inBegin;
  403. outSplit[1] += inBegin;
  404. outSplit[2] += inBegin;
  405. outSplit[3] += outSplit[2];
  406. outSplit[4] = inEnd;
  407. }
  408. AABox QuadTree::GetNodeOrBodyBounds(const BodyVector &inBodies, NodeID inNodeID) const
  409. {
  410. if (inNodeID.IsNode())
  411. {
  412. // It is a node
  413. uint32 node_idx = inNodeID.GetNodeIndex();
  414. const Node &node = mAllocator->Get(node_idx);
  415. AABox bounds;
  416. node.GetNodeBounds(bounds);
  417. return bounds;
  418. }
  419. else
  420. {
  421. // It is a body
  422. return inBodies[inNodeID.GetBodyID().GetIndex()]->GetWorldSpaceBounds();
  423. }
  424. }
  425. QuadTree::NodeID QuadTree::BuildTree(const BodyVector &inBodies, TrackingVector &ioTracking, NodeID *ioNodeIDs, int inNumber, uint inMaxDepthMarkChanged, AABox &outBounds)
  426. {
  427. // Trivial case: No bodies in tree
  428. if (inNumber == 0)
  429. {
  430. outBounds = cInvalidBounds;
  431. return NodeID::sInvalid();
  432. }
  433. // Trivial case: When we have 1 body or node, return it
  434. if (inNumber == 1)
  435. {
  436. if (ioNodeIDs->IsNode())
  437. {
  438. // When returning an existing node as root, ensure that no parent has been set
  439. Node &node = mAllocator->Get(ioNodeIDs->GetNodeIndex());
  440. node.mParentNodeIndex = cInvalidNodeIndex;
  441. }
  442. outBounds = GetNodeOrBodyBounds(inBodies, *ioNodeIDs);
  443. return *ioNodeIDs;
  444. }
  445. // Calculate centers of all bodies that are to be inserted
  446. Vec3 *centers = new Vec3 [inNumber];
  447. JPH_ASSERT(IsAligned(centers, JPH_VECTOR_ALIGNMENT));
  448. Vec3 *c = centers;
  449. for (const NodeID *n = ioNodeIDs, *n_end = ioNodeIDs + inNumber; n < n_end; ++n, ++c)
  450. *c = GetNodeOrBodyBounds(inBodies, *n).GetCenter();
  451. // The algorithm is a recursive tree build, but to avoid the call overhead we keep track of a stack here
  452. struct StackEntry
  453. {
  454. uint32 mNodeIdx; // Node index of node that is generated
  455. int mChildIdx; // Index of child that we're currently processing
  456. int mSplit[5]; // Indices where the node ID's have been split to form 4 partitions
  457. uint32 mDepth; // Depth of this node in the tree
  458. Vec3 mNodeBoundsMin; // Bounding box of this node, accumulated while iterating over children
  459. Vec3 mNodeBoundsMax;
  460. };
  461. static_assert(sizeof(StackEntry) == 64);
  462. StackEntry stack[cStackSize / 4]; // We don't process 4 at a time in this loop but 1, so the stack can be 4x as small
  463. int top = 0;
  464. // Create root node
  465. stack[0].mNodeIdx = AllocateNode(inMaxDepthMarkChanged > 0);
  466. stack[0].mChildIdx = -1;
  467. stack[0].mDepth = 0;
  468. stack[0].mNodeBoundsMin = Vec3::sReplicate(cLargeFloat);
  469. stack[0].mNodeBoundsMax = Vec3::sReplicate(-cLargeFloat);
  470. sPartition4(ioNodeIDs, centers, 0, inNumber, stack[0].mSplit);
  471. for (;;)
  472. {
  473. StackEntry &cur_stack = stack[top];
  474. // Next child
  475. cur_stack.mChildIdx++;
  476. // Check if all children processed
  477. if (cur_stack.mChildIdx >= 4)
  478. {
  479. // Terminate if there's nothing left to pop
  480. if (top <= 0)
  481. break;
  482. // Add our bounds to our parents bounds
  483. StackEntry &prev_stack = stack[top - 1];
  484. prev_stack.mNodeBoundsMin = Vec3::sMin(prev_stack.mNodeBoundsMin, cur_stack.mNodeBoundsMin);
  485. prev_stack.mNodeBoundsMax = Vec3::sMax(prev_stack.mNodeBoundsMax, cur_stack.mNodeBoundsMax);
  486. // Store parent node
  487. Node &node = mAllocator->Get(cur_stack.mNodeIdx);
  488. node.mParentNodeIndex = prev_stack.mNodeIdx;
  489. // Store this node's properties in the parent node
  490. Node &parent_node = mAllocator->Get(prev_stack.mNodeIdx);
  491. parent_node.mChildNodeID[prev_stack.mChildIdx] = NodeID::sFromNodeIndex(cur_stack.mNodeIdx);
  492. parent_node.SetChildBounds(prev_stack.mChildIdx, AABox(cur_stack.mNodeBoundsMin, cur_stack.mNodeBoundsMax));
  493. // Pop entry from stack
  494. --top;
  495. }
  496. else
  497. {
  498. // Get low and high index to bodies to process
  499. int low = cur_stack.mSplit[cur_stack.mChildIdx];
  500. int high = cur_stack.mSplit[cur_stack.mChildIdx + 1];
  501. int num_bodies = high - low;
  502. if (num_bodies == 1)
  503. {
  504. // Get body info
  505. NodeID child_node_id = ioNodeIDs[low];
  506. AABox bounds = GetNodeOrBodyBounds(inBodies, child_node_id);
  507. // Update node
  508. Node &node = mAllocator->Get(cur_stack.mNodeIdx);
  509. node.mChildNodeID[cur_stack.mChildIdx] = child_node_id;
  510. node.SetChildBounds(cur_stack.mChildIdx, bounds);
  511. if (child_node_id.IsNode())
  512. {
  513. // Update parent for this node
  514. Node &child_node = mAllocator->Get(child_node_id.GetNodeIndex());
  515. child_node.mParentNodeIndex = cur_stack.mNodeIdx;
  516. }
  517. else
  518. {
  519. // Set location in tracking
  520. SetBodyLocation(ioTracking, child_node_id.GetBodyID(), cur_stack.mNodeIdx, cur_stack.mChildIdx);
  521. }
  522. // Encapsulate bounding box in parent
  523. cur_stack.mNodeBoundsMin = Vec3::sMin(cur_stack.mNodeBoundsMin, bounds.mMin);
  524. cur_stack.mNodeBoundsMax = Vec3::sMax(cur_stack.mNodeBoundsMax, bounds.mMax);
  525. }
  526. else if (num_bodies > 1)
  527. {
  528. // Allocate new node
  529. StackEntry &new_stack = stack[++top];
  530. JPH_ASSERT(top < cStackSize / 4);
  531. uint32 next_depth = cur_stack.mDepth + 1;
  532. new_stack.mNodeIdx = AllocateNode(inMaxDepthMarkChanged > next_depth);
  533. new_stack.mChildIdx = -1;
  534. new_stack.mDepth = next_depth;
  535. new_stack.mNodeBoundsMin = Vec3::sReplicate(cLargeFloat);
  536. new_stack.mNodeBoundsMax = Vec3::sReplicate(-cLargeFloat);
  537. sPartition4(ioNodeIDs, centers, low, high, new_stack.mSplit);
  538. }
  539. }
  540. }
  541. // Delete temporary data
  542. delete [] centers;
  543. // Store bounding box of root
  544. outBounds.mMin = stack[0].mNodeBoundsMin;
  545. outBounds.mMax = stack[0].mNodeBoundsMax;
  546. // Return root
  547. return NodeID::sFromNodeIndex(stack[0].mNodeIdx);
  548. }
  549. void QuadTree::MarkNodeAndParentsChanged(uint32 inNodeIndex)
  550. {
  551. uint32 node_idx = inNodeIndex;
  552. do
  553. {
  554. // If node has changed, parent will be too
  555. Node &node = mAllocator->Get(node_idx);
  556. if (node.mIsChanged)
  557. break;
  558. // Mark node as changed
  559. node.mIsChanged = true;
  560. // Get our parent
  561. node_idx = node.mParentNodeIndex;
  562. }
  563. while (node_idx != cInvalidNodeIndex);
  564. }
  565. void QuadTree::WidenAndMarkNodeAndParentsChanged(uint32 inNodeIndex, const AABox &inNewBounds)
  566. {
  567. uint32 node_idx = inNodeIndex;
  568. for (;;)
  569. {
  570. // Mark node as changed
  571. Node &node = mAllocator->Get(node_idx);
  572. node.mIsChanged = true;
  573. // Get our parent
  574. uint32 parent_idx = node.mParentNodeIndex;
  575. if (parent_idx == cInvalidNodeIndex)
  576. break;
  577. // Find which child of the parent we're in
  578. Node &parent_node = mAllocator->Get(parent_idx);
  579. NodeID node_id = NodeID::sFromNodeIndex(node_idx);
  580. int child_idx = -1;
  581. for (int i = 0; i < 4; ++i)
  582. if (parent_node.mChildNodeID[i] == node_id)
  583. {
  584. // Found one, set the node index and child index and update the bounding box too
  585. child_idx = i;
  586. break;
  587. }
  588. JPH_ASSERT(child_idx != -1, "Nodes don't get removed from the tree, we must have found it");
  589. // To avoid any race conditions with other threads we only enlarge bounding boxes
  590. if (!parent_node.EncapsulateChildBounds(child_idx, inNewBounds))
  591. {
  592. // No changes to bounding box, only marking as changed remains to be done
  593. if (!parent_node.mIsChanged)
  594. MarkNodeAndParentsChanged(parent_idx);
  595. break;
  596. }
  597. // Update node index
  598. node_idx = parent_idx;
  599. }
  600. }
  601. bool QuadTree::TryInsertLeaf(TrackingVector &ioTracking, int inNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies)
  602. {
  603. // Tentively assign the node as parent
  604. bool leaf_is_node = inLeafID.IsNode();
  605. if (leaf_is_node)
  606. {
  607. uint32 leaf_idx = inLeafID.GetNodeIndex();
  608. mAllocator->Get(leaf_idx).mParentNodeIndex = inNodeIndex;
  609. }
  610. // Fetch node that we're adding to
  611. Node &node = mAllocator->Get(inNodeIndex);
  612. // Find an empty child
  613. for (uint32 child_idx = 0; child_idx < 4; ++child_idx)
  614. if (node.mChildNodeID[child_idx].CompareExchange(NodeID::sInvalid(), inLeafID)) // Check if we can claim it
  615. {
  616. // We managed to add it to the node
  617. // If leaf was a body, we need to update its bookkeeping
  618. if (!leaf_is_node)
  619. SetBodyLocation(ioTracking, inLeafID.GetBodyID(), inNodeIndex, child_idx);
  620. // Now set the bounding box making the child valid for queries
  621. node.SetChildBounds(child_idx, inLeafBounds);
  622. // Widen the bounds for our parents too
  623. WidenAndMarkNodeAndParentsChanged(inNodeIndex, inLeafBounds);
  624. // Update body counter
  625. mNumBodies += inLeafNumBodies;
  626. // And we're done
  627. return true;
  628. }
  629. return false;
  630. }
  631. bool QuadTree::TryCreateNewRoot(TrackingVector &ioTracking, atomic<uint32> &ioRootNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies)
  632. {
  633. // Fetch old root
  634. uint32 root_idx = ioRootNodeIndex;
  635. Node &root = mAllocator->Get(root_idx);
  636. // Create new root, mark this new root as changed as we're not creating a very efficient tree at this point
  637. uint32 new_root_idx = AllocateNode(true);
  638. Node &new_root = mAllocator->Get(new_root_idx);
  639. // First child is current root, note that since the tree may be modified concurrently we cannot assume that the bounds of our child will be correct so we set a very large bounding box
  640. new_root.mChildNodeID[0] = NodeID::sFromNodeIndex(root_idx);
  641. new_root.SetChildBounds(0, AABox(Vec3::sReplicate(-cLargeFloat), Vec3::sReplicate(cLargeFloat)));
  642. // Second child is new leaf
  643. new_root.mChildNodeID[1] = inLeafID;
  644. new_root.SetChildBounds(1, inLeafBounds);
  645. // Tentatively assign new root as parent
  646. bool leaf_is_node = inLeafID.IsNode();
  647. if (leaf_is_node)
  648. {
  649. uint32 leaf_idx = inLeafID.GetNodeIndex();
  650. mAllocator->Get(leaf_idx).mParentNodeIndex = new_root_idx;
  651. }
  652. // Try to swap it
  653. if (ioRootNodeIndex.compare_exchange_strong(root_idx, new_root_idx))
  654. {
  655. // We managed to set the new root
  656. // If leaf was a body, we need to update its bookkeeping
  657. if (!leaf_is_node)
  658. SetBodyLocation(ioTracking, inLeafID.GetBodyID(), new_root_idx, 1);
  659. // Store parent node for old root
  660. root.mParentNodeIndex = new_root_idx;
  661. // Update body counter
  662. mNumBodies += inLeafNumBodies;
  663. // And we're done
  664. return true;
  665. }
  666. // Failed to swap, someone else must have created a new root, try again
  667. mAllocator->DestructObject(new_root_idx);
  668. return false;
  669. }
  670. void QuadTree::AddBodiesPrepare(const BodyVector &inBodies, TrackingVector &ioTracking, BodyID *ioBodyIDs, int inNumber, AddState &outState)
  671. {
  672. // Assert sane input
  673. JPH_ASSERT(ioBodyIDs != nullptr);
  674. JPH_ASSERT(inNumber > 0);
  675. #ifdef JPH_ENABLE_ASSERTS
  676. // Below we just cast the body ID's to node ID's, check here that that is valid
  677. for (const BodyID *b = ioBodyIDs, *b_end = ioBodyIDs + inNumber; b < b_end; ++b)
  678. NodeID::sFromBodyID(*b);
  679. #endif
  680. // Build subtree for the new bodies, note that we mark all nodes as 'not changed'
  681. // so they will stay together as a batch and will make the tree rebuild cheaper
  682. outState.mLeafID = BuildTree(inBodies, ioTracking, (NodeID *)ioBodyIDs, inNumber, 0, outState.mLeafBounds);
  683. #ifdef JPH_DEBUG
  684. if (outState.mLeafID.IsNode())
  685. ValidateTree(inBodies, ioTracking, outState.mLeafID.GetNodeIndex(), inNumber);
  686. #endif
  687. }
  688. void QuadTree::AddBodiesFinalize(TrackingVector &ioTracking, int inNumberBodies, const AddState &inState)
  689. {
  690. // Assert sane input
  691. JPH_ASSERT(inNumberBodies > 0);
  692. // Mark tree dirty
  693. mIsDirty = true;
  694. // Get the current root node
  695. RootNode &root_node = GetCurrentRoot();
  696. for (;;)
  697. {
  698. // Check if we can insert the body in the root
  699. if (TryInsertLeaf(ioTracking, root_node.mIndex, inState.mLeafID, inState.mLeafBounds, inNumberBodies))
  700. return;
  701. // Check if we can create a new root
  702. if (TryCreateNewRoot(ioTracking, root_node.mIndex, inState.mLeafID, inState.mLeafBounds, inNumberBodies))
  703. return;
  704. }
  705. }
  706. void QuadTree::AddBodiesAbort(TrackingVector &ioTracking, const AddState &inState)
  707. {
  708. // Collect all bodies
  709. Allocator::Batch free_batch;
  710. NodeID node_stack[cStackSize];
  711. node_stack[0] = inState.mLeafID;
  712. JPH_ASSERT(node_stack[0].IsValid());
  713. int top = 0;
  714. do
  715. {
  716. // Check if node is a body
  717. NodeID child_node_id = node_stack[top];
  718. if (child_node_id.IsBody())
  719. {
  720. // Reset location of body
  721. sInvalidateBodyLocation(ioTracking, child_node_id.GetBodyID());
  722. }
  723. else
  724. {
  725. // Process normal node
  726. uint32 node_idx = child_node_id.GetNodeIndex();
  727. const Node &node = mAllocator->Get(node_idx);
  728. for (NodeID sub_child_node_id : node.mChildNodeID)
  729. if (sub_child_node_id.IsValid())
  730. {
  731. JPH_ASSERT(top < cStackSize);
  732. node_stack[top] = sub_child_node_id;
  733. top++;
  734. }
  735. // Mark it to be freed
  736. mAllocator->AddObjectToBatch(free_batch, node_idx);
  737. }
  738. --top;
  739. }
  740. while (top >= 0);
  741. // Now free all nodes as a single batch
  742. mAllocator->DestructObjectBatch(free_batch);
  743. }
  744. void QuadTree::RemoveBodies([[maybe_unused]] const BodyVector &inBodies, TrackingVector &ioTracking, const BodyID *ioBodyIDs, int inNumber)
  745. {
  746. // Assert sane input
  747. JPH_ASSERT(ioBodyIDs != nullptr);
  748. JPH_ASSERT(inNumber > 0);
  749. // Mark tree dirty
  750. mIsDirty = true;
  751. for (const BodyID *cur = ioBodyIDs, *end = ioBodyIDs + inNumber; cur < end; ++cur)
  752. {
  753. // Check if BodyID is correct
  754. JPH_ASSERT(inBodies[cur->GetIndex()]->GetID() == *cur, "Provided BodyID doesn't match BodyID in body manager");
  755. // Get location of body
  756. uint32 node_idx, child_idx;
  757. GetBodyLocation(ioTracking, *cur, node_idx, child_idx);
  758. // First we reset our internal bookkeeping
  759. sInvalidateBodyLocation(ioTracking, *cur);
  760. // Then we make the bounding box invalid, no queries can find this node anymore
  761. Node &node = mAllocator->Get(node_idx);
  762. node.InvalidateChildBounds(child_idx);
  763. // Finally we reset the child id, this makes the node available for adds again
  764. node.mChildNodeID[child_idx] = NodeID::sInvalid();
  765. // We don't need to bubble up our bounding box changes to our parents since we never make volumes smaller, only bigger
  766. // But we do need to mark the nodes as changed so that the tree can be rebuilt
  767. MarkNodeAndParentsChanged(node_idx);
  768. }
  769. mNumBodies -= inNumber;
  770. }
  771. void QuadTree::NotifyBodiesAABBChanged(const BodyVector &inBodies, const TrackingVector &inTracking, const BodyID *ioBodyIDs, int inNumber)
  772. {
  773. // Assert sane input
  774. JPH_ASSERT(ioBodyIDs != nullptr);
  775. JPH_ASSERT(inNumber > 0);
  776. for (const BodyID *cur = ioBodyIDs, *end = ioBodyIDs + inNumber; cur < end; ++cur)
  777. {
  778. // Check if BodyID is correct
  779. const Body *body = inBodies[cur->GetIndex()];
  780. JPH_ASSERT(body->GetID() == *cur, "Provided BodyID doesn't match BodyID in body manager");
  781. // Get the new bounding box
  782. const AABox &new_bounds = body->GetWorldSpaceBounds();
  783. // Get location of body
  784. uint32 node_idx, child_idx;
  785. GetBodyLocation(inTracking, *cur, node_idx, child_idx);
  786. // Widen bounds for node
  787. Node &node = mAllocator->Get(node_idx);
  788. if (node.EncapsulateChildBounds(child_idx, new_bounds))
  789. {
  790. // Mark tree dirty
  791. mIsDirty = true;
  792. // If bounds changed, widen the bounds for our parents too
  793. WidenAndMarkNodeAndParentsChanged(node_idx, new_bounds);
  794. }
  795. }
  796. }
  797. template <class Visitor>
  798. JPH_INLINE void QuadTree::WalkTree(const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking, Visitor &ioVisitor JPH_IF_TRACK_BROADPHASE_STATS(, LayerToStats &ioStats)) const
  799. {
  800. // Get the root
  801. const RootNode &root_node = GetCurrentRoot();
  802. #ifdef JPH_TRACK_BROADPHASE_STATS
  803. // Start tracking stats
  804. int bodies_visited = 0;
  805. int hits_collected = 0;
  806. int nodes_visited = 0;
  807. uint64 collector_ticks = 0;
  808. uint64 start = GetProcessorTickCount();
  809. #endif // JPH_TRACK_BROADPHASE_STATS
  810. NodeID node_stack[cStackSize];
  811. node_stack[0] = root_node.GetNodeID();
  812. int top = 0;
  813. do
  814. {
  815. // Check if node is a body
  816. NodeID child_node_id = node_stack[top];
  817. if (child_node_id.IsBody())
  818. {
  819. // Track amount of bodies visited
  820. JPH_IF_TRACK_BROADPHASE_STATS(++bodies_visited;)
  821. BodyID body_id = child_node_id.GetBodyID();
  822. ObjectLayer object_layer = inTracking[body_id.GetIndex()].mObjectLayer; // We're not taking a lock on the body, so it may be in the process of being removed so check if the object layer is invalid
  823. if (object_layer != cObjectLayerInvalid && inObjectLayerFilter.ShouldCollide(object_layer))
  824. {
  825. JPH_PROFILE("VisitBody");
  826. // Track amount of hits
  827. JPH_IF_TRACK_BROADPHASE_STATS(++hits_collected;)
  828. // Start track time the collector takes
  829. JPH_IF_TRACK_BROADPHASE_STATS(uint64 collector_start = GetProcessorTickCount();)
  830. // We found a body we collide with, call our visitor
  831. ioVisitor.VisitBody(body_id, top);
  832. // End track time the collector takes
  833. JPH_IF_TRACK_BROADPHASE_STATS(collector_ticks += GetProcessorTickCount() - collector_start;)
  834. // Check if we're done
  835. if (ioVisitor.ShouldAbort())
  836. break;
  837. }
  838. }
  839. else if (child_node_id.IsValid())
  840. {
  841. JPH_IF_TRACK_BROADPHASE_STATS(++nodes_visited;)
  842. // Check if stack can hold more nodes
  843. if (top + 4 < cStackSize)
  844. {
  845. // Process normal node
  846. const Node &node = mAllocator->Get(child_node_id.GetNodeIndex());
  847. JPH_ASSERT(IsAligned(&node, JPH_CACHE_LINE_SIZE));
  848. // Load bounds of 4 children
  849. Vec4 bounds_minx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinX);
  850. Vec4 bounds_miny = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinY);
  851. Vec4 bounds_minz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinZ);
  852. Vec4 bounds_maxx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxX);
  853. Vec4 bounds_maxy = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxY);
  854. Vec4 bounds_maxz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxZ);
  855. // Load ids for 4 children
  856. UVec4 child_ids = UVec4::sLoadInt4Aligned((const uint32 *)&node.mChildNodeID[0]);
  857. // Check which sub nodes to visit
  858. int num_results = ioVisitor.VisitNodes(bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz, child_ids, top);
  859. child_ids.StoreInt4((uint32 *)&node_stack[top]);
  860. top += num_results;
  861. }
  862. else
  863. JPH_ASSERT(false, "Stack full!\n"
  864. "This must be a very deep tree. Are you batch adding bodies through BodyInterface::AddBodiesPrepare/AddBodiesFinalize?\n"
  865. "If you add lots of bodies through BodyInterface::AddBody you may need to call PhysicsSystem::OptimizeBroadPhase to rebuild the tree.");
  866. }
  867. // Fetch next node until we find one that the visitor wants to see
  868. do
  869. --top;
  870. while (top >= 0 && !ioVisitor.ShouldVisitNode(top));
  871. }
  872. while (top >= 0);
  873. #ifdef JPH_TRACK_BROADPHASE_STATS
  874. // Calculate total time the broadphase walk took
  875. uint64 total_ticks = GetProcessorTickCount() - start;
  876. // Update stats under lock protection (slow!)
  877. {
  878. unique_lock lock(mStatsMutex);
  879. Stat &s = ioStats[inObjectLayerFilter.GetDescription()];
  880. s.mNumQueries++;
  881. s.mNodesVisited += nodes_visited;
  882. s.mBodiesVisited += bodies_visited;
  883. s.mHitsReported += hits_collected;
  884. s.mTotalTicks += total_ticks;
  885. s.mCollectorTicks += collector_ticks;
  886. }
  887. #endif // JPH_TRACK_BROADPHASE_STATS
  888. }
  889. void QuadTree::CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  890. {
  891. class Visitor
  892. {
  893. public:
  894. /// Constructor
  895. JPH_INLINE Visitor(const RayCast &inRay, RayCastBodyCollector &ioCollector) :
  896. mOrigin(inRay.mOrigin),
  897. mInvDirection(inRay.mDirection),
  898. mCollector(ioCollector)
  899. {
  900. mFractionStack[0] = -1;
  901. }
  902. /// Returns true if further processing of the tree should be aborted
  903. JPH_INLINE bool ShouldAbort() const
  904. {
  905. return mCollector.ShouldEarlyOut();
  906. }
  907. /// Returns true if this node / body should be visited, false if no hit can be generated
  908. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  909. {
  910. return mFractionStack[inStackTop] < mCollector.GetEarlyOutFraction();
  911. }
  912. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  913. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop)
  914. {
  915. // Test the ray against 4 bounding boxes
  916. Vec4 fraction = RayAABox4(mOrigin, mInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  917. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  918. return SortReverseAndStore(fraction, mCollector.GetEarlyOutFraction(), ioChildNodeIDs, &mFractionStack[inStackTop]);
  919. }
  920. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  921. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  922. {
  923. // Store potential hit with body
  924. BroadPhaseCastResult result { inBodyID, mFractionStack[inStackTop] };
  925. mCollector.AddHit(result);
  926. }
  927. private:
  928. Vec3 mOrigin;
  929. RayInvDirection mInvDirection;
  930. RayCastBodyCollector & mCollector;
  931. float mFractionStack[cStackSize];
  932. };
  933. Visitor visitor(inRay, ioCollector);
  934. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCastRayStats));
  935. }
  936. void QuadTree::CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  937. {
  938. class Visitor
  939. {
  940. public:
  941. /// Constructor
  942. JPH_INLINE Visitor(const AABox &inBox, CollideShapeBodyCollector &ioCollector) :
  943. mBox(inBox),
  944. mCollector(ioCollector)
  945. {
  946. }
  947. /// Returns true if further processing of the tree should be aborted
  948. JPH_INLINE bool ShouldAbort() const
  949. {
  950. return mCollector.ShouldEarlyOut();
  951. }
  952. /// Returns true if this node / body should be visited, false if no hit can be generated
  953. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  954. {
  955. return true;
  956. }
  957. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  958. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  959. {
  960. // Test the box vs 4 boxes
  961. UVec4 hitting = AABox4VsBox(mBox, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  962. return CountAndSortTrues(hitting, ioChildNodeIDs);
  963. }
  964. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  965. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  966. {
  967. // Store potential hit with body
  968. mCollector.AddHit(inBodyID);
  969. }
  970. private:
  971. const AABox & mBox;
  972. CollideShapeBodyCollector & mCollector;
  973. };
  974. Visitor visitor(inBox, ioCollector);
  975. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollideAABoxStats));
  976. }
  977. void QuadTree::CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  978. {
  979. class Visitor
  980. {
  981. public:
  982. /// Constructor
  983. JPH_INLINE Visitor(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector) :
  984. mCenterX(inCenter.SplatX()),
  985. mCenterY(inCenter.SplatY()),
  986. mCenterZ(inCenter.SplatZ()),
  987. mRadiusSq(Vec4::sReplicate(Square(inRadius))),
  988. mCollector(ioCollector)
  989. {
  990. }
  991. /// Returns true if further processing of the tree should be aborted
  992. JPH_INLINE bool ShouldAbort() const
  993. {
  994. return mCollector.ShouldEarlyOut();
  995. }
  996. /// Returns true if this node / body should be visited, false if no hit can be generated
  997. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  998. {
  999. return true;
  1000. }
  1001. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1002. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  1003. {
  1004. // Test 4 boxes vs sphere
  1005. UVec4 hitting = AABox4VsSphere(mCenterX, mCenterY, mCenterZ, mRadiusSq, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1006. return CountAndSortTrues(hitting, ioChildNodeIDs);
  1007. }
  1008. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1009. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1010. {
  1011. // Store potential hit with body
  1012. mCollector.AddHit(inBodyID);
  1013. }
  1014. private:
  1015. Vec4 mCenterX;
  1016. Vec4 mCenterY;
  1017. Vec4 mCenterZ;
  1018. Vec4 mRadiusSq;
  1019. CollideShapeBodyCollector & mCollector;
  1020. };
  1021. Visitor visitor(inCenter, inRadius, ioCollector);
  1022. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollideSphereStats));
  1023. }
  1024. void QuadTree::CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  1025. {
  1026. class Visitor
  1027. {
  1028. public:
  1029. /// Constructor
  1030. JPH_INLINE Visitor(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector) :
  1031. mPoint(inPoint),
  1032. mCollector(ioCollector)
  1033. {
  1034. }
  1035. /// Returns true if further processing of the tree should be aborted
  1036. JPH_INLINE bool ShouldAbort() const
  1037. {
  1038. return mCollector.ShouldEarlyOut();
  1039. }
  1040. /// Returns true if this node / body should be visited, false if no hit can be generated
  1041. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  1042. {
  1043. return true;
  1044. }
  1045. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1046. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  1047. {
  1048. // Test if point overlaps with box
  1049. UVec4 hitting = AABox4VsPoint(mPoint, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1050. return CountAndSortTrues(hitting, ioChildNodeIDs);
  1051. }
  1052. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1053. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1054. {
  1055. // Store potential hit with body
  1056. mCollector.AddHit(inBodyID);
  1057. }
  1058. private:
  1059. Vec3 mPoint;
  1060. CollideShapeBodyCollector & mCollector;
  1061. };
  1062. Visitor visitor(inPoint, ioCollector);
  1063. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollidePointStats));
  1064. }
  1065. void QuadTree::CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  1066. {
  1067. class Visitor
  1068. {
  1069. public:
  1070. /// Constructor
  1071. JPH_INLINE Visitor(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector) :
  1072. mBox(inBox),
  1073. mCollector(ioCollector)
  1074. {
  1075. }
  1076. /// Returns true if further processing of the tree should be aborted
  1077. JPH_INLINE bool ShouldAbort() const
  1078. {
  1079. return mCollector.ShouldEarlyOut();
  1080. }
  1081. /// Returns true if this node / body should be visited, false if no hit can be generated
  1082. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  1083. {
  1084. return true;
  1085. }
  1086. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1087. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  1088. {
  1089. // Test if point overlaps with box
  1090. UVec4 hitting = AABox4VsBox(mBox, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1091. return CountAndSortTrues(hitting, ioChildNodeIDs);
  1092. }
  1093. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1094. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1095. {
  1096. // Store potential hit with body
  1097. mCollector.AddHit(inBodyID);
  1098. }
  1099. private:
  1100. OrientedBox mBox;
  1101. CollideShapeBodyCollector & mCollector;
  1102. };
  1103. Visitor visitor(inBox, ioCollector);
  1104. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollideOrientedBoxStats));
  1105. }
  1106. void QuadTree::CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  1107. {
  1108. class Visitor
  1109. {
  1110. public:
  1111. /// Constructor
  1112. JPH_INLINE Visitor(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector) :
  1113. mOrigin(inBox.mBox.GetCenter()),
  1114. mExtent(inBox.mBox.GetExtent()),
  1115. mInvDirection(inBox.mDirection),
  1116. mCollector(ioCollector)
  1117. {
  1118. mFractionStack[0] = -1;
  1119. }
  1120. /// Returns true if further processing of the tree should be aborted
  1121. JPH_INLINE bool ShouldAbort() const
  1122. {
  1123. return mCollector.ShouldEarlyOut();
  1124. }
  1125. /// Returns true if this node / body should be visited, false if no hit can be generated
  1126. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  1127. {
  1128. return mFractionStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  1129. }
  1130. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1131. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop)
  1132. {
  1133. // Enlarge them by the casted aabox extents
  1134. Vec4 bounds_min_x = inBoundsMinX, bounds_min_y = inBoundsMinY, bounds_min_z = inBoundsMinZ, bounds_max_x = inBoundsMaxX, bounds_max_y = inBoundsMaxY, bounds_max_z = inBoundsMaxZ;
  1135. AABox4EnlargeWithExtent(mExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1136. // Test 4 children
  1137. Vec4 fraction = RayAABox4(mOrigin, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1138. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1139. return SortReverseAndStore(fraction, mCollector.GetPositiveEarlyOutFraction(), ioChildNodeIDs, &mFractionStack[inStackTop]);
  1140. }
  1141. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1142. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1143. {
  1144. // Store potential hit with body
  1145. BroadPhaseCastResult result { inBodyID, mFractionStack[inStackTop] };
  1146. mCollector.AddHit(result);
  1147. }
  1148. private:
  1149. Vec3 mOrigin;
  1150. Vec3 mExtent;
  1151. RayInvDirection mInvDirection;
  1152. CastShapeBodyCollector & mCollector;
  1153. float mFractionStack[cStackSize];
  1154. };
  1155. Visitor visitor(inBox, ioCollector);
  1156. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCastAABoxStats));
  1157. }
  1158. void QuadTree::FindCollidingPairs(const BodyVector &inBodies, const BodyID *inActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, BodyPairCollector &ioPairCollector, const ObjectLayerPairFilter &inObjectLayerPairFilter) const
  1159. {
  1160. // Note that we don't lock the tree at this point. We know that the tree is not going to be swapped or deleted while finding collision pairs due to the way the jobs are scheduled in the PhysicsSystem::Update.
  1161. // We double check this at the end of the function.
  1162. const RootNode &root_node = GetCurrentRoot();
  1163. JPH_ASSERT(root_node.mIndex != cInvalidNodeIndex);
  1164. // Assert sane input
  1165. JPH_ASSERT(inActiveBodies != nullptr);
  1166. JPH_ASSERT(inNumActiveBodies > 0);
  1167. NodeID node_stack[cStackSize];
  1168. // Loop over all active bodies
  1169. for (int b1 = 0; b1 < inNumActiveBodies; ++b1)
  1170. {
  1171. BodyID b1_id = inActiveBodies[b1];
  1172. const Body &body1 = *inBodies[b1_id.GetIndex()];
  1173. JPH_ASSERT(!body1.IsStatic());
  1174. // Expand the bounding box by the speculative contact distance
  1175. AABox bounds1 = body1.GetWorldSpaceBounds();
  1176. bounds1.ExpandBy(Vec3::sReplicate(inSpeculativeContactDistance));
  1177. // Test each body with the tree
  1178. node_stack[0] = root_node.GetNodeID();
  1179. int top = 0;
  1180. do
  1181. {
  1182. // Check if node is a body
  1183. NodeID child_node_id = node_stack[top];
  1184. if (child_node_id.IsBody())
  1185. {
  1186. // Don't collide with self
  1187. BodyID b2_id = child_node_id.GetBodyID();
  1188. if (b1_id != b2_id)
  1189. {
  1190. // Collision between dynamic pairs need to be picked up only once
  1191. const Body &body2 = *inBodies[b2_id.GetIndex()];
  1192. if (inObjectLayerPairFilter.ShouldCollide(body1.GetObjectLayer(), body2.GetObjectLayer())
  1193. && Body::sFindCollidingPairsCanCollide(body1, body2)
  1194. && bounds1.Overlaps(body2.GetWorldSpaceBounds())) // In the broadphase we widen the bounding box when a body moves, do a final check to see if the bounding boxes actually overlap
  1195. {
  1196. // Store potential hit between bodies
  1197. ioPairCollector.AddHit({ b1_id, b2_id });
  1198. }
  1199. }
  1200. }
  1201. else if (child_node_id.IsValid())
  1202. {
  1203. // Process normal node
  1204. const Node &node = mAllocator->Get(child_node_id.GetNodeIndex());
  1205. JPH_ASSERT(IsAligned(&node, JPH_CACHE_LINE_SIZE));
  1206. // Get bounds of 4 children
  1207. Vec4 bounds_minx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinX);
  1208. Vec4 bounds_miny = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinY);
  1209. Vec4 bounds_minz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinZ);
  1210. Vec4 bounds_maxx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxX);
  1211. Vec4 bounds_maxy = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxY);
  1212. Vec4 bounds_maxz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxZ);
  1213. // Test overlap
  1214. UVec4 overlap = AABox4VsBox(bounds1, bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz);
  1215. int num_results = overlap.CountTrues();
  1216. if (num_results > 0)
  1217. {
  1218. // Load ids for 4 children
  1219. UVec4 child_ids = UVec4::sLoadInt4Aligned((const uint32 *)&node.mChildNodeID[0]);
  1220. // Sort so that overlaps are first
  1221. child_ids = UVec4::sSort4True(overlap, child_ids);
  1222. // Push them onto the stack
  1223. if (top + 4 < cStackSize)
  1224. {
  1225. child_ids.StoreInt4((uint32 *)&node_stack[top]);
  1226. top += num_results;
  1227. }
  1228. else
  1229. JPH_ASSERT(false, "Stack full!\n"
  1230. "This must be a very deep tree. Are you batch adding bodies through BodyInterface::AddBodiesPrepare/AddBodiesFinalize?\n"
  1231. "If you add lots of bodies through BodyInterface::AddBody you may need to call PhysicsSystem::OptimizeBroadPhase to rebuild the tree.");
  1232. }
  1233. }
  1234. --top;
  1235. }
  1236. while (top >= 0);
  1237. }
  1238. // Test that the root node was not swapped while finding collision pairs.
  1239. // This would mean that UpdateFinalize/DiscardOldTree ran during collision detection which should not be possible due to the way the jobs are scheduled.
  1240. JPH_ASSERT(root_node.mIndex != cInvalidNodeIndex);
  1241. JPH_ASSERT(&root_node == &GetCurrentRoot());
  1242. }
  1243. #ifdef JPH_DEBUG
  1244. void QuadTree::ValidateTree(const BodyVector &inBodies, const TrackingVector &inTracking, uint32 inNodeIndex, uint32 inNumExpectedBodies) const
  1245. {
  1246. JPH_PROFILE_FUNCTION();
  1247. // Root should be valid
  1248. JPH_ASSERT(inNodeIndex != cInvalidNodeIndex);
  1249. // To avoid call overhead, create a stack in place
  1250. struct StackEntry
  1251. {
  1252. uint32 mNodeIndex;
  1253. uint32 mParentNodeIndex;
  1254. };
  1255. StackEntry stack[cStackSize];
  1256. stack[0].mNodeIndex = inNodeIndex;
  1257. stack[0].mParentNodeIndex = cInvalidNodeIndex;
  1258. int top = 0;
  1259. uint32 num_bodies = 0;
  1260. do
  1261. {
  1262. // Copy entry from the stack
  1263. StackEntry cur_stack = stack[top];
  1264. // Validate parent
  1265. const Node &node = mAllocator->Get(cur_stack.mNodeIndex);
  1266. JPH_ASSERT(node.mParentNodeIndex == cur_stack.mParentNodeIndex);
  1267. // Validate that when a parent is not-changed that all of its children are also
  1268. JPH_ASSERT(cur_stack.mParentNodeIndex == cInvalidNodeIndex || mAllocator->Get(cur_stack.mParentNodeIndex).mIsChanged || !node.mIsChanged);
  1269. // Loop children
  1270. for (uint32 i = 0; i < 4; ++i)
  1271. {
  1272. NodeID child_node_id = node.mChildNodeID[i];
  1273. if (child_node_id.IsValid())
  1274. {
  1275. if (child_node_id.IsNode())
  1276. {
  1277. // Child is a node, recurse
  1278. uint32 child_idx = child_node_id.GetNodeIndex();
  1279. JPH_ASSERT(top < cStackSize);
  1280. StackEntry &new_entry = stack[top++];
  1281. new_entry.mNodeIndex = child_idx;
  1282. new_entry.mParentNodeIndex = cur_stack.mNodeIndex;
  1283. // Validate that the bounding box is bigger or equal to the bounds in the tree
  1284. // Bounding box could also be invalid if all children of our child were removed
  1285. AABox child_bounds;
  1286. node.GetChildBounds(i, child_bounds);
  1287. AABox real_child_bounds;
  1288. mAllocator->Get(child_idx).GetNodeBounds(real_child_bounds);
  1289. JPH_ASSERT(child_bounds.Contains(real_child_bounds) || !real_child_bounds.IsValid());
  1290. }
  1291. else
  1292. {
  1293. // Increment number of bodies found
  1294. ++num_bodies;
  1295. // Check if tracker matches position of body
  1296. uint32 node_idx, child_idx;
  1297. GetBodyLocation(inTracking, child_node_id.GetBodyID(), node_idx, child_idx);
  1298. JPH_ASSERT(node_idx == cur_stack.mNodeIndex);
  1299. JPH_ASSERT(child_idx == i);
  1300. // Validate that the body bounds are bigger or equal to the bounds in the tree
  1301. AABox body_bounds;
  1302. node.GetChildBounds(i, body_bounds);
  1303. const Body *body = inBodies[child_node_id.GetBodyID().GetIndex()];
  1304. AABox cached_body_bounds = body->GetWorldSpaceBounds();
  1305. AABox real_body_bounds = body->GetShape()->GetWorldSpaceBounds(body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f));
  1306. JPH_ASSERT(cached_body_bounds == real_body_bounds); // Check that cached body bounds are up to date
  1307. JPH_ASSERT(body_bounds.Contains(real_body_bounds));
  1308. }
  1309. }
  1310. }
  1311. --top;
  1312. }
  1313. while (top >= 0);
  1314. // Check that the amount of bodies in the tree matches our counter
  1315. JPH_ASSERT(num_bodies == inNumExpectedBodies);
  1316. }
  1317. #endif
  1318. #ifdef JPH_DUMP_BROADPHASE_TREE
  1319. void QuadTree::DumpTree(const NodeID &inRoot, const char *inFileNamePrefix) const
  1320. {
  1321. // Open DOT file
  1322. std::ofstream f;
  1323. f.open(StringFormat("%s.dot", inFileNamePrefix).c_str(), std::ofstream::out | std::ofstream::trunc);
  1324. if (!f.is_open())
  1325. return;
  1326. // Write header
  1327. f << "digraph {\n";
  1328. // Iterate the entire tree
  1329. NodeID node_stack[cStackSize];
  1330. node_stack[0] = inRoot;
  1331. JPH_ASSERT(node_stack[0].IsValid());
  1332. int top = 0;
  1333. do
  1334. {
  1335. // Check if node is a body
  1336. NodeID node_id = node_stack[top];
  1337. if (node_id.IsBody())
  1338. {
  1339. // Output body
  1340. String body_id = ConvertToString(node_id.GetBodyID().GetIndex());
  1341. f << "body" << body_id << "[label = \"Body " << body_id << "\"]\n";
  1342. }
  1343. else
  1344. {
  1345. // Process normal node
  1346. uint32 node_idx = node_id.GetNodeIndex();
  1347. const Node &node = mAllocator->Get(node_idx);
  1348. // Get bounding box
  1349. AABox bounds;
  1350. node.GetNodeBounds(bounds);
  1351. // Output node
  1352. String node_str = ConvertToString(node_idx);
  1353. f << "node" << node_str << "[label = \"Node " << node_str << "\nVolume: " << ConvertToString(bounds.GetVolume()) << "\" color=" << (node.mIsChanged? "red" : "black") << "]\n";
  1354. // Recurse and get all children
  1355. for (NodeID child_node_id : node.mChildNodeID)
  1356. if (child_node_id.IsValid())
  1357. {
  1358. JPH_ASSERT(top < cStackSize);
  1359. node_stack[top] = child_node_id;
  1360. top++;
  1361. // Output link
  1362. f << "node" << node_str << " -> ";
  1363. if (child_node_id.IsBody())
  1364. f << "body" << ConvertToString(child_node_id.GetBodyID().GetIndex());
  1365. else
  1366. f << "node" << ConvertToString(child_node_id.GetNodeIndex());
  1367. f << "\n";
  1368. }
  1369. }
  1370. --top;
  1371. }
  1372. while (top >= 0);
  1373. // Finish DOT file
  1374. f << "}\n";
  1375. f.close();
  1376. // Convert to svg file
  1377. String cmd = StringFormat("dot %s.dot -Tsvg -o %s.svg", inFileNamePrefix, inFileNamePrefix);
  1378. system(cmd.c_str());
  1379. }
  1380. #endif // JPH_DUMP_BROADPHASE_TREE
  1381. #ifdef JPH_TRACK_BROADPHASE_STATS
  1382. uint64 QuadTree::GetTicks100Pct(const LayerToStats &inLayer) const
  1383. {
  1384. uint64 total_ticks = 0;
  1385. for (const LayerToStats::value_type &kv : inLayer)
  1386. total_ticks += kv.second.mTotalTicks;
  1387. return total_ticks;
  1388. }
  1389. void QuadTree::ReportStats(const char *inName, const LayerToStats &inLayer, uint64 inTicks100Pct) const
  1390. {
  1391. for (const LayerToStats::value_type &kv : inLayer)
  1392. {
  1393. double total_pct = 100.0 * double(kv.second.mTotalTicks) / double(inTicks100Pct);
  1394. double total_pct_excl_collector = 100.0 * double(kv.second.mTotalTicks - kv.second.mCollectorTicks) / double(inTicks100Pct);
  1395. double hits_reported_vs_bodies_visited = kv.second.mBodiesVisited > 0? 100.0 * double(kv.second.mHitsReported) / double(kv.second.mBodiesVisited) : 100.0;
  1396. double hits_reported_vs_nodes_visited = kv.second.mNodesVisited > 0? double(kv.second.mHitsReported) / double(kv.second.mNodesVisited) : -1.0;
  1397. std::stringstream str;
  1398. str << inName << ", " << kv.first << ", " << mName << ", " << kv.second.mNumQueries << ", " << total_pct << ", " << total_pct_excl_collector << ", " << kv.second.mNodesVisited << ", " << kv.second.mBodiesVisited << ", " << kv.second.mHitsReported << ", " << hits_reported_vs_bodies_visited << ", " << hits_reported_vs_nodes_visited;
  1399. Trace(str.str().c_str());
  1400. }
  1401. }
  1402. uint64 QuadTree::GetTicks100Pct() const
  1403. {
  1404. uint64 total_ticks = 0;
  1405. total_ticks += GetTicks100Pct(mCastRayStats);
  1406. total_ticks += GetTicks100Pct(mCollideAABoxStats);
  1407. total_ticks += GetTicks100Pct(mCollideSphereStats);
  1408. total_ticks += GetTicks100Pct(mCollidePointStats);
  1409. total_ticks += GetTicks100Pct(mCollideOrientedBoxStats);
  1410. total_ticks += GetTicks100Pct(mCastAABoxStats);
  1411. return total_ticks;
  1412. }
  1413. void QuadTree::ReportStats(uint64 inTicks100Pct) const
  1414. {
  1415. unique_lock lock(mStatsMutex);
  1416. ReportStats("RayCast", mCastRayStats, inTicks100Pct);
  1417. ReportStats("CollideAABox", mCollideAABoxStats, inTicks100Pct);
  1418. ReportStats("CollideSphere", mCollideSphereStats, inTicks100Pct);
  1419. ReportStats("CollidePoint", mCollidePointStats, inTicks100Pct);
  1420. ReportStats("CollideOrientedBox", mCollideOrientedBoxStats, inTicks100Pct);
  1421. ReportStats("CastAABox", mCastAABoxStats, inTicks100Pct);
  1422. }
  1423. #endif // JPH_TRACK_BROADPHASE_STATS
  1424. uint QuadTree::GetMaxTreeDepth(const NodeID &inNodeID) const
  1425. {
  1426. // Reached a leaf?
  1427. if (!inNodeID.IsValid() || inNodeID.IsBody())
  1428. return 0;
  1429. // Recurse to children
  1430. uint max_depth = 0;
  1431. const Node &node = mAllocator->Get(inNodeID.GetNodeIndex());
  1432. for (NodeID child_node_id : node.mChildNodeID)
  1433. max_depth = max(max_depth, GetMaxTreeDepth(child_node_id));
  1434. return max_depth + 1;
  1435. }
  1436. JPH_NAMESPACE_END