QuadTreeBroadPhase.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using System;
  2. using System.Collections.Generic;
  3. using FarseerPhysics;
  4. using FarseerPhysics.Collision;
  5. using FarseerPhysics.Dynamics;
  6. using Microsoft.Xna.Framework;
  7. public class QuadTreeBroadPhase : IBroadPhase
  8. {
  9. private const int TreeUpdateThresh = 10000;
  10. private int _currID;
  11. private Dictionary<int, Element<FixtureProxy>> _idRegister;
  12. private List<Element<FixtureProxy>> _moveBuffer;
  13. private List<Pair> _pairBuffer;
  14. private QuadTree<FixtureProxy> _quadTree;
  15. private int _treeMoveNum;
  16. /// <summary>
  17. /// Creates a new quad tree broadphase with the specified span.
  18. /// </summary>
  19. /// <param name="span">the maximum span of the tree (world size)</param>
  20. public QuadTreeBroadPhase(AABB span)
  21. {
  22. _quadTree = new QuadTree<FixtureProxy>(span, 5, 10);
  23. _idRegister = new Dictionary<int, Element<FixtureProxy>>();
  24. _moveBuffer = new List<Element<FixtureProxy>>();
  25. _pairBuffer = new List<Pair>();
  26. }
  27. ///<summary>
  28. /// The number of proxies
  29. ///</summary>
  30. public int ProxyCount
  31. {
  32. get { return _idRegister.Count; }
  33. }
  34. public void GetFatAABB(int proxyID, out AABB aabb)
  35. {
  36. if (_idRegister.ContainsKey(proxyID))
  37. aabb = _idRegister[proxyID].Span;
  38. else
  39. throw new KeyNotFoundException("proxyID not found in register");
  40. }
  41. public void UpdatePairs(BroadphaseDelegate callback)
  42. {
  43. _pairBuffer.Clear();
  44. foreach (Element<FixtureProxy> qtnode in _moveBuffer)
  45. {
  46. // Query tree, create pairs and add them pair buffer.
  47. Query(proxyID => PairBufferQueryCallback(proxyID, qtnode.Value.ProxyId), ref qtnode.Span);
  48. }
  49. _moveBuffer.Clear();
  50. // Sort the pair buffer to expose duplicates.
  51. _pairBuffer.Sort();
  52. // Send the pairs back to the client.
  53. int i = 0;
  54. while (i < _pairBuffer.Count)
  55. {
  56. Pair primaryPair = _pairBuffer[i];
  57. FixtureProxy userDataA = GetProxy(primaryPair.ProxyIdA);
  58. FixtureProxy userDataB = GetProxy(primaryPair.ProxyIdB);
  59. callback(ref userDataA, ref userDataB);
  60. ++i;
  61. // Skip any duplicate pairs.
  62. while (i < _pairBuffer.Count && _pairBuffer[i].ProxyIdA == primaryPair.ProxyIdA &&
  63. _pairBuffer[i].ProxyIdB == primaryPair.ProxyIdB)
  64. ++i;
  65. }
  66. }
  67. /// <summary>
  68. /// Test overlap of fat AABBs.
  69. /// </summary>
  70. /// <param name="proxyIdA">The proxy id A.</param>
  71. /// <param name="proxyIdB">The proxy id B.</param>
  72. /// <returns></returns>
  73. public bool TestOverlap(int proxyIdA, int proxyIdB)
  74. {
  75. AABB aabb1;
  76. AABB aabb2;
  77. GetFatAABB(proxyIdA, out aabb1);
  78. GetFatAABB(proxyIdB, out aabb2);
  79. return AABB.TestOverlap(ref aabb1, ref aabb2);
  80. }
  81. public int AddProxy(ref FixtureProxy proxy)
  82. {
  83. int proxyID = _currID++;
  84. proxy.ProxyId = proxyID;
  85. AABB aabb = Fatten(ref proxy.AABB);
  86. Element<FixtureProxy> qtnode = new Element<FixtureProxy>(proxy, aabb);
  87. _idRegister.Add(proxyID, qtnode);
  88. _quadTree.AddNode(qtnode);
  89. return proxyID;
  90. }
  91. public void RemoveProxy(int proxyId)
  92. {
  93. if (_idRegister.ContainsKey(proxyId))
  94. {
  95. Element<FixtureProxy> qtnode = _idRegister[proxyId];
  96. UnbufferMove(qtnode);
  97. _idRegister.Remove(proxyId);
  98. _quadTree.RemoveNode(qtnode);
  99. }
  100. else
  101. throw new KeyNotFoundException("proxyID not found in register");
  102. }
  103. public void MoveProxy(int proxyId, ref AABB aabb, Vector2 displacement)
  104. {
  105. AABB fatAABB;
  106. GetFatAABB(proxyId, out fatAABB);
  107. //exit if movement is within fat aabb
  108. if (fatAABB.Contains(ref aabb))
  109. return;
  110. // Extend AABB.
  111. AABB b = aabb;
  112. Vector2 r = new Vector2(Settings.AABBExtension, Settings.AABBExtension);
  113. b.LowerBound = b.LowerBound - r;
  114. b.UpperBound = b.UpperBound + r;
  115. // Predict AABB displacement.
  116. Vector2 d = Settings.AABBMultiplier * displacement;
  117. if (d.X < 0.0f)
  118. b.LowerBound.X += d.X;
  119. else
  120. b.UpperBound.X += d.X;
  121. if (d.Y < 0.0f)
  122. b.LowerBound.Y += d.Y;
  123. else
  124. b.UpperBound.Y += d.Y;
  125. Element<FixtureProxy> qtnode = _idRegister[proxyId];
  126. qtnode.Value.AABB = b; //not neccesary for QTree, but might be accessed externally
  127. qtnode.Span = b;
  128. ReinsertNode(qtnode);
  129. BufferMove(qtnode);
  130. }
  131. public FixtureProxy GetProxy(int proxyId)
  132. {
  133. if (_idRegister.ContainsKey(proxyId))
  134. return _idRegister[proxyId].Value;
  135. else
  136. throw new KeyNotFoundException("proxyID not found in register");
  137. }
  138. public void TouchProxy(int proxyId)
  139. {
  140. if (_idRegister.ContainsKey(proxyId))
  141. BufferMove(_idRegister[proxyId]);
  142. else
  143. throw new KeyNotFoundException("proxyID not found in register");
  144. }
  145. public void Query(Func<int, bool> callback, ref AABB query)
  146. {
  147. _quadTree.QueryAABB(TransformPredicate(callback), ref query);
  148. }
  149. public void RayCast(Func<RayCastInput, int, float> callback, ref RayCastInput input)
  150. {
  151. _quadTree.RayCast(TransformRayCallback(callback), ref input);
  152. }
  153. private AABB Fatten(ref AABB aabb)
  154. {
  155. Vector2 r = new Vector2(Settings.AABBExtension, Settings.AABBExtension);
  156. return new AABB(aabb.LowerBound - r, aabb.UpperBound + r);
  157. }
  158. private Func<Element<FixtureProxy>, bool> TransformPredicate(Func<int, bool> idPredicate)
  159. {
  160. Func<Element<FixtureProxy>, bool> qtPred = qtnode => idPredicate(qtnode.Value.ProxyId);
  161. return qtPred;
  162. }
  163. private Func<RayCastInput, Element<FixtureProxy>, float> TransformRayCallback(
  164. Func<RayCastInput, int, float> callback)
  165. {
  166. Func<RayCastInput, Element<FixtureProxy>, float> newCallback =
  167. (input, qtnode) => callback(input, qtnode.Value.ProxyId);
  168. return newCallback;
  169. }
  170. private bool PairBufferQueryCallback(int proxyID, int baseID)
  171. {
  172. // A proxy cannot form a pair with itself.
  173. if (proxyID == baseID)
  174. return true;
  175. Pair p = new Pair();
  176. p.ProxyIdA = Math.Min(proxyID, baseID);
  177. p.ProxyIdB = Math.Max(proxyID, baseID);
  178. _pairBuffer.Add(p);
  179. return true;
  180. }
  181. private void ReconstructTree()
  182. {
  183. //this is faster than _quadTree.Reconstruct(), since the quadtree method runs a recusive query to find all nodes.
  184. _quadTree.Clear();
  185. foreach (Element<FixtureProxy> elem in _idRegister.Values)
  186. _quadTree.AddNode(elem);
  187. }
  188. private void ReinsertNode(Element<FixtureProxy> qtnode)
  189. {
  190. _quadTree.RemoveNode(qtnode);
  191. _quadTree.AddNode(qtnode);
  192. if (++_treeMoveNum > TreeUpdateThresh)
  193. {
  194. ReconstructTree();
  195. _treeMoveNum = 0;
  196. }
  197. }
  198. private void BufferMove(Element<FixtureProxy> proxy)
  199. {
  200. _moveBuffer.Add(proxy);
  201. }
  202. private void UnbufferMove(Element<FixtureProxy> proxy)
  203. {
  204. _moveBuffer.Remove(proxy);
  205. }
  206. }