Last updated: 2026-11-26

15. Triangles and meshes from files

For new readers

Models made elsewhere arrive as meshes of triangles: this page opens the triangle (and the smooth triangle, whose normal is blended from its corners), and the reading of OBJ files and their MTL material files. The groups that hold the triangles, and the tree of boxes that makes a big mesh fast, are on the next page.

Triangles

The last primitive, and the one that lets a ray tracer draw anything a modelling program can export: a triangle given by its three corners, a reader for Wavefront OBJ files, and smooth triangles that carry a normal at each corner.

Step 1 — a triangle and the Möller–Trumbore test as wedge products

A triangle is built from three points and keeps two edge vectors and its normal, computed once:

e1 = p2 − p1        e2 = p3 − p1        normal = normalize(e2 × e1)

A point of the triangle is p1 + u e1 + v e2 with u, v ≥ 0 and u + v ≤ 1. A ray o + t d meets it where, with s = o − p1,

s = u e1 + v e2 − t d

Wedge both sides with two of the three vectors and only the unknown multiplying the third survives. Each wedge of three vectors is a multiple of the pseudoscalar e1 e2 e3, namely the determinant of their components, so Cramer's rule gives all three unknowns, with D = e1 ∧ d ∧ e2:

u = (s ∧ d ∧ e2) / D        v = (d ∧ s ∧ e1) / D        t = (e2 ∧ s ∧ e1) / D

That is the book's Möller–Trumbore algorithm, because a · (b × c) is exactly the coefficient of a ∧ b ∧ c: its det = dot(e1, d × e2) is D, its u uses dot(s, d × e2), and so on. D = 0 means the ray is parallel to the plane, a miss; u or v outside the triangle is a miss. A ray through an edge or a vertex counts as a hit (u = 0, u + v = 1, ...), as the book's inclusive tests do.

ga_triple(a, b, c) is that coefficient, written as the 3×3 determinant it is because four of them run for every ray and triangle; a test pins it against the full geometric-algebra a ∧ b ∧ c on 343 triples. The two numbers u and v travel on the intersection (intersection_with_uv), and a group passes them through when it hands a child's hit back.

make a function called triangle_params takes p1, p2, p3 returns ps
  let e1 = tuple_sub(p2, p1)
  let e2 = tuple_sub(p3, p1)
  return [p1, p2, p3, e1, e2, normalize(cross(e2, e1)), tuple_evec(e1), tuple_evec(e2)]
end

make a function called triangle takes p1, p2, p3 returns s
  return list_set(new_shape("triangle"), 6, triangle_params(p1, p2, p3))
end

make a function called smooth_triangle takes p1, p2, p3, n1, n2, n3 returns s
  return list_set(new_shape("smooth_triangle"), 6, list_push(list_push(list_push(triangle_params(p1, p2, p3), n1), n2), n3))
end

make a function called tri_p1 takes s returns p
  return s[6][0]
end

make a function called tri_p2 takes s returns p
  return s[6][1]
end

make a function called tri_p3 takes s returns p
  return s[6][2]
end

make a function called tri_e1 takes s returns v
  return s[6][3]
end

make a function called tri_e2 takes s returns v
  return s[6][4]
end

make a function called tri_normal takes s returns n
  return s[6][5]
end

make a function called tri_n1 takes s returns n
  return s[6][8]
end

make a function called tri_n2 takes s returns n
  return s[6][9]
end

make a function called tri_n3 takes s returns n
  return s[6][10]
end

# Moller-Trumbore with the four triple products written out on components (ga_triple is
# a . (b x c); the _ga function below is the same test through it, and
# the test tree, shapes/triangle/ways, checks they give exactly the same hits). A mesh runs this
# once per triangle per ray, so no vector is built here.
make a function called triangle_local_intersect takes s, r returns xs
  let ps = s[6]
  let e1 = ps[6]
  let e2 = ps[7]
  let d = r[1]
  let dx = get_x(d)
  let dy = get_y(d)
  let dz = get_z(d)
  let ax = e1[1]
  let ay = e1[2]
  let az = e1[4]
  let cx = e2[1]
  let cy = e2[2]
  let cz = e2[4]
  let det = ax * (dy * cz - dz * cy) - ay * (dx * cz - dz * cx) + az * (dx * cy - dy * cx)
  if abs(det) < epsilon() then
    return []
  end
  let f = 1 / det
  let o = r[0]
  let p1 = ps[0]
  let sx = o[1] - p1[1]
  let sy = o[2] - p1[2]
  let sz = o[4] - p1[4]
  let u = f * (sx * (dy * cz - dz * cy) - sy * (dx * cz - dz * cx) + sz * (dx * cy - dy * cx))
  if u < 0 or u > 1 then
    return []
  end
  let v = f * (dx * (sy * az - sz * ay) - dy * (sx * az - sz * ax) + dz * (sx * ay - sy * ax))
  if v < 0 or u + v > 1 then
    return []
  end
  return [intersection_with_uv(f * (cx * (sy * az - sz * ay) - cy * (sx * az - sz * ax) + cz * (sx * ay - sy * ax)), s, u, v)]
end

# the smooth triangle's normal: n2 u + n3 v + n1 (1 - u - v), from the hit alone
make a function called smooth_triangle_normal takes s, hit returns n
  let ps = s[6]
  let u = hit[2]
  let v = hit[3]
  return tuple_add(tuple_add(tuple_mul(ps[9], u), tuple_mul(ps[10], v)), tuple_mul(ps[8], 1 - u - v))
end

make a function called triangle_bounds takes s returns b
  let ps = s[6]
  let lo = [get_x(ps[0]), get_y(ps[0]), get_z(ps[0])]
  let hi = lo
  let k = 1
  while k < 3 do
    let c = [get_x(ps[k]), get_y(ps[k]), get_z(ps[k])]
    let a = 0
    while a < 3 do
      let lo = list_set(lo, a, num_min(lo[a], c[a]))
      let hi = list_set(hi, a, num_max(hi[a], c[a]))
      let a = a + 1
    end
    let k = k + 1
  end
  return [lo, hi]
end

Step 2 — smooth triangles

A smooth triangle also holds a normal at each corner, and the normal at a hit is n2 u + n3 v + n1 (1 − u − v), from the hit's u and v alone; the point is not used. The book gives normal_at and local_normal_at a third argument, the hit. PatLang has no default arguments (a missing argument is not false), so the three argument forms here are normal_at_hit and local_normal_at_hit, and the existing two-argument names pass no hit. prepare_computations passes the intersection it was given.barycentric coords: u+v:1 on the edge

# the book gives normal_at and local_normal_at a third argument, the hit, which only
# smooth triangles use. PatLang has no default arguments, so the three-argument forms
# are the _hit functions and the two-argument names pass no hit.
make a function called normal_at_hit takes s, world_point, hit returns n
  return normal_to_world(s, local_normal_at_hit(s, world_to_object(s, world_point), hit))
end

make a function called normal_at takes s, world_point returns n
  return normal_at_hit(s, world_point, false)
end

make a function called local_normal_at takes s, p returns n
  return local_normal_at_hit(s, p, false)
end

Step 3 — OBJ files

An OBJ file is lines of statements: v x y z (a vertex), vn x y z (a normal), f (a face with three or more vertices, written i, i/j, i//k or i/j/k, the k being a normal), g name (a named group). Everything else is counted and skipped. A face with more than three vertices is a convex polygon, split into a fan of triangles from its first vertex, so a pentagon gives three. A face whose vertices all have normals becomes smooth triangles. Indices are 1-based, negative ones count back from the end, and the vertex and normal lists keep a placeholder at position 0 so that vertices[1] is the first vertex as in the book.

The parser reads the file as a list of bytes and decodes numbers digit by digit into exact rationals: 0.707 is 707/1000 and -1.0000 is the integer -1. (A String must not be scanned character by character in PatLang: each index re-examines the whole string. And a number read through floating point would not be exact.) Vertices, normals and each group's triangles accumulate in vec handles, which grow in O(1) and can be shared by the functions that handle one line each; they become lists and groups at the end. Whole groups are built with group_from, which finds the bounds in one pass, and an untransformed child (every triangle) skips the eight-corner transformation of its box.

# the number in bytes[from .. to), or false; sign, digits, an optional fraction
# and an optional exponent, all exact
make a function called obj_number takes bytes, from, to returns v
  let i = from
  let sign = 1
  if i < to and bytes[i] == 45 then
    let sign = -1
    let i = i + 1
  elif i < to and bytes[i] == 43 then
    let i = i + 1
  end
  let whole = 0
  let digits = 0
  while i < to and bytes[i] >= 48 and bytes[i] <= 57 do
    let whole = whole * 10 + bytes[i] - 48
    let digits = digits + 1
    let i = i + 1
  end
  let scale = 1
  if i < to and bytes[i] == 46 then
    let i = i + 1
    while i < to and bytes[i] >= 48 and bytes[i] <= 57 do
      let whole = whole * 10 + bytes[i] - 48
      let scale = scale * 10
      let digits = digits + 1
      let i = i + 1
    end
  end
  if digits == 0 then
    return false
  end
  let value = whole / scale
  if i < to and (bytes[i] == 101 or bytes[i] == 69) then
    let i = i + 1
    let esign = 1
    if i < to and bytes[i] == 45 then
      let esign = -1
      let i = i + 1
    elif i < to and bytes[i] == 43 then
      let i = i + 1
    end
    let e = 0
    let edigits = 0
    while i < to and bytes[i] >= 48 and bytes[i] <= 57 do
      let e = e * 10 + bytes[i] - 48
      let edigits = edigits + 1
      let i = i + 1
    end
    if edigits == 0 then
      return false
    end
    let k = 0
    while k < e do
      if esign > 0 then
        let value = value * 10
      else
        let value = value / 10
      end
      let k = k + 1
    end
  end
  if i != to then
    return false
  end
  return sign * value
end
# one line [from, to): returns the number of statements it ignored (0 or 1).
# `cur` is [index of the current group, the current usemtl record or false, the vec of
# material records read so far, the directory of the file]
make a function called obj_line takes bytes, from, to, vs, ns, vts, names, bins, cur returns ignored
  let to = to
  if to > from and bytes[to - 1] == 13 then
    let to = to - 1
  end
  let fields = obj_fields(bytes, from, to)
  if fields.length == 0 then
    return 0
  end
  let f0 = fields[0]
  let cmd = obj_text(bytes, f0[0], f0[1])
  if cmd == "v" or cmd == "vn" then
    if fields.length < 4 then
      return 1
    end
    let x = obj_number(bytes, fields[1][0], fields[1][1])
    let y = obj_number(bytes, fields[2][0], fields[2][1])
    let z = obj_number(bytes, fields[3][0], fields[3][1])
    if x == false or y == false or z == false then
      return 1
    end
    if cmd == "v" then
      vec_push(vs, point(x, y, z))
    else
      vec_push(ns, vector(x, y, z))
    end
    return 0
  end
  if cmd == "vt" then
    if fields.length < 3 then
      return 1
    end
    let u = obj_number(bytes, fields[1][0], fields[1][1])
    let v = obj_number(bytes, fields[2][0], fields[2][1])
    if u == false or v == false then
      return 1
    end
    vec_push(vts, [u, v])
    return 0
  end
  if cmd == "mtllib" then
    if fields.length < 2 then
      return 1
    end
    let name = obj_text(bytes, fields[1][0], fields[1][1])
    let mpath = obj_join(vec_get(cur, 3), name)
    let mbytes = read_file_bytes(mpath, 0, 268435456)
    if mbytes.length == 0 then
      return 1
    end
    let recs = parse_mtl_bytes(mbytes, obj_dir(mpath))
    let mats = vec_get(cur, 2)
    let k = 0
    while k < recs.length do
      vec_push(mats, recs[k])
      let k = k + 1
    end
    return 0
  end
  if cmd == "usemtl" then
    let name = ""
    if fields.length > 1 then
      let name = obj_text(bytes, fields[1][0], fields[1][1])
    end
    let mats = vec_get(cur, 2)
    let found = false
    let k = 0
    while k < vec_len(mats) do
      if vec_get(mats, k)[0] == name then
        let found = vec_get(mats, k)
      end
      let k = k + 1
    end
    vec_set(cur, 1, found)
    if found == false then
      return 1
    end
    return 0
  end
  if cmd == "g" then
    let name = ""
    if fields.length > 1 then
      let name = obj_text(bytes, fields[1][0], fields[1][1])
    end
    let at = obj_name_index(names, name)
    if at < 0 then
      vec_push(names, name)
      vec_push(bins, vec_new())
      let at = vec_len(names) - 1
    end
    vec_set(cur, 0, at)
    return 0
  end
  if cmd == "f" then
    if fields.length < 4 then
      return 1
    end
    let refs = []
    let k = 1
    while k < fields.length do
      let ref = obj_face_vertex(bytes, fields[k][0], fields[k][1])
      if ref == false then
        return 1
      end
      let vi = ref[0]
      if vi < 0 then
        let vi = vec_len(vs) + vi
      end
      let ni = ref[1]
      if ni != false and ni < 0 then
        let ni = vec_len(ns) + ni
      end
      let ti = ref[2]
      if ti != false and ti < 0 then
        let ti = vec_len(vts) + ti
      end
      if vi < 1 or vi >= vec_len(vs) then
        return 1
      end
      if ni != false and (ni < 1 or ni >= vec_len(ns)) then
        return 1
      end
      # a texture index with no vt behind it is no texture coordinate, not an error (as before vt was read)
      if ti != false and (ti < 1 or ti >= vec_len(vts)) then
        let ti = false
      end
      let refs = list_push(refs, [vi, ni, ti])
      let k = k + 1
    end
    # fan triangulation from the first vertex
    let bin = vec_get(bins, vec_get(cur, 0))
    let rec = vec_get(cur, 1)
    let smooth = true
    let k = 0
    while k < refs.length do
      if refs[k][1] == false then
        let smooth = false
      end
      let k = k + 1
    end
    let k = 1
    while k + 1 < refs.length do
      let a = refs[0]
      let b = refs[k]
      let c = refs[k + 1]
      let pa = vec_get(vs, a[0])
      let pb = vec_get(vs, b[0])
      let pc = vec_get(vs, c[0])
      let tri = false
      if smooth then
        let tri = smooth_triangle(pa, pb, pc, vec_get(ns, a[1]), vec_get(ns, b[1]), vec_get(ns, c[1]))
      else
        let tri = triangle(pa, pb, pc)
      end
      if rec != false then
        let uvs = [false, false, false]
        if a[2] != false and b[2] != false and c[2] != false then
          let uvs = [vec_get(vts, a[2]), vec_get(vts, b[2]), vec_get(vts, c[2])]
        end
        let tri = set_material(tri, obj_triangle_material(rec, [pa, pb, pc], uvs))
      end
      vec_push(bin, tri)
      let k = k + 1
    end
    return 0
  end
  return 1
end
make a function called parse_obj_bytes takes bytes returns parser
  return parse_obj_bytes_in(bytes, "")
end

The scaling of the parser, measured on grids of quads of growing size (the rows are sizes 512 to 16 200 triangles, each timed alone):

> cd examples && v2_interp.exe ch15_parse_bench.patlang | grep ' '
triangles   parse ms   microseconds per triangle
512   4667   9115
968   8734   9022
2048   18204   8888
4050   37813   9336
8192   74972   9151
16200   123230   7606

The cost per triangle stays level, so the parse is linear. (I had expected the builds of the group's child list, list_push into a list reachable from the group, to be the quadratic part. add_child in a loop measured at 500, 1 000, 2 000, 4 000 children: 1.1 s, 2.2 s, 4.4 s, 8.9 s, linear as well, so no vec was needed there.)

Step 4 — checks

A triangle is checked against its plane, inside its edges, like every shape; a ray through the middle, past each edge and alongside it, and the place of a hit (u, v), are worked by hand; a smooth triangle blends its corner normals by that place. OBJ text written for the tests covers skipped lines, exact numbers with signs and exponents, untidy whitespace, faces, fans, groups and vertex normals.

Further checks, sharing no code with what they check:

  • ga_triple is the wedge product's coefficient, exactly, on all 343 triples of seven vectors, with dependent and swapped arguments.
  • Exact barycentric geometry: on 165 rays with exact rational origins and directions, P = p1 + u e1 + v e2 holds exactly for every hit, with u, v ≥ 0 and u + v ≤ 1, and every hit lies in the triangle's plane (n · (P − p1) = 0, exactly).
  • A different algorithm on plain coordinates (intersect the plane, then three same-side edge tests) agrees with the library on every one of those rays, hit or miss, with the same t, edges and vertices included.
  • A transformed triangle gives the same t and the same world normal as the triangle with transformed corners.
  • OBJ details: comments, blank lines, tabs, Windows line endings and a last line with no newline; numbers exact; an n-gon gives n − 2 triangles for n = 3 … 8.

Step 5 — Putting it together

Two spheres of 168 triangles each, written by tools/make_meshes.patlang as OBJ files (quads and triangles, the same vertices): on the left with flat faces, on the right with a normal at each vertex (f 7//7 …). The pyramid in front is built by hand from six triangle calls. A group's material is not inherited, so a model takes its look from with_material_deep, which sets the material on every shape below a group.

# chapter 15: a square pyramid from six triangles, and two OBJ spheres of the same
# 168 triangles, one with flat faces and one with vertex normals
make a function called pyramid takes m returns g
  let a = point(-1, 0, -1)
  let b = point(1, 0, -1)
  let c = point(1, 0, 1)
  let d = point(-1, 0, 1)
  let apex = point(0, (3/2), 0)
  let g = group()
  let sides = [[a, b, apex], [b, c, apex], [c, d, apex], [d, a, apex], [a, d, c], [a, c, b]]
  let k = 0
  while k < sides.length do
    let t = set_material(triangle(sides[k][0], sides[k][1], sides[k][2]), m)
    let g = add_child(g, t)
    let k = k + 1
  end
  return g
end

make a function called build_mesh_scene takes models 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 red = material_with(color((9/10), (1/5), (1/5)), (1/10), (7/10), (3/5), 100)
  let blue = material_with(color((1/5), (3/10), (9/10)), (1/10), (7/10), (3/5), 100)
  let gold = material_with(color((9/10), (7/10), (1/10)), (1/10), (7/10), (4/10), 100)
  let flat = set_transform(with_material_deep(obj_to_group(parse_obj_file(models + "/sphere_flat.obj")), red), mat_mul(translation(-(8/5), 1, 0), rotation_y(1)))
  let smooth = set_transform(with_material_deep(obj_to_group(parse_obj_file(models + "/sphere_smooth.obj")), blue), mat_mul(translation((8/5), 1, 0), rotation_y(1)))
  let tent = set_transform(pyramid(gold), mat_mul(translation(0, 0, -1), scaling((3/5), (3/5), (3/5))))
  return [[floor_p, flat, smooth, tent], demo_light(), true]
end
# Chapter 15, "Putting It Together": two OBJ spheres of 168 triangles each, one with
# flat faces and one with vertex normals, and a pyramid built from six triangles.
include "../lib/spec.patlang"
include "../lib/png.patlang"
include "../lib/camera.patlang"
include "../lib/demo_scene.patlang"

let w = build_mesh_scene("../models")
let cam = set_camera_transform(camera(400, 200, pi() / 3), view_transform(point(0, 2, -6), point(0, 1, 0), vector(0, 1, 0)))
render_example(cam, w, "../out/ch15_meshes.png")
> tools/prender.sh examples/ch15_meshes.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 1176 s wall clock
A faceted red sphere, a smooth blue sphere and a gold pyramid

Same geometry, same silhouette: only the normal differs. The left sphere shows its facets; the right one is smooth, with the highlight a sphere would have, though its outline is still a polygon.

A speed-up found on the way

Rendering this scene took 195 s at first, against 52 s for the scene of Groups and trees of boxes at the time. The cause was not the triangles but the fixed work done for every shape on every ray: a triangle in a group has the identity transformation, and still had the ray carried into its space by two 4×4 products, the point carried by one, and the normal by a matrix. Each shape now records, when its transformation is set, whether that is the identity, and intersect, world_to_object and normal_to_world skip the products when it is. Three rows of this scene took 22.1 s before and 7.3 s after, with identical pixels (checksum 816647 before and after), the whole picture 195 s to 63 s, and the groups scene of Groups and trees of boxes rendered byte-identical to its committed image.

Checking it independently

The recursive tracer learned meshes. It reads the same OBJ files with its own parser (split on whitespace, v/vn/f with the slash forms, fan triangulation), sends every vertex through the model's transformation up front, and runs Möller–Trumbore with ordinary dot and cross products; smooth normals are interpolated from the transformed vertex normals. Every second pixel in each direction:

> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch15_meshes.png -Scene meshes -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 Groups and trees of boxes image, which it should reject.

> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch14_hexagon.png -Scene meshes -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 4055 (max difference 218); stride 4 in each direction, 5000 pixels checked

Limits

A group of triangles is tested one triangle at a time: the group's bounding box culls rays that miss the whole model, but a ray that enters the box tests all 168 (or 16 000) triangles. Subdividing the group into smaller boxes, as the book suggests, is the way to cut that; it is not done here.

Material Files for OBJ Models

Triangles and meshes from files read the shape of an OBJ model and nothing else: every triangle took whatever material the scene gave it. A model usually comes with a second file, a material file (MTL), named by a mtllib statement; its newmtl name blocks describe colours and shininess, and a usemtl name in the OBJ file says that the faces that follow are made of that. A map_Kd names a picture, which the faces wear by their texture coordinates, the vt lines.

This page reads both, and maps what they say onto the material of Light at a point, and shadows.

What an MTL statement becomes

statement our material
Kd r g b the colour (one number is a grey; default 4/5 grey). Diffuse is 1, so Kd is the reflectance
Ks r g b the specular: the mean of the three. None at all for illum 0 and 1
Ns n the shininess (default 10)
d x / Tr x transparency is 1 − d, or Tr itself
Ni x the refractive index (default 1)
illum n from 3 up the surface is ray traced, so it is reflective by the mean of Ks
map_Kd file a picture (PPM, relative to the material file), mapped by the face's vt
Ka understood and not used

Ka deserves a word. Our ambient is the renderer's own 1/10, and Ka is not used: material files very commonly say Ka 1 1 1, which taken as an ambient reflectance would wash every surface to white. A picture replaces Kd, as our patterns always have. Any statement not in the table is counted, as unknown OBJ statements always have been. The pictures must be PPM (the reader of Pictures on surfaces: texture and cube maps): a PNG or JPEG named by a model must be converted first, and one that cannot be read leaves the material plain and is counted.

# the numbers in fields[from ..], or false if any is not a number
make a function called mtl_numbers takes bytes, fields, from returns nums
  let nums = []
  let k = from
  while k < fields.length do
    let v = obj_number(bytes, fields[k][0], fields[k][1])
    if v == false then
      return false
    end
    let nums = list_push(nums, v)
    let k = k + 1
  end
  return nums
end

# [name, kd, ks, ns, d, tr, ni, illum, map, ignored]
make a function called mtl_blank takes name returns rec
  return [name, [(4/5), (4/5), (4/5)], [0, 0, 0], 10, 1, false, 1, 2, false, 0]
end

make a function called mtl_colour3 takes nums returns c
  if nums == false then
    return false
  end
  if nums.length == 1 then
    return [nums[0], nums[0], nums[0]]
  end
  if nums.length == 3 then
    return nums
  end
  return false
end

# the record changed by one statement (its fields already split)
make a function called mtl_statement takes bytes, fields, rec returns rec2
  let cmd = obj_text(bytes, fields[0][0], fields[0][1])
  let rec2 = rec
  let bad = false
  if cmd == "Kd" or cmd == "Ks" then
    let c = mtl_colour3(mtl_numbers(bytes, fields, 1))
    if c == false then
      let bad = true
    elif cmd == "Kd" then
      let rec2 = list_set(rec, 1, c)
    else
      let rec2 = list_set(rec, 2, c)
    end
  elif cmd == "Ns" or cmd == "d" or cmd == "Tr" or cmd == "Ni" or cmd == "illum" then
    let nums = mtl_numbers(bytes, fields, 1)
    if nums == false or nums.length != 1 then
      let bad = true
    elif cmd == "Ns" then
      let rec2 = list_set(rec, 3, nums[0])
    elif cmd == "d" then
      let rec2 = list_set(rec, 4, nums[0])
    elif cmd == "Tr" then
      let rec2 = list_set(rec, 5, nums[0])
    elif cmd == "Ni" then
      let rec2 = list_set(rec, 6, nums[0])
    else
      let rec2 = list_set(rec, 7, nums[0])
    end
  elif cmd == "map_Kd" then
    if fields.length < 2 then
      let bad = true
    else
      # options may come first; the file is the last field
      let last = fields[fields.length - 1]
      let rec2 = list_set(rec, 8, obj_text(bytes, last[0], last[1]))
    end
  elif cmd != "Ka" then
    let bad = true
  end
  if bad then
    let rec2 = list_set(rec2, 9, rec2[9] + 1)
  end
  return rec2
end

make a function called mtl_mean takes c returns v
  return (c[0] + c[1] + c[2]) / 3
end

# the finished record: the material, and the picture if the file names one that reads
make a function called mtl_build takes rec, dir returns out
  let ks = mtl_mean(rec[2])
  let illum = rec[7]
  let specular = ks
  if illum < 2 then
    let specular = 0
  end
  let m = material_with(color(rec[1][0], rec[1][1], rec[1][2]), (1/10), 1, specular, rec[3])
  if illum >= 3 then
    let m = with_reflective(m, ks)
  end
  let transparency = 1 - rec[4]
  if rec[5] != false then
    let transparency = rec[5]
  end
  let m = with_transparency(m, transparency)
  let m = with_refractive_index(m, rec[6])
  let ignored = rec[9]
  let uvp = false
  if rec[8] != false then
    let img = read_ppm(obj_join(dir, rec[8]))
    if img == false then
      let ignored = ignored + 1
    else
      let uvp = uv_image_smooth(img)
    end
  end
  return [rec[0], m, uvp, ignored]
end

make a function called parse_mtl_bytes takes bytes, dir returns records
  let records = []
  let rec = false
  let start = 0
  let i = 0
  while i <= bytes.length do
    if i == bytes.length or bytes[i] == 10 then
      let to = i
      if to > start and bytes[to - 1] == 13 then
        let to = to - 1
      end
      let fields = obj_fields(bytes, start, to)
      # a comment line is a field starting with #
      if fields.length > 0 and bytes[fields[0][0]] != 35 then
        if obj_text(bytes, fields[0][0], fields[0][1]) == "newmtl" then
          if rec != false then
            let records = list_push(records, mtl_build(rec, dir))
          end
          let name = ""
          if fields.length > 1 then
            let name = obj_text(bytes, fields[1][0], fields[1][1])
          end
          let rec = mtl_blank(name)
        elif rec != false then
          let rec = mtl_statement(bytes, fields, rec)
        end
      end
      let start = i + 1
    end
    let i = i + 1
  end
  if rec != false then
    let records = list_push(records, mtl_build(rec, dir))
  end
  return records
end

The OBJ side

mtllib reads the named file (relative to the OBJ file's directory) and adds its materials to the model's; usemtl makes one of them current, and each triangle made by a face after it gets that material. A name with no material gives the default and is counted. A face with v/vt indices and a current material that has a picture gets, for each of its triangles, a texture_map pattern whose mapping is triangle_uv: the three corners and their (u, v) travel in the pattern, and the point of the surface is turned into barycentric coordinates and those into a (u, v).

# the path of a file named inside an OBJ or MTL file: relative to the directory of the file that names it
make a function called obj_join takes dir, name returns path
  if dir == "" then
    return name
  end
  return dir + "/" + name
end

# the material for a triangle with these corner points and (u, v) references (each [u, v] or
# false): the material of the MTL record, with its picture, if it has one and the face has
# texture coordinates, mapped by the triangle's own (u, v)
make a function called obj_triangle_material takes rec, pts, uvs returns m
  let m = rec[1]
  if rec[2] != false and uvs[0] != false and uvs[1] != false and uvs[2] != false then
    let m = with_pattern(m, ["texture_map", rec[2], "triangle_uv", identity_matrix(), identity_matrix(), [pts[0], pts[1], pts[2], uvs[0], uvs[1], uvs[2]]])
  end
  return m
end
# the (u, v) of a point of a triangle by its corners and their own (u, v), from the barycentric
# coordinates of the point: p[5] is [p1, p2, p3, uv1, uv2, uv3]
make a function called triangle_uv takes data, pt returns uv
  let e1 = tuple_sub(data[1], data[0])
  let e2 = tuple_sub(data[2], data[0])
  let q = tuple_sub(pt, data[0])
  let d00 = dot(e1, e1)
  let d01 = dot(e1, e2)
  let d11 = dot(e2, e2)
  let d20 = dot(q, e1)
  let d21 = dot(q, e2)
  let denom = d00 * d11 - d01 * d01
  let v = (d11 * d20 - d01 * d21) / denom
  let w = (d00 * d21 - d01 * d20) / denom
  let u = 1 - v - w
  return [u * data[3][0] + v * data[4][0] + w * data[5][0], u * data[3][1] + v * data[4][1] + w * data[5][1]]
end

A texture index with no vt behind it still means "no texture coordinates", as it did before vt was read: older files that say f 1/1/1 without any vt lines load as they did.

Scenarios and oracles

  • Every statement. A material file with red plastic, glass (d, Ni, illum 3, with CRLF line ends), a matte one with Tr and illum 1, and a bare one with an unknown statement; each field is checked on exact rationals against the table.
  • Pictures. map_Kd is read relative to the file's directory; one that is not there leaves the material plain and is counted.
  • OBJ with materials. In tests/data/mtl_scene.obj, the triangles of each quad get the material of their usemtl; an undefined name gives the default, counted; a missing material file is counted and its names fall back to the default.
  • Textured faces against the picture itself. On a quad with the identity (u, v) the colour at (x, y) is the picture at (x, y) (12 points, on the right triangle of the fan); at each vertex of a triangle it is the picture at that vertex's own (u, v); at the centroid it is the picture at the mean of the three; the same after the model is moved and stretched.
  • In a world: color_at on the red quad is lighting with the red material.
  • Negative control: the picture at (0.7, 0.2) is not the picture at (0.2, 0.7), and the matte quad is not the red quad's colour.

The OBJ tests of Triangles and meshes from files still pass:

Putting it together

tools/make_blocks.patlang writes a model of five boxes and its material file: red and blue plastic, gold (illum 3: reflective), glass (d 0.2, Ni 1.5), and a crate that wears the brick picture of Bump and normal maps on every face.cf. Bump and normal maps: d is transparency, Ni is IOR

> (cd tools && v2_interp.exe make_blocks.patlang)
wrote models/blocks.obj and models/blocks.mtl
# materials of blocks.obj

newmtl red
Ka 0.2 0.0 0.0
Kd 0.85 0.12 0.12
Ks 0.5 0.5 0.5
Ns 100
d 1.0
illum 2

newmtl blue
Ka 0.0 0.0 0.2
Kd 0.15 0.25 0.85
Ks 0.4 0.4 0.4
Ns 60
d 1.0
illum 2

newmtl gold
Ka 0.2 0.15 0.0
Kd 0.9 0.7 0.1
Ks 0.9 0.8 0.3
Ns 200
d 1.0
illum 3

newmtl glass
Kd 0.9 0.95 1.0
Ks 0.9 0.9 0.9
Ns 300
d 0.2
Ni 1.5
illum 4

newmtl crate
Kd 1.0 1.0 1.0
Ks 0.1 0.1 0.1
Ns 20
map_Kd ../textures/bricks.ppm
illum 2

The boxes stand 2 mm above the floor and not on it. A box whose bottom lies exactly in the floor's plane has a face coincident with the plane: the ray meets both at the same t, which of them is "the hit" is a matter of rounding, and two correct renderers disagree about it. The first picture of this scene differed from the independent tracer at two of the 91 pixels sampled, both along the base of the glass box; after the boxes were raised, none of 5 000 did.

# chapter 25: an OBJ model with a material file. Five boxes (models/blocks.obj, which names
# models/blocks.mtl) on a checkered floor: red and blue plastic, reflective gold, glass, and a
# crate wearing the brick picture by its texture coordinates.
make a function called build_mtl_scene takes models 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 blocks = obj_to_group(parse_obj_file(models + "/blocks.obj"))
  return [[floor_p, blocks], demo_light(), true]
end
> tools/prender.sh examples/ch25_mtl.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 1095 s wall clock
five boxes from an OBJ file and its material file

Checking it independently

The point of this check is the reading of the files, so the exporter, which writes what our parser made, would prove nothing. The independent tracer reads blocks.obj and blocks.mtl itself: its own parser for v, vt, mtllib, usemtl, f, newmtl, Kd, Ks, Ns, d, Tr, Ni, illum and map_Kd, the table above as its own code, and its own picture reader and bilinear sampling. Its barycentric coordinates are signed areas of the sub-triangles, where the library's are the dot-product form.

> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch25_mtl.png -Scene mtl -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 0 (max difference 0); stride 4 in each direction, 5000 pixels checked

Negative controls: the same picture against the Triangles and meshes from files mesh scene, and the Triangles and meshes from files picture against this scene:

> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch25_mtl.png -Scene meshes -Stride 8
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 1102 (max difference 240); stride 8 in each direction, 1250 pixels checked
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch15_meshes.png -Scene mtl -Stride 8
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 1102 (max difference 240); stride 8 in each direction, 1250 pixels checked

How it is checked

> v2_interp.exe tests/run.patlang --node shapes/triangle --depth 2
[ ok ] Triangles
[ ok ]   Through the middle, past each edge, and alongside
[ ok ]   A hit on a triangle records where it is (u along the second corner, v the third)
[ ok ]   A flat triangle has one normal, from its edges
[ ok ]   A smooth triangle blends its corner normals by where the hit is
[ ok ]   Against its plane, inside its edges
[ 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 ]   Two ways to meet a triangle  (all, giving the same answer)
[ ok ]     naive: wedge products (triple products) of the edges
[ ok ]     faster: the same determinants on coordinates
[ ok ]   Further checks, independent of the code they check
[ ok ]     Ga_triple(a, b, c) is the e123 coefficient of a ^ b ^ c, exactly (343 triples
[ ok ]     Same t as the plane-then-edges algorithm on
[ ok ]     A transformed triangle: same t as the triangle with transformed corners
[ ok ]     At a vertex the interpolated normal is that vertex's normal
[ ok ]     Comments, blank lines, tabs, CRLF and a last line without newline: three vertices, one ...
checks: 14 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED
> v2_interp.exe tests/run.patlang --node shapes/meshes --depth 2
[ ok ] Meshes from files
[ ok ]   Meshes from OBJ files
[ ok ]     Lines it does not know are counted and skipped
[ ok ]     Vertices are read exactly: signs, decimals, exponents
[ ok ]     Tabs, runs of spaces and Windows line ends are taken in their stride
[ ok ]     Faces become triangles whose corners are the vertices named
[ ok ]     A face with more corners is a fan of triangles from its first corner
[ ok ]     Named groups keep their own faces; everything goes into one group at the end
[ ok ]     Vertex normals are read, and faces that name them become smooth triangles
[ ok ]     A mesh is hit where its triangles are
[ ok ]   Materials from MTL files
[ ok ]     Material files
[ ok ]     OBJ with materials
[ ok ]     Textured faces
[ ok ]     In a world
checks: 14 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED