Last updated: 2026-11-26
16. Groups and trees of boxes
For new readers
A model is a group of shapes, and a group of groups; this page opens groups (a transform shared by its children, normals carried back out through every level) and the bounding boxes that let a ray skip a whole group at once, up to a tree of boxes for meshes of thousands of triangles. The world uses the same boxes for its objects.
Groups
A group is a shape with no surface of its own: it is the shapes it holds, carried by one transformation. Nest groups and a transformation placed on the outermost one moves the whole tree. This page also asks for bounding boxes, so that a ray can skip a whole group it cannot touch.
Step 1 — shapes are values, so the parent link is attached on the way out
The book gives every shape a mutable parent pointer and builds trees by adding a
shape to a group that may already sit inside another group. Shapes here are
values: set_transform returns a new shape, and so does add_child. Two things
follow.
- A tree is built from the leaves up. A program that would add to an inner group after placing it in an outer one assembles them in the other order here; the tree is the same.
- There is no pointer to follow back up. Instead, when a group returns a child's
hit it appends itself, as the outermost ancestor, to that hit's object (as a
copy of the group without its children). A sphere found through
g2insideg1comes back assphere → g2 → g1, which is exactly the chain the book'sworld_to_objectandnormal_to_worldwalk. A shape's identity is itsid, so "the hit iss2" is checked by id.
A group's intersection is every child's intersections, merged and sorted by t.
The group's own transformation is applied by intersect, as for any shape, so the
children see the ray in group space.
make a function called intersect takes s, r returns xs
if s[8] then
return local_intersect(s, r)
end
return local_intersect(s, transform_ray(r, s[2]))
end
# a point from world space to the shape's object space, through every group
# between the two (the outermost first)
make a function called world_to_object takes s, p returns q
let q = p
if s[7] != false then
let q = world_to_object(s[7], p)
end
if s[8] then
return q
end
return mat_tuple(s[2], q)
end
# a normal from object space to world space: this shape's normal matrix, then
# each enclosing group's in turn
make a function called normal_to_world takes s, n returns w
let w = normalize(n)
if not s[8] then
let nv = mat_vec([get_x(n), get_y(n), get_z(n)])
let rows = s[4]
let w = normalize(vector(ga_vec_dot(rows[0], nv), ga_vec_dot(rows[1], nv), ga_vec_dot(rows[2], nv)))
end
if s[7] != false then
let w = normal_to_world(s[7], w)
end
return w
end
make a function called normal_at takes s, world_point returns n
return normal_at_hit(s, world_point, false)
end
# a sphere with a glassy material: transparency 1, refractive index 1.5
make a function called glass_sphere returns s
return set_material(sphere(), with_refractive_index(with_transparency(material(), 1), (3/2)))
end
normal_at is now the book's three steps: point to object space through the
parents, the shape's own local_normal_at, and the normal back out through the
parents. A normal is carried by the cofactor matrix of each level's 3×3 part (the
dual of the tangent plane, as in Light at a point, and shadows), and pattern_at_shape uses
world_to_object too, so stripes and checkers on a grouped shape follow the
group.dual matrix: normal transforms
make a function called group returns g
return new_shape("group")
end
make a function called group_children takes g returns kids
return g[6][0]
end
make a function called is_empty_group takes g returns b
return g[6][0].length == 0
end
make a function called shape_parent takes s returns p
return s[7]
end
# the group without its children: all that a hit needs to remember of it
make a function called group_frame takes g returns f
return list_set(list_set(g, 6, [[], false]), 7, false)
end
# a copy of the shape whose outermost ancestor is `frame`
make a function called attach_outer takes s, frame returns s2
if s[7] == false then
return list_set(s, 7, frame)
end
return list_set(s, 7, attach_outer(s[7], frame))
end
Step 2 — bounding boxes
Each group keeps the box that holds its children, in its own space, updated by
add_child. A child's box is moved into the parent's space by sending all eight
corners through the child's matrix and taking the box of the results (a turned
box needs all eight). A shape with an infinite side, a plane or an untruncated
cylinder, becomes all of space when transformed, since an infinite coordinate times
a zero matrix entry is not a number; such a group simply never culls.
The ray test is the cube's slab test with the faces moved: the face of axis i at
c is the plane vector π = eᵢ + c e∞, and the ray meets it at the usual
t = −(O·π)/(d·π). For a point O (with O·e∞ = −1) that is (c − oᵢ)/dᵢ, read
straight off the multivector, since this test runs at every group of every ray.
Where the cube treats a ray lying in a face plane as a miss, the box test counts
it as a hit: a box that culls must never lose a hit, and a tangent child can touch
the face.
# the built-in min and max return floats; bounds stay exact
make a function called num_min takes a, b returns v
if b < a then
return b
end
return a
end
make a function called num_max takes a, b returns v
if b > a then
return b
end
return a
end
make a function called is_finite takes v returns b
return abs(v) < infinity()
end
make a function called whole_space returns b
let inf = infinity()
return [[0 - inf, 0 - inf, 0 - inf], [inf, inf, inf]]
end
# the bounds of a shape in its OWN space
make a function called shape_bounds takes s returns b
let kind = s[5]
if kind == "plane" then
let inf = infinity()
return [[0 - inf, 0, 0 - inf], [inf, 0, inf]]
end
if kind == "cylinder" then
return [[-1, s[6][0], -1], [1, s[6][1], 1]]
end
if kind == "cone" then
let r = num_max(abs(s[6][0]), abs(s[6][1]))
return [[0 - r, s[6][0], 0 - r], [r, s[6][1], r]]
end
if kind == "triangle" or kind == "smooth_triangle" then
return triangle_bounds(s)
end
if kind == "group" then
return s[6][1]
end
if kind == "csg" then
return s[6][3]
end
if kind == "torus" then
return torus_bounds(s)
end
if kind == "implicit" or kind == "function" then
return s[6][1]
end
return [[-1, -1, -1], [1, 1, 1]]
end
# the smallest box holding the eight corners of box b sent through matrix m; a box
# with an infinite side is replaced by all of space (an infinite coordinate times a
# zero matrix entry is not a number)
make a function called transform_bounds takes m, b returns b2
let lo = [0, 0, 0]
let hi = [0, 0, 0]
let first = true
let ix = 0
while ix < 2 do
let iy = 0
while iy < 2 do
let iz = 0
while iz < 2 do
let x = b[ix][0]
let y = b[iy][1]
let z = b[iz][2]
if not (is_finite(x) and is_finite(y) and is_finite(z)) then
return whole_space()
end
let q = mat_tuple(m, point(x, y, z))
let c = [get_x(q), get_y(q), get_z(q)]
let k = 0
while k < 3 do
if first or c[k] < lo[k] then
let lo = list_set(lo, k, c[k])
end
if first or c[k] > hi[k] then
let hi = list_set(hi, k, c[k])
end
let k = k + 1
end
let first = false
let iz = iz + 1
end
let iy = iy + 1
end
let ix = ix + 1
end
return [lo, hi]
end
# a child's bounds in its parent's space (false for an empty group)
make a function called parent_space_bounds takes s returns b
let b = shape_bounds(s)
if b == false then
return false
end
# an untransformed child (every triangle of a mesh) is already in its parent's space
if s[1] == identity_matrix() then
return b
end
return transform_bounds(s[1], b)
end
make a function called bounds_union takes a, b returns u
if a == false then
return b
end
if b == false then
return a
end
let lo = [0, 0, 0]
let hi = [0, 0, 0]
let k = 0
while k < 3 do
let lo = list_set(lo, k, num_min(a[0][k], b[0][k]))
let hi = list_set(hi, k, num_max(a[1][k], b[1][k]))
let k = k + 1
end
return [lo, hi]
end
# [t_near, t_far] along one axis; [] if the ray misses the slab. The face at c is
# the plane vector pi = e_axis + c einf; for a point O (O . einf = -1) and a
# direction d, O . pi = o_axis - c and d . pi = d_axis, so t = (c - o_axis) / d_axis:
# read straight off the multivector, because this test runs at every group.
make a function called box_axis_range takes o, dvec, axis, lo, hi returns range
let inf = infinity()
let bit = 1 shl axis
let da = dvec[bit]
let oa = o[bit]
if abs(da) < epsilon() then
if (is_finite(lo) and oa < lo) or (is_finite(hi) and oa > hi) then
return []
end
return [0 - inf, inf]
end
let tlo = 0 - inf
let thi = inf
if is_finite(lo) then
let tlo = (lo - oa) / da
elif da < 0 then
let tlo = inf
end
if is_finite(hi) then
let thi = (hi - oa) / da
elif da < 0 then
let thi = 0 - inf
end
if tlo > thi then
return [thi, tlo]
end
return [tlo, thi]
end
make a function called box_hit takes b, r returns hit
# the hot path of every group and CSG shape, written straight on the ray's components
# (a point has x, y, z at 1, 2, 4 and a direction at 9, 10, 12) and the box's sides.
# A side at infinity gives t = +-infinity, so it constrains nothing; a ray parallel to
# an axis must lie between that axis' two sides, faces included.
let o = r[0]
let d = r[1]
let lo3 = b[0]
let hi3 = b[1]
let tmin = 0 - infinity()
let tmax = infinity()
let axis = 0
while axis < 3 do
let bit = 1
if axis == 1 then
let bit = 2
elif axis == 2 then
let bit = 4
end
let oa = o[bit]
let da = d[8 + bit]
if abs(da) < (1/100000) then
if oa < lo3[axis] or oa > hi3[axis] then
return false
end
else
let t1 = (lo3[axis] - oa) / da
let t2 = (hi3[axis] - oa) / da
if t1 > t2 then
let tmp = t1
let t1 = t2
let t2 = tmp
end
if t1 > tmin then
let tmin = t1
end
if t2 < tmax then
let tmax = t2
end
end
let axis = axis + 1
end
return tmin <= tmax
end
make a function called add_child takes g, s returns g2
let params = g[6]
return list_set(g, 6, [list_push(params[0], s), bounds_union(params[1], parent_space_bounds(s))])
end
make a function called group_local_intersect takes g, r returns xs
let params = g[6]
let kids = params[0]
if kids.length == 0 then
return []
end
if bounds_on(g) then
count_work(g, "box_tests", 1)
if not box_hit(params[1], r) then
return []
end
end
count_work(g, "groups_entered", 1)
let frame = group_frame(g)
let xs = []
# a group with a tree tries only the children the ray can reach, in their own order
let order = false
let tried = kids.length
if params.length > 2 then
let order = bvh_candidates(params[2], r)
let tried = order.length
end
count_work(g, "children_tested", tried)
let k = 0
while k < tried do
let which = k
if order != false then
let which = order[k][0]
end
let hs = intersect(kids[which], r)
let j = 0
while j < hs.length do
let xs = list_push(xs, list_set(hs[j], 1, attach_outer(hs[j][1], frame)))
let j = j + 1
end
let k = k + 1
end
return intersections(xs)
end
One more fact about the language: the built-in min and max return floats even
for exact arguments, which turned an exact box into one that compared unequal to
its expected value. The box code uses two comparison-based helpers, num_min and
num_max, so bounds of rational scenes stay rational.
Step 3 — checks
An empty group is hit by nothing; a group is hit wherever its children are, in order; a group's transform carries its children. Three overlapping shapes in a group, and the same in a turned, stretched group, are checked against their own functions (a group is every part of every child's surface, including the parts inside another child); a group's box holds every hit; and the hit lists with every child tried, with boxes, and with the tree of boxes are the same.
Further checks, sharing no code with what they check:
- A chain of groups against one shape with the product transformation: a
sphere two groups deep gives the same
tand the same world normal as a single sphere whose matrix is the product, with a negative control (leave a group out and the hit changes). - A pattern on a grouped shape gives the same colours as on the flattened shape.
- Bounds: every shape's box, exact boxes for scaled and translated spheres, a cube turned 45° reaching √2, infinite shapes becoming all of space, groups nesting.
- The ray/box test against the slab method on plain coordinates, 143 rays of which 70 hit, faces included.
- Boxes never lose a hit: for a grid of rays through a scene of nine rotated rings of spheres, the intersection list with the boxes on equals the list with them off, and the boxes do cull (groups entered ≪ boxes tested).
Step 4 — Putting it together: frames of rods and balls
polygon_frame(n, ...) makes a frame for any regular polygon: a ball at each corner and
a rod to the next corner, each rod a unit cylinder stretched to the length of a side,
laid along x and turned to point at the next corner, all in one group. The frame is then
a single shape: one transform stands it up, turns it and moves it. A hexagon frame
stands upright with gold balls and steel rods; a pentagon frame with the colours swapped
leans back beside it, on a checkered floor.
# a frame of n rods and n balls round a regular polygon of the given radius, lying in the
# x-z plane about the y axis: ball k at angle 2 pi k / n, a rod of radius `rod` from each
# ball to the next (a cylinder from y = 0 to 1, stretched to the rod's length, laid along
# x, then turned to point from one corner to the next), each ball and rod its own child
make a function called polygon_frame takes n, radius, rod, corner_m, rod_m returns g
let g = group()
let k = 0
while k < n do
let a0 = 2 * pi() * k / n
let a1 = 2 * pi() * (k + 1) / n
let x0 = radius * cos(a0)
let z0 = radius * sin(a0)
let dx = radius * cos(a1) - x0
let dz = radius * sin(a1) - z0
let len = sqrt(dx * dx + dz * dz)
let ball = set_material(set_transform(sphere(), mat_mul(translation(x0, 0, z0), scaling(rod * (8/5), rod * (8/5), rod * (8/5)))), corner_m)
let along = mat_mul(translation(x0, 0, z0), mat_mul(rotation_y(0 - atan2(dz, dx)), mat_mul(rotation_z(0 - pi() / 2), scaling(rod, len, rod))))
let bar = set_material(set_transform(with_limits(cylinder(), 0, 1), along), rod_m)
let g = add_child(add_child(g, ball), bar)
let k = k + 1
end
return g
end
# a hexagon frame standing up and a pentagon frame leaning back, on a checkered floor
make a function called build_hexagon_scene returns w
let floor_m = with_pattern(material_with(color(1, 1, 1), (1/10), (9/10), 0, 200), set_pattern_transform(checkers_pattern(color((9/10), (9/10), (9/10)), color((3/10), (3/10), (3/10))), scaling((1/2), (1/2), (1/2))))
let floor_p = set_material(plane(), floor_m)
let gold = with_reflective(material_with(color((9/10), (7/10), (1/10)), (1/10), (7/10), (6/10), 200), (1/10))
let steel = material_with(color((2/10), (4/10), (9/10)), (1/10), (7/10), (4/10), 100)
let hex = set_transform(polygon_frame(6, (17/20), (3/25), gold, steel), mat_mul(translation(-(11/10), (21/20), (3/5)), mat_mul(rotation_y((3/10)), rotation_x(pi() / 2))))
let pent = set_transform(polygon_frame(5, (17/20), (1/10), steel, gold), mat_mul(translation((6/5), (9/25), -(1/2)), mat_mul(rotation_y(-(2/5)), rotation_x((7/20)))))
return [[floor_p, hex, pent], demo_light(), true]
end
# Chapter 14, "Putting It Together": a hexagon built from groups -- sides of one
# sphere and one cylinder, rotated into a ring, with a smaller hexagon nested inside.
include "../lib/spec.patlang"
include "../lib/png.patlang"
include "../lib/camera.patlang"
include "../lib/demo_scene.patlang"
let w = build_hexagon_scene()
let cam = set_camera_transform(camera(400, 200, pi() / 3), view_transform(point(0, (12/5), -(13/2)), point(0, (9/10), (1/5)), vector(0, 1, 0)))
render_example(cam, w, "../out/ch14_hexagon.png")
> tools/prender.sh examples/ch14_hexagon.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 265 s wall clock
Checking it independently
The recursive tracer learned the frames by flattening them: each of the 22 leaves gets the product of its chain of transformations, so no group code is involved, and its normal is the transpose of the inverse of that product. Every second pixel in each direction:
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch14_hexagon.png -Scene hexagon -Stride 2
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 0 (max difference 0); stride 2 in each direction, 20000 pixels checked
Negative control: the same tracer against the Boxes, cylinders and cones image, which it should reject.
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch13_cylinders.png -Scene hexagon -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 3614 (max difference 190); stride 4 in each direction, 5000 pixels checked
Step 5 — what the boxes buy
A floor and n × n bags of nine marbles each, rendered at 80×40 with the boxes on
and off by tools/bench_bounds.sh (every run its own process, ten at a time, so
the absolute times include some contention). The last column compares a checksum of
all the pixel bytes: the picture is identical either way.
marbles boxes off boxes on speedup box tests bags entered same image
36 47774 ms 16445 ms 2.91x 25600 839 yes
81 80499 ms 21791 ms 3.69x 57600 718 yes
144 119446 ms 29307 ms 4.08x 102400 739 yes
324 214781 ms 47961 ms 4.48x 230400 652 yes
576 358052 ms 70099 ms 5.11x 409600 683 yes
With the boxes off, every ray tests every marble, so the time grows with the marble count (less than linearly overall, since the floor and the fixed work do not grow). With them on, a ray tests each bag's box and only the few bags it passes through, so the cost follows the number of bags, and the gain widens with the scene: 2.9× at 36 marbles, 5.1× at 576. Each bag holds only nine spheres, so a skipped bag saves nine sphere tests for the price of one box test; larger groups would gain more..
A Bounding-Volume Hierarchy
Groups and trees of boxes gave every group a box, and the performance page saw what that buys: a ray
that misses the box skips the whole group. Inside the box, though, a group still tries every
child. For a mesh of n triangles that is n triangle tests per ray, and it shows: a ray
through a sphere of 12 600 triangles costs a tenth of a second.
The fix is the same idea applied again, to the inside of the group. Put a box round each child; put a box round each pair of neighbouring boxes; and so on up to one box round the lot. A ray walks down from the top, and wherever it misses a box it skips everything below it. A mesh then costs a handful of triangle tests per ray, however large.the tree is a spatial index for the children
The rule: no picture may change
The performance page's rule stands. The tree only decides which children to try; the
children it picks are put back into their own order and tried exactly as the linear loop
tries them, so the list of hits is identical — the same t, to the last bit, in the same
order, ties included. The tests below compare hit lists, not pictures, against the plain
linear loop, which is kept as the oracle.
The tree
A node is [box, left, right]; a leaf, holding up to four children, is [box, indices].
A node is built by sorting its children along the longest side of its box, by the middle
of each child's box, and cutting the list in half. Children with no finite box, such as a
plane, cannot be put in a tree and sit in a short list of their own, tried every time.
A box is padded by a ten-millionth of its coordinates. A ray that touches a triangle at the very edge of a box can be called a miss by the slab test and a hit by the triangle test, because the two round differently, and losing that hit would change a picture. The padding costs nothing measurable and rules the case out.
group_with_bvh builds trees for a group and for every group inside it, and leaves groups of
fewer than 8 children alone: the walk costs more than it saves there. world_bounded calls
it on every top-level group, so render and render_band get the trees without a change to
any scene.
# the boxes' two corners as lists, padded
make a function called bvh_pad takes b returns padded
let lo = []
let hi = []
let k = 0
while k < 3 do
let lo = list_push(lo, b[0][k] - (1/10000000) * (1 + abs(b[0][k])))
let hi = list_push(hi, b[1][k] + (1/10000000) * (1 + abs(b[1][k])))
let k = k + 1
end
return [lo, hi]
end
make a function called bvh_finite takes b returns yes
if b == false then
return false
end
let k = 0
while k < 3 do
if abs(b[0][k]) >= infinity() or abs(b[1][k]) >= infinity() then
return false
end
let k = k + 1
end
return true
end
# a stable merge sort of [key, index] pairs, by key and then index
make a function called sort_pairs takes items returns sorted
if items.length <= 1 then
return items
end
let mid = floor(items.length / 2)
let left = []
let right = []
let i = 0
while i < items.length do
if i < mid then
let left = list_push(left, items[i])
else
let right = list_push(right, items[i])
end
let i = i + 1
end
let a = sort_pairs(left)
let b = sort_pairs(right)
let out = []
let i = 0
let j = 0
while i < a.length or j < b.length do
if j >= b.length or (i < a.length and (a[i][0] < b[j][0] or (a[i][0] == b[j][0] and a[i][1] <= b[j][1]))) then
let out = list_push(out, a[i])
let i = i + 1
else
let out = list_push(out, b[j])
let j = j + 1
end
end
return out
end
# the tree over the children `items` (indices), whose padded boxes are boxes[index]
make a function called bvh_build takes items, boxes returns node
let box = false
let k = 0
while k < items.length do
let box = bounds_union(box, boxes[items[k]])
let k = k + 1
end
if items.length <= 4 then
return [box, items]
end
# split at the middle of the children sorted along the longest side of the box
let axis = 0
let best = box[1][0] - box[0][0]
let a = 1
while a < 3 do
if box[1][a] - box[0][a] > best then
let best = box[1][a] - box[0][a]
let axis = a
end
let a = a + 1
end
let keyed = []
let k = 0
while k < items.length do
let b = boxes[items[k]]
let keyed = list_push(keyed, [b[0][axis] + b[1][axis], items[k]])
let k = k + 1
end
let sorted = sort_pairs(keyed)
let mid = floor(sorted.length / 2)
let left = []
let right = []
let k = 0
while k < sorted.length do
if k < mid then
let left = list_push(left, sorted[k][1])
else
let right = list_push(right, sorted[k][1])
end
let k = k + 1
end
return [box, bvh_build(left, boxes), bvh_build(right, boxes)]
end
# the group with a tree (and so does every group inside it); groups of fewer than 8 children
# are left as they are
make a function called group_with_bvh takes g returns g2
let params = g[6]
let kids = []
let k = 0
while k < params[0].length do
let kid = params[0][k]
if kid[5] == "group" then
let kid = group_with_bvh(kid)
end
let kids = list_push(kids, kid)
let k = k + 1
end
if kids.length < 8 then
return list_set(g, 6, [kids, params[1]])
end
let boxes = []
let items = []
let always = []
let k = 0
while k < kids.length do
let b = parent_space_bounds(kids[k])
if bvh_finite(b) then
let boxes = list_push(boxes, bvh_pad(b))
let items = list_push(items, k)
else
let boxes = list_push(boxes, false)
let always = list_push(always, k)
end
let k = k + 1
end
let tree = false
if items.length > 0 then
let tree = bvh_build(items, boxes)
end
return list_set(g, 6, [kids, params[1], [tree, always]])
end
# the indices of the children under the nodes the ray reaches, appended to out
make a function called bvh_walk takes node, r, out returns found
if not box_hit(node[0], r) then
return out
end
if node.length == 2 then
let found = out
let k = 0
while k < node[1].length do
let found = list_push(found, [node[1][k], 0])
let k = k + 1
end
return found
end
return bvh_walk(node[2], r, bvh_walk(node[1], r, out))
end
# the children to try for this ray, in the children's own order
make a function called bvh_candidates takes tree, r returns order
let found = []
if tree[0] != false then
let found = bvh_walk(tree[0], r, [])
end
let k = 0
while k < tree[1].length do
let found = list_push(found, [tree[1][k], 0])
let k = k + 1
end
return sort_pairs(found)
end
The group's own intersection is the old loop with one change: if the group has a tree, it loops over the candidates in the order the tree gives them rather than over all the children.
make a function called group_local_intersect takes g, r returns xs
let params = g[6]
let kids = params[0]
if kids.length == 0 then
return []
end
if bounds_on(g) then
count_work(g, "box_tests", 1)
if not box_hit(params[1], r) then
return []
end
end
count_work(g, "groups_entered", 1)
let frame = group_frame(g)
let xs = []
# a group with a tree tries only the children the ray can reach, in their own order
let order = false
let tried = kids.length
if params.length > 2 then
let order = bvh_candidates(params[2], r)
let tried = order.length
end
count_work(g, "children_tested", tried)
let k = 0
while k < tried do
let which = k
if order != false then
let which = order[k][0]
end
let hs = intersect(kids[which], r)
let j = 0
while j < hs.length do
let xs = list_push(xs, list_set(hs[j], 1, attach_outer(hs[j][1], frame)))
let j = j + 1
end
let k = k + 1
end
return intersections(xs)
end
Scenarios and oracles
- The tree is a tree. Every child is in it exactly once; every box contains the boxes below it; leaves hold at most four children; a group of two children gets no tree.
- The same answers. For a sphere of 396 triangles and 306 rays — hits, misses, rays that start inside, rays along an axis, rays that graze the poles — the group with a tree returns exactly the hits of the group without one, in the same order. The same under a transformation of the whole group.
- Ties. Ten identical triangles all hit at the same
t; they come back in the children's order with and without the tree. - A plane among the triangles is kept out of the tree and still found.
- Nested groups each get a tree, and the hits still match.
- The saving. A ray through 720 triangles tries all 720 in the linear loop and only a handful with the tree.
- Negative control: a tree with its leaves emptied loses hits on most of 200 rays.
What it costs, at four sizes and more
Doubling the mesh should double the cost of the linear loop, and barely move the tree's.
It also costs something to build: sorting is n log n.
> v2_interp.exe examples/ch23_bvh_bench.patlang
182 triangles: linear 53130 us a ray, tree 7450 us a ray (7.1x), tree built in 592 ms
396 triangles: linear 114810 us a ray, tree 8910 us a ray (12.8x), tree built in 1371 ms
750 triangles: linear 215750 us a ray, tree 9320 us a ray (23.1x), tree built in 3019 ms
1564 triangles: linear 400350 us a ray, tree 7720 us a ray (51.8x), tree built in 6417 ms
3100 triangles: linear 912440 us a ray, tree 9620 us a ray (94.8x), tree built in 9373 ms
6392 triangles: linear 1918850 us a ray, tree 9270 us a ray (206.9x), tree built in 31750 ms
12600 triangles: linear 3567060 us a ray, tree 9870 us a ray (361.4x), tree built in 68908 ms
The linear column doubles with each doubling of n; the tree's grows by about a tenth of
its previous value for each doubling, which is log n. The tree is built once per process;
a parallel render builds it once per band, so the build time is part of every band's
start-up (about 1.7 s at 6 400 triangles).
Nothing changed
The benchmark suite's pictures are byte-identical (its mesh scene, two spheres of about a hundred faces, goes from 3.9 s to 1.4 s), and so is the full-size picture of Triangles and meshes from files, rendered with trees:
> tools/prender.sh examples/ch15_meshes.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 1210 s wall clock
> cmp out/ch15_meshes.png docs/img/ch15_meshes.png && echo "the PNG is byte-identical to the one in [Triangles and meshes from files](15-meshes.md)"
the PNG is byte-identical to the one in [Triangles and meshes from files](15-meshes.md)
How it is checked
> v2_interp.exe tests/run.patlang --node shapes/groups --depth 2
[ ok ] Groups of shapes
[ ok ] An empty group is hit by nothing
[ ok ] A group is hit wherever its children are, in order of t
[ ok ] A group's transform carries its children
[ ok ] A group of three overlapping shapes: every part of every surface
[ ok ] Every hit lies on the surface
[ ok ] No crossing of the surface is missed
[ ok ] Normals follow the gradient of the surface's function
[ ok ] Groups in a turned, stretched group
[ ok ] Every hit lies on the surface
[ ok ] No crossing of the surface is missed
[ ok ] Normals follow the gradient of the surface's function
[ ok ] A group's bounding box holds every hit on its children
[ ok ] Three ways to search a group (all, giving the same answer)
[ ok ] naive: try every child, no boxes
[ ok ] faster: skip a child whose box the ray misses
[ ok ] fastest for many children: a tree of boxes
[ ok ] A tree of boxes for big groups
[ ok ] The tree
[ ok ] The same answers
[ ok ] The saving
[ ok ] Further checks, independent of the code they check
[ ok ] A sphere two groups deep: same t as the product transform
[ ok ] A pattern on a shape in a group sees the group's transformation
[ ok ] A sphere's bounds: -1 to 1
[ ok ] Ray/box agrees with the slab method on coordinates
[ ok ] Boxes on = boxes off: the same ts and shapes for all
[ ok ] A world with a box for each object finds exactly the intersections and shadows of the same world without them, on rays from inside and outside (negative t included)
checks: 26 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED
> v2_interp.exe tests/run.patlang --node shapes/bounds --depth 2
[ ok ] Bounding boxes
[ ok ] Each shape's own box
[ ok ] A transformed box holds the transformed corners of the original
[ ok ] The union of two boxes holds both
checks: 3 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED