DynamicTree.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /*
  2. * Box2D.XNA port of Box2D:
  3. * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
  4. *
  5. * Original source Box2D:
  6. * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
  7. *
  8. * This software is provided 'as-is', without any express or implied
  9. * warranty. In no event will the authors be held liable for any damages
  10. * arising from the use of this software.
  11. * Permission is granted to anyone to use this software for any purpose,
  12. * including commercial applications, and to alter it and redistribute it
  13. * freely, subject to the following restrictions:
  14. * 1. The origin of this software must not be misrepresented; you must not
  15. * claim that you wrote the original software. If you use this software
  16. * in a product, an acknowledgment in the product documentation would be
  17. * appreciated but is not required.
  18. * 2. Altered source versions must be plainly marked as such, and must not be
  19. * misrepresented as being the original software.
  20. * 3. This notice may not be removed or altered from any source distribution.
  21. */
  22. using System;
  23. using System.Diagnostics;
  24. using Microsoft.Xna.Framework;
  25. using System.Collections;
  26. using System.Collections.Generic;
  27. namespace Box2D.XNA
  28. {
  29. /// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
  30. internal delegate float RayCastCallbackInternal(ref RayCastInput input, int userData);
  31. /// A node in the dynamic tree. The client does not interact with this directly.
  32. internal struct DynamicTreeNode
  33. {
  34. internal bool IsLeaf()
  35. {
  36. return child1 == DynamicTree.NullNode;
  37. }
  38. /// This is the fattened AABB.
  39. internal AABB aabb;
  40. internal object userData;
  41. internal int parentOrNext;
  42. internal int child1;
  43. internal int child2;
  44. internal int leafCount;
  45. };
  46. /// A dynamic tree arranges data in a binary tree to accelerate
  47. /// queries such as volume queries and ray casts. Leafs are proxies
  48. /// with an AABB. In the tree we expand the proxy AABB by Settings.b2_fatAABBFactor
  49. /// so that the proxy AABB is bigger than the client object. This allows the client
  50. /// object to move by small amounts without triggering a tree update.
  51. ///
  52. /// Nodes are pooled and relocatable, so we use node indices rather than pointers.
  53. public class DynamicTree
  54. {
  55. internal static int NullNode = -1;
  56. /// ructing the tree initializes the node pool.
  57. public DynamicTree()
  58. {
  59. _root = NullNode;
  60. _nodeCapacity = 16;
  61. _nodeCount = 0;
  62. _nodes = new DynamicTreeNode[_nodeCapacity];
  63. // Build a linked list for the free list.
  64. for (int i = 0; i < _nodeCapacity - 1; ++i)
  65. {
  66. _nodes[i].parentOrNext = i + 1;
  67. }
  68. _nodes[_nodeCapacity - 1].parentOrNext = NullNode;
  69. _freeList = 0;
  70. _path = 0;
  71. }
  72. /// Create a proxy. Provide a tight fitting AABB and a userData pointer.
  73. public int CreateProxy(ref AABB aabb, object userData)
  74. {
  75. int proxyId = AllocateNode();
  76. // Fatten the aabb.
  77. Vector2 r = new Vector2(Settings.b2_aabbExtension, Settings.b2_aabbExtension);
  78. _nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r;
  79. _nodes[proxyId].aabb.upperBound = aabb.upperBound + r;
  80. _nodes[proxyId].userData = userData;
  81. _nodes[proxyId].leafCount = 1;
  82. InsertLeaf(proxyId);
  83. // Rebalance if necessary.
  84. int iterationCount = _nodeCount >> 4;
  85. int tryCount = 0;
  86. int height = ComputeHeight();
  87. while (height > 64 && tryCount < 10)
  88. {
  89. Rebalance(iterationCount);
  90. height = ComputeHeight();
  91. ++tryCount;
  92. }
  93. return proxyId;
  94. }
  95. /// Destroy a proxy. This asserts if the id is invalid.
  96. public void DestroyProxy(int proxyId)
  97. {
  98. Debug.Assert(0 <= proxyId && proxyId < _nodeCapacity);
  99. Debug.Assert(_nodes[proxyId].IsLeaf());
  100. RemoveLeaf(proxyId);
  101. FreeNode(proxyId);
  102. }
  103. /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB,
  104. /// then the proxy is removed from the tree and re-inserted. Otherwise
  105. /// the function returns immediately.
  106. /// @return true if the proxy was re-inserted.
  107. public bool MoveProxy(int proxyId, ref AABB aabb, Vector2 displacement)
  108. {
  109. Debug.Assert(0 <= proxyId && proxyId < _nodeCapacity);
  110. Debug.Assert(_nodes[proxyId].IsLeaf());
  111. if (_nodes[proxyId].aabb.Contains(ref aabb))
  112. {
  113. return false;
  114. }
  115. RemoveLeaf(proxyId);
  116. // Extend AABB.
  117. AABB b = aabb;
  118. Vector2 r = new Vector2(Settings.b2_aabbExtension, Settings.b2_aabbExtension);
  119. b.lowerBound = b.lowerBound - r;
  120. b.upperBound = b.upperBound + r;
  121. // Predict AABB displacement.
  122. Vector2 d = Settings.b2_aabbMultiplier * displacement;
  123. if (d.X < 0.0f)
  124. {
  125. b.lowerBound.X += d.X;
  126. }
  127. else
  128. {
  129. b.upperBound.X += d.X;
  130. }
  131. if (d.Y < 0.0f)
  132. {
  133. b.lowerBound.Y += d.Y;
  134. }
  135. else
  136. {
  137. b.upperBound.Y += d.Y;
  138. }
  139. _nodes[proxyId].aabb = b;
  140. InsertLeaf(proxyId);
  141. return true;
  142. }
  143. /// Perform some iterations to re-balance the tree.
  144. public void Rebalance(int iterations)
  145. {
  146. if (_root == NullNode)
  147. {
  148. return;
  149. }
  150. for (int i = 0; i < iterations; ++i)
  151. {
  152. int node = _root;
  153. int bit = 0;
  154. while (_nodes[node].IsLeaf() == false)
  155. {
  156. // Child selector based on a bit in the path
  157. int selector = (_path >> bit) & 1;
  158. // Select the child nod
  159. node = (selector == 0) ? _nodes[node].child1 : _nodes[node].child2;
  160. // Keep bit between 0 and 31 because _path has 32 bits
  161. // bit = (bit + 1) % 31
  162. bit = (bit + 1) & 0x1F;
  163. }
  164. ++_path;
  165. RemoveLeaf(node);
  166. InsertLeaf(node);
  167. }
  168. }
  169. /// Get proxy user data.
  170. /// @return the proxy user data or 0 if the id is invalid.
  171. public object GetUserData(int proxyId)
  172. {
  173. Debug.Assert(0 <= proxyId && proxyId < _nodeCapacity);
  174. return _nodes[proxyId].userData;
  175. }
  176. /// Get the fat AABB for a proxy.
  177. public void GetFatAABB(int proxyId, out AABB fatAABB)
  178. {
  179. Debug.Assert(0 <= proxyId && proxyId < _nodeCapacity);
  180. fatAABB = _nodes[proxyId].aabb;
  181. }
  182. /// Compute the height of the binary tree in O(N) time. Should not be
  183. /// called often.
  184. public int ComputeHeight()
  185. {
  186. return ComputeHeight(_root);
  187. }
  188. static Stack<int> stack = new Stack<int>(256);
  189. /// Query an AABB for overlapping proxies. The callback class
  190. /// is called for each proxy that overlaps the supplied AABB.
  191. public void Query(Func<int, bool> callback, ref AABB aabb)
  192. {
  193. stack.Clear();
  194. stack.Push(_root);
  195. while (stack.Count > 0)
  196. {
  197. int nodeId = stack.Pop();
  198. if (nodeId == NullNode)
  199. {
  200. continue;
  201. }
  202. DynamicTreeNode node = _nodes[nodeId];
  203. if (AABB.TestOverlap(ref node.aabb, ref aabb))
  204. {
  205. if (node.IsLeaf())
  206. {
  207. bool proceed = callback(nodeId);
  208. if (!proceed)
  209. {
  210. return;
  211. }
  212. }
  213. else
  214. {
  215. stack.Push(node.child1);
  216. stack.Push(node.child2);
  217. }
  218. }
  219. }
  220. }
  221. /// Ray-cast against the proxies in the tree. This relies on the callback
  222. /// to perform a exact ray-cast in the case were the proxy contains a Shape.
  223. /// The callback also performs the any collision filtering. This has performance
  224. /// roughly equal to k * log(n), where k is the number of collisions and n is the
  225. /// number of proxies in the tree.
  226. /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
  227. /// @param callback a callback class that is called for each proxy that is hit by the ray.
  228. internal void RayCast(RayCastCallbackInternal callback, ref RayCastInput input)
  229. {
  230. Vector2 p1 = input.p1;
  231. Vector2 p2 = input.p2;
  232. Vector2 r = p2 - p1;
  233. Debug.Assert(r.LengthSquared() > 0.0f);
  234. r.Normalize();
  235. // v is perpendicular to the segment.
  236. Vector2 v = MathUtils.Cross(1.0f, r);
  237. Vector2 abs_v = MathUtils.Abs(v);
  238. // Separating axis for segment (Gino, p80).
  239. // |dot(v, p1 - c)| > dot(|v|, h)
  240. float maxFraction = input.maxFraction;
  241. // Build a bounding box for the segment.
  242. AABB segmentAABB = new AABB();
  243. {
  244. Vector2 t = p1 + maxFraction * (p2 - p1);
  245. segmentAABB.lowerBound = Vector2.Min(p1, t);
  246. segmentAABB.upperBound = Vector2.Max(p1, t);
  247. }
  248. stack.Clear();
  249. stack.Push(_root);
  250. while (stack.Count > 0)
  251. {
  252. int nodeId = stack.Pop();
  253. if (nodeId == NullNode)
  254. {
  255. continue;
  256. }
  257. DynamicTreeNode node = _nodes[nodeId];
  258. if (AABB.TestOverlap(ref node.aabb, ref segmentAABB) == false)
  259. {
  260. continue;
  261. }
  262. // Separating axis for segment (Gino, p80).
  263. // |dot(v, p1 - c)| > dot(|v|, h)
  264. Vector2 c = node.aabb.GetCenter();
  265. Vector2 h = node.aabb.GetExtents();
  266. float separation = Math.Abs(Vector2.Dot(v, p1 - c)) - Vector2.Dot(abs_v, h);
  267. if (separation > 0.0f)
  268. {
  269. continue;
  270. }
  271. if (node.IsLeaf())
  272. {
  273. RayCastInput subInput;
  274. subInput.p1 = input.p1;
  275. subInput.p2 = input.p2;
  276. subInput.maxFraction = maxFraction;
  277. float value = callback(ref subInput, nodeId);
  278. if (value == 0.0f)
  279. {
  280. // the client has terminated the raycast.
  281. return;
  282. }
  283. if (value > 0.0f)
  284. {
  285. // Update segment bounding box.
  286. maxFraction = value;
  287. Vector2 t = p1 + maxFraction * (p2 - p1);
  288. segmentAABB.lowerBound = Vector2.Min(p1, t);
  289. segmentAABB.upperBound = Vector2.Max(p1, t);
  290. }
  291. }
  292. else
  293. {
  294. stack.Push(node.child1);
  295. stack.Push(node.child2);
  296. }
  297. }
  298. }
  299. private int CountLeaves(int nodeId)
  300. {
  301. if (nodeId == NullNode)
  302. {
  303. return 0;
  304. }
  305. Debug.Assert(0 <= nodeId && nodeId < _nodeCapacity);
  306. DynamicTreeNode node = _nodes[nodeId];
  307. if (node.IsLeaf())
  308. {
  309. Debug.Assert(node.leafCount == 1);
  310. return 1;
  311. }
  312. int count1 = CountLeaves(node.child1);
  313. int count2 = CountLeaves(node.child2);
  314. int count = count1 + count2;
  315. Debug.Assert(count == node.leafCount);
  316. return count;
  317. }
  318. private void Validate()
  319. {
  320. CountLeaves(_root);
  321. }
  322. private int AllocateNode()
  323. {
  324. // Expand the node pool as needed.
  325. if (_freeList == NullNode)
  326. {
  327. Debug.Assert(_nodeCount == _nodeCapacity);
  328. // The free list is empty. Rebuild a bigger pool.
  329. DynamicTreeNode[] oldNodes = _nodes;
  330. _nodeCapacity *= 2;
  331. _nodes = new DynamicTreeNode[_nodeCapacity];
  332. Array.Copy(oldNodes, _nodes, _nodeCount);
  333. // Build a linked list for the free list. The parent
  334. // pointer becomes the "next" pointer.
  335. for (int i = _nodeCount; i < _nodeCapacity - 1; ++i)
  336. {
  337. _nodes[i].parentOrNext = i + 1;
  338. }
  339. _nodes[_nodeCapacity-1].parentOrNext = NullNode;
  340. _freeList = _nodeCount;
  341. }
  342. // Peel a node off the free list.
  343. int nodeId = _freeList;
  344. _freeList = _nodes[nodeId].parentOrNext;
  345. _nodes[nodeId].parentOrNext = NullNode;
  346. _nodes[nodeId].child1 = NullNode;
  347. _nodes[nodeId].child2 = NullNode;
  348. _nodes[nodeId].leafCount = 0;
  349. ++_nodeCount;
  350. return nodeId;
  351. }
  352. private void FreeNode(int nodeId)
  353. {
  354. Debug.Assert(0 <= nodeId && nodeId < _nodeCapacity);
  355. Debug.Assert(0 < _nodeCount);
  356. _nodes[nodeId].parentOrNext = _freeList;
  357. _freeList = nodeId;
  358. --_nodeCount;
  359. }
  360. private void InsertLeaf(int leaf)
  361. {
  362. ++_insertionCount;
  363. if (_root == NullNode)
  364. {
  365. _root = leaf;
  366. _nodes[_root].parentOrNext = NullNode;
  367. return;
  368. }
  369. // Find the best sibling for this node
  370. AABB leafAABB = _nodes[leaf].aabb;
  371. Vector2 leafCenter = leafAABB.GetCenter();
  372. int sibling = _root;
  373. while (_nodes[sibling].IsLeaf() == false)
  374. {
  375. // Expand the node's AABB.
  376. _nodes[sibling].aabb.Combine(ref leafAABB);
  377. _nodes[sibling].leafCount += 1;
  378. int child1 = _nodes[sibling].child1;
  379. int child2 = _nodes[sibling].child2;
  380. #if false
  381. // This seems to create imbalanced trees
  382. Vector2 delta1 = Math.Abs(_nodes[child1].aabb.GetCenter() - leafCenter);
  383. Vector2 delta2 = Math.Abs(_nodes[child2].aabb.GetCenter() - leafCenter);
  384. float norm1 = delta1.x + delta1.y;
  385. float norm2 = delta2.x + delta2.y;
  386. #else
  387. // Surface area heuristic
  388. AABB aabb1 = new AABB();
  389. AABB aabb2 = new AABB();
  390. aabb1.Combine(ref leafAABB, ref _nodes[child1].aabb);
  391. aabb2.Combine(ref leafAABB, ref _nodes[child2].aabb);
  392. float norm1 = (_nodes[child1].leafCount + 1) * aabb1.GetPerimeter();
  393. float norm2 = (_nodes[child2].leafCount + 1) * aabb2.GetPerimeter();
  394. #endif
  395. if (norm1 < norm2)
  396. {
  397. sibling = child1;
  398. }
  399. else
  400. {
  401. sibling = child2;
  402. }
  403. }
  404. // Create a new parent for the siblings.
  405. int oldParent = _nodes[sibling].parentOrNext;
  406. int newParent = AllocateNode();
  407. _nodes[newParent].parentOrNext = oldParent;
  408. _nodes[newParent].userData = null;
  409. _nodes[newParent].aabb.Combine(ref leafAABB, ref _nodes[sibling].aabb);
  410. _nodes[newParent].leafCount = _nodes[sibling].leafCount + 1;
  411. if (oldParent != NullNode)
  412. {
  413. // The sibling was not the root.
  414. if (_nodes[oldParent].child1 == sibling)
  415. {
  416. _nodes[oldParent].child1 = newParent;
  417. }
  418. else
  419. {
  420. _nodes[oldParent].child2 = newParent;
  421. }
  422. _nodes[newParent].child1 = sibling;
  423. _nodes[newParent].child2 = leaf;
  424. _nodes[sibling].parentOrNext = newParent;
  425. _nodes[leaf].parentOrNext = newParent;
  426. }
  427. else
  428. {
  429. // The sibling was the root.
  430. _nodes[newParent].child1 = sibling;
  431. _nodes[newParent].child2 = leaf;
  432. _nodes[sibling].parentOrNext = newParent;
  433. _nodes[leaf].parentOrNext = newParent;
  434. _root = newParent;
  435. }
  436. }
  437. private void RemoveLeaf(int leaf)
  438. {
  439. if (leaf == _root)
  440. {
  441. _root = NullNode;
  442. return;
  443. }
  444. int parent = _nodes[leaf].parentOrNext;
  445. int grandParent = _nodes[parent].parentOrNext;
  446. int sibling;
  447. if (_nodes[parent].child1 == leaf)
  448. {
  449. sibling = _nodes[parent].child2;
  450. }
  451. else
  452. {
  453. sibling = _nodes[parent].child1;
  454. }
  455. if (grandParent != NullNode)
  456. {
  457. // Destroy parent and connect sibling to grandParent.
  458. if (_nodes[grandParent].child1 == parent)
  459. {
  460. _nodes[grandParent].child1 = sibling;
  461. }
  462. else
  463. {
  464. _nodes[grandParent].child2 = sibling;
  465. }
  466. _nodes[sibling].parentOrNext = grandParent;
  467. FreeNode(parent);
  468. // Adjust ancestor bounds.
  469. parent = grandParent;
  470. while (parent != NullNode)
  471. {
  472. AABB oldAABB = _nodes[parent].aabb;
  473. _nodes[parent].aabb.Combine(ref _nodes[_nodes[parent].child1].aabb, ref _nodes[_nodes[parent].child2].aabb);
  474. Debug.Assert(_nodes[parent].leafCount > 0);
  475. _nodes[parent].leafCount -= 1;
  476. parent = _nodes[parent].parentOrNext;
  477. }
  478. }
  479. else
  480. {
  481. _root = sibling;
  482. _nodes[sibling].parentOrNext = NullNode;
  483. FreeNode(parent);
  484. }
  485. }
  486. private int ComputeHeight(int nodeId)
  487. {
  488. if (nodeId == NullNode)
  489. {
  490. return 0;
  491. }
  492. Debug.Assert(0 <= nodeId && nodeId < _nodeCapacity);
  493. DynamicTreeNode node = _nodes[nodeId];
  494. int height1 = ComputeHeight(node.child1);
  495. int height2 = ComputeHeight(node.child2);
  496. return 1 + Math.Max(height1, height2);
  497. }
  498. int _root;
  499. DynamicTreeNode[] _nodes;
  500. int _nodeCount;
  501. int _nodeCapacity;
  502. int _freeList;
  503. /// This is used incrementally traverse the tree for re-balancing.
  504. int _path;
  505. int _insertionCount;
  506. }
  507. }