public void AddNode(NodeBase node) { Quadrant quad = GetQuadrant(node.Position); node.CurrentQuadrant = quad; quad.AddNode(node); }
public QuadTree() { // create the quadrants Quadrants = new Quadrant[Width, Height]; for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { Rect r = new Rect(x * quadrantLength, y * quadrantLength, quadrantLength, quadrantLength); Quadrants[x, y] = new Quadrant(x, y, r); } } // set the neigbours for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { Quadrant quad = Quadrants[x, y]; quad.north = TryGetQuadrant(x, y - 1); quad.northEast = TryGetQuadrant(x + 1, y - 1); quad.east = TryGetQuadrant(x + 1, y); quad.southEast = TryGetQuadrant(x + 1, y + 1); quad.south = TryGetQuadrant(x, y + 1); quad.southWest = TryGetQuadrant(x - 1, y + 1); quad.west = TryGetQuadrant(x - 1, y); quad.northWest = TryGetQuadrant(x - 1, y - 1); } } }
public void Clear() { for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { Quadrant q = Quadrants[x, y]; q.Clear(); } } }
public void UpdateNodeQuadrant(NodeBase node) { Quadrant quad = GetQuadrant(node.Position); if (quad != node.CurrentQuadrant) { node.CurrentQuadrant.RemoveNode(node); node.CurrentQuadrant = quad; quad.AddNode(node); } }
/// <summary> /// Enumerates all quadrants /// </summary> public IEnumerable <Quadrant> AllQuadrants() { for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { Quadrant q = Quadrants[x, y]; yield return(q); } } }
/// <summary> /// Efficiently gets all the nodes in a given rectangle /// </summary> public IEnumerable <NodeBase> GetNodesInRect(Rect rectangle) { Quadrant topLeftQuad = GetQuadrant(rectangle.TopLeft); Quadrant bottomRightQuad = GetQuadrant(rectangle.BottomRight); for (int x = topLeftQuad.X; x <= bottomRightQuad.X; x++) { for (int y = topLeftQuad.Y; y <= bottomRightQuad.Y; y++) { Quadrant q = Quadrants[x, y]; foreach (NodeBase n in q.Nodes) { if (rectangle.Contains(n.Position)) { yield return(n); } } } } }