QuadTree.cpp 55 KB

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