Last updated: 2026-11-26

7. One model, many threads, and the graphics card

For new readers

A film of a hundred and fifty frames is only practical if a picture can be shared out. This page does that twice: across the cores of the machine (one model, built once, read by many threads), and on the graphics card, with a renderer written in CUDA that uses the same equations in doubles and must give the very bytes the interpreter gives. The interpreter stays the oracle: the scenes the card renders are checked against it, byte for byte.

One Model, Many Threads

Until now a picture was rendered by many processes: the picture was cut into bands, one process per band, and each process built the whole scene for itself before it rendered a row. The model is not changed by rendering, so building it once per band is wasted work, and for the animals of Animals: a bird, a rabbit and a fox and Animals: a bird, a rabbit and a fox it was not small: reading the fur pictures and making 8 400 tufts took about a minute, 61 times over (60 bands and the assembly), and each process held its own copy of the pictures in memory.

The remedy is the one the model suggests: the model is one object, shared; what changes while rendering belongs to each worker. PatLang has parallel_map, which runs a function on each item of a list in its own thread. The scene is built once, and each thread is given the camera and the world (a value, shared and never written) and a list of bands.

What a thread must not share

What a thread changes must be its own. In PatLang v2 a vec, a string builder and an object's fields belong to one thread at a time: threads may read one together, but a thread that changes one while another reads it stops the program. Lists are values, which any number of threads can read. So the model holds nothing that rendering changes:shared state must be read-only else the program stops

  • Counters of work (boxes tested, children tried, rays cast, solver steps) are kept only by a Tracing object (lib/shape.patlang) that a test or benchmark gives a shape or a world (with_tracing, world_with_tracing) when it means to count; a threaded render is given none that counts.
  • A function surface's tape (Surfaces of any function) is only its instructions, a list. The four register files a run computes in are vecs made by whoever runs it, once a ray (fa_roots) or once a normal (fa_gradient), so each thread computes in its own.
  • A picture (a texture or a bump map) read from a file is a list, which every thread can read; a canvas being drawn on keeps its samples in a vec, and canvas_sample and pixel_at read either kind.
  • How far a render has got (the status server of a threaded render) is counted by each worker in a virtual file of its own (vfs_write, under a directory named for that render), which the server reads: the virtual files are what every thread of a process may change.
# The four register files a run works in ([value low, value high, derivative low, derivative high]),
# vecs as long as the tape. They are made by whoever runs the tape, once for all the runs of one
# ray (fa_roots) or one normal (fa_gradient): a vec belongs to the thread that writes it, so the
# threads of a threaded render (camera.patlang) each compute in their own.
make a function called fa_registers takes tape returns regs
  let n = tape[1]
  return [fa_zero_vec(n), fa_zero_vec(n), fa_zero_vec(n), fa_zero_vec(n)]
end

The threads' bands are interleaved (thread t renders bands t, t + n, t + 2n, โ€ฆ), so that the work is spread evenly although some bands cost more than others, and at most 18 threads are used, so that the computer can be used while a picture renders (--cores changes that; the process-based tools use at most 18 as well, PAT_CORES).

# what each thread does: render its bands, one after another
# (item: [camera, world, band numbers, number of bands, progress record or false, id of the thread])
make a function called render_bands_task takes item returns parts
  let parts = []
  let rows = 0
  let j = 0
  while j < item[2].length do
    let k = item[2][j]
    let y0 = band_start(item[0][1], item[3], k)
    let y1 = band_start(item[0][1], item[3], k + 1)
    let parts = list_push(parts, render_rows(item[0], item[1], y0, y1, item[4], item[5], rows))
    let rows = rows + (y1 - y0)
    let j = j + 1
  end
  rp_finish(item[4], item[5])
  return parts
end

# how many threads at most: all the cores but two, so that the computer can still be used while a picture renders
make a function called default_cores returns n
  return 18
end

# the whole image as RGB bytes, in `bands` bands rendered by `cores` threads at once (thread t takes bands t, t + cores, t + 2 cores, ...);
# the same bytes as render_band(c, w, 0, height)
make a function called render_threaded takes c, w, bands, cores returns bytes
  return render_threaded_progress(c, w, bands, cores, false)
end

# the bytes of bands 0 to bands - 1 in order, from the results of n threads of which thread t rendered bands t, t + n, t + 2 n, ...
make a function called join_bands takes results, bands, n returns bytes
  let bytes = []
  let k = 0
  while k < bands do
    let part = results[k % n][to_int(floor(k / n))]
    let j = 0
    while j < part.length do
      let bytes = list_push(bytes, part[j])
      let j = j + 1
    end
    let k = k + 1
  end
  return bytes
end

Scenarios and oracles

The oracle is the serial render: the same picture, byte for byte, from render_band over all the rows. The scenes use everything a thread has to read: function surfaces with a twist and a smooth union and CSG and a reflecting floor; a grass texture, a bump map and a tree (and the bounding hierarchy of Groups and trees of boxes); the fur picture and a body of ellipsoids; and a stereo pair in fog. The number of threads differs from the number of bands each time (5 bands on 2 threads, 7 on 3, 3 on 8).

Everything before still passes (the 36 test files, in the order the files are named), and the benchmark's picture checksums are those they were.

What it costs and saves

The pond garden of Trees, plants and a garden at 240 ร— 144 pixels in 36 bands, rendered by 18 processes and by 18 threads:

wall clock
18 processes (RENDER_PROCS=1 tools/render_scene.sh) 192 s
18 threads (tools/render_scene.sh) 95 s

and the two PNG files are identical. Of the 95 s, 76 s were rendering and about 19 s building the scene once. tools/render_scene.sh now renders by threads; RENDER_PROCS=1 gives the processes back.

What has not changed: the examples that are not written in the scene language (examples/*.patlang) render by processes through tools/prender.sh, or by threads when given --threads n; they call render_example, which takes both.

The Graphics Card

The picture of the rabbit in the meadow took two hours on eighteen cores, and a hundred and fifty frames of it would take days. The work is made for a graphics card: every pixel is its own problem, no pixel needs another's answer, and the arithmetic is floating point. This page puts the renderer on the card, and keeps what makes this renderer this one. It does not turn anything into triangles, and it does not use a ray-tracing library. It runs the same equations, in the same order, in the same double precision, on the same scene, and it is checked against the interpreter's pictures byte by byte.

The plan: the interpreter stays the oracle

PatLang still builds the scene. Nothing about the language, the scene files, the expressions, the rigs or the fur changes. A step in the middle writes the built world as plain text (the exporter that the independent PowerShell checks already read), and a program in CUDA reads that text, uploads it to the card, and renders it.

scene file โ”€โ”€(PatLang builds it)โ”€โ”€> world โ”€โ”€(tools/export_scene.patlang)โ”€โ”€> text โ”€โ”€(gpu/rt.exe)โ”€โ”€> picture
                                                                                         ^
the interpreter's own renderer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ same picture? โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The text has one line for each fact the renderer needs: V and K (the camera, as the library holds it, down to the inverse of its view matrix), A (the fog), Q (the antialiasing the scene asks for), S (the light, one line for each sample of an area light), P (a shape, with its matrix and its material), N, U, B (its pattern, its texture map, its bump map), C (a CSG node), F (the tape of a function surface), and T (a shape of the world).

# Writes a scene as plain text for the independent checker (tools/verify_recursive.ps1
# -SceneFile): groups flattened, every shape with its full transformation matrix, CSG
# nodes by reference, the light's sample points, the camera.
#   v2_interp.exe tools/export_scene.patlang --view front|side --out out/dalek_front.txt
#   v2_interp.exe tools/export_scene.patlang --scene lawn --view front --out out/lawn_front.txt
#   v2_interp.exe tools/export_scene.patlang --scene implicit --out out/implicit.txt
#   v2_interp.exe tools/export_scene.patlang --scene file --file scenes/garden.scene --out out/garden.txt
#
#   V from(3) to(3) fov            the camera
#   H shift                        the window of the camera moved sideways by this much (a stereo eye)
#   A density falloff r g b        the atmosphere (fog and mist), if the scene has one
#   K w h hw hh pixel_size ox oy oz m(16)   the camera as the library holds it: size in pixels, half width and height, pixel size, where rays start, the inverse of the view (by rows)
#   Q aa n | Q adaptive depth threshold   the scene's antialiasing
#   M g top step range             air that bends light (a mirage), if the scene has it
#   S x y z                        one sample point of the (area) light
#   P id kind m(16) a d s sh refl trn ri r g b [extra]
#                                  a primitive; m is its matrix by rows; extra: the
#                                  cylinder's min max closed, the torus's R r, an implicit surface's
#                                  box (6 numbers), term count and terms (c i j k); a triangle's first point,
#                                  two edges and normal (12 numbers) and, if smooth, its three vertex normals (9 more)
#   N id kind r g b r g b m(16)    the primitive's pattern (stripe/checkers): two colours, matrix by rows
#   U id mapping checkers w h r g b r g b m(16)
#   U id mapping image nearest|smooth path m(16)
#   U id cube cube <six of the above, left front right back up down> m(16)
#                                  the primitive's texture map: its mapping (spherical, planar, cylindrical), the UV
#                                  pattern, the pattern's matrix by rows (the picture is the PPM file at `path`)
#   B id mapping normal_map|height_map strength path m(16)
#                                  the primitive's bump map: mapping, kind, strength, the PPM file, the bump's matrix
#   F id x0 y0 z0 x1 y1 z1 nreg out n (code a b k)*   the tape of a function surface: box, registers, output register, instructions
#   X id x0 y0 z0 x1 y1 z1 text    the text an implicit surface was typed as (statements joined by ;)
#   C id op left right             a CSG node
#   T id                           a shape of the world (everything else hangs below these)

Writing a shape is shared by the whole-scene exporter and by the animation's (below), so it lives in lib/export.patlang.

One thread to a pixel

The kernel is the renderer of parts II and IV written for a thread. A ray is made for the pixel (the camera's own numbers, so that the ray is the interpreter's ray to the last bit), the shapes are tried, the nearest hit is taken, and the colour is the Phong colour at that point, plus reflection and refraction by recursion, blended by Schlick's approximation, and finally mixed with the fog. The adaptive antialiasing is the book's scheme: four corners and the centre, cut into quarters where a corner differs from the centre by more than a threshold.

__device__ V3 shade_at(V3 org, V3 dir, int rem, double t, int prim) {
  const Shape &s = S.shapes[prim];
  V3 p = add(org, mul(dir, t));
  V3 op = apply_pt(s.ti, p), ln;
  if (s.kind == K_TRIANGLE) ln = mk(s.tv[9], s.tv[10], s.tv[11]);
  else if (s.kind == K_SMOOTH) {
    double tt, u = 0, v = 0;
    tri_intersect(s, apply_pt(s.ti, org), apply_dir(s.ti, dir), tt, u, v);
    const double *w = s.tv;
    double a = 1 - u - v;
    ln = mk(w[15] * u + w[18] * v + w[12] * a, w[16] * u + w[19] * v + w[13] * a, w[17] * u + w[20] * v + w[14] * a);
  }
  else if (s.kind == K_FUNCTION) ln = function_normal(s, op);
  else if (s.kind == K_TORUS) ln = torus_normal(s, op);
  else if (s.kind == K_IMPLICIT) ln = implicit_normal(s, op);
  else if (s.kind == K_PLANE) ln = mk(0, 1, 0);
  else if (s.kind == K_CUBE) {
    double ax = fabs(op.x), ay = fabs(op.y), az = fabs(op.z);
    double mx = fmax(ax, fmax(ay, az));
    if (mx == ax) ln = mk(op.x, 0, 0); else if (mx == ay) ln = mk(0, op.y, 0); else ln = mk(0, 0, op.z);
  } else if (s.kind == K_CYLINDER || s.kind == K_CONE) {
    double dist = op.x * op.x + op.z * op.z, rmax, rmin;
    if (s.kind == K_CYLINDER) { rmax = 1; rmin = 1; } else { rmax = s.mx * s.mx; rmin = s.mn * s.mn; }
    if (dist < rmax && op.y >= s.mx - EPS) ln = mk(0, 1, 0);
    else if (dist < rmin && op.y <= s.mn + EPS) ln = mk(0, -1, 0);
    else if (s.kind == K_CYLINDER) ln = mk(op.x, 0, op.z);
    else { double yy = sqrt(dist); if (op.y > 0) yy = -yy; ln = mk(op.x, yy, op.z); }
  } else ln = mk(op.x, op.y, op.z);
  V3 nrm = unit(apply_dir_t(s.ti, ln));
  V3 eye = mul(dir, -1.0);
  if (dot(nrm, eye) < 0) nrm = mul(nrm, -1.0);
  if (s.bump) nrm = perturb_normal(s, p, nrm);
  V3 over = add(p, mul(nrm, EPS)), under = add(p, mul(nrm, -EPS));
  // n1 and n2 by the walk over the sorted hits (needed only where light goes through the surface)
  double n1 = 1.0, n2 = 1.0;
  if (s.trn != 0) media_indices(org, dir, n1, n2);
  V3 base = s.c;
  if (s.pat != P_NONE) base = pat_color(s, over);
  V3 surf = mk(0, 0, 0);
  V3 eff = mk(base.x * S.lcol.x, base.y * S.lcol.y, base.z * S.lcol.z);   // the surface colour under the light's colour (lighting_color: effective)
  double factor = 1;
  if (S.spot) {   // a spotlight: full inside the inner half-angle, none at and beyond the outer, linear in the angle between (light.patlang: spot_factor)
    V3 sv = sub(over, S.lights[0]);
    if (sqrt(dot(sv, sv)) != 0) {
      double cs = dot(S.sdir, unit(sv));
      if (cs > 1) cs = 1;
      if (cs < -1) cs = -1;
      double theta = acos(cs);
      if (theta <= S.sinner) factor = 1;
      else if (theta >= S.souter) factor = 0;
      else factor = (S.souter - theta) / (S.souter - S.sinner);
    }
  }
  for (int li = 0; li < S.nlights; li++) {
    V3 lp = S.lights[li];
    V3 lv = unit(sub(lp, over));
    double ldn = dot(lv, nrm);
    surf = add(surf, mul(eff, s.a));
    if (ldn >= 0 && factor > 0) {
      V3 sd = sub(lp, over);
      double dist = sqrt(dot(sd, sd));
      sd = unit(sd);
      bool shadowed = any_hit(over, sd, dist);
      if (!shadowed) {
#ifdef NEGCTL
        surf = add(surf, mul(base, s.d * ldn * 1.05));   // negative control
#else
        surf = add(surf, mul(eff, s.d * ldn * factor));
#endif
        V3 inv = mul(lv, -1.0);
        double k2 = 2 * dot(inv, nrm);
        V3 rv = sub(inv, mul(nrm, k2));
        double rde = dot(rv, eye);
        if (rde > 0) {
#ifdef NEGCTL
          double f = pow(rde, s.sh + 1);   // negative control: a deliberate change that the comparison must catch
#else
          double f = pow(rde, s.sh);
#endif
          double sp = s.s * f * factor;
          surf = add(surf, mk(S.lcol.x * sp, S.lcol.y * sp, S.lcol.z * sp)); }
      }
    }
  }
  surf = mul(surf, 1.0 / S.nlights);
  V3 refl = mk(0, 0, 0);
  if (s.refl != 0 && rem >= 1) {
    double kk = 2 * dot(dir, nrm);
    V3 rd = sub(dir, mul(nrm, kk));
    refl = mul(trace(over, rd, rem - 1), s.refl);
  }
  V3 refr = mk(0, 0, 0);
  bool tir = false;
  double ratio = n1 / n2, cosI = dot(eye, nrm), sin2T = ratio * ratio * (1.0 - cosI * cosI);
  if (sin2T > 1.0) tir = true;
  if (s.trn != 0 && rem >= 1 && !tir) {
    double cosT = sqrt(1.0 - sin2T);
    V3 rf = sub(mul(nrm, ratio * cosI - cosT), mul(eye, ratio));
    refr = mul(trace(under, rf, rem - 1), s.trn);
  }
  V3 seen;
  if (s.refl > 0 && s.trn > 0) {
    double cosS = cosI, reflectance = 0;
    bool skip = false;
    if (n1 > n2) { if (tir) { reflectance = 1.0; skip = true; } else cosS = sqrt(1.0 - sin2T); }
    if (!skip) {
      double r0 = pow((n1 - n2) / (n1 + n2), 2.0);
      reflectance = r0 + (1 - r0) * pow(1 - cosS, 5.0);
    }
    seen = add(surf, add(mul(refl, reflectance), mul(refr, 1 - reflectance)));
  } else seen = add(surf, add(refl, refr));
  return seen;
}

The shapes of the book (sphere, plane, cube, cylinder, cone) and CSG trees of them are intersected as the interpreter does it, the CSG by merging the hits of the two sides and keeping or dropping them by the rule of the operation. A pattern or a texture map is looked up at the point; a bump map tilts the normal. All of it is the library's arithmetic, function by function (lib/texture.patlang, lib/bump.patlang), not the independent checker's.

What it is for

The picture this was started for, the rabbit in its meadow at 800 x 600 with adaptive antialiasing, took the interpreter 7412 seconds on eighteen cores.

a rabbit sitting up in a meadow, an oak behind it, flowers in front

A tree over the world

The meadow has six and a half thousand shapes, nearly all of them the cones of the fur. A ray cannot try them all. The host builds a bounding-volume tree over the roots of the world (the box of each root, then boxes of boxes, split at the middle along the longest axis), uploads it, and a ray walks it with a small stack of its own, skipping a branch whose box the ray misses. A tree only skips shapes that could not have been hit, so it cannot change a picture. One thing could: when two shapes are hit at exactly the same distance, the one that comes first in the world wins (as in a stable sort), so a tie goes to the lower index and not to whichever branch the walk met first.BVH culls empty space so the ray never tests shapes it cannot hit

// the slab test of the ray against a node's box (conservative: a box is a little larger than the shape)
__device__ inline bool hits_box(const Node &nd, V3 org, V3 inv, double tmax) {
  double o[3] = {org.x, org.y, org.z}, iv[3] = {inv.x, inv.y, inv.z};
  double t0 = -1e300, t1 = tmax;
  for (int a = 0; a < 3; a++) {
    double ta = (nd.lo[a] - o[a]) * iv[a], tb = (nd.hi[a] - o[a]) * iv[a];
    if (ta != ta || tb != tb) { if (o[a] < nd.lo[a] || o[a] > nd.hi[a]) return false; continue; }   // a ray parallel to the slab and on its plane
    if (ta > tb) { double x = ta; ta = tb; tb = x; }
    if (ta > t0) t0 = ta;
    if (tb < t1) t1 = tb;
  }
  return t0 <= t1;
}

__device__ inline V3 inv_dir(V3 d) { return mk(1.0 / d.x, 1.0 / d.y, 1.0 / d.z); }

// every hit of the ray with the world, sorted by t (for the walk over the surfaces a ray is inside, which only a transparent surface needs)
__device__ __noinline__ int all_hits(V3 org, V3 dir, Hit *h) {
  int n = 0;
  V3 inv = inv_dir(dir);
  for (int r = 0; r < S.nunb; r++) node_hits(S.unbounded[r], org, dir, h, n, MAXH);
  if (S.nnodes > 0) {
    int stack[48], sp = 0;
    stack[sp++] = 0;
    while (sp > 0) {
      const Node &nd = S.nodes[stack[--sp]];
      if (!hits_box(nd, org, inv, 1e300)) continue;
      if (nd.left < 0) node_hits(S.roots[nd.right], org, dir, h, n, MAXH);
      else { stack[sp++] = nd.left; stack[sp++] = nd.right; }
    }
  }
  return n;
}

// the smallest t >= 0 at which the root is hit; the primitive hit is returned in prim
__device__ bool root_first(int root, V3 org, V3 dir, double &best, int &prim) {
  STAT(1);
  const Shape &s = S.shapes[root];
  bool found = false;
  if (s.kind != K_CSG) {
    double ts[MAXROOTS + 8];
    int k = prim_hits(s, org, dir, ts);
    for (int i = 0; i < k; i++) if (ts[i] >= 0 && (!found || ts[i] < best)) { best = ts[i]; prim = root; found = true; }
    return found;
  }
  Hit h[MAXH]; int n = 0;
  node_hits(root, org, dir, h, n, MAXH);
  for (int i = 0; i < n; i++) if (h[i].t >= 0) { best = h[i].t; prim = h[i].s; return true; }
  return false;
}

// the nearest hit with t >= 0 (ties go to the root that comes first in the world, as in a stable sort)
__device__ __noinline__ bool closest_hit(V3 org, V3 dir, double &best, int &prim) {
  STAT(2);
  bool found = false; int best_root = 0x7fffffff;
  V3 inv = inv_dir(dir);
  for (int r = 0; r < S.nunb; r++) {
    double t; int p;
    int root = S.unbounded[r];
    if (root_first(root, org, dir, t, p) && (!found || t < best || (t == best && root < best_root))) { best = t; prim = p; best_root = root; found = true; }
  }
  if (S.nnodes > 0) {
    int stack[48], sp = 0;
    stack[sp++] = 0;
    while (sp > 0) {
      const Node &nd = S.nodes[stack[--sp]];
      if (!hits_box(nd, org, inv, found ? best : 1e300)) continue;
      if (nd.left < 0) {
        double t; int p; int root = S.roots[nd.right];
        if (root_first(root, org, dir, t, p) && (!found || t < best || (t == best && root < best_root))) { best = t; prim = p; best_root = root; found = true; }
      } else { stack[sp++] = nd.left; stack[sp++] = nd.right; }
    }
  }
  return found;
}

// is there a hit with 0 <= t < dist (a shadow ray)
__device__ __noinline__ bool any_hit(V3 org, V3 dir, double dist) {
  STAT(3);
  V3 inv = inv_dir(dir);
  for (int r = 0; r < S.nunb; r++) { double t; int p; if (root_first(S.unbounded[r], org, dir, t, p) && t < dist) return true; }
  if (S.nnodes > 0) {
    int stack[48], sp = 0;
    stack[sp++] = 0;
    while (sp > 0) {
      const Node &nd = S.nodes[stack[--sp]];
      if (!hits_box(nd, org, inv, dist)) continue;
      if (nd.left < 0) { double t; int p; if (root_first(S.roots[nd.right], org, dir, t, p) && t < dist) return true; }
      else { stack[sp++] = nd.left; stack[sp++] = nd.right; }
    }
  }
  return false;

Two more savings are exact too. Only a surface that light goes through needs the list of every hit along the ray (to find out which medium the ray was in, for refraction), so only a transparent surface asks for it, and a shadow ray stops at the first hit it finds.

Being the same

The first scene came out right on the first try: every byte equal. The next, at twice the size and with the antialiasing, was not. Two columns of pixels down the middle of the picture, where the camera looks straight along the line of symmetry of the scene, differed by up to 26 levels, and nowhere else.

The ground is a checker pattern whose boundary lies exactly on the middle line, so a ray there is on a knife edge: whether a point at x = 0 is in one square or the next depends on whether the arithmetic gave it 0 or -1e-17. The camera's matrices in the library produce an exact 0 where the card produced a tiny negative number. The card was not wrong in any way a person could see, but it was not the same, and the reason was that the CUDA compiler fuses a multiplication and an addition into one operation with one rounding (a fused multiply-add) unless it is told not to. The interpreter rounds after each. With -fmad=false, every byte matched again.

That is the whole difficulty of "the same maths on another machine", in one flag: the answers are the same only if the arithmetic is the same operation for operation, and the compiler's idea of an equivalent expression is not always yours. Functions of the C library for sin, exp, atan2 and acos are not required to agree to the last bit between the card and the interpreter, and they do not always: they account for the few bytes below that differ by one level.

Function surfaces

The rabbit's body and the ground are function surfaces (Surfaces of any function): a ray is followed through interval arithmetic that bounds the function and its slope along each stretch of ray, stretches are halved until the function is monotone on them, and a bracketed Newton finds the root. The card runs the same instructions: the tape that the library compiles (F lines of the exported text), each opcode with the same interval rules, the same halving, the same Newton and bisection, the same cut-off at a hundred thousand steps, the same sort and the same removal of a root found twice.

__device__ int fa_roots(const Shape &s, V3 o, V3 d, double t0, double t1, double *out) {
  double ts[MAXROOTS]; int nts = 0;
  double stk[256][2]; int sp = 0;
  stk[sp][0] = t0; stk[sp][1] = t1; sp++;
  int steps = 0, limit = 100000;
  double tol = 0.0000000001 * (1 + fabs(t1));
  while (sp > 0 && steps < limit) {
    sp--;
    double a = stk[sp][0], b = stk[sp][1];
    steps++;
    double xl = o.x + d.x * a, xh = o.x + d.x * b, yl = o.y + d.y * a, yh = o.y + d.y * b, zl = o.z + d.z * a, zh = o.z + d.z * b;
    double xi[4] = {nmin(xl, xh), nmax(xl, xh), d.x, d.x}, yi[4] = {nmin(yl, yh), nmax(yl, yh), d.y, d.y}, zi[4] = {nmin(zl, zh), nmax(zl, zh), d.z, d.z}, r[4];
    fa_run(s, xi, yi, zi, true, r);
    if (r[0] > 0 || r[1] < 0) {
      // no root here
    } else if (r[2] > 0 || r[3] < 0) {
      double fa, fb, dd;
      fa_point(s, o, d, a, fa, dd);
      fa_point(s, o, d, b, fb, dd);
      if (fa * fb <= 0) {
        double t = fa_refine(s, o, d, a, b, fa, fb);
        double ft;
        fa_point(s, o, d, t, ft, dd);
        if (fabs(ft) <= 0.000001 * (fabs(fa) + fabs(fb)) && nts < MAXROOTS) ts[nts++] = t;
      }
    } else if (b - a <= tol) {
      double fa, fb, dd;
      fa_point(s, o, d, a, fa, dd);
      fa_point(s, o, d, b, fb, dd);
      if (fa * fb < 0 && fabs(r[0]) < inf_d() && fabs(r[1]) < inf_d() && nts < MAXROOTS) ts[nts++] = (a + b) / 2;
    } else {
      double mid = (a + b) / 2;
      if (sp + 2 <= 256) {
        stk[sp][0] = mid; stk[sp][1] = b; sp++;
        stk[sp][0] = a; stk[sp][1] = mid; sp++;
      }
    }
  }
#ifdef STATS
  if (steps > 1000) STAT(5);
  if (steps > 10000) STAT(6);
  if (steps >= limit) STAT(7);
#endif
  for (int i = 1; i < nts; i++) { double v = ts[i]; int j = i; while (j > 0 && ts[j - 1] > v) { ts[j] = ts[j - 1]; j--; } ts[j] = v; }
  int n = 0;
  for (int k = 0; k < nts; k++) if (n == 0 || ts[k] - out[n - 1] > 0.000000001 * (1 + fabs(ts[k]))) out[n++] = ts[k];
  return n;
}

// the stretch of the ray inside a box, as lib/shape.patlang: box_range
__device__ bool box_range(const double *b, V3 o, V3 d, double &tmin, double &tmax) {
  double oo[3] = {o.x, o.y, o.z}, dd[3] = {d.x, d.y, d.z};
  tmin = 0 - inf_d(); tmax = inf_d();
  for (int ax = 0; ax < 3; ax++) {
    double da = dd[ax], oa = oo[ax], lo = b[ax], hi = b[3 + ax], tlo, thi;
    if (fabs(da) < EPS) {
      if (oa < lo || oa > hi) return false;
      tlo = 0 - inf_d(); thi = inf_d();
    } else {
      tlo = (lo - oa) / da; thi = (hi - oa) / da;
      if (tlo > thi) { double x = tlo; tlo = thi; thi = x; }
    }
    if (tlo > tmin) tmin = tlo;
    if (thi < tmax) tmax = thi;
  }
  return tmin <= tmax;
}

The first version walked the tape as the interpreter does, an instruction at a time. It was correct, and it took 9.1 seconds for the 240 x 180 meadow (the interpreter: 1617 seconds on eighteen cores). On a card an instruction fetched and a register read are memory reads with a long wait, and a tape of a hundred and twenty instructions has a chain of them.

The second version is the same program written out. gpu/gen_tapes.py reads the tapes of the scene and writes each as straight-line CUDA, with the registers as variables, so that the compiler keeps them wherever it likes and there is nothing to fetch. It does the arithmetic in the same order, so the answers are the same bytes (the check below renders a scene both ways and compares). The picture took 4.6 seconds instead of 9.1.

"""Writes the tapes of the function surfaces of exported scenes (the F lines) as straight-line CUDA code, one device function for each distinct tape.

   py -3.11 gpu/gen_tapes.py gen_tapes.cuh scene.txt [more.txt ...]

Two tapes with the same instructions and different numbers (the rabbit of one frame of the animation and the rabbit of the next) are the same
function: the numbers are read from the scene when it runs, and only the shape of the tape is compiled in. rt.cu looks each tape of its scene up by that
shape (gen_keys below) and walks the tapes it does not find.

The interpreter in rt.cu (fa_run) walks a tape instruction by instruction, and on a graphics card that walk is slow: each instruction is a read
of memory and a chain of dependent reads of the registers. The function written here does the same arithmetic in the same order, with the registers as
variables, so the compiler keeps them where it likes and there is nothing to fetch. It is the same program, written out for one tape.
rt.cu finds each tape of its scene among these by its shape, so the tapes are not numbered by the scene.

The numbers of a tape are not compiled in, only its shape: two tapes with the same instructions and different constants are the same function, the constants being read when it runs. That matters for the animation, where the rabbit's tapes change from one frame to the next in their numbers but, over a hundred and fifty frames, take only eight distinct shapes. They are compiled once.

One launch, or many

The first timings of the meadow were ten times worse than they should have been, and the cause was not in the arithmetic at all. A picture can be made in one launch of the kernel, or in bands of rows, one launch each (the first version made bands, so that no launch would run long enough for the system to stop it as a hung program). A launch is over when its slowest thread is. The rabbit's fur and the ground's function surface make a few pixels a thousand times dearer than their neighbours, so each band waits for its few dear pixels, and the bands' waits add up. The same picture, the same arithmetic:

bands of    8 rows   32.8 s
bands of   20 rows   15.7 s
bands of   45 rows    7.8 s
bands of   90 rows    7.9 s
the whole picture      4.6 s

One launch is the default. It is only a few seconds here, and on this machine the system's watchdog did not stop launches of that length; --rows n makes bands where it would.

Checks

gpu/check_all.sh renders each scene with the interpreter and on the card and compares the pictures:

scene by scene (interpreter picture against the card's):
  fog_test_200x120: rendered 200x120 on the card in 55.1 ms (10 shapes)
  fog_test_200x120: 200x120: bytes equal 72000/72000; pixels differing by more than 1: 0/24000; by exactly 1: 0; max difference 0
  gpu_basic_400x240: rendered 400x240 on the card in 75.0 ms (19 shapes)
  gpu_basic_400x240: 400x240: bytes equal 288000/288000; pixels differing by more than 1: 0/96000; by exactly 1: 0; max difference 0
  gpu_textures_200x120: rendered 200x120 on the card in 38.3 ms (4 shapes)
  gpu_textures_200x120: 200x120: bytes equal 71998/72000; pixels differing by more than 1: 0/24000; by exactly 1: 2; max difference 1
  threads_test_120x80: rendered 120x80 on the card in 79.8 ms (7 shapes)
  threads_test_120x80: 120x80: bytes equal 28800/28800; pixels differing by more than 1: 0/9600; by exactly 1: 0; max difference 0
  mirage_160x80: rendered 160x80 on the card in 50.1 ms (90 shapes)
  mirage_160x80: 160x80: bytes equal 38400/38400; pixels differing by more than 1: 0/12800; by exactly 1: 0; max difference 0
  stereo_test left eye 100x60: 100x60: bytes equal 18000/18000; pixels differing by more than 1: 0/6000; by exactly 1: 0; max difference 0
  stereo_test right eye 100x60: 100x60: bytes equal 18000/18000; pixels differing by more than 1: 0/6000; by exactly 1: 0; max difference 0
  ch15 meshes 400x200: 400x200: bytes equal 240000/240000; pixels differing by more than 1: 0/80000; by exactly 1: 0; max difference 0
  torus 400x200: bytes equal 240000/240000; pixels differing by more than 1: 0/80000; by exactly 1: 0; max difference 0
  torus (torus by interval) 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  spot 400x200: bytes equal 240000/240000; pixels differing by more than 1: 0/80000; by exactly 1: 0; max difference 0
  implicit 400x200: bytes equal 240000/240000; pixels differing by more than 1: 0/80000; by exactly 1: 0; max difference 0
  implicit (implicit by roots) 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  cubemap 400x200: bytes equal 240000/240000; pixels differing by more than 1: 0/80000; by exactly 1: 0; max difference 0
  plane 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  patterns 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  glass 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  cubes 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  cylinders 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  hexagon 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  csg 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  soft 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  texture 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  bump 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  mtl 200x100: bytes equal 59999/60000; pixels differing by more than 1: 0/20000; by exactly 1: 1; max difference 1
  expressions 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  functions 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  warps 200x100: bytes equal 60000/60000; pixels differing by more than 1: 0/20000; by exactly 1: 0; max difference 0
  dalek front 100x140: bytes equal 42000/42000; pixels differing by more than 1: 0/14000; by exactly 1: 0; max difference 0
  dalek side 100x140: bytes equal 42000/42000; pixels differing by more than 1: 0/14000; by exactly 1: 0; max difference 0
  dalek lawn 100x140: bytes equal 42000/42000; pixels differing by more than 1: 0/14000; by exactly 1: 0; max difference 0
  gpu_lights (lamp 0) 200x120: bytes equal 72000/72000; pixels differing by more than 1: 0/24000; by exactly 1: 0; max difference 0
  gpu_lights (lamp 1) 200x120: bytes equal 72000/72000; pixels differing by more than 1: 0/24000; by exactly 1: 0; max difference 0
  gpu_lights (lamp 2) 200x120: bytes equal 72000/72000; pixels differing by more than 1: 0/24000; by exactly 1: 0; max difference 0
  rabbit_meadow_60x45: rendered 60x45 on the card in 4124.5 ms (6533 shapes)
  rabbit_meadow_60x45: 60x45: bytes equal 8100/8100; pixels differing by more than 1: 0/2700; by exactly 1: 0; max difference 0
the tapes walked against the tapes written out as code (rabbit meadow, 60x45):
  rendered 60x45 on the card in 2055.7 ms (6533 shapes)
  the two pictures are the same bytes
negative control (one constant changed in the renderer; the pictures must differ from the interpreter's):
  gpu_basic_400x240: 400x240: bytes equal 108385/288000; pixels differing by more than 1: 52823/96000; by exactly 1: 11246; max difference 28

The rabbit meadow at 240 x 180, with adaptive antialiasing, fog, a normal map on the ground, a height map on every fur cone, and the rabbit's six function surfaces, has exactly the bytes of the interpreter's picture (129600 of 129600); the interpreter took 1617 seconds on eighteen threads and the card 4.6 seconds, 350 times faster.

The negative control is the renderer built with one factor changed (the diffuse term of the light multiplied by 1.05): it must not agree, and it does not (more than half the pixels differ). A check that cannot fail is not a check.

What it costs

Time against picture size, doubling each side (four times the pixels) at each row, for the scene of scenes/gpu_basic.scene (shapes, CSG, patterns, glass, adaptive antialiasing); the card's figure is the render alone, the best of three passes, and does not include the second or so that a process takes to bring the card up and read the scene.

size        interpreter  card (best)  speedup
100x60           7803 ms      51.1 ms     153x
200x120         22081 ms      32.6 ms     677x
400x240         66358 ms      44.9 ms    1478x
800x480        231149 ms      62.0 ms    3728x

The interpreter's time grows by a factor near three to four at each step, as the pixels do once its start-up is paid. The card's hardly grows: a scene of sixteen shapes does not fill it at these sizes, and the time is the time of the dearest pixel, not of the sum of them. That is why the ratio in the last column keeps climbing, and why it is not a figure to quote. The meadow is the fairer comparison, a scene that has real work in it: 240 x 180, adaptive antialiasing, the interpreter 1617 seconds on eighteen threads, the card 4.6 seconds.

The start-up of a process matters for an animation, where a process starts for each frame, and so does the cost of the interpreter in building the scene to export it: the meadow takes two and a half minutes to build, and the rabbit of a frame a minute or so. Those exports are now the longest part of the film, not the rendering.

The animation

A hundred and fifty frames of the rabbit's loop cost the interpreter about five and a half hours of eighteen cores for the windows alone, with no antialiasing. On the card each frame is the whole picture, antialiased, with nothing windowed, and takes 4.1 seconds on average, so the film is rendered in ten minutes: the meadow is exported once (base.txt), and each frame exports only the rabbit's shapes (tools/export_animation_frame.patlang, a minute of interpreter time each, several at a time); the renderer reads the two files together (--add), as one scene.

# The rabbit of one frame of the animation (examples/rabbit_animation.patlang), written as plain text for the graphics-card renderer (gpu/rt.cu), to be read
# after the meadow without the rabbit (tools/export_scene.patlang --scene file --file scenes/rabbit_animation.scene):
#   v2_interp.exe tools/export_animation_frame.patlang --frame 37 [--frames 150] --out out/anim_gpu/rabbit_037.txt
#   rt meadow.txt image.ppm --add rabbit_037.txt
# Only the rabbit moves, so only its shapes are written for a frame: the same ones that the interpreter's driver builds for it.
# The ids start at 100000 (--offset) so that they do not meet those of the meadow.

Frame 0, rendered this way without antialiasing, has exactly the bytes of the frame that The film: a rabbit in a meadow's window method makes. The film is made by tools/render_animation_gpu.sh and tools/make_animation.sh:

#!/usr/bin/env bash
# The frames of the rabbit animation on the graphics card: the meadow (out/anim_gpu/base.txt) with the rabbit of each frame added to it
# (out/anim_gpu/rabbit_NNN.txt, from tools/export_animation_frames.sh), one frame after another, skipping those already made:
#   tools/render_animation_gpu.sh [frames=150] [dir=out/anim_gpu]
# The renderer is built once with the tapes of every frame compiled in (gpu/gen_tapes.py). Frames are written as PPM; tools/make_animation.sh
# turns them into a video (EXT=ppm tools/make_animation.sh out/anim_gpu).
cd "$(dirname "$0")/.."
frames="${1:-150}"; dir="${2:-out/anim_gpu}"
(cd gpu && cmd //c ".\build_gen.bat rt_anim.exe ..\$(echo "$dir" | tr / '\')\base.txt ..\$(echo "$dir" | tr / '\')\rabbit_*.txt" 2>&1 | grep -i " error\|nvcc fatal"; true)
for ((f = 0; f < frames; f++)); do
  n=$(printf "%03d" $f)
  [ -s "$dir/frame_$n.ppm" ] && continue
  ./gpu/rt_anim.exe "$dir/base.txt" "$dir/frame_$n.tmp" --add "$dir/rabbit_$n.txt" > "$dir/render_$n.log" && mv "$dir/frame_$n.tmp" "$dir/frame_$n.ppm"
  echo "frame $f: $(cat "$dir/render_$n.log" | tail -1)"
done
echo "frames in $dir: $(ls "$dir"/frame_*.ppm | wc -l)"

A mirage, triangles, two eyes

Three more pieces of the interpreter are on the card, each by the same method (port the library's function, then compare):

  • The mirage of Air: fog, mist and mirages. A ray in air whose index rises with height is followed by Runge-Kutta steps, its path cut where it leaves the layer by bisection, and the chords of the steps are the rays that meet the world; the fog is the sum of the optical depths of the steps. It is the library's own mirage_segment and mirage_color_at, line for line.
  • Triangles, flat and smooth, as the exporter writes them (the first point, the two edges and the normal as the library holds them, so that the card's Moller-Trumbore starts from the same numbers).
  • The two eyes of a stereo pair, from the eye's own camera.

Refraction through a CSG solid treats the whole tree as one medium (container_key in the library: the outermost CSG node above a primitive), and so does the card; a glass lens made by intersecting two spheres, in scenes/gpu_basic.scene, checks it.

The film, 150 frames at 30 frames a second and 240 x 180, looping (the last frame is the first): img/rabbit_animation.gif and img/rabbit_animation.mp4.

the rabbit looks round, nibbles a flower and sits up again

The rest of the shapes

The first version stopped with a message at anything it did not know: the torus, the implicit surfaces of The torus and other polynomial surfaces (polynomials in x, y and z), cube-mapped textures, the textures of a triangle by the coordinates of its corners (a model from an OBJ file with vt lines), and any light but a white point: a coloured one, or a spotlight. All of them are on the card now, by the same method as before (port the library's function, then compare the pictures).

The torus. A ray meets a torus where a quartic in t is zero (The torus and other polynomial surfaces). The card builds the five coefficients in the library's order, and finds the real roots inside the stretch where the ray is in the torus's box. The numbers the library works out from the radii (R + r, R^2 - r^2, 4 R^2, R^2, r^2) are written into the exported text as the library works them out, so that a radius such as 3/10, which a double cannot hold, gives the card the same rounded number that the library uses.

__device__ __noinline__ int torus_hits(const Shape &s, V3 o, V3 d, double *ts) {
  double w0, w1;
  if (!box_range(s.fbox, o, d, w0, w1)) return 0;
  double k = s.tv[3], r2 = s.tv[4];
  double a = d.x * d.x + d.y * d.y + d.z * d.z;
  double b = o.x * d.x + o.y * d.y + o.z * d.z;
  double cc = o.x * o.x + o.y * o.y + o.z * o.z;
  double alpha = d.x * d.x + d.z * d.z;
  double beta = o.x * d.x + o.z * d.z;
  double gamma = o.x * o.x + o.z * o.z;
  double c[5];
  c[0] = (cc + k) * (cc + k) - r2 * gamma;
  c[1] = 4 * b * (cc + k) - 2 * r2 * beta;
  c[2] = 2 * a * (cc + k) + 4 * b * b - r2 * alpha;
  c[3] = 4 * a * b;
  c[4] = a * a;
  if (s.method == 2) return poly_roots_interval(c, 5, w0 * 1.0, w1 * 1.0, ts);
  return poly_roots(c, 5, w0 * 1.0, w1 * 1.0, ts);
}

__device__ V3 torus_normal(const Shape &s, V3 p) {
  double q = p.x * p.x + p.y * p.y + p.z * p.z;
  double radial = q - s.tv[5] - s.tv[6];
  return unit(mk(radial * p.x, (q + s.tv[5] - s.tv[6]) * p.y, radial * p.z));
}

Roots of a polynomial. The library has two root finders (lib/poly.patlang): one finds the extremes of the polynomial from the roots of its derivative, and a sign change between two extremes holds exactly one root, found by Newton steps kept inside the bracket; the other halves intervals, bounding the polynomial over each by interval arithmetic and by the mean-value form. The card has both, statement for statement. The torus uses the first by default and a polynomial surface the second; the exporter writes which is meant (G), since a program can choose the other with a global.

__device__ __noinline__ int poly_roots(const double *c0, int n0, double lo, double hi, double *roots) {
  double L[MAXC][MAXC], D[MAXC][MAXC];
  int Ln[MAXC], Dn[MAXC];
  Ln[0] = poly_trim(c0, n0);
  for (int k = 0; k < Ln[0]; k++) L[0][k] = c0[k];
  if (Ln[0] <= 1) return 0;
  int top = 0;
  while (Ln[top] > 2) {
    int n = Ln[top];
    for (int k = 1; k < n; k++) D[top][k - 1] = L[top][k] * k;
    Dn[top] = n - 1;
    Ln[top + 1] = poly_trim(D[top], Dn[top]);
    for (int k = 0; k < Ln[top + 1]; k++) L[top + 1][k] = D[top][k];
    top++;
  }
  double cur[MAXC], crit[MAXC]; int ncur = 0, ncrit = 0;
  // the top of the chain: nothing, or a straight line
  if (Ln[top] == 2) {
    double x = 0 - L[top][0] / L[top][1];
    if (x >= lo && x <= hi) cur[ncur++] = x;
  }
  for (int j = top - 1; j >= 0; j--) {
    ncrit = ncur;
    for (int k = 0; k < ncur; k++) crit[k] = cur[k];
    double cuts[MAXC + 2]; int nc = 0;
    cuts[nc++] = lo;
    for (int k = 0; k < ncrit; k++) cuts[nc++] = crit[k];
    cuts[nc++] = hi;
    ncur = 0;
    for (int k = 0; k + 1 < nc; k++) {
      double a = cuts[k], b = cuts[k + 1];
      double fa = poly_eval(L[j], Ln[j], a), fb = poly_eval(L[j], Ln[j], b);
      if (fa == 0 && k == 0) { if (ncur < MAXC) cur[ncur++] = a; }
      if ((fa < 0 && fb > 0) || (fa > 0 && fb < 0)) { double r = poly_refine(L[j], Ln[j], D[j], Dn[j], a, b); if (ncur < MAXC) cur[ncur++] = r; }
      else if (fb == 0 && b > a && fa != 0) { if (ncur < MAXC) cur[ncur++] = b; }
    }
  }
  for (int k = 0; k < ncur; k++) roots[k] = cur[k];
  return ncur;
}

Polynomial surfaces. The polynomial in t of a surface is built from where the ray enters the surface's box (so that the numbers stay the size of the box), by the powers of the three linear functions of the ray and the terms of the surface, in the order of implicit_ray_poly. The normal is the gradient: the exporter sends the three derivative polynomials as the library holds them, since a derivative's coefficient made on the card (a rational times a whole number, rounded once) could differ in the last bit from the library's. The powers in the gradient are pow of a float and a whole number in the library, which is the C library's pow; the card cannot call that one, so it forms a whole power as a double-double product and rounds once, which is what pow returns where it is correctly rounded.

Cube maps and the corners' coordinates. A point of a cube map takes the face along which it lies farthest out and the (u, v) on that face, as cube_face_index and cube_uv do, and six pictures are read for it. A triangle with texture coordinates computes its (u, v) from the barycentric coordinates of the point, with the library's own arithmetic.

Lights. The colour of the light multiplies the surface colour in the ambient and diffuse terms and is the colour of the highlight, and a spotlight scales the diffuse and specular terms by its cone: one where the angle is inside the inner half-angle, nothing beyond the outer, linear between (spot_factor).

One pixel

The first check of the implicit surfaces came out with 239997 of 240000 bytes equal. One pixel, on the red heart, was 130 in the interpreter's picture and 25 in the card's, a lit pixel against one in shadow. The three wrong bytes were the whole difference, and finding them took reports from both sides. The program, built with a probe (-DPROBE), prints for a chosen pixel every hit of every implicit surface, with the ray; and the library's own intersection function, copied into a script that prints what it is given and what it finds, was run on the same pixel. The first ray, from the eye to the pixel, met the heart in two places for the library (7.58 and 8.71 along the ray, the entry and the exit) and in one for the card (the exit).

The ray did not begin the same. The library carries a ray into a shape's own space with the inverse of the shape's matrix that it found when the matrix was set, and the card inverted the exported matrix by its own method. The two inverses differ in the last few bits of some entries, so that the ray in the shape's space differed by about 6e-15 in its origin. For the sphere and the plane that is nothing. For a polynomial of degree six, whose coefficients are built from powers of that origin and whose roots are found to 1e-12, it was enough to lose the entry into the heart for one ray out of eighty thousand.

The exporter now writes the library's own inverse (the J line) for every shape that is not inside a group, and the card uses it. The heart's pixel is then equal, and so is every other. A shape inside a group or a CSG solid is reached in the library through a chain of inverses (the group's, then the shape's), and the card uses the inverse of their product, which can differ in the last bits; every picture below agrees byte for byte all the same, but a polynomial surface inside a group is the case where the difference could show.

Checked

The torus by both root finders, the implicit surfaces by both, the spotlight, the coloured lights (a point, a spot and an area light, scenes/gpu_lights.scene) and the cube map each agree with the interpreter byte for byte, and so do the other demonstration scenes of the library and the Dalek of Built objects: solid geometry and a Dalek and Pictures on surfaces: texture and cube maps (gpu/check_all.sh, above). The one picture with a difference is the model with a material file (mtl), where one byte of 60000 is one level out, the same sort of difference that the textured globe shows, from the C library's acos and atan2.

On the card the implicit scene of The torus and other polynomial surfaces at 400 x 200 takes 0.09 seconds; the interpreter, on one core, took two and a half minutes for the same picture.

What is not here yet

Nothing of the library's shapes, patterns or lights is left off the card, and the renderer still stops with a message when a scene has a shape, pattern, mapping or light it does not know, rather than drawing something else. What differs from the interpreter is below the level of a byte: the shapes inside groups reach their own space by one inverse instead of a chain of them (above), and the C library's functions (sin, exp, acos, atan2) are not the same code on the two machines.

How it is checked

> v2_interp.exe tests/run.patlang --node picture/threads --depth 2
[ ok ] Rendering on many threads
[ ok ]   Threads share a model
[ ok ]     Function surfaces, twists, CSG
[ ok ]     Grass texture, bump map, a tree
[ ok ]     Fur picture and a body of ellipsoids
[ ok ]     Stereo pair of a scene with fog
[ ok ]   A render that can be asked how far it has got
[ ok ]     A render that is running answers a status query from outside it (signal_query to the port ...
checks: 5 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED