Last updated: 2026-11-26

25. Colours, the canvas and picture files

For new readers

The end of every picture: colours, a canvas to hold them, and the files a picture is saved as (plain PPM text, and PNG with its checksums), and the PPM reader that brings pictures back in as textures.

Drawing on a Canvas

Colours, a canvas, and a way to look at the result. The book writes plain-text PPM; this project also writes PNG, so images open anywhere without a converter.

Step 1 — colours are vectors

The book notes that a colour is a tuple. Here an RGB triple is the Euclidean GA vector r e1 + g e2 + b e3, so adding, subtracting and scaling colours are the algebra's own linear operations (the same ga_add, ga_sub, ga_scale used for points and vectors in Points, directions and motions in the conformal algebra).

The Hadamard product (blending two colours) is not a geometric product — it multiplies matching components. It is the one colour operation that reads the coefficients directly, and it is marked as such in the code.

make a function called color takes r, g, b returns c
  return cga_evec(r, g, b)
end

make a function called red takes c returns v
  return c[1]
end

make a function called green takes c returns v
  return c[2]
end

make a function called blue takes c returns v
  return c[4]
end

# Colours have only their three components, so the sums and scalings below are the
# algebra's ga_add / ga_sub / ga_scale (the test tree, foundations/colours/fast, checks them against
# those) written on the three numbers instead of 32.
make a function called color_add takes a, b returns c
  return color(a[1] + b[1], a[2] + b[2], a[4] + b[4])
end

make a function called color_sub takes a, b returns c
  return color(a[1] - b[1], a[2] - b[2], a[4] - b[4])
end

make a function called color_scale takes a, s returns c
  return color(a[1] * s, a[2] * s, a[4] * s)
end

make a function called color_mul takes a, b returns c
  return color(red(a) * red(b), green(a) * green(b), blue(a) * blue(b))
end

make a function called color_eq takes a, b returns ok
  return equal(red(a), red(b)) and equal(green(a), green(b)) and equal(blue(a), blue(b))
end

Step 2 — the canvas

A 900×550 canvas is 1.5 million numbers. PatLang lists are values: writing one element of a list that is reachable from two places copies the whole list. Measured, 2000 writes into a canvas held inside a wrapper list took:

pixels × 3 time for 2000 write_pixel
10 000 125 ms
40 000 1 297 ms
160 000 5 635 ms
640 000 22 891 ms

Each doubling-of-size costs 4× — O(n) per write, so O(n²) for a render. The canvas therefore keeps its pixels in a host vec handle, where vec_set is O(1), and the rest of the code stays purely functional.mixing fast mut with pure code

make a function called canvas takes w, h returns c
  let store = vec_new()
  let i = 0
  while i < w * h * 3 do
    vec_push(store, 0)
    let i = i + 1
  end
  return [w, h, store]
end

make a function called canvas_width takes c returns w
  return c[0]
end

make a function called canvas_height takes c returns h
  return c[1]
end

make a function called write_pixel takes c, x, y, col returns done
  if x < 0 or y < 0 or x >= c[0] or y >= c[1] then
    return false
  end
  let i = (y * c[0] + x) * 3
  vec_set(c[2], i, red(col))
  vec_set(c[2], i + 1, green(col))
  vec_set(c[2], i + 2, blue(col))
  return true
end

# A canvas under construction keeps its samples in a vec handle (O(1) to write, but a handle belongs to the thread that made
# it); a picture read from a file (ppm.patlang) keeps them in a list, which any thread can read.
make a function called pixel_at takes c, x, y returns col
  let i = (y * c[0] + x) * 3
  return color(canvas_sample(c, i), canvas_sample(c, i + 1), canvas_sample(c, i + 2))
end

Step 3 — PPM

canvas_to_ppm clamps each component to 0‥1, scales to 0‥255 with rounding, and breaks lines at 70 characters, only between numbers.

# Scale a 0..1 component to 0..255, rounding and clamping: an int.
make a function called to_byte takes v returns b
  let f = v * 255 + 1/2
  if f < 0 then
    return 0
  end
  if f >= 256 then
    return 255
  end
  return to_int(floor(f))
end

# Plain-text PPM (P3). Lines are kept to at most 70 characters, breaking
# only between numbers. `line` is a string builder; `n` tracks its length.
make a function called canvas_to_ppm takes c returns ppm
  let out = sb_new()
  sb_push(out, "P3" + chr(10) + c[0] + " " + c[1] + chr(10) + "255" + chr(10))
  let y = 0
  while y < c[1] do
    let line = sb_new()
    let n = 0
    let x = 0
    while x < c[0] do
      let i = (y * c[0] + x) * 3
      let k = 0
      while k < 3 do
        let tok = "" + to_byte(canvas_sample(c, i + k))
        if n == 0 then
          sb_push(line, tok)
          let n = tok.length
        elif n + 1 + tok.length > 70 then
          sb_push(out, sb_str(line) + chr(10))
          let line = sb_new()
          sb_push(line, tok)
          let n = tok.length
        else
          sb_push(line, " " + tok)
          let n = n + 1 + tok.length
        end
        let k = k + 1
      end
      let x = x + 1
    end
    sb_push(out, sb_str(line) + chr(10))
    let y = y + 1
  end
  return sb_str(out)
end

Step 4 — PNG

PNG is a signature plus length-prefixed chunks, each with a CRC-32. The pixel data is a zlib stream; to keep the encoder small and exact it uses stored (uncompressed) deflate blocks of up to 65 535 bytes, with an Adler-32 trailer. Files are bigger than a compressing encoder would make, but every decoder reads them.

make a function called png_crc_table returns t
  let t = []
  let n = 0
  while n < 256 do
    let c = n
    let k = 0
    while k < 8 do
      if (c band 1) == 1 then
        let c = 3988292384 bxor (c shr 1)
      else
        let c = c shr 1
      end
      let k = k + 1
    end
    let t = list_push(t, c)
    let n = n + 1
  end
  return t
end

# Running CRC state (not yet finalised): feed bytes through the table.
make a function called crc_update takes table, crc, bytes returns next
  let c = crc
  let i = 0
  while i < bytes.length do
    let c = table[(c bxor bytes[i]) band 255] bxor (c shr 8)
    let i = i + 1
  end
  return c
end

make a function called crc32 takes bytes returns v
  return crc_update(png_crc_table(), 4294967295, bytes) bxor 4294967295
end

make a function called adler32 takes bytes returns v
  let a = 1
  let b = 0
  let i = 0
  while i < bytes.length do
    let a = (a + bytes[i]) % 65521
    let b = (b + a) % 65521
    let i = i + 1
  end
  return (b shl 16) bor a
end

make a function called be32 takes n returns bs
  return [(n shr 24) band 255, (n shr 16) band 255, (n shr 8) band 255, n band 255]
end

make a function called append_all takes dst, src returns out
  let out = dst
  let i = 0
  while i < src.length do
    let out = list_push(out, src[i])
    let i = i + 1
  end
  return out
end
make a function called png_chunk takes type_str, data returns bs
  let body = []
  let i = 0
  while i < 4 do
    let body = list_push(body, char_code(type_str, i))
    let i = i + 1
  end
  let body = append_all(body, data)
  let out = be32(data.length)
  let out = append_all(out, body)
  return append_all(out, be32(crc32(body)))
end

# zlib stream of stored blocks (<= 65535 bytes each) over `raw`.
make a function called zlib_stored takes raw returns z
  let z = [120, 1]
  let pos = 0
  let n = raw.length
  if n == 0 then
    let z = append_all(z, [1, 0, 0, 255, 255])
  end
  while pos < n do
    let len = n - pos
    if len > 65535 then
      let len = 65535
    end
    let final = 0
    if pos + len >= n then
      let final = 1
    end
    let z = list_push(z, final)
    let z = append_all(z, [len band 255, (len shr 8) band 255, (65535 - len) band 255, ((65535 - len) shr 8) band 255])
    let j = 0
    while j < len do
      let z = list_push(z, raw[pos + j])
      let j = j + 1
    end
    let pos = pos + len
  end
  return append_all(z, be32(adler32(raw)))
end

# The whole file as a list of byte values.
make a function called canvas_to_png takes c returns bs
  let raw = []
  let y = 0
  while y < c[1] do
    let raw = list_push(raw, 0)
    let x = 0
    while x < c[0] do
      let i = (y * c[0] + x) * 3
      let raw = list_push(raw, to_byte(canvas_sample(c, i)))
      let raw = list_push(raw, to_byte(canvas_sample(c, i + 1)))
      let raw = list_push(raw, to_byte(canvas_sample(c, i + 2)))
      let x = x + 1
    end
    let y = y + 1
  end
  let ihdr = append_all(be32(c[0]), be32(c[1]))
  let ihdr = append_all(ihdr, [8, 2, 0, 0, 0])
  let out = [137, 80, 78, 71, 13, 10, 26, 10]
  let out = append_all(out, png_chunk("IHDR", ihdr))
  let out = append_all(out, png_chunk("IDAT", zlib_stored(raw)))
  return append_all(out, png_chunk("IEND", []))
end

make a function called save_png takes c, path returns ok
  return write_file_bytes(path, canvas_to_png(c))
end

Step 5 — checks

Colours add, subtract, scale and blend channel by channel; a new canvas is black; a written pixel reads back and its neighbours stay black; channel values become bytes by scaling, rounding and clamping; PPM text has its header, its rows, lines of at most 70 characters with no number split, and a closing newline, and reads back to the same bytes. The checksum functions are checked against published known-answer vectors (crc32("123456789") = 0xCBF43926, adler32("Wikipedia") = 0x11E60398) rather than against themselves.

Step 6 — scaling check

PNG encoding time doubles with the pixel count (each row is 4× the pixels of the one above it, and about 4× the time), so the writer is linear:

canvas time
100×62 66 ms
200×124 250 ms
400×248 1 093 ms
800×496 4 324 ms

Step 7 — Putting it together: the projectile on a canvas

The ball leaves a ledge two units up at normalize(vector(3, 4, 0)) * 10, that is exactly (6, 8, 0), with gravity −1/8 and a headwind of −1/80 each tick. The canvas is 720×300, and its y-axis runs downwards, so the program plots y = height − world y. write_pixel ignores points outside the canvas, so a flight that leaves the picture cannot write past its edge.

# Plot a ball's flight on a canvas and save it as a PNG and as a PPM.
include "../lib/tuple.patlang"
include "../lib/spec.patlang"
include "../lib/png.patlang"

make a function called tick takes env, proj returns next
  let position = tuple_add(proj[0], proj[1])
  let velocity = tuple_add(tuple_add(proj[1], env[0]), env[1])
  return [position, velocity]
end

let start = point(0, 2, 0)
let velocity = tuple_mul(normalize(vector(3, 4, 0)), 10)
let p = [start, velocity]
let e = [vector(0, -1/8, 0), vector(-1/80, 0, 0)]
let c = canvas(720, 300)
let ink = color(1, (2/5), (2/5))
let ticks = 0
while get_y(p[0]) > 0 do
  let p = tick(e, p)
  let ticks = ticks + 1
  let px = floor(get_x(p[0]))
  let py = 300 - floor(get_y(p[0]))
  write_pixel(c, px, py, ink)
end
print("landed after " + ticks + " ticks")
save_png(c, "../out/ch02_projectile.png")
write_file("../out/ch02_projectile.ppm", canvas_to_ppm(c))
print("wrote out/ch02_projectile.png and .ppm")
> cd examples && v2_interp.exe ch02_projectile.patlang
landed after 130 ticks
wrote out/ch02_projectile.png and .ppm

Projectile arc

Verifying the file independently

A new file format is worth distrusting. The PNG is decoded by .NET's own decoder, and the pixel count is cross-checked against the PPM, parsed by a separate script:

> powershell.exe -NoProfile -File tools/verify_png.ps1 out/ch02_projectile.png
decoded by .NET: 720x300, non-black pixels: 129, first: (358,38) = rgb(255,102,102)
> tools/ppm_stats.sh out/ch02_projectile.ppm
parsed from PPM: non-black pixels: 129

How it is checked

> v2_interp.exe tests/run.patlang --node foundations/colours --depth 2
[ ok ] Colours
[ ok ]   A colour has red, green and blue
[ ok ]   Colours add, subtract, scale and blend channel by channel
[ ok ]   Colour arithmetic  (all, giving the same answer)
[ ok ]     naive: the 32-coefficient operations
[ ok ]     faster: three channels only
checks: 4 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED
> v2_interp.exe tests/run.patlang --node foundations/canvas --depth 2
[ ok ] The canvas and picture files
[ ok ]   A new canvas is black everywhere
[ ok ]   A written pixel reads back; its neighbours stay black; off the canvas nothing is written
[ ok ]   Channel values become bytes: scaled to 255, rounded, clamped
[ ok ]   Plain PPM text
[ ok ]     Three header lines: P3, width and height, 255
[ ok ]     Pixels are written row by row as bytes
[ ok ]     No line is longer than 70 characters, and no number is split
[ ok ]     The text ends with a newline
[ ok ]     A PPM read back gives the same bytes
[ ok ]   PNG files
[ ok ]     CRC-32 and Adler-32 give the published check values
[ ok ]     Signature, then a header chunk with the size, 8-bit RGB
checks: 10 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED

Graduate Attributes

Modelled on this page

  • Researcher: Checksum functions are verified against published known-answer vectors rather than against themselves.
  • Critical Thinker: A new file format is treated with distrust and cross-checked against independent parsing scripts.
  • Digitally Fluent: Technical specifications for PPM and PNG formats are described with precise attention to data structures and checksums.

University of Reading Graduate Attributes framework.