/// <summary> /// Get the objects in this tree that intersect with the specified rectangle. /// </summary> /// <param name="searchRect">The rectangle to find objects in.</param> /// <param name="results">A reference to a list that will be populated with the results.</param> internal void GetObjects(PreciseRectangle searchRect, ref List <T> results) { // We can't do anything if the results list doesn't exist if (results != null) { if (searchRect.Contains(rect)) { // If the search area completely contains this quad, just get every object this quad and all it's children have GetAllObjects(ref results); } else if (searchRect.Intersects(rect)) { // Otherwise, if the quad isn't fully contained, only add objects that intersect with the search rectangle if (objects != null) { for (int i = 0; i < objects.Count; i++) { if (searchRect.Intersects(objects[i].Data.QuadBounds)) { results.Add(objects[i].Data); } } } // Get the objects for the search rectangle from the children if (childTL != null) { childTL.GetObjects(searchRect, ref results); childTR.GetObjects(searchRect, ref results); childBL.GetObjects(searchRect, ref results); childBR.GetObjects(searchRect, ref results); } } } }
/// <summary> /// Insert an item into this QuadTree object. /// </summary> /// <param name="item">The item to insert.</param> internal void Insert(QuadTreeObject <T> item) { // If this quad doesn't contain the items rectangle, do nothing, unless we are the root if (!rect.Contains(item.Data.QuadBounds)) { //System.Diagnostics.Debug.Assert(parent == null, "We are not the root, and this object doesn't fit here. How did we get here?"); if (parent == null) { // This object is outside of the QuadTree bounds, we should add it at the root level Add(item); } else { parent.Insert(item); return; } } if (objects == null || (childTL == null && objects.Count + 1 <= maxObjectsPerNode)) { // If there's room to add the object, just add it Add(item); } else { // No quads, create them and bump objects down where appropriate if (childTL == null) { Subdivide(); } // Find out which tree this object should go in and add it there QuadTreeNode <T> destTree = GetDestinationTree(item); if (destTree == this) { Add(item); } else { destTree.Insert(item); } } }