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/paint-shop.ts
import * as THREE from 'three';
import { Dabber, mirrorDabs, SHAPES, shapeAxes, type PaintOp, type Shape, type ShapeKind, type Stroke } from './game/car-paint.js';
import type { Game } from './game/game.js';
import type { GarageView, Pick } from './game/garage.js';
import { sfxClick } from './game/sound.js';
import { cleanTitle, newDesignId, roundPoint, STORAGE_BUDGET, type Design, type DesignInfo, type Designs } from './paint-designs.js';

/**
 * The paint shop: the player's car in the studio, painted with a brush (colour, size,
 * opacity, hardness) or the eraser, or with shapes (put on with a click, dragged about,
 * sized in width and length, turned and coloured), over a base colour. Undo and redo;
 * designs saved, loaded, deleted and put on the car. Left-drag paints; right-drag (or
 * the hand tool, or two fingers) turns the car round; the wheel or a pinch zooms.
 * Mirror paints everything on the other side as well, mirrored down the middle of the
 * car; the picker picks up the colour the paint really is where it's clicked. The Saved
 * designs tab shows each design kept (a picture of the car in it), to put on the car,
 * open, copy or delete.
 */

type Tool = 'brush' | 'eraser' | 'shape' | 'orbit' | 'pick';

const SWATCHES = [0xffffff, 0x1b1d22, 0xff4f5e, 0xffb21e, 0xffe14a, 0x2fc9a0, 0x2f7fe0, 0x7a4cff, 0xff6fc8, 0x8a5a3c, 0x9aa3b5, 0x00d0ff];

const ICONS: Record<ShapeKind, string> = {
  circle: '<circle cx="12" cy="12" r="8"/>',
  square: '<rect x="4" y="4" width="16" height="16"/>',
  triangle: '<path d="M12 4 20 20H4Z"/>',
  diamond: '<path d="M12 3 21 12 12 21 3 12Z"/>',
  star: '<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6-4.5-4.2 6.1-.7Z"/>',
  heart: '<path d="M12 20C4 14 3 9 6 6.5c2.5-2 5-1 6 1.5 1-2.5 3.5-3.5 6-1.5 3 2.5 2 7.5-6 13.5Z"/>',
  ring: '<circle cx="12" cy="12" r="6.5" fill="none" stroke="currentColor" stroke-width="3.5"/>',
  arrow: '<path d="M12 3 20 12H15V21H9V12H4Z"/>',
};

const hex = (c: number) => `#${c.toString(16).padStart(6, '0')}`;
const fromHex = (s: string) => parseInt(s.slice(1), 16) & 0xffffff;
/** The brush size slider (0 to 100) to a radius in metres: 4 mm to 40 cm. */
const brushRadius = (k: number) => 0.004 * Math.pow(100, k / 100);
const sliderOf = (r: number) => Math.round((Math.log(r / 0.004) / Math.log(100)) * 100);

function el<T extends HTMLElement>(sel: string): T {
  const e = document.querySelector<T>(sel);
  if (!e) throw new Error(`Missing element ${sel}`);
  return e;
}

interface Snapshot {
  ops: PaintOp[];
  base: number;
}

export interface ShopHooks {
  game: Game;
  designs: Designs;
  canvas: HTMLCanvasElement;
  /** The design on the car now (its id), or null. */
  appliedId: () => string | null;
  /** Put a (saved) design on the car, or plain paint. */
  apply: (design: Design | null) => void;
  /** The shop has closed. */
  closed: () => void;
}

export class PaintShop {
  private readonly root = el<HTMLElement>('#shop');
  private open = false;
  private design: Design = { id: newDesignId(), name: 'My design', base: 0xff4f5e, ops: [] };
  /** Kept since the last change (or never saved). */
  private savedOnce = false;
  private dirty = false;
  private tool: Tool = 'brush';
  /** The tool the picker picks a colour for (and goes back to after). */
  private lastTool: Exclude<Tool, 'pick'> = 'brush';
  /** New marks go on both sides, mirrored down the middle of the car. */
  private mirror = false;
  private readonly brush = { color: 0xffffff, size: 0.04, opacity: 1, hard: 0.85 };
  private readonly shapeSet: Omit<Shape, 't' | 'c' | 'n'> = { kind: 'circle', color: 0xffc93c, opacity: 1, w: 0.5, l: 0.5, rot: 0 };
  private selected = -1;
  private undoStack: Snapshot[] = [];
  private redoStack: Snapshot[] = [];
  /** The livery needs repainting from the list (after an undo, a shape moved...). */
  private needsReplay = false;
  /** The stroke being painted, and its dabs not yet drawn. */
  private live: { op: Stroke; dabber: Dabber; pending: number[] } | null = null;
  /** A brush drag going on: the line is painted wherever it's over paint (broken where it crosses glass), all one undo. */
  private brushing: { checkpointed: boolean } | null = null;
  /** The shape being dragged about: how far its centre is from the grab point, and whether it's moved yet. */
  private drag: { offset: THREE.Vector3; moved: boolean; twin: boolean } | null = null;
  /** What each pointer on the view is doing. */
  private readonly pointers = new Map<number, { x: number; y: number }>();
  private gesture: 'tool' | 'orbit' | 'pinch' | 'none' = 'none';
  private pinchDist = 0;
  /** A slider's being dragged: the undo point is taken at its first step. */
  private editing = false;
  /** Pictures of the saved designs (by id and stored size, so a changed design gets a new one). */
  private readonly thumbs = new Map<string, string>();
  /** The thumbnails being made (a newer list stops an older one). */
  private thumbJob = 0;

  constructor(private readonly hooks: ShopHooks) {
    this.buildUi();
    this.bindView();
    const loop = () => {
      requestAnimationFrame(loop);
      if (this.open) this.frame();
    };
    requestAnimationFrame(loop);
  }

  get isOpen(): boolean {
    return this.open;
  }

  /** Open the shop on a design (a new one from the car's colour if none). */
  async show(design: Design | null, base: number): Promise<void> {
    this.open = true;
    this.root.hidden = false;
    const g = this.hooks.game.openGarage();
    g.view('left');
    if (design) this.load(design, true);
    else this.load({ id: newDesignId(), name: await this.freshName(), base, ops: [] }, false);
    this.setTab('paint');
    void this.renderDesigns();
    el<HTMLButtonElement>('#shopDone').focus();
  }

  private async freshName(): Promise<string> {
    const names = new Set((await this.hooks.designs.list()).map((d) => d.name));
    for (let i = 1; ; i++) if (!names.has(`Design ${i}`)) return `Design ${i}`;
  }

  private load(d: Design, saved: boolean): void {
    this.design = { ...d, ops: [...d.ops] };
    this.savedOnce = saved;
    this.dirty = false;
    this.undoStack = [];
    this.redoStack = [];
    this.select(-1);
    el<HTMLInputElement>('#shopName').value = d.name;
    el<HTMLInputElement>('#shopBase').value = hex(d.base);
    this.hooks.game.setPaint(d.base);
    this.needsReplay = true;
    this.renderState();
  }

  private async close(): Promise<void> {
    if (!(await this.settle())) return;
    this.open = false;
    this.root.hidden = true;
    this.endStroke();
    this.hooks.game.closeGarage();
    this.hooks.closed();
  }

  // ---- Changes, undo and redo --------------------------------------------------------

  private snapshot(): Snapshot {
    return { ops: [...this.design.ops], base: this.design.base };
  }

  /** Before a change: the undo point. */
  private checkpoint(): void {
    this.undoStack.push(this.snapshot());
    if (this.undoStack.length > 200) this.undoStack.shift();
    this.redoStack = [];
    this.dirty = true;
    this.renderState();
  }

  private restore(s: Snapshot): void {
    this.design.ops = [...s.ops];
    this.design.base = s.base;
    el<HTMLInputElement>('#shopBase').value = hex(s.base);
    this.hooks.game.setPaint(s.base);
    this.select(this.selected < this.design.ops.length && this.design.ops[this.selected]?.t === 'shape' ? this.selected : -1);
    this.needsReplay = true;
    this.dirty = true;
    this.renderState();
  }

  private undo(): void {
    const s = this.undoStack.pop();
    if (!s || this.live) return;
    this.redoStack.push(this.snapshot());
    this.restore(s);
  }

  private redo(): void {
    const s = this.redoStack.pop();
    if (!s || this.live) return;
    this.undoStack.push(this.snapshot());
    this.restore(s);
  }

  // ---- Each frame ------------------------------------------------------------------------

  private frame(): void {
    this.frameCar();
    const paint = this.hooks.game.paint;
    if (this.needsReplay) {
      this.needsReplay = false;
      paint.replay(this.design.ops);
    } else if (this.live && this.live.pending.length) {
      this.drawDabs(this.live.op, this.live.pending);
      this.live.pending = [];
    }
    this.markSelected();
  }

  /** The open part of the view, between the panels, for the car to be framed in. */
  private frameCar(): void {
    const view = this.hooks.canvas.getBoundingClientRect();
    const top = el<HTMLElement>('.shop-top').getBoundingClientRect();
    const tools = el<HTMLElement>('.shop-tools').getBoundingClientRect();
    const panel = el<HTMLElement>('.shop-panel').getBoundingClientRect();
    const pad = 4;
    let x0 = view.left;
    let x1 = view.right;
    let y1 = view.bottom;
    const y0 = top.bottom + pad;
    // Side by side (wide) or stacked under the car (narrow).
    if (panel.top > tools.top - 1 && panel.width > view.width * 0.6) y1 = Math.min(tools.top, panel.top) - pad;
    else {
      x0 = tools.width ? tools.right + pad : x0;
      x1 = panel.width ? panel.left - pad : x1;
    }
    this.hooks.game.openGarage().frame({ x: x0 - view.left, y: y0 - view.top, w: x1 - x0, h: y1 - y0 });
  }

  private markSelected(): void {
    const g = this.hooks.game.openGarage();
    const s = this.design.ops[this.selected];
    if (!s || s.t !== 'shape') return g.mark(null);
    const ax = shapeAxes(s);
    g.mark({ c: new THREE.Vector3(...s.c), u: ax.u, v: ax.v, n: ax.n, w: s.w, l: s.l }, !!s.mirror);
  }

  // ---- The view: painting, placing shapes, turning the car round ---------------------------

  private pick(e: { clientX: number; clientY: number }): Pick | null {
    const r = this.hooks.canvas.getBoundingClientRect();
    return this.hooks.game.openGarage().pick(this.hooks.game.car, ((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
  }

  private bindView(): void {
    const c = this.hooks.canvas;
    c.addEventListener('pointerdown', (e) => {
      if (!this.open) return;
      e.preventDefault();
      c.setPointerCapture(e.pointerId);
      this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
      if (this.pointers.size >= 2) {
        // A second finger: turning and zooming, not painting (the line just begun is dropped).
        this.cancelStroke();
        this.gesture = 'pinch';
        this.pinchDist = this.spread();
        return;
      }
      if (e.button === 1 || e.button === 2 || this.tool === 'orbit' || (e.pointerType === 'mouse' && e.altKey)) this.gesture = 'orbit';
      else {
        this.gesture = 'tool';
        this.toolDown(e);
      }
    });
    c.addEventListener('pointermove', (e) => {
      if (!this.open) return;
      const g = this.hooks.game.openGarage();
      const was = this.pointers.get(e.pointerId);
      if (!was) {
        // Hovering: the brush shown where it would paint.
        if (e.pointerType === 'mouse') this.hover(e);
        return;
      }
      if (this.gesture === 'orbit') g.orbit(e.clientX - was.x, e.clientY - was.y);
      else if (this.gesture === 'pinch') {
        const before = this.centre();
        this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
        const after = this.centre();
        g.orbit(after.x - before.x, after.y - before.y);
        const d = this.spread();
        if (this.pinchDist > 0 && d > 0) g.zoom(this.pinchDist / d);
        this.pinchDist = d;
        return;
      } else if (this.gesture === 'tool') {
        for (const ev of e.getCoalescedEvents?.() ?? [e]) this.toolMove(ev);
        if (e.pointerType === 'mouse') this.hover(e);
      }
      this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
    });
    const up = (e: PointerEvent) => {
      if (!this.pointers.delete(e.pointerId)) return;
      if (this.gesture === 'tool') this.toolUp();
      if (this.pointers.size === 0) this.gesture = 'none';
    };
    c.addEventListener('pointerup', up);
    c.addEventListener('pointercancel', up);
    c.addEventListener('pointerleave', () => {
      if (this.open && this.pointers.size === 0) this.hooks.game.openGarage().brush(null);
    });
    c.addEventListener('contextmenu', (e) => {
      if (this.open) e.preventDefault();
    });
    c.addEventListener(
      'wheel',
      (e) => {
        if (!this.open) return;
        e.preventDefault();
        this.hooks.game.openGarage().zoom(Math.exp(e.deltaY * 0.0012));
      },
      { passive: false },
    );
    window.addEventListener('keydown', (e) => {
      if (!this.open || e.target instanceof HTMLInputElement || e.target instanceof HTMLSelectElement) return;
      const mod = e.ctrlKey || e.metaKey;
      if (mod && e.code === 'KeyZ') e.shiftKey ? this.redo() : this.undo();
      else if (mod && e.code === 'KeyY') this.redo();
      else if (mod && e.code === 'KeyS') void this.save();
      else if ((e.code === 'Delete' || e.code === 'Backspace') && this.selected >= 0) this.deleteShape();
      else if (e.code === 'Escape') this.select(-1);
      else if (e.code === 'KeyB') this.setTool('brush');
      else if (e.code === 'KeyE') this.setTool('eraser');
      else if (e.code === 'KeyS') this.setTool('shape');
      else if (e.code === 'KeyI') this.setTool('pick');
      else if (e.code === 'KeyM') this.toggleMirror();
      else if (e.code === 'BracketLeft' || e.code === 'BracketRight') {
        const k = sliderOf(this.brush.size) + (e.code === 'BracketLeft' ? -5 : 5);
        this.brush.size = brushRadius(Math.max(0, Math.min(100, k)));
        this.renderTool();
      } else return;
      e.preventDefault();
      e.stopPropagation();
    });
  }

  private centre(): { x: number; y: number } {
    const p = [...this.pointers.values()];
    return { x: p.reduce((s, q) => s + q.x, 0) / p.length, y: p.reduce((s, q) => s + q.y, 0) / p.length };
  }

  private spread(): number {
    const [a, b] = [...this.pointers.values()];
    return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
  }

  private hover(e: PointerEvent): void {
    const g = this.hooks.game.openGarage();
    if (this.tool !== 'brush' && this.tool !== 'eraser') return g.brush(null);
    const p = this.pick(e);
    if (p?.paint) g.brush(p.point, p.normal, this.brush.size, this.mirror);
    else g.brush(null);
  }

  private toolDown(e: PointerEvent): void {
    const p = this.pick(e);
    if (this.tool === 'pick') {
      if (!p) return;
      // The colour the part really is there (not as it looks in the light), for the tool before.
      const c = p.paint ? this.hooks.game.paint.colorAt(p.point, p.normal, this.design.base) : (p.color ?? this.design.base);
      this.setTool(this.lastTool);
      this.setColor(c, true);
      this.status(`Picked ${hex(c)}`);
      return;
    }
    if (this.tool === 'brush' || this.tool === 'eraser') {
      this.brushing = { checkpointed: false };
      if (p?.paint) this.startLine(p);
      else if (p) this.status('Only the paintwork takes paint: not the glass, the wheels or the trim.');
    } else if (this.tool === 'shape') {
      if (!p) return this.select(-1);
      // On a shape: pick it up (to drag); elsewhere on the paint, a new one.
      const hit = this.shapeAt(p);
      if (hit) {
        this.select(hit.index);
        const s = this.design.ops[hit.index] as Shape;
        // (Grabbed by its mirror image: dragged from there, the shape itself following on the other side.)
        const c = new THREE.Vector3(hit.twin ? -s.c[0] : s.c[0], s.c[1], s.c[2]);
        this.drag = { offset: c.sub(p.point), moved: false, twin: hit.twin };
        return;
      }
      if (!p.paint) return this.status('Shapes go on the paintwork: not the glass, the wheels or the trim.');
      this.checkpoint();
      const s: Shape = { t: 'shape', ...this.shapeSet, c: vec3(p.point), n: vec3(p.normal), ...(this.mirror ? { mirror: true } : {}) };
      this.design.ops.push(s);
      this.select(this.design.ops.length - 1);
      this.drag = { offset: new THREE.Vector3(), moved: true, twin: false };
      this.needsReplay = true;
    }
  }

  private toolMove(e: { clientX: number; clientY: number }): void {
    if (this.brushing) {
      const p = this.pick(e);
      if (!p?.paint) this.endStroke();
      else if (this.live) this.addPoint(p);
      else this.startLine(p);
    } else if (this.drag && this.selected >= 0) {
      const p = this.pick(e);
      if (!p?.paint) return;
      if (!this.drag.moved) {
        this.checkpoint();
        this.drag.moved = true;
      }
      const s = this.design.ops[this.selected] as Shape;
      // The grab point's offset, laid flat on the face it's now over.
      const off = this.drag.offset.clone().addScaledVector(p.normal, -this.drag.offset.dot(p.normal));
      const c = p.point.clone().add(off);
      const n = p.normal.clone();
      if (this.drag.twin) {
        c.x = -c.x;
        n.x = -n.x;
      }
      this.design.ops[this.selected] = { ...s, c: vec3(c), n: vec3(n) };
      this.needsReplay = true;
    }
  }

  private toolUp(): void {
    this.endStroke();
    this.brushing = null;
    this.drag = null;
  }

  /** A line of the brush begins (the drag's first over paint, or back on paint after crossing glass). */
  private startLine(p: Pick): void {
    if (!this.brushing!.checkpointed) {
      this.checkpoint();
      this.brushing!.checkpointed = true;
    }
    const op: Stroke = { t: 'stroke', color: this.brush.color, opacity: this.brush.opacity, size: this.brush.size, hard: this.brush.hard, erase: this.tool === 'eraser', pts: [], ...(this.mirror ? { mirror: true } : {}) };
    this.design.ops.push(op);
    this.live = { op, dabber: new Dabber(op.size), pending: [] };
    this.addPoint(p);
  }

  /** A point on the stroke: kept if it's moved on far enough from the last (stored strokes stay small). */
  private addPoint(p: Pick): void {
    const live = this.live!;
    const pt = roundPoint([p.point.x, p.point.y, p.point.z, p.normal.x, p.normal.y, p.normal.z]);
    const pts = live.op.pts;
    const n = pts.length;
    if (n && Math.hypot(pts[n - 6]! - pt[0]!, pts[n - 5]! - pt[1]!, pts[n - 4]! - pt[2]!) < Math.max(0.002, live.op.size * 0.25)) return;
    pts.push(...pt);
    live.dabber.add(pt, live.pending);
  }

  private endStroke(): void {
    const live = this.live;
    if (!live) return;
    if (live.pending.length) this.drawDabs(live.op, live.pending);
    this.live = null;
    this.renderState();
  }

  /**
   * New dabs of a stroke into the livery (and their mirror image, if it's mirrored). The
   * eraser rubs out brush paint but not shapes, so it can't just be drawn over the top:
   * the design's repainted with it instead.
   */
  private drawDabs(op: Stroke, dabs: number[]): void {
    if (op.erase) {
      this.needsReplay = true;
      return;
    }
    const paint = this.hooks.game.paint;
    paint.dabs(op, dabs, !op.mirror);
    if (op.mirror) paint.dabs(op, mirrorDabs(dabs));
  }

  /** Drop the stroke being painted (a second finger came down). */
  private cancelStroke(): void {
    const b = this.brushing;
    this.live = null;
    this.brushing = null;
    this.drag = null;
    if (!b?.checkpointed) return;
    const s = this.undoStack.pop();
    if (s) this.restore(s);
  }

  /**
   * The topmost shape under a pick (twin: by its mirror image), or null. Only where it
   * shows: not where it's been rubbed out or painted over, nor in its box's corners
   * outside it (there a click puts a new shape on top instead).
   */
  private shapeAt(p: Pick): { index: number; twin: boolean } | null {
    if (!p.paint) return null;
    const there = this.hooks.game.paint.paintAt(p.point, p.normal);
    const shows = (s: Shape) => {
      const d = Math.abs(((there.color >> 16) & 255) - ((s.color >> 16) & 255)) + Math.abs(((there.color >> 8) & 255) - ((s.color >> 8) & 255)) + Math.abs((there.color & 255) - (s.color & 255));
      return there.cover > Math.max(0.05, s.opacity * 0.5) && d <= 30;
    };
    for (let i = this.design.ops.length - 1; i >= 0; i--) {
      const s = this.design.ops[i]!;
      if (s.t !== 'shape') continue;
      const ax = shapeAxes(s);
      for (const twin of s.mirror ? [false, true] : [false]) {
        // (The mirror image tested as the pick mirrored back onto the shape.)
        const point = twin ? new THREE.Vector3(-p.point.x, p.point.y, p.point.z) : p.point;
        const normal = twin ? new THREE.Vector3(-p.normal.x, p.normal.y, p.normal.z) : p.normal;
        const d = point.clone().sub(new THREE.Vector3(...s.c));
        if (Math.abs(d.dot(ax.n)) > 0.35 || normal.dot(ax.n) < 0.1) continue;
        if (Math.abs(d.dot(ax.u)) <= s.w / 2 && Math.abs(d.dot(ax.v)) <= s.l / 2 && shows(s)) return { index: i, twin };
      }
    }
    return null;
  }

  // ---- Shapes ----------------------------------------------------------------------------

  private select(i: number): void {
    this.selected = i;
    const s = this.design.ops[i];
    if (s?.t === 'shape') {
      Object.assign(this.shapeSet, { kind: s.kind, color: s.color, opacity: s.opacity, w: s.w, l: s.l, rot: s.rot });
    }
    this.renderTool();
  }

  /** Change the selected shape (or, with none selected, the next one's settings). */
  private editShape(change: Partial<Omit<Shape, 't' | 'c' | 'n'>>, commit: boolean): void {
    Object.assign(this.shapeSet, change);
    const s = this.design.ops[this.selected];
    if (s?.t === 'shape') {
      if (!this.editing) this.checkpoint();
      this.editing = !commit;
      this.design.ops[this.selected] = { ...s, ...change };
      this.needsReplay = true;
    }
    this.renderTool();
  }

  /** Mirror on or off for what's painted next; a shape that's picked up is mirrored (or not) with it. */
  private toggleMirror(): void {
    this.mirror = !this.mirror;
    const s = this.design.ops[this.selected];
    if (s?.t === 'shape' && !!s.mirror !== this.mirror) {
      this.checkpoint();
      const { mirror: _was, ...rest } = s;
      void _was;
      this.design.ops[this.selected] = this.mirror ? { ...rest, mirror: true } : rest;
      this.needsReplay = true;
    }
    this.status(this.mirror ? 'Mirror on: painting both sides.' : 'Mirror off.');
    this.renderTool();
  }

  private deleteShape(): void {
    if (this.selected < 0) return;
    this.checkpoint();
    this.design.ops.splice(this.selected, 1);
    this.select(-1);
    this.needsReplay = true;
  }

  // ---- Saving --------------------------------------------------------------------------

  /**
   * Before leaving the design being painted (for another, a new one, or out of the shop):
   * if it's changed, save it first, or not, or stay. Returns whether to go on.
   */
  private async settle(): Promise<boolean> {
    if (!this.dirty) return true;
    const name = cleanTitle(el<HTMLInputElement>('#shopName').value) || 'this design';
    if (!this.hooks.designs.canSave) return this.ask(`Leave “${name}” without its changes? (This host can’t keep designs.)`, 'Leave it', 'Stay');
    const k = await this.choose(`Save your changes to “${name}” first?`, [
      ['Save', 'go'],
      ['Don’t save', 'ghost'],
      ['Cancel', 'ghost'],
    ]);
    if (k === 0) return this.save();
    return k === 1;
  }

  private async save(): Promise<boolean> {
    if (!this.hooks.designs.canSave) {
      this.status('This host has no storage: designs can’t be kept.');
      return false;
    }
    this.design.name = cleanTitle(el<HTMLInputElement>('#shopName').value) || 'My design';
    try {
      const bytes = await this.hooks.designs.save(this.design);
      this.savedOnce = true;
      this.dirty = false;
      this.status(`Saved “${this.design.name}” (${kb(bytes)})`);
      void this.renderDesigns();
      this.renderState();
      return true;
    } catch (err) {
      this.status(err instanceof Error ? err.message : 'Couldn’t save.');
      return false;
    }
  }

  private async useOnCar(): Promise<void> {
    // (Without storage it can't be kept, but it can still go on the car until the game's closed.)
    this.design.name = cleanTitle(el<HTMLInputElement>('#shopName').value) || 'My design';
    if (this.hooks.designs.canSave && (this.dirty || !this.savedOnce)) {
      if (!(await this.save())) return;
    }
    this.hooks.apply(this.design);
    if (!this.hooks.designs.canSave) {
      this.dirty = false;
      this.renderState();
    }
    this.status(`“${this.design.name}” is on your car.`);
    void this.renderDesigns();
  }

  // ---- The panels ------------------------------------------------------------------------

  private status(text: string): void {
    const s = el<HTMLElement>('#shopStatus');
    s.textContent = text;
    s.hidden = !text;
    clearTimeout(Number(s.dataset.t));
    if (text) s.dataset.t = String(setTimeout(() => (s.hidden = true), 4000));
  }

  private async ask(text: string, yes: string, no: string): Promise<boolean> {
    return (await this.choose(text, [
      [yes, 'go'],
      [no, 'ghost'],
    ])) === 0;
  }

  /** A question with a button for each answer; returns which was pressed (the last, the way out, is focused). */
  private choose(text: string, answers: [string, string][]): Promise<number> {
    const box = el<HTMLElement>('#shopAsk');
    el<HTMLElement>('#shopAskText').textContent = text;
    const row = el<HTMLElement>('#shopAskButtons');
    row.textContent = '';
    return new Promise((resolve) => {
      const buttons = answers.map(([label, cls], i) =>
        button(label, cls, () => {
          box.hidden = true;
          resolve(i);
        }),
      );
      row.append(...buttons);
      box.hidden = false;
      buttons[buttons.length - 1]!.focus();
    });
  }

  private setTool(t: Tool): void {
    this.setTab('paint');
    this.tool = t;
    if (t !== 'pick') this.lastTool = t;
    if (t !== 'shape' && t !== 'pick') this.select(-1);
    this.hooks.game.openGarage().brush(null);
    this.renderTool();
  }

  private renderState(): void {
    el<HTMLButtonElement>('#shopUndo').disabled = this.undoStack.length === 0;
    el<HTMLButtonElement>('#shopRedo').disabled = this.redoStack.length === 0;
    el<HTMLElement>('#shopDirty').hidden = !this.dirty;
  }

  /** The tool panel: the brush's settings, or the shapes' (with the picker, those of the tool it's picking for). */
  private renderTool(): void {
    for (const b of this.root.querySelectorAll<HTMLButtonElement>('[data-tool]')) b.setAttribute('aria-pressed', String(b.dataset.tool === this.tool));
    el<HTMLButtonElement>('#shopMirror').setAttribute('aria-pressed', String(this.mirror));
    const tool = this.tool === 'pick' ? this.lastTool : this.tool;
    const shape = tool === 'shape';
    el<HTMLElement>('#shopBrushSet').hidden = shape || tool === 'orbit';
    el<HTMLElement>('#shopShapeSet').hidden = !shape;
    el<HTMLElement>('#shopColorRow').hidden = tool === 'eraser' || tool === 'orbit';
    const color = shape ? this.shapeSet.color : this.brush.color;
    el<HTMLInputElement>('#shopColor').value = hex(color);
    for (const b of this.root.querySelectorAll<HTMLButtonElement>('.shop-swatches button')) b.setAttribute('aria-pressed', String(Number(b.dataset.c) === color));
    const set = (id: string, v: number, text: string) => {
      el<HTMLInputElement>(`#${id}`).value = String(v);
      el<HTMLOutputElement>(`#${id}Out`).textContent = text;
    };
    set('shopSize', sliderOf(this.brush.size), `${(this.brush.size * 200).toFixed(this.brush.size < 0.05 ? 1 : 0)} cm`);
    set('shopOpacity', Math.round(this.brush.opacity * 100), `${Math.round(this.brush.opacity * 100)}%`);
    set('shopHard', Math.round(this.brush.hard * 100), `${Math.round(this.brush.hard * 100)}%`);
    const sh = this.shapeSet;
    set('shopW', Math.round(sh.w * 100), `${Math.round(sh.w * 100)} cm`);
    set('shopL', Math.round(sh.l * 100), `${Math.round(sh.l * 100)} cm`);
    set('shopRot', Math.round((sh.rot * 180) / Math.PI), `${Math.round((sh.rot * 180) / Math.PI)}°`);
    set('shopShapeOpacity', Math.round(sh.opacity * 100), `${Math.round(sh.opacity * 100)}%`);
    for (const b of this.root.querySelectorAll<HTMLButtonElement>('[data-shape]')) b.setAttribute('aria-pressed', String(b.dataset.shape === sh.kind));
    const sel = this.selected >= 0;
    el<HTMLButtonElement>('#shopDeleteShape').disabled = !sel;
    el<HTMLElement>('#shopShapeHint').textContent = sel ? 'Drag it to move it; these change it.' : 'Click the car to put one on; click one to pick it up.';
  }

  /** Show the paint tab (the tools' settings) or the saved designs. */
  private setTab(tab: 'paint' | 'designs'): void {
    const designs = tab === 'designs';
    el<HTMLElement>('#shopPaintTab').hidden = designs;
    el<HTMLElement>('#shopDesignsTab').hidden = !designs;
    el<HTMLButtonElement>('#tabPaint').setAttribute('aria-selected', String(!designs));
    el<HTMLButtonElement>('#tabDesigns').setAttribute('aria-selected', String(designs));
    if (designs) void this.renderDesigns();
  }

  private get designsShown(): boolean {
    return !el<HTMLElement>('#shopDesignsTab').hidden;
  }

  /** A saved design, as kept (the one being painted, if it hasn't changed since). */
  private async stored(id: string): Promise<Design | null> {
    return id === this.design.id && !this.dirty && this.savedOnce ? this.design : this.hooks.designs.load(id);
  }

  /** The saved designs: a card for each, with a picture of the car in it and what can be done with it. */
  private async renderDesigns(): Promise<void> {
    const list = el<HTMLElement>('#shopList');
    const d = this.hooks.designs;
    const [designs, used] = await Promise.all([d.list(), d.used()]);
    const applied = this.hooks.appliedId();
    el<HTMLElement>('#shopCount').textContent = designs.length ? String(designs.length) : '';
    list.textContent = '';
    if (!d.canSave) {
      const p = document.createElement('p');
      p.className = 'hint';
      p.textContent = 'This host has no storage, so designs can’t be kept. You can still paint, and put it on your car until you leave.';
      list.append(p);
    }
    for (const info of designs) {
      const li = document.createElement('li');
      li.className = 'shop-card';
      li.classList.toggle('current', info.id === this.design.id);
      li.classList.toggle('on-car', info.id === applied);
      const thumb = document.createElement('button');
      thumb.type = 'button';
      thumb.className = 'shop-thumb';
      thumb.setAttribute('aria-label', `Open “${info.name}”`);
      thumb.style.setProperty('--c', hex(info.base));
      const img = document.createElement('img');
      img.alt = '';
      img.dataset.key = thumbKey(info);
      const pic = this.thumbs.get(thumbKey(info));
      if (pic) img.src = pic;
      else img.hidden = true;
      thumb.append(img);
      thumb.addEventListener('click', () => void this.openDesign(info));
      const body = document.createElement('div');
      body.className = 'shop-card-info';
      const name = document.createElement('b');
      name.className = 'shop-item-name';
      name.textContent = info.name;
      const meta = document.createElement('small');
      meta.textContent = [kb(info.bytes), info.id === applied ? 'on your car' : '', info.id === this.design.id ? 'open' : ''].filter(Boolean).join(' · ');
      const actions = document.createElement('div');
      actions.className = 'shop-card-buttons';
      const use = button(info.id === applied ? 'On car' : 'Use on car', 'go small', () => void this.useSaved(info));
      use.disabled = info.id === applied;
      const open = button('Open', 'ghost', () => void this.openDesign(info));
      open.disabled = info.id === this.design.id;
      const copy = button('Copy', 'ghost', () => void this.copyDesign(info));
      const del = button('Delete', 'ghost danger', async () => {
        if (!(await this.ask(`Delete “${info.name}”?`, 'Delete', 'Keep'))) return;
        await d.remove(info.id);
        if (info.id === applied) this.hooks.apply(null);
        if (info.id === this.design.id) this.savedOnce = false;
        this.status(`Deleted “${info.name}”.`);
        void this.renderDesigns();
      });
      actions.append(use, open, copy, del);
      body.append(name, meta, actions);
      li.append(thumb, body);
      list.append(li);
    }
    if (d.canSave && designs.length === 0) {
      const p = document.createElement('p');
      p.className = 'hint';
      p.textContent = 'No saved designs yet: paint one and press Save, and it’s kept here.';
      list.append(p);
    }
    el<HTMLButtonElement>('#shopPlain').disabled = applied === null;
    const meter = el<HTMLElement>('#shopMeter');
    const frac = Math.min(1, used / STORAGE_BUDGET);
    meter.style.setProperty('--used', String(frac));
    meter.classList.toggle('full', frac > 0.9);
    el<HTMLElement>('#shopMeterText').textContent = d.canSave ? `Storage: ${kb(used)} of ${kb(STORAGE_BUDGET)} used` : 'No storage';
    if (this.designsShown) void this.makeThumbs(designs);
  }

  /**
   * Pictures of the saved designs that haven't one yet: each painted on the car in turn and
   * photographed in the studio, the design being painted put straight back after each.
   * One a frame, and not while a line or a shape is being dragged.
   */
  private async makeThumbs(designs: DesignInfo[]): Promise<void> {
    const job = ++this.thumbJob;
    const game = this.hooks.game;
    const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));
    for (const info of designs) {
      const key = thumbKey(info);
      if (this.thumbs.has(key)) continue;
      while (this.open && (this.live || this.drag)) await nextFrame();
      if (job !== this.thumbJob || !this.open || !this.designsShown) return;
      const des = await this.stored(info.id);
      if (!des || job !== this.thumbJob || !this.open) continue;
      game.paint.replay(des.ops);
      game.setPaint(des.base);
      this.thumbs.set(key, game.openGarage().snapshot(game.renderer, 192, 112));
      game.paint.replay(this.design.ops);
      game.setPaint(this.design.base);
      for (const img of el<HTMLElement>('#shopList').querySelectorAll<HTMLImageElement>(`img[data-key="${key}"]`)) {
        img.src = this.thumbs.get(key)!;
        img.hidden = false;
      }
      await nextFrame();
    }
  }

  /** Paint a saved design (the one being painted settled first). */
  private async openDesign(info: DesignInfo): Promise<void> {
    if (info.id === this.design.id || !(await this.settle())) return;
    const des = await this.hooks.designs.load(info.id);
    if (!des) return this.status('That design couldn’t be read.');
    this.load(des, true);
    this.status(`Painting “${des.name}”.`);
    void this.renderDesigns();
  }

  /** Put a saved design on the car (if it's the one being painted and it's changed: save first, or use it as kept). */
  private async useSaved(info: DesignInfo): Promise<void> {
    if (info.id === this.design.id && this.dirty) {
      const k = await this.choose(`Save your changes to “${info.name}” before it goes on the car?`, [
        ['Save', 'go'],
        ['Use it as saved', 'ghost'],
        ['Cancel', 'ghost'],
      ]);
      if (k === 2 || (k === 0 && !(await this.save()))) return;
    }
    const des = await this.stored(info.id);
    if (!des) return this.status('That design couldn’t be read.');
    this.hooks.apply(des);
    this.status(`“${des.name}” is on your car.`);
    void this.renderDesigns();
  }

  /** Keep a copy of a saved design under a new name. */
  private async copyDesign(info: DesignInfo): Promise<void> {
    const des = await this.stored(info.id);
    if (!des) return this.status('That design couldn’t be read.');
    const names = new Set((await this.hooks.designs.list()).map((x) => x.name));
    let name = cleanTitle(`${des.name} copy`);
    for (let i = 2; names.has(name); i++) name = cleanTitle(`${des.name} copy ${i}`);
    try {
      await this.hooks.designs.save({ ...des, id: newDesignId(), name });
      this.status(`Copied as “${name}”.`);
    } catch (err) {
      this.status(err instanceof Error ? err.message : 'Couldn’t copy it.');
    }
    void this.renderDesigns();
  }

  private buildUi(): void {
    const r = this.root;
    el<HTMLButtonElement>('#shopDone').addEventListener('click', () => {
      sfxClick();
      void this.close();
    });
    el<HTMLButtonElement>('#shopUndo').addEventListener('click', () => this.undo());
    el<HTMLButtonElement>('#shopRedo').addEventListener('click', () => this.redo());
    el<HTMLButtonElement>('#shopSave').addEventListener('click', () => void this.save());
    el<HTMLButtonElement>('#shopUse').addEventListener('click', () => void this.useOnCar());
    el<HTMLButtonElement>('#tabPaint').addEventListener('click', () => {
      sfxClick();
      this.setTab('paint');
    });
    el<HTMLButtonElement>('#tabDesigns').addEventListener('click', () => {
      sfxClick();
      this.setTab('designs');
    });
    el<HTMLButtonElement>('#shopNew').addEventListener('click', async () => {
      if (!(await this.settle())) return;
      this.load({ id: newDesignId(), name: await this.freshName(), base: this.design.base, ops: [] }, false);
      this.setTab('paint');
      this.status('A new design: paint away, then Save to keep it.');
    });
    el<HTMLButtonElement>('#shopPlain').addEventListener('click', () => {
      this.hooks.apply(null);
      this.status('Your car has plain paint.');
      void this.renderDesigns();
    });
    el<HTMLInputElement>('#shopName').addEventListener('input', () => {
      this.dirty = true;
      this.renderState();
    });
    el<HTMLInputElement>('#shopName').addEventListener('keydown', (e) => e.stopPropagation());
    el<HTMLButtonElement>('#shopMirror').addEventListener('click', () => {
      sfxClick();
      this.toggleMirror();
    });
    for (const b of r.querySelectorAll<HTMLButtonElement>('[data-tool]'))
      b.addEventListener('click', () => {
        sfxClick();
        this.setTool(b.dataset.tool as Tool);
      });
    for (const b of r.querySelectorAll<HTMLButtonElement>('[data-view]'))
      b.addEventListener('click', () => {
        // (Let go of the shape: it's easy to change one that's out of sight.)
        this.select(-1);
        this.hooks.game.openGarage().view(b.dataset.view as GarageView);
      });
    // Colours: swatches and a picker, for the brush or the shape.
    const sw = el<HTMLElement>('.shop-swatches');
    for (const c of SWATCHES) {
      const b = document.createElement('button');
      b.type = 'button';
      b.dataset.c = String(c);
      b.style.setProperty('--c', hex(c));
      b.setAttribute('aria-label', hex(c));
      b.addEventListener('click', () => this.setColor(c, true));
      sw.append(b);
    }
    const picker = el<HTMLInputElement>('#shopColor');
    picker.addEventListener('input', () => this.setColor(fromHex(picker.value), false));
    picker.addEventListener('change', () => this.setColor(fromHex(picker.value), true));
    const base = el<HTMLInputElement>('#shopBase');
    let baseEditing = false;
    base.addEventListener('input', () => {
      if (!baseEditing) this.checkpoint();
      baseEditing = true;
      this.design.base = fromHex(base.value);
      this.hooks.game.setPaint(this.design.base);
    });
    base.addEventListener('change', () => (baseEditing = false));
    el<HTMLButtonElement>('#shopClear').addEventListener('click', async () => {
      if (!this.design.ops.length || !(await this.ask('Clear everything painted on this design?', 'Clear', 'Cancel'))) return;
      this.checkpoint();
      this.design.ops = [];
      this.select(-1);
      this.needsReplay = true;
    });
    // Brush sliders.
    const slider = (id: string, apply: (v: number, commit: boolean) => void) => {
      const input = el<HTMLInputElement>(`#${id}`);
      input.addEventListener('input', () => apply(Number(input.value), false));
      input.addEventListener('change', () => apply(Number(input.value), true));
      input.addEventListener('keydown', (e) => e.stopPropagation());
    };
    slider('shopSize', (v) => {
      this.brush.size = brushRadius(v);
      this.renderTool();
    });
    slider('shopOpacity', (v) => {
      this.brush.opacity = Math.max(0.02, v / 100);
      this.renderTool();
    });
    slider('shopHard', (v) => {
      this.brush.hard = v / 100;
      this.renderTool();
    });
    // Shapes.
    const kinds = el<HTMLElement>('#shopShapes');
    for (const k of SHAPES) {
      const b = document.createElement('button');
      b.type = 'button';
      b.dataset.shape = k;
      b.title = k[0]!.toUpperCase() + k.slice(1);
      b.setAttribute('aria-label', b.title);
      b.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${ICONS[k]}</svg>`;
      b.addEventListener('click', () => this.editShape({ kind: k }, true));
      kinds.append(b);
    }
    slider('shopW', (v, commit) => this.editShape({ w: v / 100 }, commit));
    slider('shopL', (v, commit) => this.editShape({ l: v / 100 }, commit));
    slider('shopRot', (v, commit) => this.editShape({ rot: (v * Math.PI) / 180 }, commit));
    slider('shopShapeOpacity', (v, commit) => this.editShape({ opacity: Math.max(0.02, v / 100) }, commit));
    el<HTMLButtonElement>('#shopDeleteShape').addEventListener('click', () => this.deleteShape());
    this.renderTool();
    this.renderState();
  }

  private setColor(c: number, commit: boolean): void {
    if ((this.tool === 'pick' ? this.lastTool : this.tool) === 'shape') this.editShape({ color: c }, commit);
    else {
      this.brush.color = c;
      this.renderTool();
    }
  }
}

function vec3(v: THREE.Vector3): [number, number, number] {
  return [Math.round(v.x * 1000) / 1000, Math.round(v.y * 1000) / 1000, Math.round(v.z * 1000) / 1000];
}

/** A saved design's picture's key: its id and size, so a changed design gets a new picture. */
function thumbKey(info: DesignInfo): string {
  return `${info.id}:${info.bytes}`;
}

function kb(bytes: number): string {
  return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(bytes < 10240 ? 1 : 0)} KB`;
}

function button(text: string, cls: string, onClick: () => void): HTMLButtonElement {
  const b = document.createElement('button');
  b.type = 'button';
  b.className = cls;
  b.textContent = text;
  b.addEventListener('click', () => {
    sfxClick();
    onClick();
  });
  return b;
}