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/main.ts
import { CONFIG_DOMAIN, STORAGE_DOMAIN, storage } from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';
import { startSettings } from './napplet-settings.js';
import { Game, PAINTS, type Quality } from './game/game.js';

const QUALITIES: Quality[] = ['auto', 'low', 'medium', 'high'];
import { Input } from './game/input.js';
import { MAPS, World, type MapId } from './game/world.js';
import { setSoundEnabled, setVolume, sfxClick, unlockAudio, type VolumeKind } from './game/sound.js';
import { fmt, Hud } from './hud.js';
import { defaultRoute, generateRoute, raceTime, snapToRoad, type RaceRoute } from './game/race.js';
import { RouteEditor } from './route-editor.js';
import { Online, type BoardId } from './online.js';
import { Designs, type Design } from './paint-designs.js';
import { PaintShop } from './paint-shop.js';
import './styles.css';

// Drift City keeps its own golden-hour palette; it never follows the host theme.

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

const app = el<HTMLElement>('#app');
const canvas = el<HTMLCanvasElement>('#view');
const menu = el<HTMLElement>('#menu');
const pauseScreen = el<HTMLElement>('#pause');

// ---- Saved progress (optional storage domain) ------------------------------------
const canStore = runtimeHasDomain(STORAGE_DOMAIN);
function save(key: string, value: string | number): void {
  if (!canStore) return;
  storage.setItem(key, String(value)).catch(() => undefined);
}
const bestKey = (map: MapId) => (map === 'city' ? 'best-drift' : `best-drift-${map}`);

/** A planned race, as saved: the waypoints (re-snapped to the roads on loading), circuit or not, laps. */
interface SavedRoute {
  way: { x: number; z: number }[];
  loop: boolean;
  laps: number;
}

interface Saved {
  map: MapId;
  paint: number;
  zoom: number | null;
  traffic: boolean;
  volumes: Record<VolumeKind, number>;
  /** The time of day, hours. */
  time: number;
  /** The graphics setting. */
  graphics: Quality;
  bests: Record<MapId, number>;
  routes: Partial<Record<MapId, SavedRoute>>;
}

function parseRoute(text: string | null): SavedRoute | undefined {
  if (!text) return undefined;
  try {
    const r = JSON.parse(text) as SavedRoute;
    if (!Array.isArray(r.way) || r.way.length < 2 || r.way.length > 40) return undefined;
    if (!r.way.every((p) => Number.isFinite(p.x) && Number.isFinite(p.z))) return undefined;
    return { way: r.way.map((p) => ({ x: p.x, z: p.z })), loop: r.loop === true, laps: [1, 2, 3, 5].includes(r.laps) ? r.laps : 2 };
  } catch {
    return undefined;
  }
}

/** Read what was saved last time, giving up quickly so a slow host never blocks play. */
async function loadSaved(): Promise<Saved> {
  const saved: Saved = { map: 'city', paint: 0, zoom: null, traffic: true, volumes: { master: 1, music: 1, engine: 1, effects: 1 }, time: 15, graphics: 'auto', bests: { city: 0, hills: 0, test: 0 }, routes: {} };
  if (!canStore) return saved;
  const read = async () => {
    const keys = ['map', 'paint', 'zoom', 'traffic', 'volumes', 'time', 'graphics', ...MAPS.map((m) => `route-${m.id}`), ...MAPS.map((m) => bestKey(m.id))];
    const values = await Promise.all(keys.map((k) => storage.getItem(k)));
    const [map, p, z, t, vols, hrs, gfx, ...rest] = values;
    if (QUALITIES.includes(gfx as Quality)) saved.graphics = gfx as Quality;
    const h = Number(hrs);
    if (hrs !== null && Number.isFinite(h) && h >= 0 && h < 24) saved.time = h;
    saved.traffic = t !== 'off';
    try {
      const v = JSON.parse(vols ?? 'null') as Partial<Record<VolumeKind, unknown>> | null;
      for (const k of Object.keys(saved.volumes) as VolumeKind[]) {
        const n = Number(v?.[k]);
        if (v && Number.isFinite(n)) saved.volumes[k] = Math.max(0, Math.min(1, n));
      }
    } catch {
      // Keep the defaults.
    }
    const routes = rest.slice(0, MAPS.length);
    const bests = rest.slice(MAPS.length);
    MAPS.forEach((m, i) => {
      const r = parseRoute(routes[i] ?? null);
      if (r) saved.routes[m.id] = r;
    });
    if (MAPS.some((m) => m.id === map)) saved.map = map as MapId;
    const pn = Number(p);
    if (p !== null && Number.isInteger(pn) && pn >= 0 && pn < PAINTS.length) saved.paint = pn;
    const zn = Number(z);
    if (z !== null && Number.isInteger(zn)) saved.zoom = zn;
    MAPS.forEach((m, i) => {
      const b = Number(bests[i]);
      if (Number.isFinite(b) && b > 0) saved.bests[m.id] = Math.round(b);
    });
  };
  try {
    await Promise.race([read(), new Promise((resolve) => setTimeout(resolve, 1200))]);
  } catch {
    // Storage is a convenience; play goes on without it.
  }
  return saved;
}

// The map's built a step at a time (it takes a few seconds), so the page stays responsive.
void loadSaved().then(async (saved) => boot(saved, await World.create(saved.map)));

function boot(saved: Saved, world: World): void {
  const bests = saved.bests;
  const input = new Input(app);
  input.onActivity = unlockAudio;
  // Sound (the menu's music) straight away, where the browser and the host allow a page
  // to play before it's been clicked; where they don't, it starts the moment anything is
  // clicked, tapped or pressed, anywhere on the page.
  unlockAudio();
  for (const type of ['pointerdown', 'keydown', 'touchstart'] as const) window.addEventListener(type, unlockAudio, { capture: true, passive: true });
  let paint = saved.paint;
  const game = new Game(canvas, input, PAINTS[paint]!.color, saved.map, world);
  // For tests: ?debug exposes the game.
  if (import.meta.env.DEV || new URLSearchParams(location.search).has('debug')) (window as unknown as { __game: Game }).__game = game;
  game.state.best = bests[game.mapId];
  if (saved.zoom !== null) game.setZoom(saved.zoom);
  game.setTraffic(saved.traffic);
  game.onZoom = (z) => save('zoom', z);
  const hud = new Hud(game.world.map);
  const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
  game.shakeEnabled = !reducedMotion;

  // Touch layout on phones and tablets, or as soon as someone touches the screen.
  const setTouch = (on: boolean) => app.classList.toggle('touch-ui', on);
  setTouch(matchMedia('(pointer: coarse)').matches);
  app.addEventListener('pointerdown', (e) => {
    if (e.pointerType === 'touch') setTouch(true);
  });
  for (const b of app.querySelectorAll<HTMLButtonElement>('.pedal')) input.bindTouch(b, b.dataset.k as Parameters<Input['bindTouch']>[1]);

  // ---- Host settings (optional config domain) --------------------------------------
  if (runtimeHasDomain(CONFIG_DOMAIN)) {
    startSettings((values) => {
      setSoundEnabled(values.sound !== false);
      hud.setMph(values.mph === true);
      game.shakeEnabled = !reducedMotion && values.screenShake !== false;
    });
  }

  // ---- Paint swatches ----------------------------------------------------------------
  const swatchGroups = [...app.querySelectorAll<HTMLElement>('.paints')];
  for (const group of swatchGroups)
    PAINTS.forEach((p, i) => {
      const b = document.createElement('button');
      b.type = 'button';
      b.setAttribute('role', 'radio');
      b.setAttribute('aria-label', p.name);
      b.title = p.name;
      b.style.setProperty('--c', `#${p.color.toString(16).padStart(6, '0')}`);
      b.addEventListener('click', () => {
        sfxClick();
        setPaint(i, true);
      });
      group.append(b);
    });
  function setPaint(i: number, persist: boolean): void {
    paint = i;
    // (A swatch picked: plain paint, instead of a design.)
    if (persist && livery) {
      livery = null;
      void designs.apply(null);
      game.setLivery(null);
      renderLivery();
    }
    if (!livery) game.setPaint(PAINTS[i]!.color);
    renderSwatches();
    if (persist) save('paint', i);
  }
  function renderSwatches(): void {
    for (const group of swatchGroups) group.querySelectorAll('button').forEach((b, k) => b.setAttribute('aria-checked', String(!livery && k === paint)));
  }

  // ---- The account, its records, and its car design ---------------------------------
  const online = new Online();
  const designs = new Designs(online, canStore);
  /** The design on the car (null: plain paint, the swatch). */
  let livery: Design | null = null;
  let accountId = '';
  async function loadLivery(): Promise<void> {
    const id = await designs.appliedId();
    livery = id ? await designs.load(id) : null;
    if (!shop.isOpen) applyLivery();
  }
  function applyLivery(): void {
    if (livery) game.setLivery(livery);
    else {
      game.setLivery(null);
      game.setPaint(PAINTS[paint]!.color);
    }
    renderLivery();
  }
  function renderLivery(): void {
    const note = el<HTMLElement>('#liveryNote');
    note.hidden = !livery;
    note.textContent = livery ? `Your car wears “${livery.name}”. Pick a colour for plain paint.` : '';
    renderSwatches();
  }
  const accName = el<HTMLElement>('#accName');
  const accNote = el<HTMLElement>('#accNote');
  const accAvatar = el<HTMLElement>('#accAvatar');
  const accEdit = el<HTMLButtonElement>('#accEdit');
  // (Not a form: the sandbox blocks form submission.)
  const accForm = el<HTMLElement>('#accForm');
  const accInput = el<HTMLInputElement>('#accInput');
  const seconds = (ms: number) => `${(ms / 1000).toFixed(2)} s`;
  function renderAccount(): void {
    const a = online.account;
    accName.textContent = a.name;
    accAvatar.textContent = (a.name.trim()[0] ?? '?').toUpperCase();
    accAvatar.classList.toggle('signed', a.signedIn);
    const r = online.records;
    const records = r.longestDrift || r.racesWon ? ` · best drift ${seconds(r.longestDrift)} · ${r.racesWon} won` : '';
    accNote.textContent = (a.signedIn ? 'Signed in with Nostr' : online.canSignIn ? 'Guest (sign in through your host for your Nostr name)' : 'Playing as a guest') + records;
    accEdit.hidden = a.signedIn;
    if (a.signedIn) accForm.hidden = true;
  }
  online.onChange = () => {
    renderAccount();
    if (online.account.id !== accountId) {
      accountId = online.account.id;
      void loadLivery();
    }
  };
  accEdit.addEventListener('click', () => {
    sfxClick();
    accForm.hidden = !accForm.hidden;
    accInput.value = online.account.name === 'Guest' ? '' : online.account.name;
    if (!accForm.hidden) accInput.focus();
  });
  function setName(): void {
    void online.setGuestName(accInput.value);
    accForm.hidden = true;
    accEdit.focus();
  }
  el<HTMLButtonElement>('#accOk').addEventListener('click', setName);
  // (Typing a name never drives the car.)
  accInput.addEventListener('keydown', (e) => {
    e.stopPropagation();
    if (e.code === 'Escape') accForm.hidden = true;
    else if (e.code === 'Enter' || e.code === 'NumpadEnter') {
      // (Used up here, or it'd go on to press the button focused next.)
      e.preventDefault();
      setName();
    }
  });

  // ---- The paint shop --------------------------------------------------------------
  const shop = new PaintShop({
    game,
    designs,
    canvas,
    appliedId: () => livery?.id ?? null,
    apply: (d) => {
      livery = d ? { ...d, ops: [...d.ops] } : null;
      void designs.apply(d?.id ?? null);
      renderLivery();
    },
    closed: () => {
      applyLivery();
      showStep('mode');
      el<HTMLButtonElement>('#shopBtn').focus();
    },
  });
  el<HTMLButtonElement>('#shopBtn').addEventListener('click', () => {
    sfxClick();
    menu.hidden = true;
    void shop.show(livery, livery?.base ?? PAINTS[paint]!.color);
  });
  setPaint(paint, false);
  renderAccount();
  void online.start();

  // ---- Map picker --------------------------------------------------------------------
  const mapList = el<HTMLElement>('.maps');
  const mapButtons = MAPS.map((m) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.setAttribute('role', 'radio');
    b.innerHTML = `<span class="map-name">${m.name}</span><span class="map-blurb">${m.blurb}</span>`;
    b.addEventListener('click', () => chooseMap(m.id));
    mapList.append(b);
    return b;
  });
  function renderMaps(): void {
    MAPS.forEach((m, i) => mapButtons[i]!.setAttribute('aria-checked', String(m.id === game.mapId)));
  }
  function chooseMap(id: MapId): void {
    if (id === game.mapId) return;
    sfxClick();
    for (const b of mapButtons) b.disabled = true;
    mapButtons[MAPS.findIndex((m) => m.id === id)]!.setAttribute('aria-checked', 'true');
    // Let the button repaint before the (blocking) world build.
    setTimeout(() => {
      game.setMap(id);
      game.state.best = bests[id];
      hud.setMap(game.world.map);
      save('map', id);
      for (const b of mapButtons) b.disabled = false;
      renderMaps();
    }, 30);
  }
  renderMaps();

  // ---- Screens: mode, then map, then (racing) the route planner ---------------------
  let kind: 'free' | 'race' = 'free';
  const steps = [...menu.querySelectorAll<HTMLElement>('[data-step]')];
  const modeButtons = [...menu.querySelectorAll<HTMLButtonElement>('[data-mode]')];
  const driveBtn = el<HTMLButtonElement>('#driveBtn');
  const planner = el<HTMLElement>('#planner');
  const results = el<HTMLElement>('#results');
  const editor = new RouteEditor(el<HTMLCanvasElement>('#routeMap'));
  if (import.meta.env.DEV || new URLSearchParams(location.search).has('debug')) (window as unknown as { __editor: RouteEditor }).__editor = editor;
  const loopBox = el<HTMLInputElement>('#loopBox');
  const lapsSel = el<HTMLSelectElement>('#lapsSel');
  const lapsLabel = el<HTMLElement>('#lapsLabel');
  const routeLen = el<HTMLElement>('#routeLen');
  const raceBtn = el<HTMLButtonElement>('#raceBtn');
  const distSlider = el<HTMLInputElement>('#distSlider');
  const distValue = el<HTMLElement>('#distValue');
  let raced: { route: RaceRoute; laps: number } | null = null;

  function showStep(step: 'mode' | 'map'): void {
    for (const sct of steps) sct.hidden = sct.dataset.step !== step;
    menu.hidden = false;
    driveBtn.textContent = kind === 'race' ? 'Continue' : 'Drive';
    (step === 'mode' ? el<HTMLButtonElement>('#modeNext') : driveBtn).focus();
  }
  function setKind(k: 'free' | 'race'): void {
    kind = k;
    for (const b of modeButtons) b.setAttribute('aria-checked', String(b.dataset.mode === k));
  }
  for (const b of modeButtons)
    b.addEventListener('click', () => {
      sfxClick();
      setKind(b.dataset.mode === 'race' ? 'race' : 'free');
    });
  // Volume sliders, on the start menu and the pause screen (kept in step): the master
  // volume, and music, engines and effects under it.
  const VOLUMES: [VolumeKind, string][] = [
    ['master', 'Master'],
    ['music', 'Music'],
    ['engine', 'Engine'],
    ['effects', 'Effects'],
  ];
  const sliders: { kind: VolumeKind; input: HTMLInputElement; out: HTMLOutputElement }[] = [];
  for (const k of Object.keys(saved.volumes) as VolumeKind[]) setVolume(k, saved.volumes[k]);
  let saveVol = 0;
  for (const box of document.querySelectorAll<HTMLElement>('[data-volumes]'))
    for (const [kind, name] of VOLUMES) {
      const label = document.createElement('label');
      label.textContent = name;
      const input = document.createElement('input');
      input.type = 'range';
      input.min = '0';
      input.max = '100';
      input.step = '1';
      input.value = String(Math.round(saved.volumes[kind] * 100));
      input.setAttribute('aria-label', name + ' volume');
      const out = document.createElement('output');
      out.textContent = input.value;
      label.htmlFor = input.id = `vol-${kind}-${sliders.length}`;
      box.append(label, input, out);
      sliders.push({ kind, input, out });
      input.addEventListener('input', () => {
        const v = Number(input.value) / 100;
        saved.volumes[kind] = v;
        setVolume(kind, v);
        for (const s of sliders)
          if (s.kind === kind) {
            s.input.value = input.value;
            s.out.textContent = input.value;
          }
        // Saved once it's been still a moment, not on every step of a drag.
        clearTimeout(saveVol);
        saveVol = window.setTimeout(() => save('volumes', JSON.stringify(saved.volumes)), 400);
      });
      // (Arrow keys on a focused slider move it, not the car.)
      input.addEventListener('keydown', (e) => e.stopPropagation());
    }
  // The time of day, on the same panels: a slider through the day and night.
  game.setTimeOfDay(saved.time);
  const clock = (h: number) => `${String(Math.floor(h)).padStart(2, '0')}:${String(Math.round((h % 1) * 60)).padStart(2, '0')}`;
  const timeSliders: { input: HTMLInputElement; out: HTMLOutputElement }[] = [];
  let saveTime = 0;
  for (const box of document.querySelectorAll<HTMLElement>('[data-volumes]')) {
    const label = document.createElement('label');
    label.textContent = 'Time';
    const input = document.createElement('input');
    input.type = 'range';
    input.min = '0';
    input.max = '23.75';
    input.step = '0.25';
    input.value = String(saved.time);
    input.setAttribute('aria-label', 'Time of day');
    const out = document.createElement('output');
    out.textContent = clock(saved.time);
    label.htmlFor = input.id = `time-${timeSliders.length}`;
    box.append(label, input, out);
    timeSliders.push({ input, out });
    input.addEventListener('input', () => {
      const h = Number(input.value);
      saved.time = h;
      game.setTimeOfDay(h);
      for (const s of timeSliders) {
        s.input.value = input.value;
        s.out.textContent = clock(h);
      }
      clearTimeout(saveTime);
      saveTime = window.setTimeout(() => save('time', h), 400);
    });
    input.addEventListener('keydown', (e) => e.stopPropagation());
  }
  // The graphics setting, on the same panels: Auto (showing the tier it's at), Low, Medium, High.
  game.setQuality(saved.graphics);
  const tierName = { low: 'Low', medium: 'Med', high: 'High' } as const;
  const gfxText = () => {
    const g = game.graphics;
    return g.quality === 'auto' ? `Auto·${tierName[g.tier]}` : tierName[g.tier];
  };
  const gfxSliders: { input: HTMLInputElement; out: HTMLOutputElement }[] = [];
  for (const box of document.querySelectorAll<HTMLElement>('[data-volumes]')) {
    const label = document.createElement('label');
    label.textContent = 'Graphics';
    const input = document.createElement('input');
    input.type = 'range';
    input.min = '0';
    input.max = '3';
    input.step = '1';
    input.value = String(QUALITIES.indexOf(saved.graphics));
    input.setAttribute('aria-label', 'Graphics quality');
    input.setAttribute('aria-valuetext', saved.graphics);
    const out = document.createElement('output');
    out.textContent = gfxText();
    label.htmlFor = input.id = `gfx-${gfxSliders.length}`;
    box.append(label, input, out);
    gfxSliders.push({ input, out });
    input.addEventListener('input', () => {
      const q = QUALITIES[Number(input.value)]!;
      saved.graphics = q;
      game.setQuality(q);
      for (const sl of gfxSliders) {
        sl.input.value = input.value;
        sl.input.setAttribute('aria-valuetext', q);
        sl.out.textContent = gfxText();
      }
      save('graphics', q);
    });
    input.addEventListener('keydown', (e) => e.stopPropagation());
  }
  game.onQuality = () => {
    for (const sl of gfxSliders) sl.out.textContent = gfxText();
  };
  // Traffic on or off, for free driving and racing alike.
  const trafficBox = el<HTMLInputElement>('#trafficBox');
  trafficBox.checked = saved.traffic;
  trafficBox.addEventListener('change', () => {
    sfxClick();
    game.setTraffic(trafficBox.checked);
    save('traffic', trafficBox.checked ? 'on' : 'off');
  });
  el<HTMLButtonElement>('#modeNext').addEventListener('click', () => {
    sfxClick();
    showStep('map');
  });
  el<HTMLButtonElement>('#mapBack').addEventListener('click', () => {
    sfxClick();
    showStep('mode');
  });

  // ---- Leaderboards ------------------------------------------------------------------
  const boards = el<HTMLElement>('#boards');
  const boardTabs = [...boards.querySelectorAll<HTMLButtonElement>('[data-board]')];
  let board: BoardId = 'longest-drift-v1';
  let boardTimer = 0;
  let synced = false;
  const boardScore = (b: BoardId, v: number) => (b === 'longest-drift-v1' ? seconds(v) : `${v} ${v === 1 ? 'win' : 'wins'}`);
  async function refreshBoard(): Promise<void> {
    const note = el<HTMLElement>('#boardNote');
    const rows = el<HTMLOListElement>('#boardRows');
    const r = online.records;
    el<HTMLElement>('#boardMine').textContent = `${online.account.name}: best drift ${seconds(r.longestDrift)} · ${r.racesWon} ${r.racesWon === 1 ? 'race' : 'races'} won`;
    if (!online.canShare) {
      rows.textContent = '';
      note.textContent = 'Shared leaderboards need a host with the soyLI backend. Your own records are still kept.';
      return;
    }
    const shown = board;
    try {
      if (!synced) {
        synced = true;
        await online.sync();
      }
      const { rows: list, own } = await online.read(shown);
      if (shown !== board || boards.hidden) return;
      rows.textContent = '';
      for (const row of list) {
        const li = document.createElement('li');
        li.classList.toggle('me', row.own);
        const n = document.createElement('span');
        n.textContent = row.name;
        const t = document.createElement('span');
        t.textContent = boardScore(shown, row.score);
        li.append(n, t);
        rows.append(li);
      }
      note.textContent = list.length ? (own && !list.some((x) => x.own) ? `Your best here: ${boardScore(shown, own.score)}` : '') : 'No scores yet: be the first.';
    } catch (err) {
      note.textContent = err instanceof Error ? err.message : 'The leaderboard did not answer.';
    }
  }
  function setBoard(b: BoardId): void {
    board = b;
    for (const t of boardTabs) t.setAttribute('aria-checked', String(t.dataset.board === b));
    el<HTMLOListElement>('#boardRows').textContent = '';
    void refreshBoard();
  }
  for (const t of boardTabs)
    t.addEventListener('click', () => {
      sfxClick();
      setBoard(t.dataset.board as BoardId);
    });
  function closeBoards(): void {
    sfxClick();
    boards.hidden = true;
    clearInterval(boardTimer);
    showStep('mode');
    el<HTMLButtonElement>('#boardsBtn').focus();
  }
  el<HTMLButtonElement>('#boardsBtn').addEventListener('click', () => {
    sfxClick();
    menu.hidden = true;
    boards.hidden = false;
    setBoard(board);
    // (At most every couple of seconds while it's open.)
    clearInterval(boardTimer);
    boardTimer = window.setInterval(() => void refreshBoard(), 2500);
    el<HTMLButtonElement>('#boardsClose').focus();
  });
  el<HTMLButtonElement>('#boardsClose').addEventListener('click', closeBoards);
  window.addEventListener('keydown', (e) => {
    if (!boards.hidden && e.code === 'Escape') closeBoards();
  });

  function drive(): void {
    unlockAudio();
    sfxClick();
    menu.hidden = true;
    planner.hidden = true;
    results.hidden = true;
    pauseScreen.hidden = true;
    hud.visible = true;
    game.endRace();
    hud.setRoute(null);
    game.start();
    canvas.focus();
  }

  // ---- Race planner --------------------------------------------------------------------
  function savedWay(): { way: ReturnType<typeof snapToRoad>[]; loop: boolean; laps: number } {
    const r = saved.routes[game.mapId];
    if (r) return { way: r.way.map((p) => snapToRoad(game.roads, p.x, p.z)), loop: r.loop, laps: r.laps };
    return { way: defaultRoute(game.roads, game.world.spawn.x, game.world.spawn.z), loop: false, laps: 2 };
  }
  function renderPlanner(): void {
    const r = editor.route;
    routeLen.textContent = r ? `${(r.len / 1000).toFixed(1)} km${editor.loop ? ' a lap' : ''}` : 'No way through';
    lapsLabel.hidden = !editor.loop;
    raceBtn.disabled = !editor.valid;
    raceBtn.title = editor.valid ? '' : 'Make the route at least 400 m long';
  }
  editor.onChange = renderPlanner;
  function openPlanner(): void {
    sfxClick();
    game.endRace();
    hud.setRoute(null);
    game.mode = 'attract';
    menu.hidden = true;
    results.hidden = true;
    pauseScreen.hidden = true;
    hud.visible = false;
    planner.hidden = false;
    const w = savedWay();
    loopBox.checked = w.loop;
    lapsSel.value = String(w.laps);
    editor.open(game.roads, game.world.map, w.way, w.loop);
    renderPlanner();
    if (editor.route) {
      const km = Math.max(0.5, Math.min(8, editor.route.len / 1000));
      distSlider.value = String(Math.round(km * 10) / 10);
      distValue.textContent = `${km.toFixed(1)} km`;
    }
    raceBtn.focus();
  }
  // The distance slider: a fresh route that long from the start flag, no road used twice.
  // The flags (and any waypoints) can still be dragged about afterwards.
  let sliding = 0;
  function routeFromSlider(fit: boolean): void {
    const km = Number(distSlider.value);
    distValue.textContent = `${km.toFixed(1)} km`;
    const start = editor.waypoints[0];
    if (!start) return;
    const seed = (start.edge * 7919 + (editor.loop ? 1 : 0)) >>> 0;
    // A few tries with different seeds, keeping the closest to the length asked for.
    const make = (m: number) => {
      for (let k = 0; k < 4; k++) {
        const w = generateRoute(game.roads, start, m, editor.loop, seed + k * 104729);
        if (w) return w;
      }
      return null;
    };
    // Not that long a route from here (few roads, or no loop that small): the nearest that is.
    let way = make(km * 1000);
    for (let d = 250; !way && d <= 4000; d += 250) way = make(km * 1000 - d) ?? make(km * 1000 + d);
    if (way) editor.setWaypoints(way, fit);
    else routeLen.textContent = 'No route from here';
  }
  distSlider.addEventListener('input', () => {
    // At most one route a frame while the slider moves.
    cancelAnimationFrame(sliding);
    sliding = requestAnimationFrame(() => routeFromSlider(false));
  });
  distSlider.addEventListener('change', () => {
    cancelAnimationFrame(sliding);
    routeFromSlider(true);
  });
  loopBox.addEventListener('change', () => {
    editor.setLoop(loopBox.checked);
    renderPlanner();
  });
  el<HTMLButtonElement>('#zoomIn').addEventListener('click', () => editor.zoom(1.4));
  el<HTMLButtonElement>('#zoomOut').addEventListener('click', () => editor.zoom(1 / 1.4));
  el<HTMLButtonElement>('#zoomFit').addEventListener('click', () => editor.fit());
  el<HTMLButtonElement>('#plannerBack').addEventListener('click', () => {
    sfxClick();
    planner.hidden = true;
    showStep('map');
  });
  el<HTMLButtonElement>('#plannerReset').addEventListener('click', () => {
    sfxClick();
    loopBox.checked = false;
    editor.setLoop(false);
    editor.setWaypoints(defaultRoute(game.roads, game.world.spawn.x, game.world.spawn.z));
    renderPlanner();
  });

  function startRace(route: RaceRoute, laps: number): void {
    unlockAudio();
    sfxClick();
    raced = { route, laps };
    planner.hidden = true;
    results.hidden = true;
    menu.hidden = true;
    pauseScreen.hidden = true;
    hud.visible = true;
    hud.setRoute(route);
    game.startRace(route, route.loop ? laps : 1);
    el<HTMLButtonElement>('#pauseRestartBtn').hidden = false;
    canvas.focus();
  }
  raceBtn.addEventListener('click', () => {
    const route = editor.route;
    if (!route || !editor.valid) return;
    const laps = Number(lapsSel.value) || 1;
    const way = editor.waypoints.map((p) => ({ x: Math.round(p.x * 10) / 10, z: Math.round(p.z * 10) / 10 }));
    saved.routes[game.mapId] = { way, loop: editor.loop, laps };
    save(`route-${game.mapId}`, JSON.stringify(saved.routes[game.mapId]));
    startRace(route, laps);
  });

  // ---- Results ---------------------------------------------------------------------------
  function showResults(): void {
    const race = game.race;
    if (!race) return;
    const pos = race.finishPosition;
    el<HTMLElement>('#resultTitle').textContent = pos === 1 ? 'You win!' : `Finished ${pos}${['st', 'nd', 'rd'][pos - 1] ?? 'th'}`;
    el<HTMLElement>('#resultTime').textContent = raceTime(race.finishTime);
    renderStandings();
    // The rivals race on to the line meanwhile (the player's car waits on the handbrake).
    game.mode = 'attract';
    input.release();
    results.hidden = false;
    el<HTMLButtonElement>('#againBtn').focus();
  }
  /** The results list: times for everyone over the line, distance to go for the rest. */
  let shownStandings = '';
  function renderStandings(): void {
    const race = game.race;
    if (!race) return;
    const rows = race.standings.map((st) => [st.name, st.player, st.out ? 'Wrecked' : st.time !== null ? raceTime(st.time) : `${(st.toGo / 1000).toFixed(1)} km to go`] as const);
    const key = JSON.stringify(rows);
    if (key === shownStandings) return;
    shownStandings = key;
    const list = el<HTMLOListElement>('#standings');
    list.textContent = '';
    for (const [name, me, text] of rows) {
      const li = document.createElement('li');
      li.classList.toggle('me', me);
      const n = document.createElement('span');
      n.textContent = name;
      const t = document.createElement('span');
      t.textContent = text;
      li.append(n, t);
      list.append(li);
    }
  }

  el<HTMLButtonElement>('#againBtn').addEventListener('click', () => {
    if (raced) startRace(raced.route, raced.laps);
  });
  el<HTMLButtonElement>('#editRouteBtn').addEventListener('click', openPlanner);
  el<HTMLButtonElement>('#resultsMenuBtn').addEventListener('click', toMenu);

  function toMenu(): void {
    sfxClick();
    game.endRace();
    hud.setRoute(null);
    game.mode = 'attract';
    pauseScreen.hidden = true;
    results.hidden = true;
    planner.hidden = true;
    hud.visible = false;
    el<HTMLButtonElement>('#pauseRestartBtn').hidden = true;
    showStep('mode');
  }

  game.onRace = (e) => {
    if (e.type === 'count') hud.bigText(String(e.n));
    else if (e.type === 'go') hud.bigText('GO!', 1100);
    else if (e.type === 'checkpoint') hud.popup(`Checkpoint ${raceTime(e.time)}`, 'bank');
    else if (e.type === 'lap') hud.popup(e.lap === e.of ? `Final lap ${raceTime(e.time)}` : `Lap ${e.lap}/${e.of}`, 'best');
    else if (e.type === 'finish') {
      if (e.position === 1) void online.raceWon();
      hud.bigText(e.position === 1 ? '1st!' : `${e.position}${['st', 'nd', 'rd'][e.position - 1] ?? 'th'}`, 1600);
      setTimeout(showResults, 1700);
    }
  };

  function pause(): void {
    if (game.mode !== 'drive') return;
    game.mode = 'paused';
    input.release();
    pauseScreen.hidden = false;
    el<HTMLButtonElement>('#resumeBtn').focus();
  }

  function resume(): void {
    if (game.mode !== 'paused') return;
    sfxClick();
    pauseScreen.hidden = true;
    game.mode = 'drive';
  }

  driveBtn.addEventListener('click', () => (kind === 'race' ? openPlanner() : drive()));
  el<HTMLButtonElement>('#resumeBtn').addEventListener('click', resume);
  el<HTMLButtonElement>('#pauseResetBtn').addEventListener('click', () => {
    game.resetCar();
    resume();
  });
  el<HTMLButtonElement>('#pauseMapBtn').addEventListener('click', toMenu);
  el<HTMLButtonElement>('#pauseRestartBtn').addEventListener('click', () => {
    if (raced) startRace(raced.route, raced.laps);
  });
  el<HTMLButtonElement>('#pauseBtn').addEventListener('click', pause);
  el<HTMLButtonElement>('#resetBtn').addEventListener('click', () => game.resetCar());
  el<HTMLButtonElement>('#camBtn').addEventListener('click', () => {
    game.setZoom(game.zoom + 1);
  });
  // Hand the keyboard back to the game after clicking a HUD button.
  for (const b of app.querySelectorAll<HTMLButtonElement>('.tools button')) b.addEventListener('click', () => b.blur());

  game.onPause = () => {
    if (game.mode === 'drive') pause();
    else if (game.mode === 'paused') resume();
  };
  // Enter on the menus presses the step's main button.
  window.addEventListener('keydown', (e) => {
    if (game.mode !== 'attract' || e.code !== 'Enter' || e.target instanceof HTMLButtonElement || e.target instanceof HTMLSelectElement) return;
    // (The key is used up here, so it doesn't also press the next step's button, focused meanwhile.)
    e.preventDefault();
    if (!menu.hidden) (steps.find((sct) => !sct.hidden)?.querySelector<HTMLButtonElement>('.go'))?.click();
    else if (!planner.hidden && !raceBtn.disabled) raceBtn.click();
  });
  // Losing focus mid-drive pauses, so no pedal is left held down.
  window.addEventListener('blur', pause);
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) pause();
  });

  game.onEvent = (e) => {
    if (e.type === 'bank') {
      hud.popup(`+${fmt.format(e.points)}${e.mult > 1 ? ` ×${e.mult}` : ''}`, 'bank');
      if (e.best) {
        hud.popup('New best drift!', 'best');
        bests[game.mapId] = e.points;
        save(bestKey(game.mapId), e.points);
      }
    } else if (e.type === 'lost') hud.popup(`Crashed −${fmt.format(e.points)}`, 'lost');
    else if (e.type === 'smash') hud.popup(`${e.label} +${fmt.format(e.points)}`, 'smash');
    else if (e.type === 'drift')
      void online.drift(e.seconds * 1000).then((longest) => {
        if (longest) hud.popup(`Longest drift ${e.seconds.toFixed(2)} s!`, 'best');
      });
  };

  // HUD refresh rides along with the render loop.
  const hudLoop = () => {
    requestAnimationFrame(hudLoop);
    if (!results.hidden) renderStandings();
    if (game.mode !== 'attract') {
      hud.setOthers(game.rivals.map((r) => ({ x: r.car.pos.x, z: r.car.pos.z, yaw: r.car.yaw, color: `#${r.spec.paint.toString(16).padStart(6, '0')}` })));
      hud.update(game.state, game.car);
      hud.updateRace(game.raceInfo());
    }
  };
  requestAnimationFrame(hudLoop);

  game.run();
}