Last updated: 2026-11-26

8. Making it fast without changing a pixel

For new readers

Before the larger scenes, the renderer was made faster without changing a single pixel: a benchmark with a checksum per picture, then exact shortcuts each kept beside the plain method it replaces, with a test that the two agree to the last bit. In the test tree these pairs are the agree nodes on the pages they belong to (the conformal algebra, matrices, each shape, groups, the world).

Making It Fast, Without Changing a Pixel

The Dalek took about 90 minutes a picture on 20 processes, and this pages before it were already slow enough to wait for. This page is about the renderer, not new features, and it has one rule: no picture may change. Every speed-up is checked against the picture it replaces, byte for byte.

Step 1 — a benchmark that can tell

tools/bench_suite.patlang renders thirteen small scenes (every shape kind, glass, meshes, CSG, soft shadows, spotlights, adaptive anti-aliasing, the implicit surfaces and the Dalek) and prints the time and a checksum of every pixel byte. tools/bench.sh runs them a few at a time, compares each checksum with tools/bench_checksums.txt and fails if one changed. A change that makes a scene faster but alters a picture shows up as a changed checksum, so a speed-up cannot be bought with a wrong image.

make a function called look takes w, width, from, to returns c
  return set_camera_transform(camera(width, floor(width / 2), pi() / 3), view_transform(from, to, vector(0, 1, 0)))
end

Step 2 — where the time went

Timing the pieces of one pixel of the scene of the camera and the world it looks at (a ray through a sphere) found that almost everything was spent on a few operations on 32-coefficient multivectors:

operation before what it really is
point + vector (position, over_point, under_point) 380 µs a translation: three additions
matrix × tuple (every ray, hit and normal) 30 µs four dot products
reflect 130 µs two geometric products to subtract a multiple of n
direction add, subtract, scale, negate 10–13 µs three numbers each, in a loop over 32
colour add, subtract, scale 10–13 µs three numbers each
sphere, plane, cylinder, cone, triangle tests 25–60 µs a quadratic on a few components

The algebra is the definition and is kept: each of these now has a written-out form that the tracer uses, and the original (tuple_translate_ga, mat_tuple_ga, reflect_ga, sphere_local_intersect_ga, and so on) stays beside it. Each has a test that runs both on a spread of inputs, including weighted points, non-unit normals, capped and limited cylinders and rays that miss. The matrix product, the direction and colour arithmetic and the intersection tests must agree bit for bit; the translation and the reflection are checked to within rounding error, because summing the products in another order moves the last bit (and the pictures that come out are identical, which is the real test).bitwise equality is strict; rounding varies by CPU

Step 3 — doing less

Faster arithmetic made every operation cheaper; four changes make the tracer ask for fewer of them. None can change which surface a ray meets.

  • Boxes for the world's objects. world_bounded gives each object a box in world space, once per picture, and a ray that misses the box (a line test, so intersections behind the origin that refraction needs are kept) never asks the object. Planes have no box.
  • The shadow search (shadow_blocker) stops at the first object in the way, tries first the object that blocked the previous sample of an area light (a soft shadow's samples nearly always share an occluder), and reuses one unit vector for both the "does this sample face the surface" test and the shadow ray. Which object is tried first cannot change whether the way is blocked, and a test checks that.
  • Refraction bookkeeping only for transparent hits. The walk over every intersection to find n1 and n2, and the under point, were done for every hit and used only by glass.
  • Corner rays shared between pixels. Adaptive anti-aliasing cast the four corners and the centre of each pixel, so every corner ray was cast four times, once from each pixel that touches it. A row of corners now serves the pixels above and below it: about two rays a pixel on flat areas instead of five. The ray through a corner is the same ray whichever pixel asks for it, so the picture is unchanged, and a test renders a band both ways and compares every byte.

Step 4 — results

The benchmark at the start of this page (checksums recorded) and now, in milliseconds (the "before" column was taken six scenes at a time, the "after" three at a time, so the comparison slightly favours the "after"):

> cat docs/data/bench_before.txt
scene          size         ms
spheres       60x30       6092
glass         60x30      19058
cubes         60x30       6437
cylinders     60x30       7304
hexagon       60x30       5476
meshes        60x30      10221
csg           60x30       6540
torus         60x30       5712
soft          60x30      55948
spot          60x30       3913
aa            60x30      58052
implicit      60x30       8657
dalek         16x22      12586
> cat docs/data/bench_after.txt
scene          size         ms  checksum
spheres       60x30        956  774126
glass         60x30       2605  237880
cubes         60x30        905  656092
cylinders     60x30        561  203247
hexagon       60x30        938  157408
meshes        60x30       3914  774187
csg           60x30       1088  543039
torus         60x30       1049  469550
soft          60x30       6904  630358
spot          60x30        588  771303
aa            60x30       2951  251204
implicit      60x30       2787  92193
dalek         16x22       3734  330676

Every checksum is the one recorded before the changes. Simple scenes run six to thirteen times faster, glass seven, the soft shadows eight, anti-aliasing twenty, and the Dalek about three. The Dalek spends most of its time in reflections (every steel and bronze part and the floor reflect, down to the depth limit), which no exact method can skip.

The whole front Dalek picture, with the same settings as in Built objects: solid geometry and a Dalek and 112 bands instead of 40 (smaller bands keep all 20 processes busy to the end): 1158 seconds, down from 5429, and the PNG is byte for byte the one rendered before.

Step 5 — fewer tests per ray, by asking about many rays at once

Steps 2 and 3 made each test cheaper and dropped the tests that could not matter. Later scenes (the meadow of the film has 414 top-level objects) showed where the time had gone next. A profile of one small picture of each kind, timing the same pixels four times with a little more work each time (the camera rays alone, then the first hit, then the shadow rays, then everything), gave three answers:

  • In the meadow, a camera ray passes the boxes of fewer than four of the 414 objects on average, and the box tests of the other 410 cost about as much as the intersections of the four. The shadow ray from each hit pays the same again.
  • Under an area light, the shadow rays are most of the time: 36 samples a point, each a ray through the world. In the scene of three solids with soft shadows they were three-quarters of the whole picture, and in the Dalek about three-fifths.
  • Shading itself (the lighting sums, patterns, fog) is a small share in every scene.

Both remedies keep the rule of this page: they decide only which tests are not needed, never the answer of a test, so every picture keeps its bytes.

A tree over the world

A big group already has a tree of boxes (Groups and trees of boxes). The world's own list of objects is the same problem one level up, so world_bounded now builds the same tree over the objects' boxes and keeps it in the world. A ray walks the tree, and only the objects under branches it reaches are tried, in the world's own order, so the list of hits is the plain loop's list, ties included. Objects with no box (the floor plane) are tried every time.

One trap: a frame of the film adds its rabbit to an already prepared meadow by joining the two lists of objects. A tree built for the meadow alone would never offer the rabbit to a ray. So the world keeps, with its tree, the number of objects it was built for, and a world whose count has changed searches the plain way.

make a function called world_with_tree takes w, boxes returns w2
  let objs = w[0]
  let w2 = w
  while w2.length < 8 do
    let w2 = list_push(w2, false)
  end
  if objs.length < 8 then
    return w2
  end
  let items = []
  let always = []
  let i = 0
  while i < objs.length do
    if boxes[i] != false then
      let items = list_push(items, i)
    else
      let always = list_push(always, i)
    end
    let i = i + 1
  end
  let tree = false
  if items.length > 0 then
    let tree = bvh_build(items, boxes)
  end
  return list_set(w2, 7, [objs.length, tree, always])
end

# the world's tree as [tree, always] (as bvh_candidates takes it), or false when it has none
# or the tree was built for other objects
make a function called world_tree takes w returns t
  if w.length < 8 or w[7] == false or world_boxes(w) == false then
    return false
  end
  if w[7][0] != w[0].length then
    return false
  end
  return [w[7][1], w[7][2]]
end

# the indices of the objects a ray may meet, in the world's own order
make a function called world_candidates takes w, r returns order
  let t = world_tree(w)
  let order = []
  if t == false then
    let i = 0
    while i < w[0].length do
      let order = list_push(order, i)
      let i = i + 1
    end
    return order
  end
  let found = bvh_candidates(t, r)
  let k = 0
  while k < found.length do
    let order = list_push(order, found[k][0])
    let k = k + 1
  end
  return order
end

# every intersection of the ray with every object, sorted by t
make a function called intersect_world takes w, r returns xs
  let all = []
  let objs = w[0]
  let boxes = world_boxes(w)
  let order = world_candidates(w, r)
  let k0 = 0
  while k0 < order.length do
    let i = order[k0]
    if may_hit(boxes, i, r) then
      let hits = intersect(objs[i], r)
      let k = 0
      while k < hits.length do
        let all = list_push(all, hits[k])
        let k = k + 1
      end
    end
    let k0 = k0 + 1
  end
  return intersections(all)
end
> v2_interp.exe tests/run.patlang --node picture/world/many --depth 2
[ ok ] A world of many objects
[ ok ]   Searching sixty-three objects  (all, giving the same answer)
[ ok ]     naive: test every object
[ ok ]     faster: a box test for every object
[ ok ]     faster again: a tree over the objects' boxes
[ ok ]   Shadows in a world of many objects  (all, giving the same answer)
[ ok ]     naive: test every object
[ ok ]     with the tree
[ ok ]   A world of more than a handful of objects gets a tree, and a ray tries few of its objects
[ ok ]   A tree whose world has had objects added (as a frame of the film adds its rabbit) is not used
[ ok ]   Negative control: a tree with all its leaves but one emptied gives different hits
checks: 8 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED

A clear way to the light

Every shadow ray from a point to the samples of a rectangular light lies inside one solid: the pyramid whose tip is the point and whose base is the light. If no object reaches into that pyramid, none of the 36 rays can be blocked, and the point sees the whole light without casting one. Whether a box and the pyramid share a point is a standard question about two convex solids: they are apart exactly when some direction separates their shadows on a line, and only a few directions need trying (the box's three edges, the pyramid's five faces, and the cross products of the box's edges with the pyramid's six edge directions). A plane has no box; it is moved into its own space, where it is y = 0, and is out of the way when all five corners of the pyramid are clearly on one side. With a tree over the world, the pyramid walks the tree as a ray does, so most objects are never looked at.

A separation must be wider than a hair before it counts, so rounding can only ever send a point to the plain loop, never let a shadow be missed.

# the pyramid's corners as plain numbers: the tip, then the light's four corners in order
make a function called hull_vertices takes p, light returns vs
  let c = light_corner(light)
  let u = tuple_mul(light_uvec(light), light_usteps(light))
  let v = tuple_mul(light_vvec(light), light_vsteps(light))
  let pts = [p, c, tuple_add(c, u), tuple_add(tuple_add(c, u), v), tuple_add(c, v)]
  let vs = []
  let k = 0
  while k < 5 do
    let vs = list_push(vs, [get_x(pts[k]) * 1.0, get_y(pts[k]) * 1.0, get_z(pts[k]) * 1.0])
    let k = k + 1
  end
  return vs
end

# does the axis a separate the pyramid from the box (centre c, half sizes h)? A gap must be
# wider than a hair, so that rounding can only ever make the test say "may meet"
make a function called hull_axis_apart takes vs, c, h, a returns apart
  let ax = a[0]
  let ay = a[1]
  let az = a[2]
  let size = abs(ax) + abs(ay) + abs(az)
  if size < 0.000000000001 then
    return false
  end
  let lo = vs[0][0] * ax + vs[0][1] * ay + vs[0][2] * az
  let hi = lo
  let k = 1
  while k < vs.length do
    let d = vs[k][0] * ax + vs[k][1] * ay + vs[k][2] * az
    if d < lo then
      let lo = d
    end
    if d > hi then
      let hi = d
    end
    let k = k + 1
  end
  let mid = c[0] * ax + c[1] * ay + c[2] * az
  let reach = h[0] * abs(ax) + h[1] * abs(ay) + h[2] * abs(az)
  let hair = 0.000000001 * size * (1 + abs(mid) + reach)
  return hi < mid - reach - hair or lo > mid + reach + hair
end

# may the pyramid (vertices vs: tip first, then the base in order around) and the box
# [lo, hi] share a point? The separating-axis test for two convex solids: they are apart
# exactly when some axis separates them, and the axes to try are the box's three, the
# pyramid's five face normals and the cross products of the box's axes with the pyramid's
# six edge directions
make a function called hull_may_meet_box takes vs, b returns yes
  let c = [(b[0][0] + b[1][0]) * 0.5, (b[0][1] + b[1][1]) * 0.5, (b[0][2] + b[1][2]) * 0.5]
  let h = [(b[1][0] - b[0][0]) * 0.5, (b[1][1] - b[0][1]) * 0.5, (b[1][2] - b[0][2]) * 0.5]
  let axes = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
  let k = 0
  while k < 3 do
    if hull_axis_apart(vs, c, h, axes[k]) then
      return false
    end
    let k = k + 1
  end
  let tip = vs[0]
  let edges = [hv_sub(vs[2], vs[1]), hv_sub(vs[4], vs[1])]
  let k = 1
  while k < 5 do
    let edges = list_push(edges, hv_sub(vs[k], tip))
    let k = k + 1
  end
  # the base, then the four sides
  if hull_axis_apart(vs, c, h, hv_cross(edges[0], edges[1])) then
    return false
  end
  let k = 1
  while k < 5 do
    let nxt = k + 1
    if nxt == 5 then
      let nxt = 1
    end
    if hull_axis_apart(vs, c, h, hv_cross(hv_sub(vs[k], tip), hv_sub(vs[nxt], tip))) then
      return false
    end
    let k = k + 1
  end
  let i = 0
  while i < 3 do
    let k = 0
    while k < edges.length do
      if hull_axis_apart(vs, c, h, hv_cross(axes[i], edges[k])) then
        return false
      end
      let k = k + 1
    end
    let i = i + 1
  end
  return true
end

# may object i of the world reach into the pyramid?
make a function called object_may_meet_hull takes w, i, vs returns yes
  let boxes = world_boxes(w)
  if boxes != false and boxes[i] != false then
    return hull_may_meet_box(vs, boxes[i])
  end
  let o = w[0][i]
  if shape_kind(o) == "plane" and o[7] == false then
    # the plane is y = 0 in its own space: apart when every corner is clearly on one side
    let above = 0
    let below = 0
    let k = 0
    while k < vs.length do
      let y = get_y(world_to_object(o, point(vs[k][0], vs[k][1], vs[k][2]))) * 1.0
      if y > 0.0000001 then
        let above = above + 1
      end
      if y < -0.0000001 then
        let below = below + 1
      end
      let k = k + 1
    end
    return not (above == vs.length or below == vs.length)
  end
  return true
end

# is the whole way from p to the light (a light with a size) clear of every object?
make a function called hull_clear takes w, light, p returns yes
  if light_kind(light) != "area" then
    return false
  end
  let vs = hull_vertices(p, light)
  let t = world_tree(w)
  if t == false then
    let i = 0
    while i < w[0].length do
      if object_may_meet_hull(w, i, vs) then
        return false
      end
      let i = i + 1
    end
    return true
  end
  # with a tree, only the objects under branches the pyramid reaches can be in the way
  let k = 0
  while k < t[1].length do
    if object_may_meet_hull(w, t[1][k], vs) then
      return false
    end
    let k = k + 1
  end
  if t[0] == false then
    return true
  end
  return hull_walk_clear(w, t[0], vs)
end

The checks include one that does not use the test at all: random boxes against random points of a pyramid, where a box said to be apart must never hold one of the points. Another builds the pyramid to a light shrunk on purpose and must find points where it misses a shadow: a check that the agreement test can fail.

> v2_interp.exe tests/run.patlang --node picture/lights/area/clear_way --depth 2
[ ok ] A point whose whole way to the light is clear casts no shadow rays
[ ok ]   Boxes beside, below, inside and near the pyramid to the light, decided by hand
[ ok ]   Where a point of the pyramid lies in a box, the test says they may meet
[ ok ]   The floor under a point does not reach into the pyramid above it; a tilted plane through it does
[ ok ]   With the shortcut, the samples seen are exactly those a plain loop finds, at every point of a grid
[ ok ]   A pyramid built to a light shrunk on purpose says clear where the plain loop finds a shadow
checks: 5 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED

What it gained

The meadow at 40 × 30, rendered twice in one process, with the world's tree and with boxes only:

> cat docs/data/world_tree.txt
meadow, 40 x 30, 414 top-level objects (PatLang v2, one process)
  with the tree over the world:  1015 s
  boxes only:                    1527 s
  bytes that differ:             0 of 3600

The tree saves a third of the time, and the two pictures have the same bytes. What remains is the work inside the objects a ray does reach (the blades of grass, the rabbit's fur), which no choice of objects can save.

The benchmark's soft shadows and the Dalek, before and after the clear way to the light (each pair run at the same time, so that both see the same load on the machine):

> cat docs/data/clear_way.txt
benchmark scenes, the four runs at the same time (PatLang v2)
scene          before    after   checksum
soft  60x30     435 s    287 s   630358 (unchanged)
dalek 16x22     190 s    187 s   943113 (unchanged)

The Dalek gains little, and the reason is instructive: a point on the Dalek is always inside the Dalek's own box, which is one box for the whole model, so its pyramid always seems to be in the way. Walking the pyramid down the Dalek's own tree, and casting the rays only at the parts it reaches, is the next step.

What did not work

PatLang can translate a program to Rust and compile it (pat --build-run). The renderer takes 34 minutes to compile that way, and the result is slower than the interpreter (2.5 seconds against 0.84 for the same picture, with the same checksum): the generated code still handles every number as a dynamic value, so there is nothing to gain from it here.

What is left

The hierarchy of boxes for large meshes has since been built (Groups and trees of boxes), and Step 5 extends it to the world. Still open: the pyramid to the light walked down a model's own tree; pyramids for blocks of camera rays, which would let a block of pixels share one search of the world; a convex-polytope primitive for the Dalek's skirt (nine half-space cubes now); and a cut-off for reflections whose weight is below one grey level, which is not exact, and so would need to be an option rather than a default.

Graduate Attributes

Modelled on this page

  • Researcher: Optimisations are validated against checksums to ensure numerical results remain identical to the original implementation.
  • Critical Thinker: Failed approaches are documented alongside successful ones to explain why certain technical choices were rejected.
  • Digitally Fluent: Performance profiling data is used to identify specific computational bottlenecks within the rendering pipeline.

University of Reading Graduate Attributes framework.