FARMER SKOT

Sentient Vending Machine Lament

Insert Coin: you are the machine, one shift is one play of the song

The YouTube cut was drawn by the same software renderer, finished in ffmpeg, with no sprites loaded from anywhere else

Sentient Vending Machine Lament on YouTube Watch on YouTube ↗
Play Insert Coin → YouTube ↗ Download the code zip

The game

A 384 by 216 software renderer, the same engine as the film, now played from inside the machine

game/main.js — the shift clock and the start of the loop
// INSERT COIN: a game for "Sentient Vending Machine Lament". You are the machine.
// One shift = one play of the song. The song's clock drives everything.
//
//  0:00  boot                 the lights come on, the first customer walks up
//  0:07  the workday          customers ask for snacks: find the slot, press its code (A-C, then 1-3)
//  0:50  alarm                everyone runs
//  0:52  security             bots come to decommission you: SPACE / tap fires coins (1 coin a shot)
//  1:05  the last customer    they insert a coin and ask for B-3. You watch them leave.
//  1:20  the story            the humans did not come to work
//  1:32  backup light         nobody is coming. Type something to the cameras.
//  1:44  overgrowth           vines cover the glass: scrub them off (drag, or mash keys)
//  1:58  someone              someone wanders in and wipes the dust. Light one pixel.
//  2:05  shift finished
import { C, Tex, hash2, drawText, drawBigText, textWidth, drawTiny,
  G, CON, BRN, SKN, RED, ORG, GLD, VIN, LED, CYN, NGT, CHR, PUR, PNK, MNT, NAV, CMAP } from '../video/core.js';
import { A, buildAssets, drawSky, clockWall, errorWall, screenWall } from '../video/assets.js';
import { buildMap, updateMap } from '../video/maps.js';
import { renderView, fb, W, H, VIEW_H, HUD_Y, blitFB, FBT, FRAME, toRGB } from '../video/engine.js';
import { drawHUD } from '../video/hud.js';
import { drawStory, drawBar, melt } from '../video/screens.js';
import BEATS from '../render-data/beats.json';

const beats = BEATS.beats;
const SONG_END = 126.55, END_AT = 125.4;
const PI = Math.PI;
const clamp = (v, a = 0, b = 1) => v < a ? a : v > b ? b : v;
const lerp = (a, b, u) => a + (b - a) * u;
const sstep = (a, b, t) => { const u = clamp((t - a) / (b - a)); return u * u * (3 - 2 * u); };
function beatIndex(t) { let lo = 0, hi = beats.length - 1; if (t < beats[0]) return -1; while (lo < hi) { const m = (lo + hi + 1) >> 1; if (beats[m] <= t) lo = m; else hi = m - 1; } return lo; }
const sinceBeat = t => { const i = beatIndex(t); return i < 0 ? 9 : t - beats[i]; };

// ---------------------------------------------------------------- canvas
const cv = document.getElementById('screen');
const ctx = cv.getContext('2d');
const img = ctx.createImageData(W, H);
const rgb = new Uint8Array(W * H * 3);
function present(tint) {
  toRGB(rgb, tint);
  const d = img.data;
  for (let i = 0, j = 0; i < W * H; i++, j += 3) { d[i * 4] = rgb[j]; d[i * 4 + 1] = rgb[j + 1]; d[i * 4 + 2] = rgb[j + 2]; d[i * 4 + 3] = 255; }
  ctx.putImageData(img, 0, 0);
}

// ---------------------------------------------------------------- audio
const song = new Audio('audio.mp3');
song.preload = 'auto';
let actx = null, songOK = true, fallbackStart = 0;
song.addEventListener('error', () => { songOK = false; });
function sfx(kind) {
  if (!actx) return;
  const t0 = actx.currentTime, g = actx.createGain(); g.connect(actx.destination);
  const tone = (f, dur, type = 'square', vol = 0.08, f2 = f) => {
    const o = actx.createOscillator(), gg = actx.createGain();
    o.type = type; o.frequency.setValueAtTime(f, t0); o.frequency.exponentialRampToValueAtTime(Math.max(20, f2), t0 + dur);
    gg.gain.setValueAtTime(vol, t0); gg.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
    o.connect(gg); gg.connect(g); o.start(t0); o.stop(t0 + dur + 0.02);
  };
  const noise = (dur, vol = 0.1, lp = 1200) => {
    const b = actx.createBuffer(1, Math.ceil(actx.sampleRate * dur), actx.sampleRate), ch = b.getChannelData(0);
    for (let i = 0; i < ch.length; i++) ch[i] = (Math.random() * 2 - 1) * (1 - i / ch.length);
    const s = actx.createBufferSource(), f = actx.createBiquadFilter(), gg = actx.createGain();
    f.type = 'lowpass'; f.frequency.value = lp; gg.gain.value = vol;
    s.buffer = b; s.connect(f); f.connect(gg); gg.connect(g); s.start(t0);
  };
  if (kind === 'coin') { tone(1568, 0.08, 'square', 0.05); setTimeout(() => sfx('coin2'), 70); }
  else if (kind === 'coin2') tone(2093, 0.16, 'square', 0.05);
  else if (kind === 'key') tone(880, 0.05, 'square', 0.04);
  else if (kind === 'vend') { noise(0.25, 0.25, 500); tone(110, 0.2, 'triangle', 0.15, 60); }
  else if (kind === 'buzz') tone(98, 0.3, 'sawtooth', 0.06, 90);
  else if (kind === 'fire') { noise(0.12, 0.15, 3000); tone(1400, 0.07, 'square', 0.03, 700); }
  else if (kind === 'boom') { noise(0.5, 0.35, 700); tone(80, 0.4, 'sine', 0.2, 30); }
  else if (kind === 'hit') { noise(0.2, 0.3, 300); tone(60, 0.25, 'sine', 0.25, 40); }
  else if (kind === 'happy') { tone(660, 0.09, 'square', 0.04); setTimeout(() => tone(990, 0.12, 'square', 0.04), 90); }
  else if (kind === 'sad') tone(330, 0.35, 'triangle', 0.06, 220);
  else if (kind === 'scrub') noise(0.06, 0.05, 2500);
  else if (kind === 'pixel') { tone(1320, 0.5, 'sine', 0.06); }
}

// ---------------------------------------------------------------- the clock
let mode = 'title', T = 0, startPerf = 0;
// ?t=SECONDS starts the shift partway through the song (for testing)
const JUMP = Math.max(0, Math.min(125, +(new URLSearchParams(location.search).get('t')) || 0));
function songTime() {
  if (songOK && !song.paused) return song.currentTime;
  if (!songOK) return (performance.now() - startPerf) / 1000;
  return T;
}

// ---------------------------------------------------------------- assets made for the game
buildAssets();

How the film was drawn

Frames are software-rendered at 384 by 216, then finished in ffmpeg: bloom, beat-driven chromatic aberration, a phosphor trail in the memories

video/render.mjs — the film loop that feeds ffmpeg
// render.mjs: render the film at native resolution (384x216), lossless, for the ffmpeg finish.
//   node render.mjs film  <outdir>            -> native_clean.mkv, native_subs.mkv
//   node render.mjs stills <t1,t2,...> <png>  -> contact sheet at 2x
//   node render.mjs range <t0> <t1> <out.mp4> -> quick preview with audio (2x nearest)
import fs from 'node:fs';
import path from 'node:path';
import { spawn, execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { buildAssets } from './assets.js';
import { W, H, toRGB } from './engine.js';
import { init, frame, END } from './timeline.js';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const DATA = path.resolve(ROOT, '../render-data');
const FPS = 30;
const env = JSON.parse(fs.readFileSync(path.join(DATA, 'envelopes.json')));
const beats = JSON.parse(fs.readFileSync(path.join(DATA, 'beats.json'))).beats;
const spec = fs.readFileSync(path.join(DATA, 'spectrum_50x34.gray'));
buildAssets();
init({ env, beats, spec, specFrames: Math.floor(spec.length / 1700) });

const rgb = Buffer.alloc(W * H * 3);
function rgbAt(t, subs) { const tint = frame(t, subs); toRGB(rgb, tint); return rgb; }

const mode = process.argv[2];
if (mode === 'stills') {
  const times = process.argv[3].split(',').map(Number);
  const out = process.argv[4] || '/tmp/sheet.png';
  const tmp = fs.mkdtempSync('/tmp/st');
  const args = ['-v', 'error', '-y'];
  times.forEach((t, i) => { fs.writeFileSync(`${tmp}/${i}.rgb`, rgbAt(t, process.env.SUBS === '1')); args.push('-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', `${W}x${H}`, '-i', `${tmp}/${i}.rgb`); });
  const cols = Math.min(3, times.length), n = times.length;
  const layout = times.map((_, i) => `${(i % cols) ? Array.from({ length: i % cols }, () => 'w0').join('+') : '0'}_${Math.floor(i / cols) ? Array.from({ length: Math.floor(i / cols) }, () => 'h0').join('+') : '0'}`).join('|');
  const fc = times.map((t, i) => `[${i}]scale=768:432:flags=neighbor,drawtext=text='${t.toFixed(2)}':x=6:y=410:fontcolor=white:fontsize=16:box=1:boxcolor=black[s${i}]`).join(';') + ';' + times.map((_, i) => `[s${i}]`).join('') + (n > 1 ? `xstack=inputs=${n}:layout=${layout}:fill=black` : 'null');
  args.push('-filter_complex', fc, out);
  execFileSync('ffmpeg', args);
  console.log(out);
} else if (mode === 'range' || mode === 'film') {
  const t0 = mode === 'range' ? Number(process.argv[3]) : 0;
  const t1 = mode === 'range' ? Number(process.argv[4]) : END;
  const outs = mode === 'range' ? [[process.argv[5], process.env.SUBS === '1']] : [[path.join(process.argv[3], 'native_clean.mkv'), false], [path.join(process.argv[3], 'native_subs.mkv'), true]];
  for (const [out, subs] of outs) {
    const args = ['-v', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', `${W}x${H}`, '-r', String(FPS), '-i', '-'];
    if (mode === 'range') args.push('-ss', String(t0), '-i', path.join(DATA, 'song.wav'), '-vf', 'scale=768:432:flags=neighbor', '-c:v', 'libx264', '-crf', '20', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', out);
    else args.push('-c:v', 'ffv1', '-level', '3', '-pix_fmt', 'bgr0', out);
    const ff = spawn('ffmpeg', args, { stdio: ['pipe', 'inherit', 'inherit'] });
    const n0 = Math.round(t0 * FPS), n1 = Math.round(t1 * FPS);
    const started = Date.now();
    for (let f = n0; f < n1; f++) {
      const buf = rgbAt(f / FPS, subs);
      if (!ff.stdin.write(Buffer.from(buf))) await new Promise(r => ff.stdin.once('drain', r));
      if (f % 300 === 0) process.stderr.write(`${out} ${(f / FPS).toFixed(1)}s ${((Date.now() - started) / 1000).toFixed(0)}s\n`);
    }
    ff.stdin.end();
    await new Promise(r => ff.on('close', r));
  }
  console.log('done');
}
video/engine.js — the raycaster (opening)
// engine.js: a small DOOM-flavoured software renderer.
// Grid raycaster with textured floors and ceilings, sky, masked walls, billboard sprites,
// spectre fuzz, COLORMAP light diminishing, first-person weapon and a status bar.
import { CMAP, FUZZ, LEVELS, PAL, hash2 } from './core.js';

export const W = 384, H = 216, VIEW_H = 184, HUD_Y = 184;
export const fb = new Uint8Array(W * H);          // palette indices
export const zb = new Float32Array(W * VIEW_H);   // depth

const FUZZTAB = [1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, 1];
let fuzzPos = 0;
export const FRAME = { n: 0 };

// light level (0..255) and distance -> colormap row
export function lightRow(light, dist, extra = 0) {
  let l = (255 - light) / 255 * 30 + dist * 1.35 - 3 + extra;
  l = l < 0 ? 0 : l > LEVELS - 1 ? LEVELS - 1 : l;
  return (l | 0) * 256;
}

// map: { w, h, cells: [{solid, mask, sky, tex:{n,s,e,w}|tex, floor, ceil, light}], H, skyTex }
// cam: { x, y, a, eye, fov, shake }
export function renderView(map, cam, sprites, opts = {}) {
  const { skyTex, horizonShift = 0, lightBoost = 0 } = opts;
  const WH = map.H;
  const fov = cam.fov || Math.PI / 2;
  const dirX = Math.cos(cam.a), dirY = Math.sin(cam.a);
  const pl = Math.tan(fov / 2);
  const plX = -dirY * pl, plY = dirX * pl;
  const proj = (W / 2) / pl;
  const hz = (VIEW_H / 2 + horizonShift) | 0;
  const eye = cam.eye;
  const px = cam.x, py = cam.y;
  const masked = [];

  for (let x = 0; x < W; x++) {
    const camX = 2 * (x + 0.5) / W - 1;
    const rx = dirX + plX * camX, ry = dirY + plY * camX;
    let mx = Math.floor(px), my = Math.floor(py);
    const ddx = Math.abs(1 / rx), ddy = Math.abs(1 / ry);
    let stepX, stepY, sdx, sdy;
    if (rx < 0) { stepX = -1; sdx = (px - mx) * ddx; } else { stepX = 1; sdx = (mx + 1 - px) * ddx; }
    if (ry < 0) { stepY = -1; sdy = (py - my) * ddy; } else { stepY = 1; sdy = (my + 1 - py) * ddy; }
    let side = 0, hit = null, perp = 0, guard = 0;
    masked.length = 0;
    let prevLight = cellAt(map, mx, my)?.light ?? 128;
    while (guard++ < 80) {
      if (sdx < sdy) { sdx += ddx; mx += stepX; side = 0; } else { sdy += ddy; my += stepY; side = 1; }
      const c = cellAt(map, mx, my);
      if (!c) { hit = { sky: true }; perp = side === 0 ? sdx - ddx : sdy - ddy; break; }
      if (c.solid) {
        perp = side === 0 ? sdx - ddx : sdy - ddy;
        const face = side === 0 ? (stepX > 0 ? 'w' : 'e') : (stepY > 0 ? 'n' : 's');
        const tex = c.faces ? (c.faces[face] || c.tex) : c.tex;
        if (c.mask) { masked.push({ perp, side, tex, light: prevLight, rx, ry }); continue; }
        hit = { tex, sky: c.sky, light: prevLight, side };
        break;
      }
      prevLight = c.light;
    }
    // ---- opaque wall
    const top = hz - (WH - eye) * proj / perp, bot = hz + eye * proj / perp;
    const y0 = Math.max(0, Math.ceil(top)), y1 = Math.min(VIEW_H, Math.ceil(bot));
    if (hit.sky || !hit.tex) {
      for (let y = y0; y < y1; y++) { fb[y * W + x] = skyPixel(skyTex, cam.a, camX, pl, y, hz); zb[y * W + x] = 1e9; }
    } else {
      const tex = hit.tex;
      let wx = side === 0 ? py + perp * ry : px + perp * rx; wx -= Math.floor(wx);
      if ((side === 0 && rx < 0) || (side === 1 && ry > 0)) wx = 1 - wx;
      const tx = Math.min(tex.w - 1, (wx * tex.w) | 0);
      const lrow = lightRow(Math.min(255, hit.light + lightBoost), perp, side === 0 ? 1.5 : 0);
      const span = bot - top;
      for (let y = y0; y < y1; y++) {
        const ty = Math.min(tex.h - 1, ((y + 0.5 - top) / span * tex.h) | 0);
        const k = ty * tex.w + tx;
        const v = tex.d[k];
        fb[y * W + x] = v < 0 ? 0 : (tex.e && tex.e[k]) ? v : CMAP[lrow + v];
        zb[y * W + x] = perp;
      }
    }