Build your room

Recording matches (rec)

Record every match to a .bkrp file of a few KB and watch it on our website, with a timeline, goals and chat.

A "rec" records your room's matches so you can watch them later: settle a disputed goal, keep a nice play, show a final. The rec.ts file in the example project records every match to replays/<date>.bkrp, and that file opens directly on our website:

bonktools.com.br/en/replays/abrir — drag the file onto the page. Nothing is uploaded: the file is read in your browser. You can even export the match as an MP4 video.

How a replay fits in a few KB

bonk.io is deterministic: with the same initial state and the same keys, the physics always gives the same result. So we don't need to record a video, only:

  • the match's initial state (is) and settings (gs), which arrive in the game-start event;
  • each player's keys, with the frame in which they were pressed;
  • the match chat.

So the website can draw the match without running the physics in the browser, we also store the track: the positions of the ball and of each player over time, taken from the ScoreTracker simulation the room already runs for the score.

Where each piece comes from

DataEventNote
is, gsroom.on('game-start')Start of the match
Keysroom.on('peer-input') + parseInputFrame()Arrive over WebRTC; become [frame, id, keys, counter]
Chatroom.on('chat-message')Recorded with the approximate frame
Positionstracker.on('state')Every 100 ms (3 frames)
Goals and scoretracker.on('score')Frame and team of each goal
Winnertracker.on('match-winner')
Endroom.on('game-end')Time to save

The .bkrp format

text
"BKRP" (4 bytes)  +  version (1 byte = 1)  +  gzip( JSON )

The JSON has these fields:

FieldContent
version, fps1 and 30
startedAtstart, in milliseconds since 1970
gs, ismatch settings and initial state
players{ id, name, team, guest, level } of each one
inputs[frame, id, keys, counter], sorted by frame and counter. Keys: left 1, right 2, up 4, down 8, kick 16, special 32
durationFrames, scores, winnerTeamduration, score by team id (2 red, 3 blue) and winner
chat[frame, name, text]
trackthe track for the website to draw (below)

The track (track, version 1, football)

FieldContent
v, step1 and every how many frames there is a sample (the example uses 3)
nsamples per entity
entsthe ball first ({k:'b'}), then one disc per player ({k:'d', id, team, name})
dthe positions: for each entity, n (x, y) pairs in hundredths, each value as a difference from the previous one, encoded as zigzag + varint and then base64
goals[frame, team] of each goal
startframe at which the initial freeze ends
field, rfield measurements (from the initial state) and disc and ball radii

Small differences take 1 or 2 bytes each: a 3-minute match fits in a few dozen KB.

The full code

ts
// rec.ts
import { mkdirSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { gzipSync } from 'node:zlib';
import {
  decodeInitialState, parseInputFrame,
  type BonkRoom, type ChatMessagePacket, type GameStartPacket, type MatchWinnerInfo,
  type PeerInputEvent, type ScoreInfo, type ScoreTracker, type StateInfo,
} from 'bonktools';

type Corpo = { x: number; y: number } | null | undefined;
type Estado = { ball?: Corpo; discs?: Corpo[] | null; ftu?: number };

/** What goes inside the .bkrp (the same format as the BonkTools rooms: the site opens it and the player draws it). */
interface Replay {
  version: 1;
  startedAt: number;
  fps: 30;
  gs: unknown;
  is: string;
  players: { id: number; name: string; team: number; guest: boolean; level: number }[];
  inputs: [number, number, number, number][]; // [frame, player id, keys, counter]
  durationFrames: number;
  scores: number[];
  winnerTeam: number | null;
  clientHash: string | null;
  track: unknown;
  chat: [number, string | null, string][];
}

/**
 * Records every match to `pasta/<date>.bkrp`.
 *
 * The game is deterministic: initial state (is) + settings (gs) + each player's keys are enough
 * to reproduce everything. We also store the "track" (ball and disc positions), taken from the
 * ScoreTracker simulation, so the site only has to draw the match.
 */
export class Gravador {
  private atual: Replay | null = null;
  private amostras = new Map<number, Estado>(); // frame -> state
  private gols: [number, number][] = [];

  constructor(
    private readonly room: BonkRoom,
    private readonly tracker: ScoreTracker,
    private readonly pasta = 'replays',
  ) {
    room.on('game-start', this.aoComecar);
    room.on('peer-input', this.aoTeclar);
    room.on('chat-message', this.aoFalar);
    room.on('game-end', this.salvar);
    tracker.on('state', this.aoSimular);
    tracker.on('score', this.aoGol);
    tracker.on('match-winner', this.aoVencer);
  }

  private readonly aoComecar = (p: GameStartPacket): void => {
    if (!p.is) return;
    this.amostras.clear();
    this.gols = [];
    this.atual = {
      version: 1, startedAt: Date.now(), fps: 30, gs: p.gs ?? null, is: p.is,
      players: [...this.room.state.players.values()].map((j) => ({ id: j.id, name: j.userName, team: j.team, guest: j.guest, level: j.level })),
      inputs: [], durationFrames: 0, scores: [], winnerTeam: null, clientHash: null, track: null, chat: [],
    };
  };

  // Players' keys arrive over WebRTC; each packet becomes [frame, id, keys, counter].
  private readonly aoTeclar = (ev: PeerInputEvent): void => {
    const k = parseInputFrame(ev.data);
    if (k && this.atual) this.atual.inputs.push([k.f, ev.playerId, k.i, k.c]);
  };

  private readonly aoFalar = (m: ChatMessagePacket): void => {
    if (!this.atual) return;
    const nome = this.room.state.players.get(m.id)?.userName ?? null;
    this.atual.chat.push([this.ultimoFrame(), nome, m.message.slice(0, 500)]);
  };

  private readonly aoSimular = (info: StateInfo): void => {
    if (this.atual) this.amostras.set(info.frame, info.state as Estado);
  };

  private readonly aoGol = (s: ScoreInfo): void => {
    this.gols.push([s.frame, s.team]);
    if (this.atual) this.atual.scores = s.scores;
  };

  private readonly aoVencer = (w: MatchWinnerInfo): void => {
    if (this.atual) this.atual.winnerTeam = w.team;
  };

  /** A bot that PLAYS (the AI) must also record its own keys: the server doesn't echo them to the host. */
  teclaPropria(id: number, k: { i: number; f: number; c: number }): void {
    this.atual?.inputs.push([k.f, id, k.i, k.c]);
  }

  private ultimoFrame(): number {
    let f = -1;
    for (const k of this.amostras.keys()) f = Math.max(f, k);
    return f;
  }

  private readonly salvar = (): void => {
    const r = this.atual;
    this.atual = null;
    if (!r || this.amostras.size < 10) return; // a match that never really started
    r.durationFrames = this.ultimoFrame();
    r.inputs.sort((a, b) => a[0] - b[0] || a[3] - b[3] || a[1] - b[1]);
    r.track = this.trilha(r);
    const corpo = gzipSync(Buffer.from(JSON.stringify(r)), { level: 9 });
    const arquivo = Buffer.concat([Buffer.from('BKRP'), Buffer.from([1]), corpo]); // signature + version + gzip(JSON)
    mkdirSync(this.pasta, { recursive: true });
    const nome = path.join(this.pasta, `${new Date(r.startedAt).toISOString().replace(/[:.]/g, '-')}.bkrp`);
    writeFileSync(nome, arquivo);
    console.log(`[rec] partida salva: ${nome} (${(arquivo.length / 1024).toFixed(0)} KB)`);
  };

  /** Track v1 (football): positions every `step` frames, in hundredths, as zigzag varint deltas. */
  private trilha(r: Replay): unknown {
    const step = 3; // the ScoreTracker steps every 100 ms = 3 frames
    const frames = [...this.amostras.keys()].sort((a, b) => a - b);
    const ultimo = frames.at(-1)!;
    const naoEspec = r.players.filter((p) => p.team > 0);
    const ents = [{ k: 'b' }, ...naoEspec.map((p) => ({ k: 'd', id: p.id, team: p.team, name: p.name.slice(0, 32) }))];
    // latest sample up to frame f
    let i = 0;
    const em = (f: number): Estado => {
      while (i + 1 < frames.length && frames[i + 1]! <= f) i++;
      return this.amostras.get(frames[i]!)!;
    };
    const valores: number[] = [];
    const serie = (pega: (e: Estado) => Corpo) => {
      i = 0;
      let px = 0, py = 0, ult = { x: 0, y: 0 };
      for (let f = 0; f <= ultimo; f += step) {
        const p = pega(em(f)) ?? ult;
        ult = p;
        const x = Math.round(p.x * 100), y = Math.round(p.y * 100);
        valores.push(x - px, y - py);
        px = x;
        py = y;
      }
    };
    serie((e) => e.ball);
    for (const p of naoEspec) serie((e) => e.discs?.[p.id]);
    const ini = decodeInitialState(r.is) as unknown as Record<string, unknown>;
    const num = (k: string, padrao: number) => (typeof ini[k] === 'number' ? (ini[k] as number) : padrao);
    const comeco = frames.find((f) => (this.amostras.get(f)!.ftu ?? 0) <= 0) ?? 0;
    return {
      v: 1, step, n: Math.floor(ultimo / step) + 1, ents, d: varints(valores).toString('base64'),
      goals: this.gols, start: comeco,
      field: { ppm: num('ppm', 11), goalHeight: num('goalHeight', 13), border: num('borderThickness', 5),
        xInner: num('borderThicknessXInner', 25), yInner: num('borderThicknessYInner', 70), w: 730, h: 500 },
      r: { disc: 1.06, ball: 0.7 },
    };
  }

  destroy(): void {
    this.room.off('game-start', this.aoComecar);
    this.room.off('peer-input', this.aoTeclar);
    this.room.off('chat-message', this.aoFalar);
    this.room.off('game-end', this.salvar);
    this.tracker.off('state', this.aoSimular);
    this.tracker.off('score', this.aoGol);
    this.tracker.off('match-winner', this.aoVencer);
  }
}

/** Signed integers -> zigzag -> varint (7 bits per byte). */
function varints(valores: number[]): Buffer {
  const out: number[] = [];
  for (const v of valores) {
    let z = v >= 0 ? v * 2 : -v * 2 - 1;
    while (z >= 128) {
      out.push((z % 128) | 128);
      z = Math.floor(z / 128);
    }
    out.push(z);
  }
  return Buffer.from(out);
}

Going further

  • Stats and ranking. The same events give you everything for a !status: count wins with winnerTeam and goals with score. The "goal scorer" is the player from the scoring team who touched the ball last, and you can find them from the track (the disc closest to the ball in the frames before the goal). Store it in a JSON file or SQLite.
  • Publishing replays. Send the .bkrp to a Discord channel (see Discord integration) or to your own website.
  • Replay as video on Discord. The website exports MP4 in the browser; on a server, you can draw the frames from the track and pipe them through ffmpeg.