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/fx.ts
import * as THREE from 'three';

/**
 * Tyre smoke (soft round billboards that swell, rise and fade; white off tarmac, the
 * ground's own colour as dust off dirt and sand), skid marks (strips laid behind the back
 * wheels, kept until the buffer wraps: black rubber on tarmac, ruts on dirt and sand,
 * torn brown turf flecked with grass on grass), and the mud and clumps of grass a wheel
 * throws up drifting on a lawn.
 */

/** What a wheel's on, for the marks and the spray it leaves. */
export type Ground = 'asphalt' | 'paving' | 'grass' | 'dirt' | 'sand';

const SMOKE_MAX = 700;

const smokeVert = /* glsl */ `
  attribute float size;
  attribute float alpha;
  attribute vec3 tint;
  varying float vAlpha;
  varying vec3 vTint;
  uniform float scale;
  void main() {
    vAlpha = alpha;
    vTint = tint;
    vec4 mv = modelViewMatrix * vec4(position, 1.0);
    gl_PointSize = size * scale / -mv.z;
    gl_Position = projectionMatrix * mv;
  }
`;
// Lit like the scene: its colour (sRGB) by the light falling on it, then tone mapped and
// put out as everything else is, so it greys at dusk and goes dim and bluish at night.
const smokeFrag = /* glsl */ `
  varying float vAlpha;
  varying vec3 vTint;
  uniform vec3 light;
  void main() {
    vec2 c = gl_PointCoord - 0.5;
    float d = length(c);
    if (d > 0.5) discard;
    float a = smoothstep(0.5, 0.15, d) * vAlpha;
    vec3 tint = pow(vTint, vec3(2.2));
    gl_FragColor = vec4(tint * light * (0.92 + 0.08 * (0.5 - c.y)), a);
    #include <tonemapping_fragment>
    #include <colorspace_fragment>
  }
`;

/** How much of the sun's (or moon's) light a puff scatters, as against the sky's. */
const SMOKE_SCATTER = 0.6;
/** Overall brightness: the afternoon's smoke near white, without its outshining white paint after dark. */
const SMOKE_GAIN = 0.7;

interface Puff {
  x: number;
  y: number;
  z: number;
  vx: number;
  vy: number;
  vz: number;
  life: number;
  max: number;
  size: number;
  grow: number;
  alpha: number;
  /** Its colour (r, g, b, 0 to 1). */
  c: [number, number, number];
  /** How fast it rises (smoke) or hangs low (dust). */
  lift: number;
}

const SMOKE_WHITE: [number, number, number] = [0.95, 0.95, 0.94];
/** Dust off each kind of loose ground: the colour of what's thrown up. */
const DUST: Partial<Record<Ground, [number, number, number]>> = {
  dirt: [0.55, 0.42, 0.29],
  sand: [0.88, 0.8, 0.62],
  grass: [0.45, 0.36, 0.24],
};

export class Smoke {
  readonly points: THREE.Points;
  private readonly puffs: Puff[] = [];
  private readonly pos = new Float32Array(SMOKE_MAX * 3);
  private readonly size = new Float32Array(SMOKE_MAX);
  private readonly alpha = new Float32Array(SMOKE_MAX);
  private readonly tint = new Float32Array(SMOKE_MAX * 3);
  private readonly geo = new THREE.BufferGeometry();
  private readonly mat: THREE.ShaderMaterial;

  constructor() {
    this.geo.setAttribute('position', new THREE.BufferAttribute(this.pos, 3).setUsage(THREE.DynamicDrawUsage));
    this.geo.setAttribute('size', new THREE.BufferAttribute(this.size, 1).setUsage(THREE.DynamicDrawUsage));
    this.geo.setAttribute('alpha', new THREE.BufferAttribute(this.alpha, 1).setUsage(THREE.DynamicDrawUsage));
    this.geo.setAttribute('tint', new THREE.BufferAttribute(this.tint, 3).setUsage(THREE.DynamicDrawUsage));
    this.geo.setDrawRange(0, 0);
    this.mat = new THREE.ShaderMaterial({
      vertexShader: smokeVert,
      fragmentShader: smokeFrag,
      uniforms: { scale: { value: 600 }, light: { value: new THREE.Color(1, 1, 1) } },
      transparent: true,
      depthWrite: false,
    });
    this.points = new THREE.Points(this.geo, this.mat);
    this.points.frustumCulled = false;
    // After everything laid on the ground (skid marks, contact shadows at 1, the race
    // trail at 2), so the smoke hides them rather than their showing through it.
    this.points.renderOrder = 3;
  }

  /**
   * The light on the smoke: some of the sun's, from any side (smoke scatters it), and the
   * sky's, mostly from above. Call when the lights change.
   */
  setLight(sun: THREE.DirectionalLight, hemi: THREE.HemisphereLight): void {
    const light = this.mat.uniforms.light!.value as THREE.Color;
    const sky = hemi.groundColor.clone().lerp(hemi.color, 0.6).multiplyScalar(hemi.intensity);
    light.copy(sun.color).multiplyScalar(sun.intensity * SMOKE_SCATTER).add(sky).multiplyScalar(SMOKE_GAIN);
  }

  /** Viewport height in pixels and the camera's vertical field of view set the point scale. */
  resize(heightPx: number, fovDeg: number): void {
    this.mat.uniforms.scale!.value = heightPx / (2 * Math.tan((fovDeg * Math.PI) / 360));
  }

  /**
   * One burst at a back wheel: white tyre smoke off tarmac; off dirt and sand a cloud of
   * dust their colour, thicker, lower and slower to rise; off grass just a little.
   */
  tyre(at: THREE.Vector3, back: THREE.Vector3, carVel: THREE.Vector3, strength: number, ground: Ground = 'asphalt'): void {
    if (this.puffs.length >= SMOKE_MAX) this.puffs.shift();
    const r = Math.random;
    const dust = DUST[ground];
    if (dust) {
      const grass = ground === 'grass';
      const shade = 0.9 + r() * 0.2;
      this.puffs.push({
        x: at.x + (r() - 0.5) * 0.6,
        y: at.y + 0.2 + r() * 0.2,
        z: at.z + (r() - 0.5) * 0.6,
        vx: carVel.x * 0.25 + back.x * (2 + r() * 3) + (r() - 0.5) * 3.5,
        vy: 0.3 + r() * 0.8,
        vz: carVel.z * 0.25 + back.z * (2 + r() * 3) + (r() - 0.5) * 3.5,
        life: 0,
        max: grass ? 0.6 + r() * 0.5 : 1.6 + r() * 1.6,
        size: grass ? 0.6 + r() * 0.4 : 1.4 + r() * 0.9,
        grow: grass ? 1.5 + r() : 5 + r() * 3,
        alpha: (grass ? 0.18 + r() * 0.1 : 0.5 + r() * 0.2) * strength,
        c: [dust[0] * shade, dust[1] * shade, dust[2] * shade],
        lift: 0.12,
      });
      return;
    }
    this.puffs.push({
      x: at.x + (r() - 0.5) * 0.5,
      y: at.y + 0.3 + r() * 0.2,
      z: at.z + (r() - 0.5) * 0.5,
      vx: carVel.x * 0.3 + back.x * (1.5 + r() * 2.5) + (r() - 0.5) * 3,
      vy: 0.5 + r() * 1,
      vz: carVel.z * 0.3 + back.z * (1.5 + r() * 2.5) + (r() - 0.5) * 3,
      life: 0,
      max: 1.4 + r() * 1.4,
      size: 1.2 + r() * 0.8,
      grow: 4 + r() * 3,
      alpha: (0.35 + r() * 0.2) * strength,
      c: SMOKE_WHITE,
      lift: 0.4,
    });
  }

  /** A grey cloud where the car hit something. */
  crash(at: THREE.Vector3, power: number): void {
    const r = Math.random;
    for (let i = 0; i < 10 + power; i++) {
      if (this.puffs.length >= SMOKE_MAX) this.puffs.shift();
      const a = r() * Math.PI * 2;
      const s = 2 + r() * 4;
      this.puffs.push({ x: at.x, y: at.y + 0.6, z: at.z, vx: Math.cos(a) * s, vy: 0.5 + r() * 2, vz: Math.sin(a) * s, life: 0, max: 0.8 + r() * 0.8, size: 1.5, grow: 4, alpha: 0.4, c: SMOKE_WHITE, lift: 0.4 });
    }
  }

  update(dt: number): void {
    let n = 0;
    for (let i = this.puffs.length - 1; i >= 0; i--) {
      const p = this.puffs[i]!;
      p.life += dt;
      if (p.life >= p.max) {
        this.puffs.splice(i, 1);
        continue;
      }
      const drag = Math.exp(-2.2 * dt);
      p.vx *= drag;
      p.vz *= drag;
      p.vy = p.vy * Math.exp(-1 * dt) + p.lift * dt;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.z += p.vz * dt;
      const k = p.life / p.max;
      this.pos[n * 3] = p.x;
      this.pos[n * 3 + 1] = p.y;
      this.pos[n * 3 + 2] = p.z;
      this.size[n] = p.size + p.grow * Math.sqrt(k) * 1.6;
      this.alpha[n] = p.alpha * Math.min(1, k * 8) * (1 - k) * (1 - k);
      this.tint[n * 3] = p.c[0];
      this.tint[n * 3 + 1] = p.c[1];
      this.tint[n * 3 + 2] = p.c[2];
      n++;
    }
    this.geo.setDrawRange(0, n);
    for (const name of ['position', 'size', 'alpha', 'tint']) (this.geo.attributes[name] as THREE.BufferAttribute).needsUpdate = true;
  }

  clear(): void {
    this.puffs.length = 0;
    this.geo.setDrawRange(0, 0);
  }
}

const SKID_MAX = 6000;

/**
 * What a wheel leaves, by the ground: its colour (r, g, b), how strong it gets, how much
 * wider than a strip of rubber, and whether grass shows through it in spots.
 */
const MARK: Record<Ground, { c: [number, number, number]; max: number; wide: number; grass: number }> = {
  asphalt: { c: [0.07, 0.07, 0.08], max: 0.6, wide: 1, grass: 0 },
  paving: { c: [0.07, 0.07, 0.08], max: 0.6, wide: 1, grass: 0 },
  // Ruts: the ground churned up, darker than it.
  dirt: { c: [0.29, 0.2, 0.12], max: 0.62, wide: 1.35, grass: 0 },
  sand: { c: [0.53, 0.43, 0.28], max: 0.7, wide: 1.35, grass: 0 },
  // Turf torn up: dark brown earth, tufts of grass still in it.
  grass: { c: [0.22, 0.14, 0.07], max: 0.8, wide: 1.35, grass: 1 },
};

/** Marks laid by the wheels: each wheel adds a strip segment from where it last was. */
export class SkidMarks {
  readonly mesh: THREE.Mesh;
  private readonly pos = new Float32Array(SKID_MAX * 4 * 3);
  private readonly alpha = new Float32Array(SKID_MAX * 4);
  private readonly color = new Float32Array(SKID_MAX * 4 * 3);
  private readonly grass = new Float32Array(SKID_MAX * 4);
  private readonly geo = new THREE.BufferGeometry();
  private next = 0;
  private count = 0;
  private readonly last = new Map<number, THREE.Vector3 | null>();

  constructor() {
    const index = new Uint32Array(SKID_MAX * 6);
    for (let i = 0; i < SKID_MAX; i++) index.set([i * 4, i * 4 + 1, i * 4 + 2, i * 4, i * 4 + 2, i * 4 + 3], i * 6);
    this.geo.setIndex(new THREE.BufferAttribute(index, 1));
    this.geo.setAttribute('position', new THREE.BufferAttribute(this.pos, 3).setUsage(THREE.DynamicDrawUsage));
    this.geo.setAttribute('alpha', new THREE.BufferAttribute(this.alpha, 1).setUsage(THREE.DynamicDrawUsage));
    this.geo.setAttribute('tint', new THREE.BufferAttribute(this.color, 3).setUsage(THREE.DynamicDrawUsage));
    this.geo.setAttribute('grass', new THREE.BufferAttribute(this.grass, 1).setUsage(THREE.DynamicDrawUsage));
    const mat = new THREE.ShaderMaterial({
      vertexShader: /* glsl */ `
        attribute float alpha;
        attribute vec3 tint;
        attribute float grass;
        varying float vAlpha;
        varying vec3 vTint;
        varying float vGrass;
        varying vec2 vWp;
        void main() {
          vAlpha = alpha;
          vTint = tint;
          vGrass = grass;
          vWp = position.xz;
          gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
        }`,
      fragmentShader: /* glsl */ `
        varying float vAlpha;
        varying vec3 vTint;
        varying float vGrass;
        varying vec2 vWp;
        float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
        void main() {
          vec3 c = vTint;
          if (vGrass > 0.5) {
            // Tufts of grass left in the torn turf: spots in 9 cm cells, about a third of
            // them, in a few greens; and the earth itself a little uneven.
            vec2 cell = floor(vWp * 11.0);
            float spot = step(0.68, hash(cell));
            vec3 green = mix(vec3(0.26, 0.42, 0.14), vec3(0.4, 0.55, 0.2), hash(cell + 7.3));
            c *= 0.85 + 0.3 * hash(floor(vWp * 23.0));
            c = mix(c, green, spot);
          }
          gl_FragColor = vec4(c, vAlpha);
        }`,
      transparent: true,
      depthWrite: false,
      side: THREE.DoubleSide,
      polygonOffset: true,
      polygonOffsetFactor: -2,
      polygonOffsetUnits: -2,
    });
    this.mesh = new THREE.Mesh(this.geo, mat);
    this.mesh.frustumCulled = false;
    this.geo.setDrawRange(0, 0);
  }

  /** Wheel `id` is at `at` on `ground`, skidding with `strength` (0 lifts it off). */
  mark(id: number, at: THREE.Vector3, strength: number, ground: Ground = 'asphalt'): void {
    const prev = this.last.get(id);
    if (strength <= 0) {
      this.last.set(id, null);
      return;
    }
    if (!prev) {
      this.last.set(id, at.clone());
      return;
    }
    const dx = at.x - prev.x;
    const dz = at.z - prev.z;
    const len = Math.hypot(dx, dz);
    if (len < 0.4) return;
    if (len > 6) {
      prev.copy(at);
      return;
    }
    const m = MARK[ground];
    const w = 0.17 * m.wide;
    const nx = (-dz / len) * w;
    const nz = (dx / len) * w;
    // Just above the road paint.
    const y0 = prev.y + 0.1;
    const y1 = at.y + 0.1;
    const i = this.next;
    this.pos.set([prev.x + nx, y0, prev.z + nz, prev.x - nx, y0, prev.z - nz, at.x - nx, y1, at.z - nz, at.x + nx, y1, at.z + nz], i * 12);
    // (Loose ground takes a mark more readily: a little slip still churns it up.)
    const a = Math.min(m.max, (m.wide > 1 ? 0.4 : 0.25) + strength * 0.35);
    this.alpha.set([a, a, a, a], i * 4);
    const [cr, cg, cb] = m.c;
    this.color.set([cr, cg, cb, cr, cg, cb, cr, cg, cb, cr, cg, cb], i * 12);
    this.grass.set([m.grass, m.grass, m.grass, m.grass], i * 4);
    this.next = (this.next + 1) % SKID_MAX;
    this.count = Math.min(SKID_MAX, this.count + 1);
    this.geo.setDrawRange(0, this.count * 6);
    for (const name of ['position', 'alpha', 'tint', 'grass']) (this.geo.attributes[name] as THREE.BufferAttribute).needsUpdate = true;
    prev.copy(at);
  }

  clear(): void {
    this.count = this.next = 0;
    this.last.clear();
    this.geo.setDrawRange(0, 0);
  }
}

const CLOD_MAX = 1400;

/**
 * Drifting on grass, the back wheels throw up the lawn: specks of mud and clumps of turf,
 * flung back and up, falling and bouncing once before they lie still and go.
 */
export class Clods {
  readonly root = new THREE.Group();
  private readonly bits: { x: number; y: number; z: number; vx: number; vy: number; vz: number; life: number; floor: number; big: boolean; c: [number, number, number] }[] = [];
  private readonly layers: { pos: Float32Array; col: Float32Array; geo: THREE.BufferGeometry }[] = [];

  constructor() {
    // Small specks of mud, and bigger clumps of turf.
    for (const size of [0.11, 0.24]) {
      const pos = new Float32Array(CLOD_MAX * 3);
      const col = new Float32Array(CLOD_MAX * 3);
      const geo = new THREE.BufferGeometry();
      geo.setAttribute('position', new THREE.BufferAttribute(pos, 3).setUsage(THREE.DynamicDrawUsage));
      geo.setAttribute('color', new THREE.BufferAttribute(col, 3).setUsage(THREE.DynamicDrawUsage));
      geo.setDrawRange(0, 0);
      const pts = new THREE.Points(geo, new THREE.PointsMaterial({ size, vertexColors: true }));
      pts.frustumCulled = false;
      this.root.add(pts);
      this.layers.push({ pos, col, geo });
    }
  }

  /** A spray off a back wheel at `at`, flung back along `back`, as hard as `strength`. */
  spray(at: THREE.Vector3, back: THREE.Vector3, carVel: THREE.Vector3, strength: number): void {
    const r = Math.random;
    const n = 1 + Math.round(strength * 3);
    for (let k = 0; k < n; k++) {
      if (this.bits.length >= CLOD_MAX) this.bits.shift();
      const big = r() < 0.3;
      const out = (big ? 2 : 3) + r() * 3.5 * strength;
      let c: [number, number, number];
      if (!big) c = [0.24 + r() * 0.06, 0.16 + r() * 0.04, 0.09 + r() * 0.03];
      else if (r() < 0.6) c = [0.3 + r() * 0.1, 0.46 + r() * 0.1, 0.16 + r() * 0.06];
      else c = [0.3, 0.21, 0.12];
      this.bits.push({
        x: at.x + (r() - 0.5) * 0.4,
        y: at.y + 0.15,
        z: at.z + (r() - 0.5) * 0.4,
        vx: carVel.x * 0.35 + back.x * out + (r() - 0.5) * 2.5,
        vy: 1.5 + r() * (big ? 2.2 : 3.2),
        vz: carVel.z * 0.35 + back.z * out + (r() - 0.5) * 2.5,
        life: 0,
        floor: at.y + 0.05,
        big,
        c,
      });
    }
  }

  update(dt: number): void {
    const counts = [0, 0];
    for (let i = this.bits.length - 1; i >= 0; i--) {
      const b = this.bits[i]!;
      b.life += dt;
      if (b.life > 1.6) {
        this.bits.splice(i, 1);
        continue;
      }
      if (b.y > b.floor || b.vy > 0) {
        b.vy -= 16 * dt;
        const drag = Math.exp(-0.8 * dt);
        b.vx *= drag;
        b.vz *= drag;
        b.x += b.vx * dt;
        b.y += b.vy * dt;
        b.z += b.vz * dt;
        // Landing: a little bounce, then it lies there.
        if (b.y < b.floor) {
          b.y = b.floor;
          b.vy = Math.abs(b.vy) > 2 ? -b.vy * 0.25 : 0;
          b.vx *= 0.35;
          b.vz *= 0.35;
        }
      }
      const layer = b.big ? 1 : 0;
      const L = this.layers[layer]!;
      const n = counts[layer]!;
      counts[layer] = n + 1;
      L.pos[n * 3] = b.x;
      L.pos[n * 3 + 1] = b.y;
      L.pos[n * 3 + 2] = b.z;
      L.col.set(b.c, n * 3);
    }
    this.layers.forEach((L, k) => {
      L.geo.setDrawRange(0, counts[k]!);
      (L.geo.attributes.position as THREE.BufferAttribute).needsUpdate = true;
      (L.geo.attributes.color as THREE.BufferAttribute).needsUpdate = true;
    });
  }

  clear(): void {
    this.bits.length = 0;
    for (const L of this.layers) L.geo.setDrawRange(0, 0);
  }
}

const SPRAY_MAX = 900;

/** Water gushing from a knocked-over hydrant: droplets shot up that fall back and splash. */
export class Spray {
  readonly points: THREE.Points;
  private readonly drops: { x: number; y: number; z: number; vx: number; vy: number; vz: number; life: number; floor: number }[] = [];
  private readonly jets: { x: number; y: number; z: number; t: number }[] = [];
  private readonly pos = new Float32Array(SPRAY_MAX * 3);
  private readonly geo = new THREE.BufferGeometry();
  private readonly mat: THREE.PointsMaterial;

  constructor() {
    this.geo.setAttribute('position', new THREE.BufferAttribute(this.pos, 3).setUsage(THREE.DynamicDrawUsage));
    this.geo.setDrawRange(0, 0);
    this.mat = new THREE.PointsMaterial({ color: 0xd8ecff, size: 0.38, transparent: true, opacity: 0.8, depthWrite: false });
    this.points = new THREE.Points(this.geo, this.mat);
    this.points.frustumCulled = false;
  }

  /** Start a fountain at a broken hydrant (base position). */
  burst(x: number, y: number, z: number): void {
    this.jets.push({ x, y, z, t: 0 });
    if (this.jets.length > 8) this.jets.shift();
  }

  update(dt: number): void {
    // Each jet gushes for a few seconds, tailing off.
    for (let j = this.jets.length - 1; j >= 0; j--) {
      const jet = this.jets[j]!;
      jet.t += dt;
      const strength = Math.max(0, 1 - jet.t / 9);
      if (strength <= 0) {
        this.jets.splice(j, 1);
        continue;
      }
      const n = Math.round(260 * dt * (0.4 + strength));
      for (let k = 0; k < n && this.drops.length < SPRAY_MAX; k++) {
        const a = Math.random() * Math.PI * 2;
        const out = Math.random() * 1.6 * strength;
        this.drops.push({ x: jet.x, y: jet.y + 0.4, z: jet.z, vx: Math.cos(a) * out, vy: (6 + Math.random() * 4) * (0.5 + strength * 0.5), vz: Math.sin(a) * out, life: 0, floor: jet.y });
      }
    }
    let n = 0;
    for (let i = this.drops.length - 1; i >= 0; i--) {
      const d = this.drops[i]!;
      d.life += dt;
      d.vy -= 14 * dt;
      d.x += d.vx * dt;
      d.y += d.vy * dt;
      d.z += d.vz * dt;
      if (d.y < d.floor || d.life > 3) {
        this.drops.splice(i, 1);
        continue;
      }
      this.pos[n * 3] = d.x;
      this.pos[n * 3 + 1] = d.y;
      this.pos[n * 3 + 2] = d.z;
      n++;
    }
    this.geo.setDrawRange(0, n);
    (this.geo.attributes.position as THREE.BufferAttribute).needsUpdate = true;
  }

  clear(): void {
    this.drops.length = 0;
    this.jets.length = 0;
    this.geo.setDrawRange(0, 0);
  }
}