Back to Drift City
SOURCE / PINNED RELEASE

Made of little things.

Drift City

Release
098731aa0f0f…
Author-recorded commit
2822ea0a4f5b…
License
LICENSE
Author’s source reference
nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855

Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/game/car-paint.ts
import * as THREE from 'three';

/**
 * The player's own paint job: brush strokes and shapes painted onto the car's bodywork.
 *
 * The bodywork (the paint-coloured parts only: never the glass, the wheels, the lights or
 * the black trim) is mapped onto one 2048² texture, the livery, by five straight-on views
 * of the body (box projection): its two sides, its top, its nose and its tail. Each face
 * of the body shows the view it faces most. A face hidden in its view behind another
 * (inside the cabin, say) shows none of it.
 *
 * For each texel of the livery, a smaller map (the surface map) holds where on the body
 * it lands: how far out along its view, and which way the surface faces there. That lets
 * every mark be drawn in 3D, on the GPU, straight into the livery: a brush dab is a ball
 * that colours the surface inside it, and a shape is a stencil projected onto the body
 * from in front of the face it was put on. Both run on across the edges between views
 * (from the side up over the bonnet, say), so they wrap round the car's corners.
 *
 * The livery holds premultiplied sRGB colour and its cover, over the car's base colour.
 *
 * The eraser rubs out brush paint only, never shapes (paint over a shape and rub it out,
 * and the shape's there again). So a design is drawn from its last mark back to its
 * first, each under what's drawn so far, while the eraser strokes met on the way build a
 * mask of what's rubbed out: every brush stroke under them is drawn through the mask,
 * the shapes as they are. A brush stroke being painted is the last mark, so it's simply
 * drawn over the top as it goes.
 */

export const LIVERY_SIZE = 2048;
/** The surface map: half the livery's size (the depth changes slowly, and the views are flat). */
const SURFACE_SIZE = 1024;

/** One of the five views: its axes (outward, across, up), their ranges (m, body frame) and its rectangle in the livery (px). */
interface View {
  n: THREE.Vector3;
  u: THREE.Vector3;
  v: THREE.Vector3;
  range: [number, number, number, number];
  rect: [number, number, number, number];
}

const X = new THREE.Vector3(1, 0, 0);
const Y = new THREE.Vector3(0, 1, 0);
const Z = new THREE.Vector3(0, 0, 1);
const neg = (a: THREE.Vector3) => a.clone().negate();

/** (Even pixel edges, so they fall on whole texels of the half-size surface map; gaps between, so filtering doesn't bleed.) */
const VIEWS: View[] = [
  { n: X, u: Z, v: Y, range: [-2.35, 2.35, 0.15, 1.5], rect: [0, 0, 1786, 512] },
  { n: neg(X), u: neg(Z), v: Y, range: [-2.35, 2.35, 0.15, 1.5], rect: [0, 516, 1786, 512] },
  { n: Y, u: Z, v: X, range: [-2.35, 2.35, -1.3, 1.3], rect: [0, 1032, 1786, 988] },
  { n: Z, u: Y, v: X, range: [0.15, 1.5, -1.3, 1.3], rect: [1792, 0, 252, 494] },
  { n: neg(Z), u: Y, v: X, range: [0.15, 1.5, -1.3, 1.3], rect: [1792, 500, 252, 494] },
];

/** The views as uniforms, shared by every shader here and the car's. */
const VIEW_UNIFORMS = {
  viewN: { value: VIEWS.map((w) => w.n) },
  viewU: { value: VIEWS.map((w) => w.u) },
  viewV: { value: VIEWS.map((w) => w.v) },
  /** u0, u1, v0, v1 (m). */
  viewRange: { value: VIEWS.map((w) => new THREE.Vector4(...w.range)) },
  /** x, y, w, h in the livery's UV (0 to 1). */
  viewRect: { value: VIEWS.map((w) => new THREE.Vector4(...w.rect).multiplyScalar(1 / LIVERY_SIZE)) },
};

/** GLSL: the views, and the view a surface with normal n shows (-1: none, facing down). */
const VIEW_GLSL = /* glsl */ `
  uniform vec3 viewN[5];
  uniform vec3 viewU[5];
  uniform vec3 viewV[5];
  uniform vec4 viewRange[5];
  uniform vec4 viewRect[5];
  int viewOf(vec3 n) {
    vec3 a = abs(n);
    if (a.x >= a.y && a.x >= a.z) return n.x > 0.0 ? 0 : 1;
    if (a.y >= a.z) return n.y > 0.0 ? 2 : -1;
    return n.z > 0.0 ? 3 : 4;
  }
  /** Where a point in the body's frame lies in a view's rectangle, in the livery's UV. */
  vec2 viewUv(int k, vec3 p) {
    vec4 r = viewRange[k];
    vec2 t = (vec2(dot(p, viewU[k]), dot(p, viewV[k])) - r.xz) / (r.yw - r.xz);
    return viewRect[k].xy + t * viewRect[k].zw;
  }
`;

/** GLSL for the stamps and shapes: the surface under a texel of a view (xyz, and w the cover: 0 for no surface). */
const SURFACE_GLSL = /* glsl */ `
  uniform sampler2D surfaceMap;
  flat varying int vView;
  varying vec2 vAt;
  varying vec2 vUv;
  vec4 surface(out vec3 n) {
    vec4 s = texture2D(surfaceMap, vUv);
    n = s.xyz;
    if (dot(n, n) < 0.25) return vec4(0.0);
    return vec4(viewU[vView] * vAt.x + viewV[vView] * vAt.y + viewN[vView] * s.w, 1.0);
  }
`;

/**
 * GLSL: a quad over a view's rectangle, clipped to it, for the part (u0, v0, u1, v1, in
 * the view's metres) a mark might cover. corner: the quad's corner (0 or 1 each way).
 */
const QUAD_GLSL = /* glsl */ `
  void placeQuad(int k, vec4 box, vec2 corner) {
    vec4 r = viewRange[k];
    box = vec4(max(box.xy, r.xz), min(box.zw, r.yw));
    vec2 at = mix(box.xy, box.zw, corner);
    if (box.z <= box.x || box.w <= box.y) at = vec2(-1000.0);
    vView = k;
    vAt = at;
    vec2 t = (at - r.xz) / (r.yw - r.xz);
    vUv = viewRect[k].xy + t * viewRect[k].zw;
    gl_Position = vec4(vUv * 2.0 - 1.0, 0.0, 1.0);
  }
`;

/** The shapes a shape can be. */
export const SHAPES = ['circle', 'square', 'triangle', 'diamond', 'star', 'heart', 'ring', 'arrow'] as const;
export type ShapeKind = (typeof SHAPES)[number];

/** GLSL: each shape's signed distance (negative inside), in its own frame where it fills -1 to 1 each way (+y forward). */
const SHAPE_GLSL = /* glsl */ `
  float sdBox(vec2 p, vec2 b) { vec2 d = abs(p) - b; return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); }
  float sdTri(vec2 p, vec2 p0, vec2 p1, vec2 p2) {
    vec2 e0 = p1 - p0, e1 = p2 - p1, e2 = p0 - p2;
    vec2 v0 = p - p0, v1 = p - p1, v2 = p - p2;
    vec2 pq0 = v0 - e0 * clamp(dot(v0, e0) / dot(e0, e0), 0.0, 1.0);
    vec2 pq1 = v1 - e1 * clamp(dot(v1, e1) / dot(e1, e1), 0.0, 1.0);
    vec2 pq2 = v2 - e2 * clamp(dot(v2, e2) / dot(e2, e2), 0.0, 1.0);
    float s = sign(e0.x * e2.y - e0.y * e2.x);
    vec2 d = min(min(vec2(dot(pq0, pq0), s * (v0.x * e0.y - v0.y * e0.x)), vec2(dot(pq1, pq1), s * (v1.x * e1.y - v1.y * e1.x))), vec2(dot(pq2, pq2), s * (v2.x * e2.y - v2.y * e2.x)));
    return -sqrt(d.x) * sign(d.y);
  }
  float sdStar(vec2 p) {
    const vec2 k1 = vec2(0.809016994375, -0.587785252292);
    const vec2 k2 = vec2(-k1.x, k1.y);
    float r = 1.0, rf = 0.45;
    p.x = abs(p.x);
    p -= 2.0 * max(dot(k1, p), 0.0) * k1;
    p -= 2.0 * max(dot(k2, p), 0.0) * k2;
    p.x = abs(p.x);
    p.y -= r;
    vec2 ba = rf * vec2(-k1.y, k1.x) - vec2(0.0, 1.0);
    float h = clamp(dot(p, ba) / dot(ba, ba), 0.0, r);
    return length(p - ba * h) * sign(p.y * ba.x - p.x * ba.y);
  }
  float sdHeart(vec2 q) {
    // (Its point at the bottom, its lobes 0.6 out either side and 1.1 up.)
    vec2 p = vec2(abs(q.x) * 0.6, (q.y + 1.0) * 0.55);
    if (p.y + p.x > 1.0) return sqrt(dot(p - vec2(0.25, 0.75), p - vec2(0.25, 0.75))) - sqrt(2.0) / 4.0;
    vec2 a = p - vec2(0.0, 1.0);
    vec2 b = p - 0.5 * max(p.x + p.y, 0.0);
    return sqrt(min(dot(a, a), dot(b, b))) * sign(p.x - p.y);
  }
  float shapeDist(int kind, vec2 p) {
    if (kind == 0) return length(p) - 1.0;
    if (kind == 1) return sdBox(p, vec2(1.0));
    if (kind == 2) return sdTri(p, vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(0.0, 1.0));
    if (kind == 3) return (abs(p.x) + abs(p.y) - 1.0) * 0.7071;
    if (kind == 4) return sdStar(p * vec2(1.0, 1.05) + vec2(0.0, 0.1));
    if (kind == 5) return sdHeart(p);
    if (kind == 6) return abs(length(p) - 0.8) - 0.2;
    return min(sdBox(p - vec2(0.0, -0.45), vec2(0.32, 0.55)), sdTri(p, vec2(-1.0, 0.1), vec2(1.0, 0.1), vec2(0.0, 1.0)));
  }
`;

/** A brush stroke: dabs along a line on the body (points in the body's frame, metres, with the surface's normal at each). */
export interface Stroke {
  t: 'stroke';
  /** sRGB colour. */
  color: number;
  opacity: number;
  /** Radius, m. */
  size: number;
  /** 0 soft to 1 hard edged. */
  hard: number;
  erase: boolean;
  /** x, y, z, nx, ny, nz for each point. */
  pts: number[];
  /** Painted on the other side too, mirrored down the middle of the car. */
  mirror?: boolean;
}

/** A shape stencilled onto the body from in front of the point it's centred on. */
export interface Shape {
  t: 'shape';
  kind: ShapeKind;
  color: number;
  opacity: number;
  /** Full width and length, m. */
  w: number;
  l: number;
  /** Turned about the surface's normal, radians. */
  rot: number;
  c: [number, number, number];
  n: [number, number, number];
  /** On the other side too, mirrored down the middle of the car. */
  mirror?: boolean;
}

export type PaintOp = Stroke | Shape;

/**
 * Dabs (x, y, z, nx, ny, nz each) mirrored down the middle of the car: its x across from
 * left to right, so x and the normal's x turn round. (The paintwork is the same both sides.)
 */
export function mirrorDabs(d: readonly number[]): number[] {
  const out = d.slice();
  for (let i = 0; i < out.length; i += 6) {
    out[i] = -out[i]!;
    out[i + 3] = -out[i + 3]!;
  }
  return out;
}

/** The view a surface facing n shows (as viewOf in the shaders), or -1. */
function viewOf(n: THREE.Vector3): number {
  const a = [Math.abs(n.x), Math.abs(n.y), Math.abs(n.z)];
  if (a[0]! >= a[1]! && a[0]! >= a[2]!) return n.x > 0 ? 0 : 1;
  if (a[1]! >= a[2]!) return n.y > 0 ? 2 : -1;
  return n.z > 0 ? 3 : 4;
}

const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
const toSrgb = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);

/** A shape's axes on the body: across (its width), up (its length) and out (its normal), turned by its rotation. */
export function shapeAxes(s: Pick<Shape, 'n' | 'rot'>): { u: THREE.Vector3; v: THREE.Vector3; n: THREE.Vector3 } {
  const n = new THREE.Vector3(...s.n).normalize();
  // Upright on the sides, nose and tail; pointing forward on the bonnet, roof and boot.
  const ref = Math.abs(n.y) < 0.8 ? Y : Z;
  const v = ref.clone().addScaledVector(n, -ref.dot(n)).normalize();
  const u = new THREE.Vector3().crossVectors(v, n).normalize();
  const c = Math.cos(s.rot);
  const si = Math.sin(s.rot);
  return { u: u.clone().multiplyScalar(c).addScaledVector(v, si), v: v.clone().multiplyScalar(c).addScaledVector(u, -si), n };
}

/** How far in front of and behind its point a shape reaches into the body (m). */
const SHAPE_DEPTH = 0.35;

/** The dabs along a stroke: one every fifth of the brush's radius. */
export class Dabber {
  private last: number[] | null = null;
  /** How far along the line from the last point the next dab is due. */
  private due = 0;
  constructor(private readonly size: number) {}

  /** Dabs from the line to point p (x, y, z, nx, ny, nz), into out. */
  add(p: number[], out: number[]): void {
    const step = Math.max(0.0012, this.size * 0.2);
    const a = this.last;
    this.last = p;
    if (!a) {
      out.push(...p);
      this.due = step;
      return;
    }
    const len = Math.hypot(p[0]! - a[0]!, p[1]! - a[1]!, p[2]! - a[2]!);
    let d = this.due;
    for (; d <= len; d += step) {
      const t = d / len;
      const nx = a[3]! + (p[3]! - a[3]!) * t;
      const ny = a[4]! + (p[4]! - a[4]!) * t;
      const nz = a[5]! + (p[5]! - a[5]!) * t;
      const nl = Math.hypot(nx, ny, nz) || 1;
      out.push(a[0]! + (p[0]! - a[0]!) * t, a[1]! + (p[1]! - a[1]!) * t, a[2]! + (p[2]! - a[2]!) * t, nx / nl, ny / nl, nz / nl);
    }
    this.due = d - len;
  }
}

/** A quad per view, instanced: corner xy, view index z. */
function viewQuads(): { pos: Float32Array; index: number[] } {
  const pos: number[] = [];
  const index: number[] = [];
  for (let k = 0; k < 5; k++) {
    const b = k * 4;
    pos.push(0, 0, k, 1, 0, k, 1, 1, k, 0, 1, k);
    index.push(b, b + 1, b + 2, b, b + 2, b + 3);
  }
  return { pos: new Float32Array(pos), index };
}

const premultipliedOver = {
  blending: THREE.CustomBlending,
  blendEquation: THREE.AddEquation,
  blendSrc: THREE.SrcAlphaFactor,
  blendDst: THREE.OneMinusSrcAlphaFactor,
  blendSrcAlpha: THREE.OneFactor,
  blendDstAlpha: THREE.OneMinusSrcAlphaFactor,
};
/** Premultiplied colour put under what's there already (drawing from the top mark down). */
const premultipliedUnder = {
  blending: THREE.CustomBlending,
  blendEquation: THREE.AddEquation,
  blendSrc: THREE.OneMinusDstAlphaFactor,
  blendDst: THREE.OneFactor,
  blendSrcAlpha: THREE.OneMinusDstAlphaFactor,
  blendDstAlpha: THREE.OneFactor,
};
/** Cover added to the eraser's mask (in its red), over what's there. */
const maskOver = {
  blending: THREE.CustomBlending,
  blendEquation: THREE.AddEquation,
  blendSrc: THREE.OneFactor,
  blendDst: THREE.OneMinusSrcAlphaFactor,
  blendSrcAlpha: THREE.OneFactor,
  blendDstAlpha: THREE.OneMinusSrcAlphaFactor,
};

/** How a mark's drawn: over the top (as it's painted), under what's there (replaying), or into the eraser's mask. */
const enum Mode {
  Over = 0,
  Under = 1,
  Mask = 2,
}

const srgb = (hex: number) => new THREE.Vector3(((hex >> 16) & 255) / 255, ((hex >> 8) & 255) / 255, (hex & 255) / 255);

export class CarPaint {
  /** The livery, for the car's paint to show. */
  readonly livery: THREE.WebGLRenderTarget;
  /** The surface map, for the car's paint to tell faces hidden in their view. */
  get surface(): THREE.Texture {
    return this.surfaceRT.texture;
  }
  private readonly surfaceRT: THREE.WebGLRenderTarget;
  private readonly scene = new THREE.Scene();
  private readonly camera = new THREE.OrthographicCamera();
  private readonly dabGeo = new THREE.InstancedBufferGeometry();
  private dabCap = 0;
  private dabBuf!: THREE.InstancedInterleavedBuffer;
  /** Nothing, drawn to remake the livery's smaller sizes after it's cleared. */
  private readonly nothing = new THREE.Mesh();
  private readonly dabMesh: THREE.Mesh;
  /** Brush dabs: over the top, under (through the eraser's mask), and an eraser's into the mask. */
  private readonly dabMats: Record<Mode, THREE.ShaderMaterial>;
  private readonly shapeMesh: THREE.Mesh;
  /** Shapes, drawn under what's there (the eraser never reaches them). */
  private readonly shapeMat: THREE.ShaderMaterial;
  /** What the eraser strokes over the marks drawn so far (replaying from the top) have rubbed out. */
  private readonly eraseMask: THREE.WebGLRenderTarget;
  /** Each stroke's dabs, worked out once (and again if it's grown since). */
  private readonly dabCache = new WeakMap<Stroke, { points: number; dabs: number[] }>();

  constructor(
    private readonly renderer: THREE.WebGLRenderer,
    paintMeshes: THREE.Mesh[],
  ) {
    this.livery = new THREE.WebGLRenderTarget(LIVERY_SIZE, LIVERY_SIZE, {
      type: THREE.UnsignedByteType,
      format: THREE.RGBAFormat,
      generateMipmaps: true,
      minFilter: THREE.LinearMipmapLinearFilter,
      magFilter: THREE.LinearFilter,
      depthBuffer: false,
    });
    this.livery.texture.anisotropy = Math.min(4, renderer.capabilities.getMaxAnisotropy());
    this.surfaceRT = new THREE.WebGLRenderTarget(SURFACE_SIZE, SURFACE_SIZE, {
      type: THREE.HalfFloatType,
      format: THREE.RGBAFormat,
      minFilter: THREE.NearestFilter,
      magFilter: THREE.NearestFilter,
      generateMipmaps: false,
      depthBuffer: true,
    });
    this.bakeSurface(paintMeshes);
    this.eraseMask = new THREE.WebGLRenderTarget(LIVERY_SIZE, LIVERY_SIZE, {
      type: THREE.UnsignedByteType,
      format: THREE.RedFormat,
      minFilter: THREE.NearestFilter,
      magFilter: THREE.NearestFilter,
      generateMipmaps: false,
      depthBuffer: false,
    });

    const quads = viewQuads();
    this.dabGeo.setAttribute('position', new THREE.BufferAttribute(quads.pos, 3));
    this.dabGeo.setIndex(quads.index);
    this.growDabs(4096);
    const uniforms = () => ({
      ...VIEW_UNIFORMS,
      surfaceMap: { value: this.surfaceRT.texture },
      eraseMask: { value: this.eraseMask.texture },
      color: { value: new THREE.Vector3() },
      opacity: { value: 1 },
      size: { value: 0.05 },
      hard: { value: 1 },
    });
    const dabShader = {
      vertexShader: /* glsl */ `
        ${VIEW_GLSL}
        flat varying int vView;
        varying vec2 vAt;
        varying vec2 vUv;
        ${QUAD_GLSL}
        attribute vec3 dab;
        attribute vec3 dabN;
        uniform float size;
        flat varying vec3 vCentre;
        flat varying vec3 vNormal;
        void main() {
          int k = int(position.z + 0.5);
          vec2 c = vec2(dot(dab, viewU[k]), dot(dab, viewV[k]));
          // (Not on a view that faces away from where it's painted.)
          float facing = dot(dabN, viewN[k]);
          vec4 box = facing < -0.3 ? vec4(1.0, 1.0, -1.0, -1.0) : vec4(c - size, c + size);
          placeQuad(k, box, position.xy);
          vCentre = dab;
          vNormal = dabN;
        }`,
      fragmentShader: /* glsl */ `
        ${VIEW_GLSL}
        ${SURFACE_GLSL}
        uniform vec3 color;
        uniform float opacity;
        uniform float size;
        uniform float hard;
        uniform sampler2D eraseMask;
        flat varying vec3 vCentre;
        flat varying vec3 vNormal;
        void main() {
          vec3 n;
          vec4 p = surface(n);
          if (p.w < 0.5 || dot(n, vNormal) < -0.3) discard;
          float d = distance(p.xyz, vCentre);
          // (At least a texel and a half of soft edge, for smooth lines.)
          float edge = max((1.0 - hard) * size, 0.004);
          float a = opacity * (1.0 - smoothstep(size - edge, size, d));
          #if MODE == 1
            // (Under the marks above, through what the eraser strokes above have rubbed out.)
            a *= 1.0 - texture2D(eraseMask, vUv).r;
          #endif
          if (a <= 0.0) discard;
          #if MODE == 1
            gl_FragColor = vec4(color * a, a);
          #elif MODE == 2
            gl_FragColor = vec4(a);
          #else
            gl_FragColor = vec4(color, a);
          #endif
        }`,
    };
    const dab = (mode: Mode, blend: object) => new THREE.ShaderMaterial({ ...dabShader, defines: { MODE: mode }, uniforms: uniforms(), depthTest: false, depthWrite: false, ...blend });
    this.dabMats = { [Mode.Over]: dab(Mode.Over, premultipliedOver), [Mode.Under]: dab(Mode.Under, premultipliedUnder), [Mode.Mask]: dab(Mode.Mask, maskOver) };
    this.dabMesh = new THREE.Mesh(this.dabGeo, this.dabMats[Mode.Over]);
    this.dabMesh.frustumCulled = false;

    const shapeGeo = new THREE.BufferGeometry();
    shapeGeo.setAttribute('position', new THREE.BufferAttribute(quads.pos, 3));
    shapeGeo.setIndex(quads.index);
    const shapeUniforms = () => ({
      ...uniforms(),
      centre: { value: new THREE.Vector3() },
      axisU: { value: new THREE.Vector3() },
      axisV: { value: new THREE.Vector3() },
      axisN: { value: new THREE.Vector3() },
      halfSize: { value: new THREE.Vector2() },
      kind: { value: 0 },
    });
    const shapeShader = {
      vertexShader: /* glsl */ `
        ${VIEW_GLSL}
        flat varying int vView;
        varying vec2 vAt;
        varying vec2 vUv;
        ${QUAD_GLSL}
        uniform vec3 centre;
        uniform vec3 axisU;
        uniform vec3 axisV;
        uniform vec3 axisN;
        uniform vec2 halfSize;
        void main() {
          int k = int(position.z + 0.5);
          // The box the stencil reaches through, seen in this view.
          vec4 box = vec4(1e5, 1e5, -1e5, -1e5);
          for (int i = 0; i < 8; i++) {
            vec3 q = centre + axisU * halfSize.x * ((i & 1) == 0 ? -1.0 : 1.0) + axisV * halfSize.y * ((i & 2) == 0 ? -1.0 : 1.0) + axisN * ${SHAPE_DEPTH.toFixed(2)} * ((i & 4) == 0 ? -1.0 : 1.0);
            vec2 c = vec2(dot(q, viewU[k]), dot(q, viewV[k]));
            box = vec4(min(box.xy, c), max(box.zw, c));
          }
          if (dot(axisN, viewN[k]) < -0.1) box = vec4(1.0, 1.0, -1.0, -1.0);
          placeQuad(k, box, position.xy);
        }`,
      fragmentShader: /* glsl */ `
        ${VIEW_GLSL}
        ${SURFACE_GLSL}
        ${SHAPE_GLSL}
        uniform vec3 color;
        uniform float opacity;
        uniform vec3 centre;
        uniform vec3 axisU;
        uniform vec3 axisV;
        uniform vec3 axisN;
        uniform vec2 halfSize;
        uniform int kind;
        void main() {
          vec3 n;
          vec4 p = surface(n);
          vec3 d = p.xyz - centre;
          float depth = dot(d, axisN);
          vec2 q = vec2(dot(d, axisU) / halfSize.x, dot(d, axisV) / halfSize.y);
          float sd = shapeDist(kind, q);
          float aa = max(fwidth(sd), 1e-4);
          float a = opacity * (1.0 - smoothstep(-aa * 0.7, aa * 0.7, sd));
          // Only faces turned towards it, near enough the surface it was put on.
          a *= smoothstep(0.1, 0.25, dot(n, axisN)) * (1.0 - smoothstep(${(SHAPE_DEPTH * 0.8).toFixed(2)}, ${SHAPE_DEPTH.toFixed(2)}, abs(depth)));
          if (p.w < 0.5 || a <= 0.0) discard;
          gl_FragColor = vec4(color * a, a);
        }`,
    };
    this.shapeMat = new THREE.ShaderMaterial({ ...shapeShader, uniforms: shapeUniforms(), depthTest: false, depthWrite: false, ...premultipliedUnder });
    this.shapeMesh = new THREE.Mesh(shapeGeo, this.shapeMat);
    this.shapeMesh.frustumCulled = false;
    this.clear();
  }

  private growDabs(n: number): void {
    this.dabCap = n;
    // Position and normal of each dab, from the one array.
    const inter = new THREE.InstancedInterleavedBuffer(new Float32Array(n * 6), 6, 1);
    inter.setUsage(THREE.DynamicDrawUsage);
    this.dabBuf = inter;
    this.dabGeo.setAttribute('dab', new THREE.InterleavedBufferAttribute(inter, 3, 0));
    this.dabGeo.setAttribute('dabN', new THREE.InterleavedBufferAttribute(inter, 3, 3));
  }

  /** Where the body is, in each view: rendered once, from the paint-coloured meshes (in the body's frame). */
  private bakeSurface(meshes: THREE.Mesh[]): void {
    const mat = new THREE.ShaderMaterial({
      uniforms: { outward: { value: new THREE.Vector3() } },
      side: THREE.DoubleSide,
      vertexShader: /* glsl */ `
        varying vec3 vPos;
        varying vec3 vN;
        void main() {
          vPos = (modelMatrix * vec4(position, 1.0)).xyz;
          vN = transpose(inverse(mat3(modelMatrix))) * normal;
          gl_Position = projectionMatrix * viewMatrix * vec4(vPos, 1.0);
        }`,
      fragmentShader: /* glsl */ `
        uniform vec3 outward;
        varying vec3 vPos;
        varying vec3 vN;
        void main() {
          vec3 n = normalize(vN);
          // (Facing the view: the nearest surface is the outside of the body.)
          if (dot(n, outward) < 0.0) n = -n;
          gl_FragColor = vec4(n, dot(vPos, outward));
        }`,
    });
    const scene = new THREE.Scene();
    for (const m of meshes) {
      const copy = new THREE.Mesh(m.geometry, mat);
      copy.matrixAutoUpdate = false;
      // (Its place in the body, made fresh: it may not have been drawn yet.)
      m.updateMatrix();
      copy.matrix.copy(m.matrix);
      scene.add(copy);
    }
    scene.updateMatrixWorld(true);
    const cam = new THREE.OrthographicCamera();
    cam.matrixAutoUpdate = false;
    const r = this.renderer;
    const restore = this.saveState();
    r.setRenderTarget(this.surfaceRT);
    r.setClearColor(0x000000, 0);
    r.clear(true, true, false);
    const rt = this.surfaceRT;
    const k = SURFACE_SIZE / LIVERY_SIZE;
    for (const w of VIEWS) {
      const [u0, u1, v0, v1] = w.range;
      cam.left = u0;
      cam.right = u1;
      cam.bottom = v0;
      cam.top = v1;
      cam.near = 0.1;
      cam.far = 20;
      cam.updateProjectionMatrix();
      cam.matrix.makeBasis(w.u, w.v, w.n).setPosition(w.n.clone().multiplyScalar(10));
      cam.updateMatrixWorld(true);
      mat.uniforms.outward!.value.copy(w.n);
      rt.viewport.set(w.rect[0] * k, w.rect[1] * k, w.rect[2] * k, w.rect[3] * k);
      rt.scissor.copy(rt.viewport);
      rt.scissorTest = true;
      r.setRenderTarget(rt);
      r.render(scene, cam);
    }
    rt.viewport.set(0, 0, SURFACE_SIZE, SURFACE_SIZE);
    rt.scissorTest = false;
    restore();
    mat.dispose();
  }

  private saveState(): () => void {
    const r = this.renderer;
    const target = r.getRenderTarget();
    const autoClear = r.autoClear;
    const color = r.getClearColor(new THREE.Color());
    const alpha = r.getClearAlpha();
    const shadows = r.shadowMap.autoUpdate;
    r.autoClear = false;
    r.shadowMap.autoUpdate = false;
    return () => {
      r.setRenderTarget(target);
      r.autoClear = autoClear;
      r.setClearColor(color, alpha);
      r.shadowMap.autoUpdate = shadows;
    };
  }

  /** Wipe the livery clean (the base colour all over). */
  clear(): void {
    const restore = this.saveState();
    this.renderer.setRenderTarget(this.livery);
    this.renderer.setClearColor(0x000000, 0);
    this.renderer.clear(true, false, false);
    restore();
  }

  /** Draw marks into the livery. mipmaps: remake the smaller sizes after (once, after the last draw of a batch). */
  private draw(mesh: THREE.Mesh, mipmaps: boolean, target: THREE.WebGLRenderTarget = this.livery): void {
    this.livery.texture.generateMipmaps = mipmaps;
    this.scene.add(mesh);
    this.renderer.setRenderTarget(target);
    this.renderer.render(this.scene, this.camera);
    this.scene.remove(mesh);
    this.livery.texture.generateMipmaps = true;
  }

  /** Paint dabs (x, y, z, nx, ny, nz each) with a stroke's brush, over the top (the stroke being painted: the last mark). */
  dabs(s: Omit<Stroke, 'pts' | 't'>, dabs: number[], mipmaps = true): void {
    if (s.erase) return;
    this.drawDabs(s, dabs, mipmaps, Mode.Over);
  }

  private drawDabs(s: Omit<Stroke, 'pts' | 't'>, dabs: number[], mipmaps: boolean, mode: Mode): void {
    const n = dabs.length / 6;
    if (n === 0) return;
    if (n > this.dabCap) this.growDabs(Math.max(n, this.dabCap * 2));
    const inter = this.dabBuf;
    (inter.array as Float32Array).set(dabs);
    inter.needsUpdate = true;
    inter.clearUpdateRanges();
    inter.addUpdateRange(0, n * 6);
    this.dabGeo.instanceCount = n;
    const mat = this.dabMats[mode];
    mat.uniforms.color!.value.copy(srgb(s.color));
    mat.uniforms.opacity!.value = s.opacity;
    mat.uniforms.size!.value = s.size;
    mat.uniforms.hard!.value = s.hard;
    this.dabMesh.material = mat;
    const restore = this.saveState();
    this.draw(this.dabMesh, mipmaps, mode === Mode.Mask ? this.eraseMask : this.livery);
    restore();
  }

  /** A stroke's dabs (worked out once, and again once it's grown). */
  private dabsOf(op: Stroke): number[] {
    const had = this.dabCache.get(op);
    if (had && had.points === op.pts.length) return had.dabs;
    const dabs: number[] = [];
    const d = new Dabber(op.size);
    for (let k = 0; k < op.pts.length; k += 6) d.add(op.pts.slice(k, k + 6), dabs);
    this.dabCache.set(op, { points: op.pts.length, dabs });
    return dabs;
  }

  /** Stencil a shape (and, if it's mirrored, its mirror image), under what's there. */
  private shape(s: Shape): void {
    if (s.mirror) this.stencil(s, true);
    this.stencil(s, false);
  }

  /** One stencil of a shape; twin: its mirror image, down the middle of the car (axes and all, so it's a true reflection). */
  private stencil(s: Shape, twin: boolean): void {
    const mat = this.shapeMat;
    const ax = shapeAxes(s);
    const u = mat.uniforms;
    const flip = (v: THREE.Vector3) => (twin ? v.set(-v.x, v.y, v.z) : v);
    u.color!.value.copy(srgb(s.color));
    u.opacity!.value = s.opacity;
    u.centre!.value.set(twin ? -s.c[0] : s.c[0], s.c[1], s.c[2]);
    u.axisU!.value.copy(flip(ax.u));
    u.axisV!.value.copy(flip(ax.v));
    u.axisN!.value.copy(flip(ax.n));
    u.halfSize!.value.set(s.w / 2, s.l / 2);
    u.kind!.value = SHAPES.indexOf(s.kind);
    this.shapeMesh.material = mat;
    const restore = this.saveState();
    this.draw(this.shapeMesh, false);
    restore();
  }

  /**
   * The colour the paintwork really is at a point on the body facing n (sRGB): the
   * livery there over the base colour, without the light and shade.
   */
  colorAt(p: THREE.Vector3, n: THREE.Vector3, base: number): number {
    const b = srgb(base);
    let [r, g, bl] = [b.x, b.y, b.z];
    const { color, cover: a } = this.paintAt(p, n);
    if (a > 0.004) {
      // (Laid over the base in linear light, as the car's shader does.)
      const mix = (c: number, under: number) => toSrgb(toLinear(under) * (1 - a) + toLinear(c / 255) * a);
      [r, g, bl] = [mix((color >> 16) & 255, r), mix((color >> 8) & 255, g), mix(color & 255, bl)];
    }
    const to8 = (c: number) => Math.max(0, Math.min(255, Math.round(c * 255)));
    return (to8(r) << 16) | (to8(g) << 8) | to8(bl);
  }

  /** What's painted at a point on the body facing n: its colour (sRGB, as painted) and how much it covers the base (0 to 1). */
  paintAt(p: THREE.Vector3, n: THREE.Vector3): { color: number; cover: number } {
    const k = viewOf(n);
    if (k < 0) return { color: 0, cover: 0 };
    const w = VIEWS[k]!;
    const [u0, u1, v0, v1] = w.range;
    const tu = (p.dot(w.u) - u0) / (u1 - u0);
    const tv = (p.dot(w.v) - v0) / (v1 - v0);
    if (tu < 0 || tu > 1 || tv < 0 || tv > 1) return { color: 0, cover: 0 };
    const px = new Uint8Array(4);
    this.renderer.readRenderTargetPixels(this.livery, Math.floor(w.rect[0] + tu * w.rect[2]), Math.floor(w.rect[1] + tv * w.rect[3]), 1, 1, px);
    const a = px[3]! / 255;
    if (a < 0.004) return { color: 0, cover: 0 };
    // (Premultiplied in the livery.)
    const c = (i: number) => Math.min(255, Math.round(px[i]! / a));
    return { color: (c(0) << 16) | (c(1) << 8) | c(2), cover: a };
  }

  /**
   * Repaint everything from a design's list of marks: from the last back to the first,
   * each under what's there, the eraser strokes met on the way rubbing out the brush
   * strokes under them (not the shapes).
   */
  replay(ops: readonly PaintOp[]): void {
    this.clear();
    const restore = this.saveState();
    this.renderer.setRenderTarget(this.eraseMask);
    this.renderer.setClearColor(0x000000, 0);
    this.renderer.clear(true, false, false);
    for (let i = ops.length - 1; i >= 0; i--) {
      const op = ops[i]!;
      if (op.t === 'shape') {
        this.shape(op);
        continue;
      }
      const mode = op.erase ? Mode.Mask : Mode.Under;
      const dabs = this.dabsOf(op);
      this.drawDabs(op, dabs, false, mode);
      if (op.mirror) this.drawDabs(op, mirrorDabs(dabs), false, mode);
    }
    // (The livery's smaller sizes, remade once.)
    this.draw(this.nothing, true);
    restore();
  }

  dispose(): void {
    this.livery.dispose();
    this.surfaceRT.dispose();
    this.dabGeo.dispose();
    this.shapeMesh.geometry.dispose();
    this.eraseMask.dispose();
    for (const m of [...Object.values(this.dabMats), this.shapeMat]) m.dispose();
  }
}

/**
 * Let a car's paint material show a livery over its base colour (for the paint-coloured
 * meshes). Returns its uniforms: the livery and its surface map, on (off for plain paint),
 * and the body's inverse world matrix (kept up to date by the car).
 */
export interface LiveryUniforms {
  map: { value: THREE.Texture | null };
  surface: { value: THREE.Texture | null };
  on: { value: boolean };
  bodyInverse: { value: THREE.Matrix4 };
}

export function withLivery(m: THREE.MeshStandardMaterial): LiveryUniforms {
  const own: LiveryUniforms = { map: { value: null }, surface: { value: null }, on: { value: false }, bodyInverse: { value: new THREE.Matrix4() } };
  const before = m.onBeforeCompile.bind(m);
  const src = m.onBeforeCompile.toString();
  m.onBeforeCompile = (shader, renderer) => {
    before(shader, renderer);
    Object.assign(shader.uniforms, VIEW_UNIFORMS, { liveryMap: own.map, liveryOn: own.on, bodyInverse: own.bodyInverse, liverySurface: own.surface });
    shader.vertexShader = shader.vertexShader
      .replace('#include <common>', '#include <common>\nuniform mat4 bodyInverse;\nvarying vec3 vBodyPos;\nvarying vec3 vBodyN;')
      .replace(
        '#include <project_vertex>',
        '#include <project_vertex>\nvBodyPos = (bodyInverse * modelMatrix * vec4(transformed, 1.0)).xyz;\nvBodyN = mat3(bodyInverse) * (transpose(inverse(mat3(modelMatrix))) * objectNormal);',
      );
    shader.fragmentShader = shader.fragmentShader
      .replace(
        '#include <common>',
        `#include <common>\nuniform sampler2D liveryMap;\nuniform sampler2D liverySurface;\nuniform bool liveryOn;\nvarying vec3 vBodyPos;\nvarying vec3 vBodyN;\n${VIEW_GLSL}`,
      )
      .replace(
        '#include <color_fragment>',
        /* glsl */ `#include <color_fragment>
        if (liveryOn) {
          vec3 bn = normalize(vBodyN);
          int k = viewOf(bn);
          if (k >= 0) {
            vec2 uv = viewUv(k, vBodyPos);
            // (Not on a face hidden in its view behind another, as inside the cabin.)
            float shown = 1.0 - step(0.03, texture2D(liverySurface, uv).w - dot(vBodyPos, viewN[k]));
            vec4 lv = texture2D(liveryMap, uv) * shown;
            if (lv.a > 0.001) {
              vec3 c = lv.rgb / lv.a;
              c = mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
              diffuseColor.rgb = mix(diffuseColor.rgb, c, lv.a);
            }
          }
        }`,
      );
  };
  const key = m.customProgramCacheKey.bind(m);
  m.customProgramCacheKey = () => key() + '|livery|' + src;
  m.needsUpdate = true;
  return own;
}