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/rivals.ts
import * as THREE from 'three';
import { Car, CAR_SPEED } from './car.js';
import type { RaceRoute, RouteSample } from './race.js';
import type { World } from './world.js';

/**
 * Race rivals: each one drives a car just like the player's (the same physics, so it
 * slides, scrapes walls, flies off ramps and gets knocked about the same way), worked by
 * an AI at the pedals, wheel and handbrake.
 *
 * Each frame the driver looks along the route: where its racing line is (keeping right,
 * cutting in to the inside of bends, moving across to get past anything slower or coming
 * the other way), how fast each bend ahead can be taken, and how hard it must brake to be
 * down to that speed by the time it gets there. Into a tight bend at speed it flicks the
 * handbrake and holds the car in a drift, the nose pointed into the corner and the
 * throttle on, then straightens up out of it. Stuck against something, it backs off and
 * tries again; lost or wedged for long, it's put back on the route.
 */

export interface RivalSpec {
  name: string;
  paint: number;
  /** How close to the limit it takes bends (1 = right on it). */
  pace: number;
  /** How readily it drifts a tight bend rather than gripping round it (0..1). */
  drift: number;
}

/** Something on the road: where it is, how it's moving and its size. */
export interface Obstacle {
  x: number;
  z: number;
  vx: number;
  vz: number;
  len: number;
  wid: number;
  /** A jump ramp, rising this way: taken head on it's a jump; from any other side it's a solid block. */
  ramp?: { dx: number; dz: number };
}

const wrap = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));
/** How fast the car can turn (rad/s) at speed v, gripping and sliding (from car.ts). */
const gripTurn = (v: number) => Math.min(2.4 / (1 + Math.max(0, v - 8) / 18), v / 5.4);
const slideTurn = (v: number) => Math.min(2.6 / (1 + v / 40), v / 2.7);
/** Braking the AI plans with (m/s²): a little under the car's 9. */
const DECEL = 8;

/**
 * The fastest a bend of curvature k (1/m) can be drifted. Sliding off the throttle, the line
 * of travel swings round at up to k_scrub / 2 = 2.25 rad/s (see Rival.slide), well past
 * what the tyres manage gripping at speed; this keeps a margin under that.
 */
function driftSpeed(k: number): number {
  return k < 1e-4 ? CAR_SPEED : Math.min(CAR_SPEED, 1.45 / k);
}

/** The fastest a bend of curvature k (1/m) can be taken, gripping or (if drift) sliding. */
function cornerSpeed(k: number, drift: boolean): number {
  if (k < 1e-4) return CAR_SPEED;
  let lo = 6;
  let hi = CAR_SPEED;
  for (let i = 0; i < 18; i++) {
    const v = (lo + hi) / 2;
    const turn = drift ? Math.max(gripTurn(v), slideTurn(v) * 0.9) : gripTurn(v);
    if (v * k <= turn * 0.86) lo = v;
    else hi = v;
  }
  return lo;
}

const _p: RouteSample = { x: 0, z: 0, tx: 0, tz: 1, hw: 4 };
const _q: RouteSample = { x: 0, z: 0, tx: 0, tz: 1, hw: 4 };
const _r: RouteSample = { x: 0, z: 0, tx: 0, tz: 1, hw: 4 };
const _v = new THREE.Vector3();

export class Rival {
  readonly car: Car;
  readonly name: string;
  /** Distance along the route, unwrapped (laps add on). */
  s: number;
  /** How far right of the route's line it's driving, and where it means to be. */
  private off: number;
  private offTarget: number;
  finished: number | null = null;
  /** Seconds pushing against something without moving; seconds left backing off. */
  private stuck = 0;
  private reversing = 0;
  /** Seconds lost off the route. */
  private lost = 0;
  /** Seconds left of a handbrake flick into a drift; whether it's holding a drift now. */
  private flick = 0;
  private drifting = false;
  /**
   * Smoothness, as a driver's hands and feet have it: the slip angle it's steering for,
   * eased towards what the drift wants rather than jumped to; the wheel and pedals as
   * they are now (they move only so fast); how long the road's been straight (a drift
   * isn't dropped on a moment's straight) and since it last let a drift go (not taken
   * straight up again).
   */
  private deltaRef = 0;
  private wheelOut = 0;
  private throttleOut = 0;
  private straightFor = 0;
  private sinceDrift = 9;
  /** Whether the drift controller had the wheel last frame. */
  private sliding = false;
  /** Traffic in the turn ahead (last frame): it plans that bend for grip, not a drift. */
  private traffic = false;
  /** Which way the drift it's in turns (+1 left). */
  private driftSign = 1;
  /** Swinging round where the route doubles back, and which way (+1 left). */
  private spinning = false;
  private spinSign = 1;

  constructor(
    readonly spec: RivalSpec,
    route: RaceRoute,
    slot: { s: number; off: number },
    world: World,
  ) {
    this.name = spec.name;
    this.s = slot.s;
    this.off = this.offTarget = slot.off;
    const p = route.at(slot.s, _p);
    const x = p.x - p.tz * slot.off;
    const z = p.z + p.tx * slot.off;
    this.car = new Car(x, z, Math.atan2(p.tx, p.tz), spec.paint);
    this.car.place(x, z, Math.atan2(p.tx, p.tz), world.height(x, z, (p.y ?? 0) + 0.5));
  }

  /**
   * Decide this frame's pedals, wheel and handbrake. go is false until the start;
   * leader is how far along the route the player is; obstacles are everything else on
   * the road nearby (traffic, the player, the other rivals).
   */
  think(dt: number, route: RaceRoute, world: World, go: boolean, leader: number, obstacles: Obstacle[]): void {
    const car = this.car;
    if (!go) {
      car.throttle = 0;
      car.turning = 0;
      car.handbrake = true;
      return;
    }
    car.handbrake = false;
    const vel = car.velocity(_v);
    const speed = Math.hypot(vel.x, vel.z);
    // Where it is along the route (near where it was, so it can't skip a loop of it).
    const pr = route.project(car.pos.x, car.pos.z, this.s + speed * dt, 15, 45, 0.3);
    const p = route.at(pr.s, _p);
    if (pr.d < p.hw + 25) {
      this.s = pr.s;
      this.lost = 0;
    } else this.lost += dt;
    const hw = Math.max(1.4, p.hw - 1.3);
    // The bends ahead: how sharply the route turns at each point, as curvature.
    const curve = (d: number) => {
      const a = route.at(this.s + d - 5, _q);
      const b = route.at(this.s + d + 5, _r);
      return wrap(Math.atan2(b.tx, b.tz) - Math.atan2(a.tx, a.tz)) / 10;
    };
    // Speed: for each point ahead, how fast it could be going here and still brake down
    // to that point's corner speed in time.
    const driftReady = this.spec.drift > 0.2;
    let target = CAR_SPEED;
    let sharpest = 0;
    let sharpAt = 0;
    let turnSign = 0;
    const reach = 20 + (speed * speed) / (2 * DECEL);
    for (let d = 4; d <= reach; d += 4) {
      const k = curve(d);
      // A drift carries more speed through a bend than grip can, so through the sweeping
      // ones it comes in faster, up to a quarter faster for the keenest drifter. (Not the
      // tight corners, where arriving hot only runs it wide into the kerb; and not with
      // traffic in the bend, which calls the drift off.)
      const grip = cornerSpeed(Math.abs(k), false);
      const sweep = driftReady && !this.traffic && Math.abs(k) < 0.035 ? Math.min(grip * 1.25, driftSpeed(Math.abs(k))) : grip;
      const vc = (grip + Math.max(0, sweep - grip) * this.spec.drift) * this.spec.pace;
      target = Math.min(target, Math.sqrt(vc * vc + 2 * DECEL * Math.max(0, d - 6)));
      if (Math.abs(k) > Math.abs(sharpest)) {
        sharpest = k;
        sharpAt = d;
      }
    }
    // Which way the nearest real bend goes (+1 left, -1 right).
    for (let d = 6; d <= 40; d += 4) {
      const k = curve(d);
      if (Math.abs(k) > 0.012) {
        turnSign = Math.sign(k);
        break;
      }
    }
    // The racing line: the right of the road, cutting to the inside of a bend.
    // It keeps to its own (right) half of the road, the oncoming traffic's half only to
    // get past something: within that, the inside of a bend.
    // (Own half: in town both its lanes; out of town its one lane, kept to the middle of it.)
    // (On a one-way road there is no oncoming half: the whole width is its own.)
    const lo = p.oneway ? -hw : Math.min(hw - 0.2, p.hw > 6 ? 1.5 : 1.7);
    let pref = (lo + hw) / 2;
    if (turnSign !== 0) pref = turnSign > 0 ? lo : hw;
    // Everything ahead: how far along and across the route, and how fast along it.
    const ahead: { lat: number; along: number; speed: number; wid: number; solid: boolean }[] = [];
    for (const o of obstacles) {
      // A ramp met head on is a jump: carry on over it.
      if (o.ramp && o.ramp.dx * p.tx + o.ramp.dz * p.tz > 0.75) continue;
      const along = (o.x - car.pos.x) * p.tx + (o.z - car.pos.z) * p.tz - (o.ramp ? o.len / 2 : 0);
      if (along < -3 || along > 35 + speed * 1.8) continue;
      const lat = -(o.x - p.x) * p.tz + (o.z - p.z) * p.tx;
      ahead.push({ lat, along, speed: o.vx * p.tx + o.vz * p.tz, wid: o.wid + (o.ramp ? 0.8 : 0), solid: !!o.ramp });
    }
    const blockedAt = (lat: number) =>
      ahead.some(
        (a) =>
          Math.abs(a.lat - lat) < (a.wid + 1.9) / 2 + 0.7 &&
          a.along > 0 &&
          ((a.speed < Math.max(speed, 8) - 1.5 && a.along < 14 + speed * 1.4) || (a.speed < -1 && a.along < 40 + speed * 2.2)),
      );
    if (!blockedAt(pref)) this.offTarget = pref;
    else if (blockedAt(this.offTarget)) {
      // The clear line nearest where it is, if there is one.
      let best = this.offTarget;
      let bestD = Infinity;
      // Over into the oncoming half only with a long clear view of it.
      const oncomingClear = !obstacles.some((o) => {
        const along = (o.x - car.pos.x) * p.tx + (o.z - car.pos.z) * p.tz;
        const lat = -(o.x - p.x) * p.tz + (o.z - p.z) * p.tx;
        return along > -4 && along < 100 + speed * 3 && lat < lo && o.vx * p.tx + o.vz * p.tz < 1;
      });
      for (let lat = -hw; lat <= hw + 0.01; lat += 0.9)
        if ((lat >= lo - 0.3 || oncomingClear) && !blockedAt(lat) && Math.abs(lat - this.off) < bestD) {
          best = lat;
          bestD = Math.abs(lat - this.off);
        }
      this.offTarget = best;
    }
    // Dodging something it saw coming: hold that line a moment.
    if (this.dodgeTime > 0) {
      this.dodgeTime -= dt;
      this.offTarget = this.dodgeOff;
    }
    this.offTarget = Math.max(-hw, Math.min(hw, this.offTarget));
    this.off += Math.max(-8 * dt, Math.min(8 * dt, this.offTarget - this.off));
    // Anything still square in the way: don't run into the back of anything moving; but
    // anything stopped there (a queue, a wreck) it noses into and shoves aside rather
    // than waiting behind for ever.
    for (const a of ahead)
      if (a.along > 0 && Math.abs(a.lat - this.off) < (a.wid + 1.9) / 2 + 0.2) {
        const gap = Math.max(0, a.along - 5);
        const stop = Math.sqrt(Math.max(0, a.speed) ** 2 + 2 * DECEL * gap);
        target = Math.min(target, a.speed > 2 || a.solid ? stop : Math.max(6, stop));
      }
    // Pace: ease off a touch when far ahead of the player.
    if (this.s - leader > 250) target *= 0.95;
    if (this.finished !== null) target = Math.min(target, route.loop ? 14 : 0);
    if (!route.loop) target = Math.min(target, Math.sqrt(2 * DECEL * Math.max(0, route.len - 8 - this.s)));
    // The heading it wants: the way the road runs just ahead, turned towards its line by
    // how far off it it is (so it follows the bends rather than cutting across them).
    const lead = route.at(this.s + 2 + speed * 0.12, _q);
    const latNow = -(car.pos.x - p.x) * p.tz + (car.pos.z - p.z) * p.tx;
    const want = wrap(Math.atan2(lead.tx, lead.tz) - Math.atan2(2.4 * (this.off - latNow), speed + 3));
    // Where the route turns right back on itself (a U-turn at a waypoint): in at about
    // 10 m/s, then a handbrake turn, the wheel on full lock, to swing it round.
    const heading = (d: number) => {
      const a = route.at(this.s + d, _r);
      return Math.atan2(a.tx, a.tz);
    };
    const h0 = heading(0);
    const reversal = Math.abs(wrap(heading(16) - h0)) > 2.3;
    if (reversal) {
      target = Math.min(target, 10);
      if (!this.spinning && Math.abs(wrap(heading(7) - h0)) > 1.2) {
        this.spinning = true;
        // Round to the left (across the road's other half) unless the route curls right.
        let sign = 0;
        for (let d = 2; d <= 16 && !sign; d += 2) if (Math.abs(curve(d)) > 0.05) sign = Math.sign(curve(d));
        this.spinSign = sign || 1;
      }
    }
    // Turns: how far the route swings round over the next stretch, and whether it's in
    // one right now. Into any real turn at speed it flicks the handbrake and drifts it
    // (the keener drivers taking gentler ones too); the moment the road straightens out,
    // it lets go of the drift.
    const swing = wrap(heading(10 + speed * 0.9) - h0);
    const inTurn = Math.abs(curve(3)) > 0.012 || Math.abs(curve(9)) > 0.014 || Math.abs(wrap(heading(14) - h0)) > 0.22;
    const needs = 0.85 - 0.45 * this.spec.drift;
    // Where it's really going over the next second or so (sliding, turning), and what it
    // would hit on the way: a car, a wall, a post (not a prop: it drives through those); and whether it's running wide
    // off the road.
    const travelNow = speed > 2 ? Math.atan2(vel.x, vel.z) : car.yaw;
    const travelRate = this.lastTravel === null ? 0 : wrap(travelNow - this.lastTravel) / Math.max(1e-3, dt);
    this.travelRate += (travelRate - this.travelRate) * Math.min(1, dt * 10);
    this.lastTravel = travelNow;
    const danger = this.predict(vel.x, vel.z, this.travelRate, world, obstacles);
    const wide = this.runsWide(vel.x, vel.z, this.travelRate, route);
    // Traffic in the turn ahead: take it gripping, not sideways.
    const busy = (this.traffic = ahead.some((a) => a.along > 0 && a.along < 30 + speed && (a.lat > -1 || (p.hw < 6 && a.along < 45)) && Math.abs(a.lat) < hw + 2.5 && !a.solid));
    this.straightFor = inTurn ? 0 : this.straightFor + dt;
    this.sinceDrift = this.drifting ? 0 : this.sinceDrift + dt;
    if (!this.drifting && !reversal && driftReady && !danger && !busy && speed > 12 && this.sinceDrift > 0.7 && Math.abs(swing) > needs && Math.abs(wrap(heading(6) - h0)) > 0.08) {
      this.flick = 0.3;
      this.drifting = true;
      this.driftSign = Math.sign(swing);
    }
    // Out of the turn, too slow, or about to hit something or run off the road: drop the drift.
    if (this.drifting && (this.straightFor > 0.25 || speed < 7 || (danger && danger.t < 1.1) || wide)) {
      this.drifting = false;
      this.flick = 0;
    }
    // Something in its path: steer for the side of the road away from it.
    if (danger) {
      // A wall or post: back towards the middle of the road. A car: round it, if there's room.
      const lat = -(danger.x - p.x) * p.tz + (danger.z - p.z) * p.tx;
      const away = lat > this.off ? lat - 3.2 : lat + 3.2;
      if (danger.world) this.dodgeOff = (lo + hw) / 2;
      else if (Math.abs(away) <= hw) this.dodgeOff = away;
      this.dodgeTime = danger.world || Math.abs(away) <= hw ? 0.6 : 0;
    }
    void sharpest;
    void sharpAt;
    // Gripping: the wheel turns it at up to its grip limit, so the wheel needed is the turn
    // wanted over what full lock gives at this speed.
    const err = wrap(want - car.yaw);
    let wheel = -(err * 4.2) / Math.max(0.25, gripTurn(Math.abs(car.speed)));
    // Throttle to the target speed; brake hard when well over it.
    let throttle = speed < target - 0.6 ? 1 : speed > target + 1.8 ? -1 : 0.35;
    // Not so much throttle on full lock at low speed that the wheels spin it into a donut.
    if (!this.drifting && Math.abs(wheel) > 0.8 && speed < 16) throttle = Math.min(throttle, 0.75);
    // Sliding (or flicking the handbrake to start a slide): the drift controller works the
    // wheel, throttle and handbrake instead. Out of a turn, or with trouble ahead, it lets
    // the slide go and gets the tyres gripping again. (Not for a slow wheelspin, which
    // the grip steering handles.)
    const slipNow = Math.abs(Math.atan2(car.slip, Math.max(1, Math.abs(car.speed))));
    const sliding = this.flick > 0 || (car.sliding && (this.drifting ? speed > 6 : speed > 9 && slipNow > 0.2));
    if (!sliding) this.sliding = false;
    if (sliding) {
      const curveNow = curve(2 + speed * 0.25);
      const ctl = this.slide(dt, speed, vel, want, speed * curveNow, this.drifting && !danger && !wide, target);
      wheel = ctl.wheel;
      throttle = ctl.throttle;
      car.handbrake = ctl.handbrake;
    }
    // About to hit something: brake (harder the sooner); running wide: lift.
    if (danger && danger.t < 0.9 && speed > 4) throttle = -1;
    else if (danger && speed > 8) throttle = Math.min(throttle, 0);
    if (wide && !this.drifting) throttle = Math.min(throttle, speed > 12 ? -0.6 : 0.2);
    if (this.spinning) {
      // Round until it faces the way the route now goes, then drive off.
      const after = route.at(this.s + 18, _q);
      const left = wrap(Math.atan2(after.tx, after.tz) - car.yaw);
      if (Math.abs(left) < 0.5 || speed < 0.5 && this.slow > 2) {
        this.spinning = false;
        this.s += 6;
      } else {
        car.handbrake = speed > 3;
        wheel = -this.spinSign;
        throttle = speed < 4 ? 0.7 : 0.15;
        this.drifting = false;
      }
    }
    // Stuck nose-in to something: back off with the wheel turned the other way, then try again.
    if (this.reversing > 0) {
      this.reversing -= dt;
      throttle = -1;
      wheel = Math.sign(err) || 1;
    } else if (speed < 1.2 && throttle > 0) {
      this.stuck += dt;
      if (this.stuck > 1.4) {
        this.reversing = 1.1;
        this.stuck = 0;
      }
    } else this.stuck = Math.max(0, this.stuck - dt);
    // Wedged or lost for long: back onto the route where it left it.
    this.slow = speed < 1.5 ? this.slow + dt : 0;
    if (this.lost > 3 || this.slow > 6) this.reset(route, world);
    // Hands and feet: in and out of a drift (and for a moment after) the wheel turns at
    // most about lock to lock in a third of a second and the throttle swings full on to
    // off in a quarter, so the slide builds and unwinds smoothly; otherwise quicker, as a
    // driver braking and steering on grip is; quickest in an emergency.
    const urgent = (danger && danger.t < 0.9) || this.reversing > 0 || this.spinning;
    const easing = this.sliding || this.sinceDrift < 0.8;
    const wStep = (urgent ? 14 : easing ? 7 : 11) * dt;
    const tStep = (urgent ? 20 : easing ? 5 : 12) * dt;
    wheel = Math.max(-1, Math.min(1, wheel));
    this.wheelOut += Math.max(-wStep, Math.min(wStep, wheel - this.wheelOut));
    this.throttleOut += Math.max(-tStep, Math.min(tStep, throttle - this.throttleOut));
    // (Braking for something ahead is never held back.)
    if (throttle < -0.5 && danger) this.throttleOut = throttle;
    car.throttle = this.throttleOut;
    car.turning = this.wheelOut;
  }

  /**
   * The drift controller: two loops, as autonomous-drifting controllers are built. The outer
   * one decides how fast the line of travel must turn to follow the road (the road's own
   * curve, plus a pull back onto the line). The inner one holds the slip angle (the angle
   * between the nose and the way it's going) that gives that turn: in this car's physics
   * a sliding car's line of travel swings towards its nose at k sin(2 delta) / 2, k being
   * how hard the tyres scrub (lower with the throttle on, which is how the throttle sets
   * the angle), so it picks delta from that and steers the nose to it. Its wheel is worked
   * out from the same physics as the car's: yaw rate = -wheel * steer + align * slip angle.
   * As the road straightens the slip angle it wants falls to nothing, so it unwinds the
   * drift smoothly and the tyres grip again. Without the intent to drift, it lets the
   * slide go (off the throttle, nose in line with its travel).
   *
   * The handbrake flick that starts a drift is the same controller with the handbrake on
   * (scrub 1.6, align 1.0), swinging the nose round to the angle wanted, then letting go.
   */
  private slide(dt: number, speed: number, vel: THREE.Vector3, wantTravel: number, omegaFF: number, intent: boolean, target: number): { wheel: number; throttle: number; handbrake: boolean } {
    const car = this.car;
    const theta = Math.atan2(vel.x, vel.z);
    const delta = wrap(theta - car.yaw);
    // Outer loop: the turn rate wanted of the line of travel.
    const omega = omegaFF + Math.max(-0.45, Math.min(0.45, 1.6 * wrap(wantTravel - theta)));
    // The pedals: throttle on (scrub 2) to hold a drift, unless it needs to turn harder than
    // that can manage, or it's going too fast: then off the throttle (scrub 4.5, slowing).
    let throttle = 0.05;
    let k = 4.5;
    // Letting a slide go, it still lets the nose follow the road a little, so it doesn't
    // run straight on while the tyres find their grip.
    let deltaWant = Math.max(-0.4, Math.min(0.4, 0.5 * Math.asin(Math.max(-0.97, Math.min(0.97, (-2 * omega) / k)))));
    if (!intent) {
      // Letting it go: easing off rather than lifting all at once (which snaps the tyres
      // back into grip), and the angle unwound gradually (below).
      // (Back on the gas as it straightens, if it's below the speed it wants.)
      throttle = speed < target - 1 ? 0.7 : Math.min(0.45, Math.max(0.05, Math.abs(delta) * 0.9));
      k = 4.5 - 2.5 * Math.min(1, throttle / 0.45);
      deltaWant = Math.max(-0.4, Math.min(0.4, 0.5 * Math.asin(Math.max(-0.97, Math.min(0.97, (-2 * omega) / k)))));
    }
    if (intent) {
      const tooFast = speed > target + 2.5;
      if (Math.abs(omega) < 0.92 && !tooFast) {
        throttle = speed < target - 1 ? 0.95 : 0.7;
        k = 2;
      }
      deltaWant = 0.5 * Math.asin(Math.max(-0.97, Math.min(0.97, (-2 * omega) / k)));
      deltaWant = Math.max(-0.78, Math.min(0.78, deltaWant));
    }
    // The flick: handbrake on until the nose is round to most of the angle wanted.
    let handbrake = false;
    if (this.flick > 0) {
      this.flick -= dt;
      handbrake = true;
      throttle = 0.3;
      k = 1.6;
      // Swing the nose into the bend at least this far, even before the bend itself starts.
      deltaWant = -this.driftSign * Math.max(Math.abs(deltaWant), 0.4);
      if (Math.abs(delta) > Math.abs(deltaWant) * 0.7 && Math.sign(delta) === Math.sign(deltaWant)) this.flick = 0;
    }
    // The angle steered for eases towards the one wanted: in at up to about 100 degrees a
    // second, out at about 60, so the nose swings in and straightens up smoothly. (It
    // starts from wherever the car's angle is now, so taking over a slide doesn't jerk.)
    if (!this.sliding) this.deltaRef = delta;
    this.sliding = true;
    const growing = Math.abs(deltaWant) > Math.abs(this.deltaRef) && Math.sign(deltaWant) === Math.sign(this.deltaRef || deltaWant);
    const step = (growing ? 2.2 : 1.25) * dt;
    this.deltaRef += Math.max(-step, Math.min(step, deltaWant - this.deltaRef));
    // Inner loop: the yaw rate that keeps the slip angle where it's wanted (turning with
    // the line of travel, plus a correction), and the wheel that gives it.
    const rate = -k * Math.sin(delta) * Math.cos(delta);
    const yawRate = rate + 4.2 * wrap(theta - this.deltaRef - car.yaw);
    const align = handbrake ? 1 : throttle > 0.15 ? 1.6 - 1.4 * Math.min(1, throttle) : 1.6;
    const steer = Math.max(0.3, Math.min((handbrake ? 3 : 2.6) / (1 + speed / 40), speed / 2.7));
    const slipAngle = Math.atan2(car.slip, Math.max(1, Math.abs(car.speed)));
    const dir = car.speed < 0 ? -1 : 1;
    const wheel = Math.max(-1, Math.min(1, (align * slipAngle - yawRate) / (steer * dir)));
    return { wheel, throttle, handbrake };
  }

  /** Which way it was travelling last frame, and how fast that's turning (rad/s). */
  private lastTravel: number | null = null;
  /** A line across the road it's swerving to, and for how much longer. */
  private dodgeOff = 0;
  private dodgeTime = 0;
  private travelRate = 0;

  /** Its path over the next second or so: travelling as it is, the line of travel turning at rate. */
  private path(vx: number, vz: number, rate: number, out: (t: number, x: number, z: number) => boolean): void {
    let x = this.car.pos.x;
    let z = this.car.pos.z;
    const dt = 0.1;
    for (let t = dt; t <= 1.3 + 1e-6; t += dt) {
      const a = rate * t;
      const c = Math.cos(a);
      const sn = Math.sin(a);
      x += (vx * c + vz * sn) * dt;
      z += (vz * c - vx * sn) * dt;
      if (out(t, x, z)) return;
    }
  }

  /** The first thing on its path, if any: when, where, and whether it's the world (a wall, a post, a prop) or a vehicle. */
  private predict(vx: number, vz: number, rate: number, world: World, obstacles: Obstacle[]): { t: number; x: number; z: number; world: boolean } | null {
    if (Math.hypot(vx, vz) < 3) return null;
    let hit: { t: number; x: number; z: number; world: boolean } | null = null;
    this.path(vx, vz, rate, (t, x, z) => {
      // (Only what would stop it: anything that can be knocked over, it just drives through.)
      if (t >= 0.2 && world.squareBlocked(x, z, 1.0, true, this.car.pos.y)) {
        hit = { t, x, z, world: true };
        return true;
      }
      for (const o of obstacles) {
        // Oncoming traffic keeps to its own side (the line it's on deals with that).
        if (o.ramp || o.vx * vx + o.vz * vz < -4) continue;
        // The obstacle where it'll be then, as a line along the way it's moving.
        const ox = o.x + o.vx * t;
        const oz = o.z + o.vz * t;
        const ov = Math.hypot(o.vx, o.vz);
        const half = ov > 1 ? Math.max(0, o.len / 2 - o.wid / 2) : 0;
        const ux = ov > 1 ? o.vx / ov : 0;
        const uz = ov > 1 ? o.vz / ov : 0;
        const k = Math.max(-half, Math.min(half, (x - ox) * ux + (z - oz) * uz));
        const d = Math.hypot(x - (ox + ux * k), z - (oz + uz * k));
        const r = 1.25 + (ov > 1 ? o.wid / 2 : Math.max(o.wid, Math.min(o.len, 6)) / 2) + 0.4;
        if (d < r) {
          hit = { t, x: o.x, z: o.z, world: false };
          return true;
        }
      }
      return false;
    });
    return hit;
  }

  /** Is it running wide: off the road's edge on its path in the next 0.7 s? */
  private runsWide(vx: number, vz: number, rate: number, route: RaceRoute): boolean {
    let wide = false;
    this.path(vx, vz, rate, (t, x, z) => {
      if (t < 0.6) return false;
      const pr = route.project(x, z, this.s, 5, 40, 0.3);
      wide = pr.d > route.at(pr.s, _r).hw + 0.3;
      return true;
    });
    return wide;
  }

  /** Seconds hardly moving since the start. */
  private slow = 0;

  /** Back on the route at its place along it, facing the right way, stopped. */
  reset(route: RaceRoute, world: World): void {
    const p = route.at(this.s, _p);
    const x = p.x - p.tz * this.off;
    const z = p.z + p.tx * this.off;
    this.car.place(x, z, Math.atan2(p.tx, p.tz), world.height(x, z, (p.y ?? 0) + 0.5));
    this.lost = 0;
    this.stuck = 0;
    this.reversing = 0;
    this.drifting = false;
    this.spinning = false;
    this.slow = 0;
    this.lastTravel = null;
    this.travelRate = 0;
  }
}

/**
 * Two cars meeting: pushed apart, and an equal share of the bump each way, which breaks
 * their tails loose like any hit. Returns how hard they hit (closing speed, m/s), 0 if they
 * didn't touch.
 */
export function collideCars(a: Car, b: Car): number {
  if (Math.abs(a.pos.y - b.pos.y) > 2) return 0;
  if (Math.hypot(a.pos.x - b.pos.x, a.pos.z - b.pos.z) > 6) return 0;
  const circles = (c: Car) => {
    const hx = Math.sin(c.yaw);
    const hz = Math.cos(c.yaw);
    return [-1.25, 0, 1.25].map((k) => ({ x: c.pos.x + hx * k, z: c.pos.z + hz * k }));
  };
  const ca = circles(a);
  const cb = circles(b);
  let best: { nx: number; nz: number; pen: number } | null = null;
  for (const p of ca)
    for (const q of cb) {
      const dx = p.x - q.x;
      const dz = p.z - q.z;
      const d = Math.hypot(dx, dz);
      const pen = 2.1 - d;
      if (pen > 0 && (!best || pen > best.pen)) best = { nx: d > 1e-4 ? dx / d : 1, nz: d > 1e-4 ? dz / d : 0, pen };
    }
  if (!best) return 0;
  const { nx, nz, pen } = best;
  a.pos.x += (nx * pen) / 2;
  a.pos.z += (nz * pen) / 2;
  b.pos.x -= (nx * pen) / 2;
  b.pos.z -= (nz * pen) / 2;
  const va = a.velocity(new THREE.Vector3());
  const vb = b.velocity(new THREE.Vector3());
  const vn = (va.x - vb.x) * nx + (va.z - vb.z) * nz;
  if (vn >= 0) return 0;
  // Equal masses, a little bounce.
  const j = (-(1 + 0.3) * vn) / 2;
  a.setVelocity(va.x + j * nx, va.z + j * nz);
  b.setVelocity(vb.x - j * nx, vb.z - j * nz);
  return -vn;
}