Broad Phase: Bounding Volume Hierarchy
A bounding volume hierarchy (BVH) is a tree of boxes. Each leaf holds one object's AABB; each inner node holds a box that encloses both of its children. To find what overlaps a query box, start at the root: if the query misses a node's box, it misses everything below it, and the whole subtree is skipped. With a reasonably balanced tree a query visits about log n levels instead of n objects.
BVHs handle what grids handle badly: objects of wildly different sizes, huge mostly empty worlds, and static level geometry. The same tree also answers raycasts, so engines use BVHs everywhere: Box2D's dynamic tree, the bounding-volume structures in PhysX and Jolt, and every ray tracer.
Building a tree top-down
The simplest build is recursive:
- Compute the box around all objects in the set.
- If one object is left, make a leaf.
- Otherwise pick the longest axis of the box, sort the objects by their centre along it, split at the median, and build the two halves.
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <string>
#include <memory>
struct AABB {
double minX, minY, maxX, maxY;
AABB merge(const AABB& o) const {
return {std::min(minX, o.minX), std::min(minY, o.minY), std::max(maxX, o.maxX), std::max(maxY, o.maxY)};
}
};
struct Object { std::string name; AABB box; };
struct Node {
AABB box;
int object = -1; // leaf: index into objects
std::unique_ptr<Node> left, right;
};
std::vector<Object> objects = {
{"rock", {1, 1, 2, 2}}, {"crate", {3, 1, 4, 2}}, {"tree", {2, 6, 3, 9}},
{"wall", {10, 0, 11, 8}}, {"enemy", {12, 3, 13, 4}}, {"coin", {14, 7, 14.5, 7.5}},
};
std::unique_ptr<Node> build(std::vector<int> ids) {
auto node = std::make_unique<Node>();
node->box = objects[ids[0]].box;
for (int id : ids) node->box = node->box.merge(objects[id].box);
if (ids.size() == 1) { node->object = ids[0]; return node; }
bool splitX = (node->box.maxX - node->box.minX) >= (node->box.maxY - node->box.minY);
auto centre = [&](int id) {
const AABB& b = objects[id].box;
return splitX ? b.minX + b.maxX : b.minY + b.maxY; // 2 * centre is fine for sorting
};
std::sort(ids.begin(), ids.end(), [&](int a, int b) { return centre(a) < centre(b); });
size_t mid = ids.size() / 2;
node->left = build({ids.begin(), ids.begin() + mid});
node->right = build({ids.begin() + mid, ids.end()});
return node;
}
void print(const Node* n, int depth) {
std::cout << std::string(depth * 2, ' ') << "[" << n->box.minX << "," << n->box.minY << " .. "
<< n->box.maxX << "," << n->box.maxY << "]";
if (n->object >= 0) std::cout << " " << objects[n->object].name;
std::cout << "\n";
if (n->left) { print(n->left.get(), depth + 1); print(n->right.get(), depth + 1); }
}
int main() {
std::cout << std::fixed << std::setprecision(1);
auto root = build({0, 1, 2, 3, 4, 5});
print(root.get(), 0);
}[1.0,0.0 .. 14.5,9.0]
[1.0,1.0 .. 4.0,9.0]
[1.0,1.0 .. 2.0,2.0] rock
[2.0,1.0 .. 4.0,9.0]
[3.0,1.0 .. 4.0,2.0] crate
[2.0,6.0 .. 3.0,9.0] tree
[10.0,0.0 .. 14.5,8.0]
[12.0,3.0 .. 13.0,4.0] enemy
[10.0,0.0 .. 14.5,8.0]
[10.0,0.0 .. 11.0,8.0] wall
[14.0,7.0 .. 14.5,7.5] coin
The root covers the whole level; its first split separates the left cluster (rock, crate, tree) from the right one (wall, enemy, coin), which is exactly what makes queries fast: a query on the right never looks inside the left subtree. The next split is less pretty. The left cluster is taller than wide, so it is split on y, and the median puts the crate together with the tree, in a tall box that is mostly empty space. A query between the crate and the tree enters that box for nothing. Better split rules (see the note on SAH below) fix exactly this.
Querying
A query is a recursive walk that stops at any node whose box misses the query box. This program builds a tree over 2,000 boxes and counts node visits for a few queries:
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <memory>
#include <cstdint>
struct Lcg {
uint32_t s;
void seed(uint32_t v) { s = v; }
double next() { s = s * 1664525u + 1013904223u; return (s >> 8) / 16777216.0; }
};
struct AABB {
double minX, minY, maxX, maxY;
AABB merge(const AABB& o) const {
return {std::min(minX, o.minX), std::min(minY, o.minY), std::max(maxX, o.maxX), std::max(maxY, o.maxY)};
}
bool overlaps(const AABB& o) const { return minX <= o.maxX && o.minX <= maxX && minY <= o.maxY && o.minY <= maxY; }
};
struct Node { AABB box; int object = -1; std::unique_ptr<Node> left, right; };
std::vector<AABB> boxes;
std::unique_ptr<Node> build(std::vector<int> ids) {
auto n = std::make_unique<Node>();
n->box = boxes[ids[0]];
for (int id : ids) n->box = n->box.merge(boxes[id]);
if (ids.size() == 1) { n->object = ids[0]; return n; }
bool splitX = (n->box.maxX - n->box.minX) >= (n->box.maxY - n->box.minY);
auto c = [&](int id) { return splitX ? boxes[id].minX + boxes[id].maxX : boxes[id].minY + boxes[id].maxY; };
size_t mid = ids.size() / 2;
std::nth_element(ids.begin(), ids.begin() + mid, ids.end(), [&](int a, int b) { return c(a) < c(b); });
n->left = build({ids.begin(), ids.begin() + mid});
n->right = build({ids.begin() + mid, ids.end()});
return n;
}
void query(const Node* n, const AABB& q, int& visits, std::vector<int>& hits) {
visits++;
if (!n->box.overlaps(q)) return; // prune the whole subtree
if (n->object >= 0) { hits.push_back(n->object); return; }
query(n->left.get(), q, visits, hits);
query(n->right.get(), q, visits, hits);
}
int depth(const Node* n) { return n->left ? 1 + std::max(depth(n->left.get()), depth(n->right.get())) : 0; }
int main() {
Lcg g; g.seed(11);
std::vector<int> ids;
for (int i = 0; i < 2000; i++) {
double x = g.next() * 500, y = g.next() * 500, s = 0.5 + g.next() * 4;
boxes.push_back({x, y, x + s, y + s});
ids.push_back(i);
}
boxes.push_back({0, 240, 500, 245}); // one long wall across the level
ids.push_back(2000);
auto root = build(ids);
std::cout << "objects: " << boxes.size() << ", tree depth: " << depth(root.get()) << "\n";
AABB queries[] = {{100, 100, 105, 105}, {300, 50, 330, 80}, {0, 0, 500, 500}, {250, 241, 251, 243}};
for (const AABB& q : queries) {
int visits = 0; std::vector<int> hits;
query(root.get(), q, visits, hits);
std::cout << "query " << std::setw(3) << q.minX << "," << std::setw(3) << q.minY << " size "
<< std::setw(3) << q.maxX - q.minX << ": " << std::setw(4) << hits.size() << " hits, "
<< std::setw(4) << visits << " node visits\n";
}
}objects: 2001, tree depth: 11
query 100,100 size 5: 0 hits, 31 node visits
query 300, 50 size 30: 14 hits, 81 node visits
query 0, 0 size 500: 2001 hits, 4001 node visits
query 250,241 size 1: 2 hits, 29 node visits
A tree over 2,001 objects has 4,001 nodes (2,001 leaves plus 2,000 inner nodes). A small query visits about 30 of them, a 30 × 30 query 81, and a query covering the whole world visits every node (no tree can beat "return everything"). The long wall is just one more leaf: its box is wide, so it makes a few inner boxes on its path wide too, but it doesn't need special handling the way it would in a grid.
Note: The median split is simple and always balanced, but not always the fastest tree. Engines and ray tracers often use the surface area heuristic (SAH): try several split positions and pick the one that minimizes
area(left) * count(left) + area(right) * count(right), since the chance that a query hits a box grows with its area (perimeter in 2D).
Dynamic trees for moving objects
Rebuilding the whole tree every step is wasteful when most objects stay still. Physics engines use a dynamic AABB tree instead (Box2D's b2DynamicTree is the textbook example):
- Insert and remove single leaves. A new leaf goes next to the sibling whose box grows least when it is added, and the boxes up the path are refitted.
- Fattened AABBs: each leaf stores a box slightly larger than the object (Box2D adds a small margin). While the object stays inside its fat box, the tree doesn't change at all. Only when it leaves the box is the leaf removed and reinserted.
- Rotations of nodes, like a self-balancing binary search tree, keep the tree from degenerating when objects are inserted in an unlucky order.
- Static and dynamic objects often live in separate trees, so the large static level never needs to be rebalanced because of moving crates.
| Structure | Best when | Weak when |
|---|---|---|
| Uniform grid | many similar-sized objects in a bounded area | sizes vary a lot, sparse huge worlds |
| Sweep and prune | coherent motion, objects spread along an axis | clustering on the sweep axis, teleports |
| BVH / dynamic tree | mixed sizes, raycasts, static geometry | very many tiny fast-moving objects (refits and reinserts) |
Test yourself
During a BVH query, what does it mean when the query box misses an inner node's box?
- Only that node's left child can be skipped
- The entire subtree below that node can be skipped
- The query must restart at the root
- The tree must be rebuilt
What are fattened AABBs in a dynamic tree for?
- Making collisions more accurate
- Letting small movements happen without updating the tree
- Storing the object's mass
- Avoiding the narrow phase
What does the surface area heuristic try to minimize when choosing a split?
- The depth of the tree
- The expected query cost, estimated as child area times child object count
- The number of leaves
- Memory use