A zero-dependency 2D quadtree spatial index for Rust: fast rectangular range queries over point data.
A flat Vec of points makes a range query an O(n) linear scan. A quadtree
recursively splits its region into four quadrants once a node holds more
points than a configured capacity, so a range query only has to visit the
handful of regions that actually overlap the query rectangle instead of
every point in the structure. This is the data structure behind:
- Broad-phase collision detection in game engines — instead of testing every object against every other object (O(n^2)), only test pairs whose quadrant regions overlap.
- Geospatial indexing — find every point-of-interest inside a map viewport without scanning the whole dataset.
- Image / terrain level-of-detail systems — find every sample point inside a visible tile.
use rs_quadtree::{QuadTree, Rectangle};
fn main() {
// A 1000x1000 world, splitting nodes once they hold more than 4 points.
let boundary = Rectangle::new(0.0, 0.0, 1000.0, 1000.0);
let mut tree = QuadTree::new(boundary, 4);
tree.insert((120.0, 340.0), "player");
tree.insert((125.0, 342.0), "npc");
tree.insert((900.0, 10.0), "treasure_chest");
// insert() returns false (never panics) for points outside the root
// boundary.
assert!(!tree.insert((-5.0, 0.0), "off_map"));
// Find everything within a 50x50 box near (100, 300).
let nearby = tree.query_range(&Rectangle::new(100.0, 300.0, 50.0, 50.0));
for item in nearby {
println!("found: {item}");
}
}Each QuadTree node owns a Rectangle boundary and a list of points. While
a node holds capacity points or fewer, insert just appends to that list.
Once an insert would push it over capacity, the node subdivides: it
creates four children — northwest, northeast, southwest, southeast, each
covering one quadrant of the parent's boundary — and re-inserts its own
points into whichever child quadrant now contains them. From then on, every
insert into that node is routed to the correct child by comparing the point
against the node's midpoint (x < mid_x → west, y < mid_y → north) and
recursing; the node's own point list stays empty once it's divided.
query_range(range) walks the tree starting at the root:
- If the node's boundary doesn't intersect
rangeat all, prune the whole subtree — none of its points (or its children's points) can possibly be in range. - Otherwise, check every point stored directly in this node against
range.contains_point(..)and collect the matches. - If the node has children, recurse into all four.
This keeps the average-case cost close to the number of quadrants that actually overlap the query, rather than the total number of points in the tree.
Boundary-inclusion convention. Rectangle covers the half-open interval
[x, x + width) x [y, y + height): the left and top edges are included, the
right and bottom edges are excluded. This convention is applied consistently
everywhere a rectangle is tested against a point or another rectangle,
which is what makes subdivision correct: a point exactly on the line
between two sibling quadrants always belongs to exactly one of them (the
one whose region starts there), never both, never neither. The same
convention is used for range queries, so a point sitting exactly on a query
rectangle's right or bottom edge is excluded from the result — pick a query
rectangle that extends slightly past the edge you care about if you want it
included.
Safety net against pathological input. If many points share the exact
same coordinate, no amount of subdividing can ever separate them into
different quadrants, so naive quadtrees can recurse forever trying to split
a node that's still over capacity after splitting. QuadTree caps
subdivision at a fixed maximum depth; past that depth a node simply keeps
accepting points beyond its nominal capacity instead of subdividing
further, so insert always terminates and never panics.
insert returns false (not a panic) for a point outside the tree's root
boundary, and query_range on an empty tree or a non-matching range simply
returns an empty Vec.
cargo test includes unit tests for Rectangle's boundary/intersection
semantics and quadtree edge cases (out-of-bounds inserts, empty-tree
queries, forced subdivision, thousands of duplicate points at one
coordinate), plus two randomized cross-check tests that are the main
correctness evidence:
- A deterministic xorshift64 PRNG (seeded, no external
randdependency) generates 8,000 and 5,000 pseudo-random 2D points respectively, inserted into quadtrees with small node capacities (6 and 4) so multiple levels of subdivision are actually exercised. - For each test, 5–7 differently shaped/positioned query rectangles are run (a small interior box, a large box covering most of the space, a box hugging a corner, a box hugging an edge, a thin sliver, a box matching nothing, and a box covering the whole world).
- Every query is answered two ways: once via
QuadTree::query_range, and once via a brute-force linear scan over the same full point set using the sameRectangle::contains_pointsemantics. - Both results are converted to a
HashSetof point IDs and asserted exactly equal — not just matching counts. Any divergence between the tree's pruning logic and the brute-force scan fails the test.
Run it yourself:
cargo test --verboseMIT — see LICENSE.