Back to Faultline
SOURCE / PINNED RELEASE

Made of little things.

Faultline

Release
da1ffaa5624c…
Author-recorded commit
60f5f03189db…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6932b12c78c

Archive hash verified: 5a2e0492417ec4e7…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/match.ts
import { roundArena, setBroken } from './maps';
import { groundHeight } from './terrain';
import { teams, recoilFor } from './simulation';
import { arenas, clamp, type Vec } from './maps';
import {
  Bots,
  DT,
  FIRE,
  AIM,
  GOAL,
  HZ,
  ROUND,
  DUCK,
  World,
  spawn,
  stepPlayer,
  validInput,
  equipLoadout,
  type Effect,
  type Grenade,
  type Input,
  type Player,
} from './simulation';
import { Effects } from './effects';
import { Controls } from './controls';
import { Rooms, record, type Packet } from './network';
import { nextViewTick, queueCommand } from './playout';
import { Renderer } from './renderer';
import { ServerView } from './server-view';
import { encodePlayers, decodePlayers } from './snapshot';
import { guns, isPrimary, isSecondary } from './weapons';
import { settings } from './napplet-settings';
export type Seat = {
  key: string;
  id: number;
  gun: number;
  secondary: number;
  ready: boolean; // v4 compatibility with hosts that still offer ready-up.
  ping?: number;
  name: string;
  profile?: string;
};
type Frame = { tick: number; players: Player[]; grenades: Grenade[] };
export const callsigns = ['Rook', 'Flint', 'Mica', 'Sable', 'Wren', 'Slate', 'Pike', 'Ash'];
const vector = (v: unknown): v is Vec =>
  Array.isArray(v) && v.length === 3 && v.every((n) => Number.isFinite(n) && Math.abs(n) < 140);
function validEffect(v: unknown): v is Effect {
  return (
    record(v) &&
    ['shot', 'death', 'hit', 'blast', 'impact', 'blood', 'glass'].includes(String(v.kind)) &&
    vector(v.o) &&
    vector(v.v) &&
    typeof v.who === 'number' &&
    typeof v.other === 'number' &&
    (isPrimary(v.gun) || isSecondary(v.gun)) &&
    Number.isInteger(v.id)
  );
}
function decodeGrenade(v: unknown, limit: number): Grenade | null {
  if (
    !Array.isArray(v) ||
    v.length !== 4 ||
    (v[3] !== 0 && v[3] !== 1) ||
    !v.every((n) => Number.isFinite(n) && Math.abs(n) < limit)
  )
    return null;
  return { x: v[0], y: v[1], z: v[2], vx: 0, vy: 0, vz: 0, owner: -1, fuse: 0, rocket: v[3] === 1 };
}
export class Match {
  world: World | null = null;
  mine = 0;
  arena = 0;
  round = 0;
  level = arenas[0];
  private paneMask = 0;
  teamMode = false;
  scores: [number, number] = [0, 0];
  name(id: number) {
    return this.seats.find((s) => s.id === id)?.name || callsigns[id] || 'Player';
  }
  solo = false;
  paused = false;
  ended = false;
  seats: Seat[] = [];
  tick = 0;
  private bot?: Bots;
  private predicted?: Player;
  private seq = 0;
  private pending: Input[] = [];
  private sendTicks = 0;
  private queues = new Map<number, Input[]>();
  private frames: Frame[] = [];
  private anchor = 0;
  private lastFx = 0;
  private renderTick = 0;
  private lastDraw = 0;
  private correction: Vec = [0, 0, 0];
  private fx = new Effects();
  private interval = 0;
  private raf = 0;
  private last = 0;
  private accumulator = 0;
  private lastHud = '';
  private lastFeed = 0;
  private reduced = matchMedia('(prefers-reduced-motion: reduce)');
  private hud = Object.fromEntries(
    [
      'hud-map',
      'round-clock',
      'network-label',
      'health',
      'ammo',
      'frags',
      'gun-label',
      'game-message',
      'killfeed',
      'hitmark',
      'damage',
      'cross',
    ].map((id) => [id, document.getElementById(id)!]),
  );
  private renderer?: Renderer;
  private overview = new ServerView();
  constructor(
    private canvas: HTMLCanvasElement,
    private controls: Controls,
    private rooms: Rooms,
    private finished: () => void,
    private audio: (kind: 'shot' | 'blast' | 'hit', gun: number, level?: number, pan?: number) => void,
  ) {
    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      if (rect.width) this.renderer?.resize(rect.width, rect.height, settings.scale);
    };
    new ResizeObserver(resize).observe(canvas);
    window.addEventListener('gameconfig', resize);
  }
  start(round: number, arena: number, seats: Seat[], solo: boolean, teamMode = false) {
    this.stop();
    this.round = round;
    this.arena = arena;
    this.solo = solo;
    this.teamMode = teamMode;
    this.scores = [0, 0];
    this.level = roundArena(arenas[arena]);
    this.seats = seats;
    this.mine = solo ? 0 : (seats.find((s) => s.key === this.rooms.actor)?.id ?? -1);
    this.paneMask = this.level.boxes.reduce((mask, b) => mask | (b.pane ?? 0), 0);
    this.tick = this.seq = this.renderTick = this.lastFx = 0;
    this.frames = [];
    this.lastDraw = 0;
    this.correction = [0, 0, 0];
    this.pending = [];
    this.sendTicks = 0;
    this.queues.clear();
    this.ended = this.paused = false;
    this.fx.reset();
    for (const key of ['remote', 'position', 'aim', 'shots', 'ack', 'blasts'])
      delete this.canvas.dataset[key];
    this.hud.killfeed.textContent = '';
    this.lastHud = '';
    if (solo || this.rooms.host) {
      this.world = new World(arenas[arena], teamMode);
      this.level = this.world.map;
      this.scores = this.world.scores;
      for (const s of seats) this.world.add(s.id, s.gun, s.secondary);
      if (solo) {
        this.bot = new Bots(this.level);
        const [x, z, yaw] = arenas[arena].practiceContact;
        Object.assign(this.world.players.get(1)!, {
          x,
          y: groundHeight(this.level.terrain, x, z),
          z,
          yaw,
          protect: 0,
        });
      }
    }
    const seat = seats.find((s) => s.id === this.mine);
    const game = document.querySelector<HTMLElement>('#game')!;
    game.classList.toggle('spectating', !seat);
    this.canvas.setAttribute('aria-label', seat
      ? 'First-person arena. Use WASD to move and F to fire.'
      : 'Live 3D bird’s-eye view of the match');
    document.querySelector<HTMLElement>('#shell')!.hidden = true;
    game.hidden = false;
    this.hud['hud-map'].textContent = arenas[arena].name;
    this.hud['game-message'].textContent = '';
    this.hud.hitmark.hidden = true;
    if (seat) {
      this.predicted = spawn(arenas[arena], this.mine, seat.gun, 1, seat.secondary);
      this.controls.sync(this.predicted);
      this.controls.start();
    }
    this.renderer ??= new Renderer(this.canvas);
    const size = this.canvas.getBoundingClientRect();
    this.renderer.resize(size.width, size.height, settings.scale);
    this.last = performance.now();
    this.accumulator = 0;
    this.interval = window.setInterval(() => this.pump(), 1000 / HZ);
    const paint = (time: number) => {
      if (!document.hidden) this.draw(time);
      this.raf = requestAnimationFrame(paint);
    };
    this.raf = requestAnimationFrame(paint);
  }
  stop() {
    clearInterval(this.interval);
    cancelAnimationFrame(this.raf);
    this.controls.stop();
    this.round = 0;
    this.world = null;
    this.bot = undefined;
    this.predicted = undefined;
    document.querySelector<HTMLElement>('#game')!.hidden = true;
    document.querySelector<HTMLElement>('#shell')!.hidden = false;
  }
  menu(open: boolean) {
    this.paused = open;
    if (open) this.controls.stop();
    else this.controls.start();
  }
  private pump() {
    const now = performance.now();
    this.accumulator = Math.min(0.14, this.accumulator + (now - this.last) / 1000);
    this.last = now;
    while (this.accumulator >= DT) {
      this.accumulator -= DT;
      if (!this.ended && !(this.solo && (this.paused || document.hidden))) this.step();
      this.fx.step(this.level, DT);
    }
  }
  private step() {
    const me = this.world?.players.get(this.mine) ?? this.predicted;
    if (this.world) {
      const inputs = new Map<number, Input>();
      if (me) inputs.set(this.mine, this.controls.input(++this.seq, me, this.world.tick));
      for (const p of this.world.players.values())
        if (p.id !== this.mine) {
          const input = this.bot?.input(this.world, p) ?? this.queues.get(p.id)?.shift();
          if (input) inputs.set(p.id, input);
        }
      const beforeLife = me?.life;
      this.world.advance(inputs);
      this.tick = this.world.tick;
      const self = this.world.players.get(this.mine);
      if (self && self.life !== beforeLife) this.controls.sync(self);
      const events = this.world.effects.splice(0);
      for (const e of events) this.effect(e);
      if (!this.solo) {
        for (let k = 0; k < events.length; k += 36)
          this.rooms.send({ t: 'fx', r: this.round, e: events.slice(k, k + 36) });
        if (this.rooms.connected.size && (this.tick % 3 === 0 || this.world.done)) this.broadcast();
      }
      if (this.world.done) this.finish();
    } else {
      if (!me || !this.frames.length || performance.now() - this.anchor > 1600) return;
      // Clock the prediction window from actual acknowledgements. A suspended
      // host can still answer ping while its simulation advances very slowly.
      const lead = clamp(Math.ceil(this.rooms.rtt * HZ / 1000) + 9, 12, 36);
      if (this.pending.length < lead) {
        const i = this.controls.input(++this.seq, me, Math.floor(this.renderTick));
        if (stepPlayer(this.level, this.predicted!, i) & FIRE)
          this.fireLocal(this.predicted!.gun, this.predicted!.buttons);
        this.pending.push(i);
      }
      if (++this.sendTicks >= 2 && this.pending.length) {
        const packet = { t: 'input', r: this.round, b: this.pending.slice(-9) };
        if (this.rooms.transientInputs && this.rooms.fastReady) void this.rooms.snapshot(packet);
        else this.rooms.send(packet);
        this.sendTicks = 0;
      }
    }
  }
  private fireLocal(gun: number, buttons: number) {
    const kick = recoilFor(gun, buttons);
    this.fx.localShot(kick);
    this.audio('shot', gun);
    this.controls.pitch = clamp(this.controls.pitch + kick * 0.32, -1.36, 1.36);
  }
  private effect(e: Effect) {
    if (e.id <= this.lastFx) return;
    this.lastFx = e.id;
    this.fx.receive(e, this.mine, this.players());
    const listener = this.world?.players.get(this.mine) ?? this.predicted;
    if (!listener) return;
    const dx = e.o[0] - (listener?.x ?? 0),
      dz = e.o[2] - (listener?.z ?? 0),
      distance = Math.hypot(dx, dz);
    const level = 1 / (1 + distance * 0.13),
      pan = clamp(
        (dx * Math.cos(this.controls.yaw) - dz * Math.sin(this.controls.yaw)) / Math.max(2, distance),
        -0.85,
        0.85,
      );
    if (e.kind === 'shot' && e.who === this.mine && this.world)
      this.fireLocal(e.gun, listener?.buttons ?? 0);
    else if (e.kind === 'shot' && e.who !== this.mine) this.audio('shot', e.gun, level, pan);
    if (e.kind === 'blast') this.audio('blast', 0, level, pan);
    if (e.kind === 'hit' && e.who === this.mine) this.audio('hit', 0);
    if (e.kind === 'death') {
      this.hud.killfeed.textContent = this.name(e.who) + '  ›  ' + this.name(e.other);
      this.lastFeed = performance.now();
    }
  }
  private broadcast() {
    const w = this.world!;
    const packet = {
      t: 'state',
      r: this.round,
      k: w.tick,
      glass: w.map.broken ?? 0,
      scores: w.scores,
      p: encodePlayers(w.players.values()),
      g: w.grenades.map((g) => [
        Math.round(g.x * 100) / 100,
        Math.round(g.y * 100) / 100,
        Math.round(g.z * 100) / 100,
        Number(!!g.rocket),
      ]),
      end: w.done,
    };
    if (w.done) this.rooms.send(packet);
    else void this.rooms.snapshot(packet);
  }
  packet(from: string, msg: Packet) {
    if (!this.round || msg.r !== this.round) return;
    if (this.world) {
      const seat = this.seats.find((s) => s.key === from),
        p = seat && this.world.players.get(seat.id);
      if (seat && p && msg.t === 'equip' && isPrimary(msg.primary) && isSecondary(msg.secondary)) {
        this.setSeatLoadout(seat, msg.primary, msg.secondary);
        return;
      }
      if (!p || msg.t !== 'input' || !Array.isArray(msg.b) || msg.b.length > 9) return;
      let queue = this.queues.get(p.id);
      if (!queue) {
        queue = [];
        this.queues.set(p.id, queue);
      }
      for (const i of msg.b) {
        if (validInput(i) && i[6] === p.life) queueCommand(queue, i, p.ack, p.buttons);
      }
      return;
    }
    if (from !== this.rooms.owner) return;
    if (msg.t === 'fx' && Array.isArray(msg.e) && msg.e.length <= 80) {
      for (const e of msg.e) if (validEffect(e)) this.effect(e);
      return;
    }
    if (
      msg.t !== 'state' ||
      typeof msg.k !== 'number' ||
      !Number.isInteger(msg.k) ||
      msg.k <= this.tick ||
      msg.k > ROUND ||
      !Array.isArray(msg.g) ||
      msg.g.length > 32
    )
      return;
    const glass = msg.glass,
      scores = msg.scores;
    const allowed = this.paneMask;
    if (
      typeof glass !== 'number' ||
      !Number.isSafeInteger(glass) ||
      glass < 0 ||
      glass > allowed ||
      (glass & ~allowed) !== 0 ||
      !Array.isArray(scores) ||
      scores.length !== 2 ||
      !scores.every((n) => Number.isInteger(n) && n >= 0 && n <= GOAL + 8)
    )
      return;
    const players = decodePlayers(msg.p, this.level.size),
      grenades = msg.g.map((v) => decodeGrenade(v, this.level.size + 32));
    if (!players || grenades.some((g) => !g)) return;
    const mine = players.find((p) => p?.id === this.mine);
    if (!mine) return;
    const life = mine.life !== this.predicted?.life;
    setBroken(this.level, glass);
    this.scores = [scores[0], scores[1]];
    this.tick = msg.k;
    this.seq = Math.max(this.seq, mine.ack);
    this.anchor = performance.now();
    this.frames.push({ tick: this.tick, players, grenades: grenades as Grenade[] });
    if (this.frames.length > 18) this.frames.shift();
    this.pending = this.pending.filter((i) => i[0] > mine.ack && i[6] === mine.life);
    const before = this.predicted;
    this.predicted = { ...mine };
    for (const i of this.pending) stepPlayer(this.level, this.predicted, i);
    if (before && !life && before.hp && mine.hp) {
      const offset: Vec = [before.x - this.predicted.x + this.correction[0],
        before.y - this.predicted.y + this.correction[1], before.z - this.predicted.z + this.correction[2]];
      this.correction = Math.hypot(...offset) < 1 ? offset : [0, 0, 0];
    } else this.correction = [0, 0, 0];
    if (life) this.controls.sync(mine);
    if (msg.end === true) this.finish();
  }
  private setSeatLoadout(seat: Seat, primary: number, secondary: number) {
    seat.gun = primary;
    seat.secondary = secondary;
    const p = this.world?.players.get(seat.id);
    if (p) equipLoadout(p, primary, secondary);
  }
  changeLoadout(primary: number, secondary: number) {
    const seat = this.seats.find((s) => s.id === this.mine);
    if (!seat || !this.round || this.ended) return false;
    if (!this.world && !this.rooms.connected.has(this.rooms.owner)) return false;
    this.setSeatLoadout(seat, primary, secondary);
    if (!this.world) this.rooms.send({ t: 'equip', r: this.round, primary, secondary });
    return true;
  }
  sendFinalState() {
    if (this.world?.done) this.broadcast();
  }
  updateSeats(seats: Seat[]) {
    const previous = this.seats;
    this.seats = seats;
    if (!this.world) return;
    for (const p of this.world.players.values())
      if (!seats.some((s) => s.id === p.id && s.key === previous.find((old) => old.id === p.id)?.key)) {
        this.world.remove(p.id);
        this.queues.delete(p.id);
      }
    for (const s of seats) if (!this.world.players.has(s.id)) this.world.add(s.id, s.gun, s.secondary);
  }
  players(): Player[] {
    return this.world ? [...this.world.players.values()] : (this.frames.at(-1)?.players ?? []);
  }
  private finish() {
    if (this.ended) return;
    this.ended = true;
    this.controls.stop();
    this.finished();
  }
  private draw(time: number) {
    const me = this.world?.players.get(this.mine) ?? this.predicted;
    const remaining = Math.max(0, Math.ceil((ROUND - this.tick) / HZ));
    const clock = Math.floor(remaining / 60) + ':' + String(remaining % 60).padStart(2, '0');
    if (this.world && this.mine === -1) {
      const players = this.players();
      const camera = this.renderer?.render(this.level, undefined, players, this.world.grenades, this.fx, time, this.reduced.matches, this.teamMode);
      if (camera) this.overview.draw(camera, players, id => this.name(id), this.teamMode);
      this.canvas.dataset.seat = String(this.mine);
      this.canvas.dataset.blasts = String(this.fx.blasts.length);
      const label = 'Dedicated host · ' + players.length + (players.length === 1 ? ' player' : ' players');
      if (this.hud['network-label'].textContent !== label) this.hud['network-label'].textContent = label;
      if (this.hud['round-clock'].textContent !== clock) this.hud['round-clock'].textContent = clock;
      return;
    }
    if (!me || !this.renderer) return;
    let others = this.players(),
      grenades = this.world?.grenades ?? this.frames.at(-1)?.grenades ?? [];
    const elapsed = this.lastDraw ? Math.max(0, time - this.lastDraw) : 0;
    this.lastDraw = time;
    if (!this.world && this.frames.length) {
      const t = nextViewTick(this.renderTick, this.tick, Math.max(0, time - this.anchor), elapsed);
      this.renderTick = t;
      const end = this.frames.findIndex((f) => f.tick >= t),
        b = this.frames[Math.max(0, end)],
        a = this.frames[Math.max(0, end - 1)];
      const f = clamp((t - a.tick) / Math.max(1, b.tick - a.tick), 0, 1);
      others = b.players.map((p) => {
        const old = a.players.find((q) => q.id === p.id);
        if (!old || old.life !== p.life || old.hp === 0 || !p.hp) return p;
        const delta = Math.atan2(Math.sin(p.yaw - old.yaw), Math.cos(p.yaw - old.yaw));
        return {
          ...p,
          x: old.x + (p.x - old.x) * f,
          y: old.y + (p.y - old.y) * f,
          z: old.z + (p.z - old.z) * f,
          yaw: old.yaw + delta * f,
          pitch: old.pitch + (p.pitch - old.pitch) * f,
        };
      });
      grenades = b.grenades;
    }
    const view = { ...me, yaw: this.controls.yaw, pitch: this.controls.pitch };
    const decay = Math.exp(-elapsed / 65);
    for (const [index, axis] of (['x', 'y', 'z'] as const).entries()) {
      this.correction[index] *= decay;
      view[axis] += this.correction[index];
    }
    this.canvas.dataset.viewTick = this.renderTick.toFixed(2);
    this.renderer.render(
      this.level,
      view,
      others,
      grenades,
      this.fx,
      time,
      this.reduced.matches,
      this.teamMode,
    );
    // These samples are the camera position and feedback actually submitted to the renderer.
    this.canvas.dataset.position = [view.x, view.z].map((v) => v.toFixed(3)).join(',');
    this.canvas.dataset.aim = view.yaw.toFixed(3);
    this.canvas.dataset.lean = String(view.lean);
    this.canvas.dataset.crouch = String(Boolean(view.buttons & 4));
    this.canvas.dataset.glass = String(this.level.broken ?? 0);
    this.canvas.dataset.shots = String(this.fx.shotCount);
    this.canvas.dataset.blasts = String(this.fx.blasts.length);
    this.canvas.dataset.seat = String(this.mine);
    this.canvas.dataset.ack = String(me.ack);
    this.canvas.dataset.remote = others
      .filter((q) => q.id !== this.mine)
      .map((q) => [q.id, q.x.toFixed(2), q.z.toFixed(2), q.pitch.toFixed(2), Number(Boolean(q.buttons & DUCK))].join(','))
      .join('|');
    const gun = guns[me.gun];
    const label = this.solo
      ? 'Practice · 3 bots'
      : this.rooms.host
        ? 'Room host · ' + (this.rooms.fastReady ? 'Realtime' : 'Reliable')
        : this.rooms.connected.size && this.frames.length && performance.now() - this.anchor < 1600
          ? this.rooms.rtt
            ? this.rooms.rtt + ' ms'
            : 'Connected'
          : 'Reconnecting';
    const key = [
      remaining,
      this.scores.join('-'),
      me.gun,
      Math.ceil(me.cook / 6),
      me.hp,
      me.ammo,
      me.frags,
      me.kills,
      Math.ceil(me.respawn / 60),
      Boolean(me.reload),
      label,
    ].join('|');
    if (key !== this.lastHud) {
      this.lastHud = key;
      this.hud['round-clock'].textContent = clock;
      this.hud['network-label'].textContent =
        label +
        ' · ' +
        (this.teamMode
          ? teams[me.id % 2] + ' · Amber ' + this.scores[0] + ' / Slate ' + this.scores[1]
          : me.kills + '/' + GOAL);
      this.hud.health.textContent = String(me.hp);
      this.hud.ammo.textContent = me.ammo + ' / ' + gun.mag;
      this.hud.frags.textContent = me.frags + ' FRAG';
      this.hud['gun-label'].textContent = (isPrimary(me.gun) ? '1 · ' : '2 · ') + gun.name;
      this.hud['game-message'].textContent = !me.hp
        ? 'Respawn in ' + Math.ceil(me.respawn / 60)
        : me.cook
          ? 'Frag · ' + (Math.ceil(me.cook / 6) / 10).toFixed(1) + ' s'
          : me.reload
            ? 'Reloading…'
            : '';
    }
    this.hud.cross.hidden = Boolean(view.buttons & AIM) || !view.hp;
    this.hud.hitmark.hidden = this.fx.hit <= 0;
    this.hud.damage.style.opacity = String(Math.min(0.9, this.fx.hurt * 2));
    if (this.fx.hurt > 0) {
      const angle = this.fx.damageBearing - view.yaw;
      this.hud.damage.style.setProperty('--hit-x', 50 + 50 * Math.sin(angle) + '%');
      this.hud.damage.style.setProperty('--hit-y', 50 - 50 * Math.cos(angle) + '%');
    }
    if (this.lastFeed && time - this.lastFeed > 3800) {
      this.hud.killfeed.textContent = '';
      this.lastFeed = 0;
    }
  }
}