QuadTree.cpp 53 KB

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