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/engine-voice.ts
/**
 * A four-cylinder engine built from real exhaust pulses.
 *
 * A short stretch of a recorded idle is cut into single firing pulses (one per
 * combustion, marked by its pressure peak). While driving, the pulses are fired again at
 * the engine's real firing rate (a four-stroke four fires twice per revolution) and
 * overlapped, so every rpm gets the true shape of an exhaust pulse instead of one loop
 * sped up into a whine. The pulses tighten a little at high revs, as they do in a real
 * exhaust, and each cylinder fires slightly differently, which gives the idle its lope.
 *
 * Load matters as much as revs: on the throttle each combustion is full and loud, off it
 * the pulses are thin overrun puffs. An intake roar (filtered noise breathing with each
 * firing) grows with throttle and revs. Ignition can be cut (gear changes, the rev
 * limiter), leaving only the faint overrun.
 *
 * Plain sample processing, no browser APIs, so it renders the same offline as live.
 */

export const IDLE_RPM = 900;
export const REDLINE_RPM = 7800;
/**
 * How much the pulses shorten as the revs rise (1 would shrink them in proportion, like
 * a sped-up recording; 0 not at all). Real exhaust pulses land in between.
 */
const TIGHTEN = 0.62;
/** The engine's low-pass corner at idle (Hz); it rises 60% by the red line. */
const LOWPASS = 2400;

export interface EngineParams {
  /** Crankshaft speed. */
  rpm: number;
  /** Throttle 0..1. */
  load: number;
  /** Combustion happening (false while the ignition is cut). */
  ignition: boolean;
}

interface Active {
  grain: Float32Array;
  pos: number;
  rate: number;
  gain: number;
  /** Samples to play before fading out (pulses never ring past the next few firings). */
  life: number;
  /** Over how many samples it fades out at the end of its life. */
  fade: number;
}

/** One second-order filter section (RBJ cookbook), for the intake noise. */
class Biquad {
  private b0 = 1;
  private b1 = 0;
  private b2 = 0;
  private a1 = 0;
  private a2 = 0;
  private x1 = 0;
  private x2 = 0;
  private y1 = 0;
  private y2 = 0;

  lowpass(freq: number, q: number, sampleRate: number): void {
    const w = (2 * Math.PI * freq) / sampleRate;
    const alpha = Math.sin(w) / (2 * q);
    const a0 = 1 + alpha;
    const c = Math.cos(w);
    this.b0 = (1 - c) / 2 / a0;
    this.b1 = (1 - c) / a0;
    this.b2 = (1 - c) / 2 / a0;
    this.a1 = (-2 * c) / a0;
    this.a2 = (1 - alpha) / a0;
  }

  bandpass(freq: number, q: number, sampleRate: number): void {
    const w = (2 * Math.PI * freq) / sampleRate;
    const alpha = Math.sin(w) / (2 * q);
    const a0 = 1 + alpha;
    this.b0 = alpha / a0;
    this.b1 = 0;
    this.b2 = -alpha / a0;
    this.a1 = (-2 * Math.cos(w)) / a0;
    this.a2 = (1 - alpha) / a0;
  }

  run(x: number): number {
    const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2;
    this.x2 = this.x1;
    this.x1 = x;
    this.y2 = this.y1;
    this.y1 = y;
    return y;
  }
}

export class EngineVoice {
  /**
   * The whole engine's pitch, as a factor: the firing rate and the pulses' own tone both
   * scaled by it (below 1, a deeper engine at the same revs).
   */
  pitch = 1;
  /** Smoothed controls, so jumps in rpm or throttle never click. */
  private rpm = IDLE_RPM;
  private load = 0;
  private fire = 0;
  private countdown = 0;
  private cylinder = 0;
  private readonly active: Active[] = [];
  private readonly intake = [new Biquad(), new Biquad()];
  /**
   * The pulses played faster at high revs carry the idle recording's fine hiss up into the
   * treble with them, which a real engine at speed doesn't have: a low-pass (two
   * sections, steep) takes it off, its corner rising a little with the revs.
   */
  private readonly smooth = [new Biquad(), new Biquad()];
  private smoothAt = 0;
  private breath = 0;
  private seed = 12345;
  /** Each cylinder's own strength, for the uneven idle of a real engine. */
  private readonly bias: number[];

  constructor(
    /** Single firing pulses, each about one idle firing period long plus a tail. */
    private readonly grains: Float32Array[],
    /** The idle firing period the pulses were cut at, in samples. */
    private readonly period: number,
    private readonly sampleRate: number,
    /** How many cylinders: a four fires twice a revolution, a V8 four times. */
    private readonly cylinders = 4,
  ) {
    for (const f of this.intake) f.bandpass(1900, 0.9, sampleRate);
    const lope = [1, 0.9, 1.07, 0.95, 1.04, 0.88, 1.1, 0.97];
    this.bias = Array.from({ length: cylinders }, (_, i) => lope[i % lope.length]!);
  }

  private random(): number {
    this.seed = (this.seed * 1664525 + 1013904223) >>> 0;
    return this.seed / 4294967296;
  }

  /** Render the next block of samples (overwrites out). */
  render(out: Float32Array, p: EngineParams): void {
    const sr = this.sampleRate;
    const k = 1 - Math.exp(-1 / (sr * 0.012));
    const kLoad = 1 - Math.exp(-1 / (sr * 0.03));
    const targetRpm = Math.max(IDLE_RPM * 0.8, Math.min(REDLINE_RPM * 1.05, p.rpm));
    const targetFire = p.ignition ? 1 : 0;
    for (let i = 0; i < out.length; i++) {
      this.rpm += (targetRpm - this.rpm) * k;
      this.load += (p.load - this.load) * kLoad;
      this.fire += (targetFire - this.fire) * k * 2;
      const rpmN = (this.rpm - IDLE_RPM) / (REDLINE_RPM - IDLE_RPM);
      const firingHz = (this.rpm / 60) * (this.cylinders / 2) * this.pitch;
      const interval = sr / firingHz;
      if (--this.countdown <= 0) {
        this.spawn(interval, rpmN);
        // A little cycle-to-cycle wander, more at idle.
        const wander = 1 + (this.random() - 0.5) * (0.025 * (1 - Math.min(1, rpmN * 2)) + 0.006);
        this.countdown += interval * wander;
      }
      let s = 0;
      for (let a = this.active.length - 1; a >= 0; a--) {
        const g = this.active[a]!;
        const idx = g.pos | 0;
        const frac = g.pos - idx;
        const grain = g.grain;
        if (idx + 1 >= grain.length || g.life <= 0) {
          this.active.splice(a, 1);
          continue;
        }
        let v = grain[idx]! + (grain[idx + 1]! - grain[idx]!) * frac;
        // Fade over the last stretch of its life: a good part of it, smoothly, so cutting a
        // pulse short at high revs never clicks (each cut would add a tick of hiss).
        if (g.life < g.fade) {
          const x = g.life / g.fade;
          v *= x * x * (3 - 2 * x);
        }
        s += v * g.gain;
        g.pos += g.rate;
        g.life -= 1;
      }
      // Intake roar: noise through the intake's resonance, swelling with each firing.
      this.breath *= Math.exp(-firingHz / sr * 3);
      let n = this.random() * 2 - 1;
      for (const f of this.intake) n = f.run(n);
      const roar = n * (0.35 + this.breath) * this.load * (0.15 + 0.85 * rpmN) * this.fire * 0.1;
      // (The corner moved only now and then: recomputing it every sample is wasted work.)
      if (i % 64 === 0) {
        const fc = LOWPASS * (1 + 0.6 * Math.max(0, Math.min(1, rpmN)));
        if (Math.abs(fc - this.smoothAt) > 20) {
          this.smoothAt = fc;
          for (const f of this.smooth) f.lowpass(fc, 0.6, sr);
        }
      }
      let pulse = s;
      for (const f of this.smooth) pulse = f.run(pulse);
      out[i] = pulse + roar;
    }
  }

  private spawn(interval: number, rpmN: number): void {
    // A few clean pulses: each cylinder always fires its own (as a real engine's each
    // sound a little different, the same every time). Many raw ones: any of them.
    const grain = this.grains.length <= 16 ? this.grains[this.cylinder % this.grains.length]! : this.grains[Math.floor(this.random() * this.grains.length)]!;
    // The pulse tightens with the revs, a little: real exhaust pulses are shorter at
    // speed, but not in proportion (that's what makes a sped-up loop sound wrong).
    // (Worked out from the firing rate before the pitch, then the pitch on top, so the
    // pulses come out exactly that much lower, not lowered twice.)
    const rate = Math.max(0.8, Math.min(3, Math.pow(this.period / (interval * this.pitch), TIGHTEN))) * this.pitch;
    const cyl = this.cylinder;
    this.cylinder = (this.cylinder + 1) % this.cylinders;
    // Full combustion on the throttle, thin overrun puffs off it; louder with the revs.
    // Near idle the engine burns fuel just to keep turning; at speed with the throttle
    // shut the fuel is cut and only thin overrun puffs are left.
    const floor = 0.18 + 0.4 * (1 - Math.min(1, Math.max(0, rpmN) * 3));
    const combustion = this.fire * (floor + (1 - floor) * this.load) + (1 - this.fire) * 0.1;
    const revs = 0.22 + 0.78 * Math.pow(Math.min(1.1, Math.max(0, rpmN)), 0.85);
    const jitter = 0.95 + this.random() * 0.1;
    const gain = combustion * revs * this.bias[cyl]! * jitter;
    // Let each pulse ring through a couple of firings, then fade, so high revs give a
    // clean tone rather than a wash.
    const life = Math.min(grain.length / rate, interval * 2.2);
    this.active.push({ grain, pos: 0, rate, gain, life, fade: Math.max(0.004 * this.sampleRate, life * 0.45) });
    this.breath = Math.min(1.5, this.breath + 0.6);
    if (this.active.length > 48) this.active.shift();
  }

  /**
   * Cut single firing pulses out of a steady idle recording (mono samples). Finds the
   * firing period by autocorrelation, marks each pulse's pressure peak, and takes a
   * windowed slice around it, all levelled to the same loudness.
   */
  static fromIdle(samples: Float32Array, sampleRate: number): EngineVoice {
    const { grains, period } = EngineVoice.cut(samples, sampleRate);
    return new EngineVoice(grains, period, sampleRate);
  }

  /**
   * The same from several short stretches of idle (a recording that's mostly revving,
   * with only moments of idle between): pulses cut from each at its own firing period,
   * then all stretched to one common period.
   */
  static fromSegments(segments: Float32Array[], sampleRate: number, cylinders = 4, minHz = 20, maxHz = 120, templates = 0): EngineVoice {
    const cuts = segments
      .map((s) => EngineVoice.cut(s, sampleRate, minHz, maxHz))
      .filter((c) => c.grains.length)
      .map((c) => (templates > 0 ? { period: c.period, grains: EngineVoice.average(c.grains, templates) } : c));
    const period = Math.round(cuts.reduce((a, c) => a + c.period, 0) / Math.max(1, cuts.length));
    const grains: Float32Array[] = [];
    for (const c of cuts) {
      const k = c.period / period;
      for (const g of c.grains) {
        const n = Math.max(2, Math.round(g.length / k));
        const out = new Float32Array(n);
        for (let i = 0; i < n; i++) {
          const x = i * k;
          const j = Math.min(g.length - 2, Math.floor(x));
          out[i] = g[j]! + (g[j + 1]! - g[j]!) * (x - j);
        }
        grains.push(out);
      }
    }
    return new EngineVoice(grains, period, sampleRate, cylinders);
  }

  /**
   * Pulses averaged into a few clean ones: each lined up with the first (by where they
   * match best, within a few milliseconds), then every group averaged. The recording's
   * hiss, different in every pulse, cancels out; the pulse's own shape adds up.
   */
  private static average(grains: Float32Array[], count: number): Float32Array[] {
    const ref = grains[0]!;
    const n = ref.length;
    const shift = Math.round(n * 0.08);
    const aligned = grains.map((g) => {
      let best = 0;
      let bestC = -Infinity;
      for (let d = -shift; d <= shift; d++) {
        let c = 0;
        for (let i = 0; i < n; i += 2) c += ref[i]! * (g[i + d] ?? 0);
        if (c > bestC) {
          bestC = c;
          best = d;
        }
      }
      const out = new Float32Array(n);
      for (let i = 0; i < n; i++) out[i] = g[i + best] ?? 0;
      return out;
    });
    const groups = Math.max(1, Math.min(count, aligned.length));
    const out: Float32Array[] = [];
    for (let k = 0; k < groups; k++) {
      const members = aligned.filter((_, i) => i % groups === k);
      const m = new Float32Array(n);
      for (const g of members) for (let i = 0; i < n; i++) m[i] = m[i]! + g[i]! / members.length;
      // (Averaging lowers the level a little where pulses differ: level it back.)
      let e = 0;
      let e0 = 0;
      for (let i = 0; i < n; i++) e += m[i]! * m[i]!;
      for (const g of members) for (let i = 0; i < n; i++) e0 += g[i]! * g[i]!;
      const k2 = Math.sqrt(e0 / members.length / Math.max(1e-12, e));
      for (let i = 0; i < n; i++) m[i] = m[i]! * Math.min(3, k2);
      out.push(m);
    }
    return out;
  }

  /** A recorded stretch of idle cut into single firing pulses, and the period it fires at. */
  private static cut(samples: Float32Array, sampleRate: number, minHz = 20, maxHz = 120): { grains: Float32Array[]; period: number } {
    // A smoothed copy for finding the period and the peaks.
    const lp = new Float32Array(samples.length);
    let y1 = 0;
    let y2 = 0;
    const a = Math.exp((-2 * Math.PI * 180) / sampleRate);
    for (let i = 0; i < samples.length; i++) {
      y1 = y1 * a + samples[i]! * (1 - a);
      y2 = y2 * a + y1 * (1 - a);
      lp[i] = y2;
    }
    // Firing period: autocorrelation peak between 20 and 120 Hz over the first second
    // (normalised, so a longer lag isn't favoured just for overlapping less).
    const span = Math.min(lp.length - Math.round(sampleRate / minHz), Math.round(sampleRate));
    let best = -Infinity;
    let period = Math.round(sampleRate / 44);
    for (let L = Math.round(sampleRate / maxHz); L <= Math.round(sampleRate / minHz); L += 2) {
      let s = 0;
      let e1 = 0;
      let e2 = 0;
      for (let i = 0; i < span; i += 4) {
        s += lp[i]! * lp[i + L]!;
        e1 += lp[i]! * lp[i]!;
        e2 += lp[i + L]! * lp[i + L]!;
      }
      s /= Math.sqrt(e1 * e2) + 1e-12;
      if (s > best) {
        best = s;
        period = L;
      }
    }
    // Pressure peaks, one per period.
    const marks: number[] = [];
    let at = 0;
    let peak = 0;
    for (let i = 0; i < period; i++) if (lp[i]! > lp[peak]!) peak = i;
    at = peak;
    while (at + period * 2 < lp.length) {
      marks.push(at);
      const from = at + Math.round(period * 0.7);
      const to = at + Math.round(period * 1.3);
      let m = from;
      for (let i = from; i < to; i++) if (lp[i]! > lp[m]!) m = i;
      at = m;
    }
    // Slices: a little before the peak to a tail after it, faded at both ends.
    const before = Math.round(period * 0.15);
    const after = Math.round(period * 0.6);
    const len = before + after;
    const grains: Float32Array[] = [];
    for (const m of marks) {
      if (m - before < 0 || m + after >= samples.length) continue;
      const g = new Float32Array(len);
      let e = 0;
      for (let i = 0; i < len; i++) {
        const t = i / len;
        const fadeIn = Math.min(1, i / before);
        const fadeOut = t > 0.45 ? 0.5 + 0.5 * Math.cos(((t - 0.45) / 0.55) * Math.PI) : 1;
        const w = Math.sin((fadeIn * Math.PI) / 2) ** 2 * fadeOut;
        g[i] = samples[m - before + i]! * w;
        e += g[i]! * g[i]!;
      }
      const rms = Math.sqrt(e / len);
      if (rms < 1e-5) continue;
      grains.push(g);
      (g as Float32Array & { rms?: number }).rms = rms;
    }
    // Level them: the same average loudness, but keep a little of their natural spread.
    const mean = grains.reduce((s, g) => s + (g as Float32Array & { rms: number }).rms, 0) / Math.max(1, grains.length);
    for (const g of grains) {
      const r = (g as Float32Array & { rms: number }).rms;
      const scale = (0.25 / mean) * Math.pow(mean / r, 0.7);
      for (let i = 0; i < g.length; i++) g[i] = g[i]! * scale;
    }
    return { grains, period };
  }

  get pulseCount(): number {
    return this.grains.length;
  }

  get idlePeriod(): number {
    return this.period;
  }
}