Cutaway skill: build, film and score a 3D object that takes itself apart from one picture
The skill (SKILL.md), the kit for building one HTML page and capturing a 60 fps film, the procedural sound engine, the green page and look, and 3 complete examples: a tarantula, a piranha and a wasp, each with a full film and a 10-second version. The method docs move into docs/ with the README's GIFs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,300 @@
|
||||
import {clamp01, easeOutExpo, fmt, hash, smooth} from './util.js';
|
||||
|
||||
/**
|
||||
* The director edits a sim to the music: hard cuts between wide and tight
|
||||
* shots on bar lines, punch-ins on kicks, a shake and flash on the drop,
|
||||
* glitches on stage changes, and big readable story captions on the beat.
|
||||
*
|
||||
* Beats come from cfg.beats (sims/beats.py output, injected by capture.mjs).
|
||||
* Without music it runs on a synthetic grid (cfg.director.bpm) so live pages
|
||||
* still feel edited.
|
||||
*
|
||||
* Shots crop the 3D render (crisp re-render of a sub-rectangle) when the sim
|
||||
* uses kit/stage3d; otherwise they scale the target element with CSS.
|
||||
* Sims can return `foci: [{x, y}]` (screen px) in their render info: tight
|
||||
* shots frame those points.
|
||||
*
|
||||
* Story: cfg.story = [{at | bar | drop, text, sub, kind: 'hero'|'num', hold,
|
||||
* from, to, prefix, suffix, tag}]. `drop` is in bars relative to the drop,
|
||||
* `bar` counts bars from the clip start, `hold` is in beats. *word* gets the
|
||||
* accent box.
|
||||
*/
|
||||
export const DIRECTOR = {
|
||||
enabled: true,
|
||||
bpm: 128,
|
||||
drop: null,
|
||||
hero: null,
|
||||
// cut every N beats before / after the drop
|
||||
cutBeats: [4, 2],
|
||||
shots: [
|
||||
{z: 1},
|
||||
{z: 1.75, f: 0},
|
||||
{z: 1.3, f: 1},
|
||||
{z: 2.2, f: 2},
|
||||
{z: 1.12, f: 0},
|
||||
{z: 1.6, f: 1},
|
||||
],
|
||||
punch: [0.03, 0.07],
|
||||
shake: 1,
|
||||
flash: 1,
|
||||
glitch: 1,
|
||||
target: '#gl',
|
||||
};
|
||||
|
||||
const before = (arr, t) => {
|
||||
let lo = 0;
|
||||
let hi = arr.length;
|
||||
while (lo < hi) {
|
||||
const m = (lo + hi) >> 1;
|
||||
if (arr[m] <= t) lo = m + 1;
|
||||
else hi = m;
|
||||
}
|
||||
return lo - 1;
|
||||
};
|
||||
|
||||
export function createDirector(app, cfg) {
|
||||
const d = {...DIRECTOR, ...(cfg.director || {})};
|
||||
const D = cfg.duration;
|
||||
const music = cfg.beats && cfg.beats.beats && cfg.beats.beats.length > 4;
|
||||
const spb = music ? 60 / cfg.beats.bpm : 60 / d.bpm;
|
||||
const beats = music ? cfg.beats.beats : Array.from({length: Math.ceil(D / spb) + 8}, (_, i) => i * spb);
|
||||
// pad the grid past both ends so lookups never fall off
|
||||
while (beats[0] > 0) beats.unshift(beats[0] - spb);
|
||||
while (beats[beats.length - 1] < D + 4 * spb) beats.push(beats[beats.length - 1] + spb);
|
||||
let downs = music && cfg.beats.downbeats.length ? cfg.beats.downbeats.slice() : beats.filter((_, i) => i % 4 === 0);
|
||||
while (downs[0] > 0) downs.unshift(downs[0] - 4 * spb);
|
||||
while (downs[downs.length - 1] < D + 8 * spb) downs.push(downs[downs.length - 1] + 4 * spb);
|
||||
const kicks = music ? cfg.beats.kicks : beats.map((b) => [b, 0.8]);
|
||||
const kickT = kicks.map((k) => k[0]);
|
||||
const energy = music ? cfg.beats.barEnergy : null;
|
||||
const drop = (music && cfg.beats.drop) ?? d.drop ?? Math.round((0.4 * D) / (4 * spb)) * 4 * spb;
|
||||
const dropBar = before(downs, drop + 0.01);
|
||||
|
||||
const barTime = (b) => downs[Math.max(0, Math.min(downs.length - 1, b))];
|
||||
|
||||
// ---- time warp: the sim's hero moment lands on the drop
|
||||
const warp = (t) => {
|
||||
if (d.hero == null || !d.enabled) return t;
|
||||
const h = d.hero;
|
||||
if (t <= drop) return (t / drop) * h;
|
||||
return h + ((t - drop) / (D - drop)) * (D - h);
|
||||
};
|
||||
|
||||
const beat = (t) => {
|
||||
const sh = shotAt(t);
|
||||
const bi = before(beats, t);
|
||||
const b0 = beats[Math.max(0, bi)];
|
||||
const b1 = beats[bi + 1] ?? b0 + spb;
|
||||
const ri = before(downs, t);
|
||||
const r0 = downs[Math.max(0, ri)];
|
||||
const r1 = downs[ri + 1] ?? r0 + 4 * spb;
|
||||
const ki = before(kickT, t);
|
||||
const kick = ki >= 0 ? kicks[ki][1] * Math.exp(-(t - kicks[ki][0]) / 0.11) : 0;
|
||||
const down = Math.exp(-(t - r0) / 0.18);
|
||||
return {
|
||||
music,
|
||||
bpm: 60 / spb,
|
||||
beat: bi,
|
||||
beatPhase: clamp01((t - b0) / (b1 - b0)),
|
||||
bar: ri,
|
||||
barPhase: clamp01((t - r0) / (r1 - r0)),
|
||||
kick,
|
||||
down,
|
||||
energy: energy ? energy[Math.max(0, Math.min(energy.length - 1, ri))] ?? 1 : 1,
|
||||
drop,
|
||||
sinceDrop: t - drop,
|
||||
isDrop: t >= drop,
|
||||
// current shot: sims may change camera angle per shot index
|
||||
shot: sh.k,
|
||||
shotZ: sh.shot.z || 1,
|
||||
};
|
||||
};
|
||||
|
||||
// ---- story timing
|
||||
const story = (cfg.story || []).map((s, i) => {
|
||||
const start = s.at ?? (s.bar != null ? barTime(s.bar) : s.drop != null ? barTime(dropBar + s.drop) : 0);
|
||||
const b0 = before(beats, start + 0.02);
|
||||
const hold = s.hold ?? 8;
|
||||
const end = s.end ?? beats[Math.min(beats.length - 1, b0 + hold)] ?? start + hold * spb;
|
||||
return {...s, i, start, end, b0};
|
||||
});
|
||||
|
||||
// ---- DOM layers
|
||||
app.insertAdjacentHTML(
|
||||
'beforeend',
|
||||
`<canvas class="dir-glitch"></canvas><div class="dir-flash"></div><div class="dir-story"></div>`,
|
||||
);
|
||||
const gcv = app.querySelector('.dir-glitch');
|
||||
const gctx = gcv.getContext('2d');
|
||||
const flash = app.querySelector('.dir-flash');
|
||||
const storyEl = app.querySelector('.dir-story');
|
||||
|
||||
let foci = [];
|
||||
let crop = {z: 1, x0: 0, y0: 0};
|
||||
let built = -1;
|
||||
let parts = null;
|
||||
|
||||
const stageCuts = (cfg.stages || []).map((s) => s.at).filter((a) => a > 0.2);
|
||||
|
||||
const dropBeat = before(beats, drop + 0.01);
|
||||
function shotAt(t) {
|
||||
const bi = before(beats, t);
|
||||
const isDrop = t >= drop;
|
||||
const every = isDrop ? d.cutBeats[1] : d.cutBeats[0];
|
||||
// the first beats of the drop always open wide
|
||||
if (isDrop && bi - dropBeat < every) return {shot: d.shots[0], k: 0};
|
||||
const rel = isDrop ? bi - dropBeat : bi - before(beats, 0.01);
|
||||
const k = Math.floor(rel / every) + (isDrop ? 1000 : 0);
|
||||
return {shot: d.shots[((k % d.shots.length) + d.shots.length) % d.shots.length], k};
|
||||
}
|
||||
|
||||
const target = () => document.querySelector(d.target);
|
||||
|
||||
return {
|
||||
warp,
|
||||
beat,
|
||||
/** Before the sim renders: set this frame's crop. */
|
||||
pre(t) {
|
||||
if (!d.enabled) return;
|
||||
const {shot} = shotAt(t);
|
||||
const b = beat(t);
|
||||
const punch = 1 + (b.isDrop ? d.punch[1] : d.punch[0]) * b.kick;
|
||||
const drift = 1 + 0.035 * b.barPhase;
|
||||
let z = (shot.z || 1) * punch * (shot.z > 1 ? drift : 1);
|
||||
const vw = innerWidth;
|
||||
const vh = innerHeight;
|
||||
let f = {x: vw / 2, y: vh / 2};
|
||||
if (shot.z > 1 && foci.length) f = foci[(shot.f ?? 0) % foci.length];
|
||||
else if (window.__STAGE) {
|
||||
const vp = window.__STAGE.hudViewport();
|
||||
f = {x: vw / 2, y: (vp.top + vh - vp.bottom) / 2};
|
||||
}
|
||||
// drop shake (decays over ~0.6 s)
|
||||
const sk = d.shake * (b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.25) : 0);
|
||||
const sx = sk * (hash(t * 91.7) - 0.5) * 26;
|
||||
const sy = sk * (hash(t * 53.3 + 7) - 0.5) * 26;
|
||||
const st = window.__STAGE;
|
||||
if (st) {
|
||||
crop = st.setCrop(z, f.x + sx, f.y + sy);
|
||||
} else {
|
||||
const el = target();
|
||||
if (el) {
|
||||
el.style.transformOrigin = `${f.x}px ${f.y}px`;
|
||||
el.style.transform = `translate(${sx}px, ${sy}px) scale(${z})`;
|
||||
}
|
||||
crop = {z: 1, x0: 0, y0: 0};
|
||||
}
|
||||
},
|
||||
/** After the sim renders: remember its foci, draw overlays and the story. */
|
||||
post(t, info = {}) {
|
||||
if (!d.enabled) return;
|
||||
if (info.foci && info.foci.length) {
|
||||
// convert from this frame's cropped screen back to base screen coords
|
||||
foci = info.foci.map((p) => ({x: crop.x0 + p.x / crop.z, y: crop.y0 + p.y / crop.z}));
|
||||
}
|
||||
const b = beat(t);
|
||||
const vw = innerWidth;
|
||||
const vh = innerHeight;
|
||||
|
||||
// flash: accent bloom on downbeats after the drop, white hit on the drop
|
||||
const dropHit = b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.22) : 0;
|
||||
const onBar = b.isDrop ? 0.16 * b.down * b.energy : 0;
|
||||
flash.style.opacity = String(d.flash * Math.min(0.85, dropHit * 0.7 + onBar));
|
||||
|
||||
// glitch: 3 frames around each stage change and the drop
|
||||
const gl = [...stageCuts, b.drop].some((c) => t >= c - 0.03 && t < c + 0.1);
|
||||
if (gcv.width !== vw || gcv.height !== vh) {
|
||||
gcv.width = vw;
|
||||
gcv.height = vh;
|
||||
}
|
||||
gctx.clearRect(0, 0, vw, vh);
|
||||
const src = document.getElementById('gl');
|
||||
if (gl && d.glitch && src && src.width) {
|
||||
const n = 7;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const y = Math.floor(hash(t * 13 + i) * vh);
|
||||
const h = 6 + Math.floor(hash(t * 7 + i * 3) * 60);
|
||||
const dx = (hash(t * 31 + i * 5) - 0.5) * 120;
|
||||
const sx = src.width / vw;
|
||||
gctx.globalAlpha = 0.9;
|
||||
gctx.drawImage(src, 0, y * sx, src.width, h * sx, dx, y, vw, h);
|
||||
}
|
||||
gctx.globalAlpha = 0.25;
|
||||
gctx.fillStyle = cfg.accent;
|
||||
gctx.fillRect(0, Math.floor(hash(t * 3.3) * vh), vw, 3 + hash(t) * 10);
|
||||
gctx.globalAlpha = 1;
|
||||
}
|
||||
|
||||
// ---- story
|
||||
const cur = story.find((s) => t >= s.start && t < s.end);
|
||||
if (!cur) {
|
||||
storyEl.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
if (built !== cur.i) {
|
||||
built = cur.i;
|
||||
const words = (cur.text || '').split(/\s+/).filter(Boolean);
|
||||
storyEl.innerHTML = `<div class="cap ${cur.kind || 'hero'}">
|
||||
${cur.tag ? `<div class="cap-tag">${cur.tag}</div>` : ''}
|
||||
<div class="cap-main">${
|
||||
cur.kind === 'num'
|
||||
? `<span class="w"><span class="n"></span></span>`
|
||||
: (() => {
|
||||
// *several words* → each word gets the accent box
|
||||
let on = false;
|
||||
return words
|
||||
.map((w) => {
|
||||
const open = w.startsWith('*');
|
||||
const close = w.endsWith('*') && (w.length > 1 || on);
|
||||
if (open) on = true;
|
||||
const hl = on;
|
||||
if (close) on = false;
|
||||
return `<span class="w${hl ? ' hl' : ''}">${w.replace(/^\*|\*$/g, '')}</span>`;
|
||||
})
|
||||
.join(' ');
|
||||
})()
|
||||
}</div>
|
||||
${cur.sub ? `<div class="cap-sub"></div>` : ''}
|
||||
</div>`;
|
||||
parts = {
|
||||
words: [...storyEl.querySelectorAll('.w')],
|
||||
num: storyEl.querySelector('.n'),
|
||||
sub: storyEl.querySelector('.cap-sub'),
|
||||
main: storyEl.querySelector('.cap-main'),
|
||||
};
|
||||
}
|
||||
const vp = window.__HUDVP ? window.__HUDVP() : {top: 0, bottom: 0};
|
||||
storyEl.style.top = `${vp.top}px`;
|
||||
storyEl.style.bottom = `${vp.bottom}px`;
|
||||
storyEl.style.opacity = '1';
|
||||
const ex = clamp01((t - (cur.end - 0.18)) / 0.18);
|
||||
// words slam in on successive beats (half-beats if the text is long)
|
||||
const step = parts.words.length > 4 ? 0.5 : 1;
|
||||
let lastIn = cur.start;
|
||||
parts.words.forEach((w, i) => {
|
||||
const bi = cur.b0 + i * step;
|
||||
const wt = Math.floor(bi) === bi ? beats[bi] : (beats[Math.floor(bi)] + beats[Math.ceil(bi)]) / 2;
|
||||
const k = cur.start <= 0.001 ? 1 : clamp01((t - wt) / 0.12);
|
||||
lastIn = Math.max(lastIn, wt);
|
||||
const s = 1 + 0.35 * (1 - easeOutExpo(k)) + 0.03 * b.kick;
|
||||
w.style.opacity = String(k > 0 ? 1 : 0);
|
||||
w.style.transform = `scale(${s}) translateY(${ex * -0.25}em)`;
|
||||
w.style.filter = k < 1 ? `blur(${(1 - k) * 8}px)` : 'none';
|
||||
});
|
||||
if (cur.kind === 'num' && parts.num) {
|
||||
const roll = cur.roll ?? 6;
|
||||
const k = easeOutExpo(clamp01((t - cur.start) / (roll * spb)));
|
||||
const v = cur.from + (cur.to - cur.from) * k;
|
||||
parts.num.textContent = `${cur.prefix ?? ''}${fmt(v, cur.decimals ?? 0)}${cur.suffix ?? ''}`;
|
||||
lastIn = cur.start + roll * spb * 0.6;
|
||||
}
|
||||
if (parts.sub) {
|
||||
const n = Math.floor(Math.max(0, t - lastIn - 0.15) / 0.022);
|
||||
parts.sub.textContent = cur.sub.slice(0, n);
|
||||
}
|
||||
parts.main.style.opacity = String(1 - ex);
|
||||
if (parts.sub) parts.sub.style.opacity = String(1 - ex);
|
||||
storyEl.firstElementChild.style.transform = `translateX(${ex * (hash(t * 41) - 0.5) * 40}px)`;
|
||||
},
|
||||
};
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
import {clamp01, pad} from './util.js';
|
||||
|
||||
/**
|
||||
* Instrument-style HUD: header with stage/command/clock, annotations over the
|
||||
* viewport, a terminal log and a side panel (minimap + stats) at the bottom.
|
||||
* Everything is derived from `t` and the config's stages, so it's deterministic.
|
||||
*
|
||||
* cfg.stages: [{at, name, cmd, logs: [string]}]. A log line starting with "!"
|
||||
* is highlighted in the accent. {key} tokens are replaced from `facts`.
|
||||
*/
|
||||
export function createHud(root, cfg) {
|
||||
const h = cfg.hud;
|
||||
root.insertAdjacentHTML(
|
||||
'beforeend',
|
||||
`<div class="hud">
|
||||
<div class="ann"></div>
|
||||
<div class="wm"></div>
|
||||
<div class="hdr">
|
||||
<div class="row row1">
|
||||
<div class="title"><i class="bar"></i><span class="t"></span></div>
|
||||
<div class="sub"></div>
|
||||
<div class="right"></div>
|
||||
</div>
|
||||
<div class="row row2">
|
||||
<div class="stage accent"></div>
|
||||
<div class="cmd"></div>
|
||||
<div class="time accent"></div>
|
||||
</div>
|
||||
<div class="prog"><i></i></div>
|
||||
</div>
|
||||
<div class="bot">
|
||||
<div class="term">
|
||||
<div class="thead">
|
||||
<span class="host accent"></span><span class="path"></span>
|
||||
<span class="status accent"><i></i><span></span></span>
|
||||
</div>
|
||||
<div class="prompt"></div>
|
||||
<div class="logs"></div>
|
||||
<div class="tfoot"></div>
|
||||
</div>
|
||||
<div class="side">
|
||||
<div class="shead accent"></div>
|
||||
<canvas class="mini"></canvas>
|
||||
<div class="stats"></div>
|
||||
<div class="sfoot"></div>
|
||||
</div>
|
||||
<div class="baseline"><i></i></div>
|
||||
</div>
|
||||
</div>`,
|
||||
);
|
||||
const $ = (s) => root.querySelector(s);
|
||||
const el = {
|
||||
hud: $('.hud'),
|
||||
ann: $('.ann'),
|
||||
stage: $('.row2 .stage'),
|
||||
cmd: $('.row2 .cmd'),
|
||||
time: $('.row2 .time'),
|
||||
prog: $('.prog i'),
|
||||
prompt: $('.prompt'),
|
||||
logs: $('.logs'),
|
||||
tfoot: $('.tfoot'),
|
||||
status: $('.thead .status span'),
|
||||
stats: $('.stats'),
|
||||
sfoot: $('.sfoot'),
|
||||
base: $('.baseline i'),
|
||||
mini: $('.mini'),
|
||||
};
|
||||
$('.title .t').textContent = h.title;
|
||||
$('.sub').textContent = h.subtitle;
|
||||
$('.right').textContent = h.right;
|
||||
$('.wm').textContent = cfg.watermark;
|
||||
$('.thead .host').textContent = h.host;
|
||||
$('.thead .path').textContent = h.path;
|
||||
$('.shead').textContent = h.sideTitle;
|
||||
|
||||
const stages = cfg.stages;
|
||||
const D = cfg.duration;
|
||||
const TYPE_CMD = 0.028;
|
||||
const TYPE_LOG = 0.011;
|
||||
|
||||
// Log line schedule: each stage types its command, then its lines spread
|
||||
// over the stage.
|
||||
const lines = [];
|
||||
stages.forEach((s, i) => {
|
||||
const end = i + 1 < stages.length ? stages[i + 1].at : D;
|
||||
const t0 = s.at + 0.25 + s.cmd.length * TYPE_CMD + 0.2;
|
||||
const n = s.logs.length;
|
||||
const gap = Math.min(0.8, Math.max(0.22, (end - t0 - 0.4) / Math.max(1, n)));
|
||||
s.logs.forEach((text, j) => lines.push({at: t0 + j * gap, text, stage: i}));
|
||||
});
|
||||
|
||||
const stageAt = (t) => {
|
||||
let i = 0;
|
||||
while (i + 1 < stages.length && stages[i + 1].at <= t) i++;
|
||||
return i;
|
||||
};
|
||||
const fill = (text, facts) => text.replace(/\{(\w+)\}/g, (m, k) => (k in facts ? facts[k] : m));
|
||||
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<');
|
||||
|
||||
let lastStats = '';
|
||||
let lastLogs = '';
|
||||
const annPool = [];
|
||||
|
||||
return {
|
||||
minimap: el.mini,
|
||||
stageAt,
|
||||
setVisible(v) {
|
||||
el.hud.classList.toggle('hidden', !v);
|
||||
},
|
||||
/** Viewport between header and bottom panel, in CSS px. */
|
||||
viewport() {
|
||||
const fs = parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
return {top: 13.4 * fs, bottom: 30.5 * fs};
|
||||
},
|
||||
render(t, frame, info = {}) {
|
||||
const facts = {...cfg.facts, ...(info.facts || {})};
|
||||
const si = stageAt(t);
|
||||
const s = stages[si];
|
||||
const dt = t - s.at;
|
||||
const typed = Math.floor(Math.max(0, dt - 0.15) / TYPE_CMD);
|
||||
const cmd = fill(s.cmd, facts);
|
||||
const typing = typed < cmd.length;
|
||||
const caretOn = typing || Math.floor(t * 2.4) % 2 === 0;
|
||||
|
||||
el.stage.textContent = `${pad(si + 1, 2)} / ${s.name}`;
|
||||
el.cmd.textContent = cmd.slice(0, typed);
|
||||
el.time.textContent = `${t.toFixed(2).padStart(5, '0')} / ${D}`;
|
||||
el.prog.style.width = `${(clamp01(t / D) * 100).toFixed(2)}%`;
|
||||
el.base.style.width = `${(clamp01(dt / ((stages[si + 1]?.at ?? D) - s.at)) * 100).toFixed(2)}%`;
|
||||
el.prompt.innerHTML = `<span class="accent">></span> ${esc(cmd.slice(0, typed))}${
|
||||
caretOn ? '<i class="caret"></i>' : ''
|
||||
}`;
|
||||
|
||||
const shown = lines.filter((l) => l.at <= t);
|
||||
const rows = shown.slice(-h.logRows);
|
||||
const offset = shown.length - rows.length;
|
||||
const html = rows
|
||||
.map((l, j) => {
|
||||
const full = fill(l.text, facts);
|
||||
const hl = full.startsWith('!');
|
||||
const text = hl ? full.slice(1) : full;
|
||||
const n = Math.floor((t - l.at) / TYPE_LOG);
|
||||
const isLast = j === rows.length - 1 && n < text.length;
|
||||
return `<div><span class="ln">${pad(offset + j, 3)}</span><span class="${hl ? 'hl' : ''}">${esc(
|
||||
text.slice(0, n),
|
||||
)}</span>${isLast ? '<i class="caret"></i>' : ''}</div>`;
|
||||
})
|
||||
.join('');
|
||||
if (html !== lastLogs) {
|
||||
el.logs.innerHTML = html;
|
||||
lastLogs = html;
|
||||
}
|
||||
|
||||
el.tfoot.textContent = `frame ${pad(frame, 4)} delta ${pad((dt * 7.3) % 100, 2)} / ${s.name.toLowerCase()}`;
|
||||
el.status.textContent = info.status ?? (t >= D - 0.05 ? 'DONE' : 'RUNNING');
|
||||
el.sfoot.textContent = `view ${pad(si + 1, 2)} / ${pad(h.views, 2)} seed ${cfg.seed} · t+${dt.toFixed(2)}s`;
|
||||
|
||||
const stats = (info.stats || []).map((x) => `<div>${esc(x.label)}<b>${esc(String(x.value))}</b></div>`).join('');
|
||||
if (stats !== lastStats) {
|
||||
el.stats.innerHTML = stats;
|
||||
lastStats = stats;
|
||||
}
|
||||
|
||||
const anns = info.annotations || [];
|
||||
while (annPool.length < anns.length) {
|
||||
const d = document.createElement('div');
|
||||
el.ann.appendChild(d);
|
||||
annPool.push(d);
|
||||
}
|
||||
annPool.forEach((d, i) => {
|
||||
const a = anns[i];
|
||||
if (!a) {
|
||||
d.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
d.style.display = '';
|
||||
d.className = a.cls || '';
|
||||
d.style.left = `${a.x}px`;
|
||||
d.style.top = `${a.y}px`;
|
||||
d.style.opacity = a.opacity ?? 1;
|
||||
if (a.html !== undefined) d.innerHTML = a.html;
|
||||
else d.textContent = a.text;
|
||||
// keep labels inside the viewport (between header and bottom panel)
|
||||
const vp = this.viewport();
|
||||
const w = d.offsetWidth;
|
||||
const hh = d.offsetHeight;
|
||||
const x = Math.min(Math.max(a.x, 8), innerWidth - w - 40);
|
||||
const y = Math.min(Math.max(a.y, vp.top + hh / 2 + 8), innerHeight - vp.bottom - hh / 2 - 8);
|
||||
d.style.left = `${x}px`;
|
||||
d.style.top = `${y}px`;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import {createDirector, DIRECTOR} from './director.js';
|
||||
import {createHud} from './hud.js';
|
||||
import {merge} from './util.js';
|
||||
|
||||
/** Config every sim starts from; a sim's defaults and the post config merge over it. */
|
||||
export const BASE = {
|
||||
duration: 30,
|
||||
fps: 30,
|
||||
seed: 746337560,
|
||||
theme: 'dark',
|
||||
accent: '#f2b632',
|
||||
watermark: '',
|
||||
hud: {
|
||||
title: 'AGENT MESH',
|
||||
subtitle: '/ SIMULATION',
|
||||
right: 'VISUAL SIMULATION',
|
||||
host: 'agent@local',
|
||||
path: '~/session-01',
|
||||
sideTitle: 'LOCAL VIEW',
|
||||
logRows: 5,
|
||||
views: 10,
|
||||
},
|
||||
stages: [{at: 0, name: 'RUN', cmd: 'run', logs: []}],
|
||||
facts: {},
|
||||
director: DIRECTOR,
|
||||
story: [],
|
||||
beats: null,
|
||||
};
|
||||
|
||||
const fromBase64 = (s) => decodeURIComponent(escape(atob(s.replace(/-/g, '+').replace(/_/g, '/'))));
|
||||
|
||||
/**
|
||||
* Config sources, later wins: BASE, the sim's defaults, window.__SIM_CONFIG
|
||||
* (injected by the capture script), ?config=<base64 json>, and a few plain
|
||||
* query params (?title= ?accent= ?seed= ?theme= ?duration=).
|
||||
*/
|
||||
export function loadConfig(defaults) {
|
||||
let cfg = merge(BASE, defaults);
|
||||
if (window.__SIM_CONFIG) cfg = merge(cfg, window.__SIM_CONFIG);
|
||||
const q = new URLSearchParams(location.search);
|
||||
if (q.get('config')) {
|
||||
try {
|
||||
cfg = merge(cfg, JSON.parse(fromBase64(q.get('config'))));
|
||||
} catch (e) {
|
||||
console.warn('bad ?config', e);
|
||||
}
|
||||
}
|
||||
if (q.get('title')) cfg = merge(cfg, {hud: {title: q.get('title')}});
|
||||
if (q.get('accent')) cfg.accent = '#' + q.get('accent').replace('#', '');
|
||||
if (q.get('seed')) cfg.seed = Number(q.get('seed'));
|
||||
if (q.get('theme')) cfg.theme = q.get('theme');
|
||||
if (q.get('duration')) cfg.duration = Number(q.get('duration'));
|
||||
if (q.has('nodirector')) cfg.director = {...cfg.director, enabled: false};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Boots a sim. `setup({cfg, canvas, hud, capture})` returns (or resolves to)
|
||||
* `{render(t) -> hudInfo, resize()}`. render must be a pure function of t.
|
||||
*
|
||||
* Live mode loops in real time. Keys: space pause, h hide HUD, f fullscreen,
|
||||
* r restart, ←/→ seek 2 s, 1–9 jump to a stage.
|
||||
* Capture mode (?capture or window.__CAPTURE) exposes window.SIM.render(t).
|
||||
*/
|
||||
export async function runSim(defaults, setup) {
|
||||
const cfg = loadConfig(defaults);
|
||||
const q = new URLSearchParams(location.search);
|
||||
const capture = !!window.__CAPTURE || q.has('capture');
|
||||
const root = document.documentElement;
|
||||
root.dataset.theme = cfg.theme;
|
||||
root.style.setProperty('--accent', cfg.accent);
|
||||
document.title = `${cfg.hud.title} ${cfg.hud.subtitle}`.trim();
|
||||
|
||||
const scale = () => {
|
||||
root.style.fontSize = `${10 * Math.min(innerWidth / 1080, innerHeight / 1350)}px`;
|
||||
};
|
||||
scale();
|
||||
|
||||
const app = document.getElementById('app');
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.id = 'gl';
|
||||
app.appendChild(canvas);
|
||||
// cfg.hud.enabled === false: no instrument chrome (UI demos, infographics).
|
||||
const hud =
|
||||
cfg.hud.enabled === false
|
||||
? {minimap: null, stageAt: () => 0, setVisible() {}, viewport: () => ({top: 0, bottom: 0}), render() {}}
|
||||
: createHud(app, cfg);
|
||||
|
||||
await Promise.all([
|
||||
document.fonts.load('400 20px "JetBrains Mono"'),
|
||||
document.fonts.load('600 20px "JetBrains Mono"'),
|
||||
document.fonts.load('800 20px "Inter"'),
|
||||
]).catch(() => {});
|
||||
|
||||
window.__HUDVP = () => hud.viewport();
|
||||
const sim = await setup({cfg, canvas, hud, capture});
|
||||
if (!capture && sim.warm) await sim.warm();
|
||||
const dir = createDirector(app, cfg);
|
||||
// The sim and HUD run on warped time (hero lands on the drop); the
|
||||
// director's cuts, punches and story run on real (music) time.
|
||||
const draw = (t) => {
|
||||
const tw = dir.warp(t);
|
||||
dir.pre(t);
|
||||
const info = sim.render(tw, dir.beat(t)) || {};
|
||||
hud.render(tw, Math.round(t * cfg.fps), info);
|
||||
dir.post(t, info);
|
||||
};
|
||||
|
||||
let cur = 0;
|
||||
let paused = false;
|
||||
const resize = () => {
|
||||
scale();
|
||||
sim.resize?.();
|
||||
if (paused || capture) draw(cur);
|
||||
};
|
||||
addEventListener('resize', resize);
|
||||
resize();
|
||||
|
||||
window.SIM = {
|
||||
cfg,
|
||||
duration: cfg.duration,
|
||||
fps: cfg.fps,
|
||||
ready: true,
|
||||
render: (t) => {
|
||||
cur = t;
|
||||
draw(t);
|
||||
},
|
||||
};
|
||||
if (capture) {
|
||||
draw(0);
|
||||
return;
|
||||
}
|
||||
|
||||
let start = performance.now();
|
||||
const seek = (t) => {
|
||||
cur = ((t % cfg.duration) + cfg.duration) % cfg.duration;
|
||||
start = performance.now() - cur * 1000;
|
||||
};
|
||||
let hudOn = true;
|
||||
addEventListener('keydown', (e) => {
|
||||
if (e.key === ' ') {
|
||||
paused = !paused;
|
||||
if (!paused) seek(cur);
|
||||
} else if (e.key === 'h') {
|
||||
hudOn = !hudOn;
|
||||
hud.setVisible(hudOn);
|
||||
} else if (e.key === 'f') {
|
||||
if (document.fullscreenElement) document.exitFullscreen();
|
||||
else document.documentElement.requestFullscreen();
|
||||
} else if (e.key === 'r') seek(0);
|
||||
else if (e.key === 'ArrowRight') seek(cur + 2);
|
||||
else if (e.key === 'ArrowLeft') seek(cur - 2);
|
||||
else if (/^[1-9]$/.test(e.key) && cfg.stages[+e.key - 1]) seek(Math.max(0, cfg.stages[+e.key - 1].at));
|
||||
else return;
|
||||
e.preventDefault();
|
||||
});
|
||||
const loop = (now) => {
|
||||
if (!paused) cur = Math.max(0, (now - start) / 1000) % cfg.duration;
|
||||
draw(cur);
|
||||
// the site page swaps its poster for the canvas on this
|
||||
if (!window.SIM_SHOWN) {
|
||||
window.SIM_SHOWN = true;
|
||||
dispatchEvent(new Event('simframe'));
|
||||
}
|
||||
requestAnimationFrame(loop);
|
||||
};
|
||||
requestAnimationFrame(loop);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import * as THREE from 'three';
|
||||
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
|
||||
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
|
||||
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
|
||||
import {UnrealBloomPass} from 'three/addons/postprocessing/UnrealBloomPass.js';
|
||||
|
||||
/**
|
||||
* Renderer + scene + camera + bloom. The camera's projection centre is shifted
|
||||
* to the middle of the HUD viewport (between header and bottom panel), so the
|
||||
* subject is centred in the visible area, not behind the terminal.
|
||||
*/
|
||||
export function createStage(canvas, hud, opts = {}) {
|
||||
const {
|
||||
bg = '#09090a',
|
||||
fov = 38,
|
||||
bloom = {strength: 0.85, radius: 0.55, threshold: 0.62},
|
||||
capture = false,
|
||||
exposure = 1,
|
||||
} = opts;
|
||||
const renderer = new THREE.WebGLRenderer({
|
||||
canvas,
|
||||
antialias: false,
|
||||
preserveDrawingBuffer: true,
|
||||
powerPreference: 'high-performance',
|
||||
});
|
||||
renderer.setClearColor(new THREE.Color(bg), 1);
|
||||
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||
renderer.toneMappingExposure = exposure;
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(bg);
|
||||
const camera = new THREE.PerspectiveCamera(fov, 1, 0.5, 6000);
|
||||
|
||||
const target = new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 4});
|
||||
const composer = new EffectComposer(renderer, target);
|
||||
composer.addPass(new RenderPass(scene, camera));
|
||||
const bloomPass = new UnrealBloomPass(new THREE.Vector2(4, 4), bloom.strength, bloom.radius, bloom.threshold);
|
||||
composer.addPass(bloomPass);
|
||||
composer.addPass(new OutputPass());
|
||||
|
||||
const size = {w: 1, h: 1, centre: 0.5};
|
||||
// Director crop: render a sub-rectangle of the base view (crisp punch-ins).
|
||||
const crop = {z: 1, fx: 0, fy: 0, x0: 0, y0: 0};
|
||||
const applyView = () => {
|
||||
const {w, h, centre} = size;
|
||||
const offY = h / 2 - centre;
|
||||
if (crop.z <= 1.0001) {
|
||||
crop.x0 = 0;
|
||||
crop.y0 = 0;
|
||||
camera.setViewOffset(w, h, 0, offY, w, h);
|
||||
} else {
|
||||
const cw = w / crop.z;
|
||||
const ch = h / crop.z;
|
||||
crop.x0 = Math.min(Math.max(crop.fx - cw / 2, 0), w - cw);
|
||||
crop.y0 = Math.min(Math.max(crop.fy - ch / 2, 0), h - ch);
|
||||
camera.setViewOffset(w, h, crop.x0, offY + crop.y0, cw, ch);
|
||||
}
|
||||
camera.updateProjectionMatrix();
|
||||
};
|
||||
// opts.pr fixes the pixel ratio (a capture that wants the 3D at the output resolution, a page that adapts it)
|
||||
let prFixed = opts.pr;
|
||||
const resize = () => {
|
||||
const w = canvas.clientWidth || innerWidth;
|
||||
const h = canvas.clientHeight || innerHeight;
|
||||
const pr = prFixed ?? (capture ? 1 : Math.min(devicePixelRatio || 1, 2));
|
||||
size.w = w;
|
||||
size.h = h;
|
||||
renderer.setPixelRatio(pr);
|
||||
renderer.setSize(w, h, false);
|
||||
composer.setPixelRatio(pr);
|
||||
composer.setSize(w, h);
|
||||
const vp = hud.viewport();
|
||||
size.centre = (vp.top + (h - vp.bottom)) / 2;
|
||||
camera.aspect = w / h;
|
||||
applyView();
|
||||
};
|
||||
/** Zoom z around base-screen point (fx, fy); returns {z, x0, y0} for mapping back. */
|
||||
const setCrop = (z, fx, fy) => {
|
||||
crop.z = Math.max(1, z);
|
||||
crop.fx = fx;
|
||||
crop.fy = fy;
|
||||
applyView();
|
||||
return {z: crop.z, x0: crop.x0, y0: crop.y0};
|
||||
};
|
||||
|
||||
const v = new THREE.Vector3();
|
||||
/** World point → CSS px on screen, plus whether it's in front of the camera. */
|
||||
const project = (p) => {
|
||||
v.set(p[0] ?? p.x, p[1] ?? p.y, p[2] ?? p.z).project(camera);
|
||||
return {x: (v.x * 0.5 + 0.5) * size.w, y: (-v.y * 0.5 + 0.5) * size.h, visible: v.z < 1};
|
||||
};
|
||||
|
||||
const st = {
|
||||
THREE,
|
||||
renderer,
|
||||
scene,
|
||||
camera,
|
||||
composer,
|
||||
bloomPass,
|
||||
size,
|
||||
resize,
|
||||
setPixelRatio: (v) => {
|
||||
prFixed = v;
|
||||
resize();
|
||||
},
|
||||
project,
|
||||
render: () => composer.render(),
|
||||
setCrop,
|
||||
hudViewport: () => hud.viewport(),
|
||||
};
|
||||
window.__STAGE = st;
|
||||
return st;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/* HUD chrome shared by every sim. 1rem = 10px at the 1080x1350 reference
|
||||
size; runtime sets html font-size from the viewport so it scales. */
|
||||
|
||||
:root {
|
||||
--bg: #09090a;
|
||||
--fg: #ece6d6;
|
||||
--dim: rgba(236, 230, 214, 0.64);
|
||||
--mute: rgba(236, 230, 214, 0.38);
|
||||
--faint: rgba(236, 230, 214, 0.16);
|
||||
--line: rgba(236, 230, 214, 0.14);
|
||||
--panel: rgba(9, 9, 10, 0.9);
|
||||
--accent: #f2b632;
|
||||
--top: 13.4rem;
|
||||
--bot: 30.5rem;
|
||||
}
|
||||
:root[data-theme='light'] {
|
||||
--bg: #f3f2ee;
|
||||
--fg: #151515;
|
||||
--dim: rgba(21, 21, 21, 0.66);
|
||||
--mute: rgba(21, 21, 21, 0.42);
|
||||
--faint: rgba(21, 21, 21, 0.16);
|
||||
--line: rgba(21, 21, 21, 0.16);
|
||||
--panel: rgba(243, 242, 238, 0.93);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; background: var(--bg); overflow: hidden; }
|
||||
#app {
|
||||
position: fixed; inset: 0; color: var(--fg);
|
||||
font-family: 'JetBrains Mono', ui-monospace, monospace;
|
||||
font-variant-ligatures: none; -webkit-font-smoothing: antialiased;
|
||||
}
|
||||
#gl { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
|
||||
.hud { position: absolute; inset: 0; pointer-events: none; }
|
||||
.hud.hidden { display: none; }
|
||||
.accent { color: var(--accent); }
|
||||
|
||||
/* header */
|
||||
.hdr {
|
||||
position: absolute; left: 0; right: 0; top: 0; height: var(--top);
|
||||
padding: 2.4rem 2.8rem 0;
|
||||
background: linear-gradient(var(--bg) 0%, var(--bg) 78%, transparent 100%);
|
||||
}
|
||||
.row { display: flex; align-items: baseline; white-space: nowrap; }
|
||||
.row1 { gap: 5.6rem; }
|
||||
.title { display: flex; align-items: center; gap: 1.3rem; font-size: 3.6rem; font-weight: 600; letter-spacing: 0.04em; }
|
||||
.title .bar { display: inline-block; width: 0.75rem; height: 3.6rem; background: var(--accent); }
|
||||
.sub { font-size: 1.75rem; color: var(--dim); letter-spacing: 0.08em; }
|
||||
.right { margin-left: auto; font-size: 1.6rem; color: var(--dim); letter-spacing: 0.1em; }
|
||||
.row2 { margin-top: 2rem; font-size: 1.95rem; }
|
||||
.row2 .stage { width: 21rem; letter-spacing: 0.05em; }
|
||||
.row2 .cmd { color: var(--fg); }
|
||||
.row2 .time { margin-left: auto; letter-spacing: 0.05em; }
|
||||
.prog { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 1.2rem; height: 0.35rem; }
|
||||
.prog i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
|
||||
|
||||
/* viewport overlays */
|
||||
.ann { position: absolute; inset: 0; overflow: hidden; }
|
||||
.ann div {
|
||||
position: absolute; transform: translate(1.4rem, -50%); white-space: nowrap;
|
||||
font-size: 1.7rem; letter-spacing: 0.04em; color: var(--fg);
|
||||
text-shadow: 0 0 0.6rem var(--bg), 0 0 1.2rem var(--bg);
|
||||
}
|
||||
.ann div.a { color: var(--accent); }
|
||||
.ann div.box {
|
||||
padding: 0.8rem 1.1rem; border: 1px solid var(--line); background: var(--panel);
|
||||
text-shadow: none; line-height: 1.45; font-size: 1.55rem;
|
||||
}
|
||||
.ann div.box b { color: var(--accent); font-weight: 600; }
|
||||
.wm {
|
||||
position: absolute; right: 3rem; bottom: calc(var(--bot) + 1.6rem);
|
||||
font-size: 2.3rem; letter-spacing: 0.06em; color: var(--fg); opacity: 0.3;
|
||||
}
|
||||
|
||||
/* bottom panel */
|
||||
.bot {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; height: var(--bot);
|
||||
display: flex; border-top: 1px solid var(--line); background: var(--panel);
|
||||
padding: 2rem 2.8rem 1.6rem;
|
||||
}
|
||||
.term { flex: 1; min-width: 0; display: flex; flex-direction: column; padding-right: 2.6rem; }
|
||||
.thead { display: flex; align-items: baseline; gap: 2.4rem; font-size: 1.75rem; white-space: nowrap; }
|
||||
.thead .host { font-size: 2.1rem; }
|
||||
.thead .path { color: var(--dim); }
|
||||
.thead .status { margin-left: auto; font-size: 1.5rem; letter-spacing: 0.1em; display: flex; align-items: center; gap: 0.9rem; }
|
||||
.thead .status i { width: 1rem; height: 1rem; border-radius: 50%; background: var(--accent); display: inline-block; }
|
||||
.prompt { margin-top: 1.9rem; font-size: 2.2rem; white-space: nowrap; overflow: hidden; }
|
||||
.logs { margin-top: 1.1rem; font-size: 1.85rem; line-height: 1.52; flex: 1; overflow: hidden; }
|
||||
.logs div { white-space: nowrap; overflow: hidden; text-overflow: clip; }
|
||||
.logs .ln { color: var(--mute); display: inline-block; width: 6.4rem; }
|
||||
.logs .hl { color: var(--accent); }
|
||||
.caret { display: inline-block; width: 0.95em; height: 1.05em; vertical-align: -0.15em; background: var(--accent); margin-left: 0.15em; }
|
||||
.tfoot { font-size: 1.35rem; color: var(--mute); white-space: nowrap; letter-spacing: 0.04em; }
|
||||
.side {
|
||||
width: 31%; border-left: 1px solid var(--line); padding-left: 2.2rem;
|
||||
display: flex; flex-direction: column;
|
||||
}
|
||||
.shead { font-size: 1.45rem; letter-spacing: 0.12em; }
|
||||
.mini { width: 100%; flex: 1; min-height: 0; display: block; margin: 0.8rem 0; }
|
||||
.stats { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem 1.4rem; font-size: 1.35rem; color: var(--mute); }
|
||||
.stats b { display: block; font-size: 2rem; color: var(--fg); font-weight: 600; letter-spacing: 0.02em; }
|
||||
.sfoot { margin-top: 0.8rem; font-size: 1.3rem; color: var(--mute); letter-spacing: 0.05em; }
|
||||
.baseline { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 0.9rem; height: 0.25rem; background: var(--line); }
|
||||
.baseline i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
|
||||
|
||||
/* director layers */
|
||||
.dir-glitch { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
|
||||
.dir-flash {
|
||||
position: absolute; inset: 0; pointer-events: none; opacity: 0; mix-blend-mode: screen;
|
||||
background: radial-gradient(ellipse 75% 55% at 50% 45%, var(--accent) 0%, transparent 70%), rgba(255,255,255,0.18);
|
||||
}
|
||||
.dir-story {
|
||||
position: absolute; left: 0; right: 0; top: 0; bottom: 0; pointer-events: none;
|
||||
display: flex; align-items: flex-end; justify-content: center; padding: 0 4.5rem 6rem; opacity: 0;
|
||||
}
|
||||
.cap { text-align: center; max-width: 96rem; position: relative; }
|
||||
.cap::before {
|
||||
content: ''; position: absolute; inset: -6rem -10rem; z-index: -1;
|
||||
background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(0,0,0,0.62) 0%, rgba(0,0,0,0) 100%);
|
||||
}
|
||||
:root[data-theme='light'] .cap::before { background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(243,242,238,0.8) 0%, rgba(243,242,238,0) 100%); }
|
||||
.cap-main {
|
||||
font-family: 'Inter', 'Inter Variable', system-ui, sans-serif; font-weight: 800;
|
||||
font-size: 11.5rem; line-height: 0.98; letter-spacing: -0.035em; color: var(--fg);
|
||||
text-shadow: 0 0.4rem 2.4rem rgba(0,0,0,0.55);
|
||||
}
|
||||
.cap.num .cap-main { font-size: 15rem; font-variant-numeric: tabular-nums; letter-spacing: -0.045em; }
|
||||
.cap-main .w { display: inline-block; transform-origin: 50% 70%; }
|
||||
.cap-main .w.hl { background: var(--accent); color: #0a0a0a; padding: 0 0.14em; text-shadow: none; border-radius: 0.06em; }
|
||||
.cap-sub {
|
||||
margin-top: 2rem; font-size: 2.7rem; letter-spacing: 0.08em; text-transform: uppercase;
|
||||
color: var(--fg); opacity: 0.85; min-height: 1.3em;
|
||||
}
|
||||
.cap-tag {
|
||||
display: inline-block; margin-bottom: 1.8rem; padding: 0.5rem 1.2rem; font-size: 2.2rem; letter-spacing: 0.12em;
|
||||
border: 1px solid var(--accent); color: var(--accent); background: rgba(0,0,0,0.5);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Small pure helpers shared by every sim. Everything animated must be a pure
|
||||
// function of `t` (seconds) so live playback and frame capture match.
|
||||
|
||||
export const clamp01 = (x) => Math.min(1, Math.max(0, x));
|
||||
export const lerp = (a, b, k) => a + (b - a) * k;
|
||||
export const smooth = (x) => {
|
||||
const k = clamp01(x);
|
||||
return k * k * (3 - 2 * k);
|
||||
};
|
||||
export const easeOutCubic = (x) => 1 - Math.pow(1 - clamp01(x), 3);
|
||||
export const easeInOutCubic = (x) => {
|
||||
const k = clamp01(x);
|
||||
return k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;
|
||||
};
|
||||
export const easeOutExpo = (x) => (x >= 1 ? 1 : 1 - Math.pow(2, -10 * clamp01(x)));
|
||||
export const easeOutBack = (x, s = 1.7) => {
|
||||
const k = clamp01(x) - 1;
|
||||
return 1 + (s + 1) * k * k * k + s * k * k;
|
||||
};
|
||||
/** 0..1 progress of t between t0 and t1, eased. */
|
||||
export const prog = (t, t0, t1, ease = easeInOutCubic) => ease((t - t0) / (t1 - t0));
|
||||
|
||||
/** Seeded PRNG (mulberry32). Same seed → same sequence. */
|
||||
export const rng = (seed) => {
|
||||
let s = seed >>> 0;
|
||||
return () => {
|
||||
s = (s + 0x6d2b79f5) >>> 0;
|
||||
let x = s;
|
||||
x = Math.imul(x ^ (x >>> 15), x | 1);
|
||||
x ^= x + Math.imul(x ^ (x >>> 7), x | 61);
|
||||
return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
};
|
||||
|
||||
/** Stateless hash noise in [0,1). */
|
||||
export const hash = (n) => {
|
||||
const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;
|
||||
return x - Math.floor(x);
|
||||
};
|
||||
|
||||
/** Random unit vector from a PRNG. */
|
||||
export const randDir = (r) => {
|
||||
const u = r() * 2 - 1;
|
||||
const a = r() * Math.PI * 2;
|
||||
const s = Math.sqrt(1 - u * u);
|
||||
return [s * Math.cos(a), u, s * Math.sin(a)];
|
||||
};
|
||||
|
||||
/**
|
||||
* Keyframed value: keys = [[t, value], ...] with numbers or arrays of numbers.
|
||||
* Eased between keys, held outside.
|
||||
*/
|
||||
export const keyed = (keys, t, ease = easeInOutCubic) => {
|
||||
if (t <= keys[0][0]) return keys[0][1];
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const [t0, v0] = keys[i];
|
||||
const [t1, v1] = keys[i + 1];
|
||||
if (t <= t1) {
|
||||
const k = ease((t - t0) / (t1 - t0));
|
||||
return Array.isArray(v0) ? v0.map((v, j) => lerp(v, v1[j], k)) : lerp(v0, v1, k);
|
||||
}
|
||||
}
|
||||
return keys[keys.length - 1][1];
|
||||
};
|
||||
|
||||
export const fmt = (n, d = 0) =>
|
||||
Number(n).toLocaleString('en-US', {minimumFractionDigits: d, maximumFractionDigits: d});
|
||||
export const pad = (n, w) => String(Math.max(0, Math.floor(n))).padStart(w, '0');
|
||||
|
||||
/** Deep merge plain objects; arrays and scalars from `b` replace `a`. */
|
||||
export const merge = (a, b) => {
|
||||
if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b;
|
||||
const out = {...a};
|
||||
for (const k of Object.keys(b)) {
|
||||
out[k] =
|
||||
a && typeof a[k] === 'object' && !Array.isArray(a[k]) && a[k] !== null ? merge(a[k], b[k]) : b[k];
|
||||
}
|
||||
return out;
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
// Shader warm-up before a live page's first frame. three.js links a program the first time something draws with it,
|
||||
// and the frame waits on every one in turn: 1-2 s on a phone or an integrated GPU, and a frozen page meanwhile. Here
|
||||
// all of them start at once and the page awaits them without blocking (renderer.compileAsync, KHR_parallel_shader_compile):
|
||||
// the scene's materials and the ones held by post passes (GTAO, bloom, ink, output), which compileAsync never meets
|
||||
// on its own because they only reach the renderer inside composer.render().
|
||||
//
|
||||
// A warmed program only helps when its cache key matches the one the frame asks for, so everything here mirrors the
|
||||
// frame: each set compiles against the target it draws into (tone mapping, colour space), pass quads have no normals
|
||||
// like three's fullscreen triangle, override materials (GTAO's normals) see the scene's lights and shadows, and the
|
||||
// two settings three only fixes on its first render (PCFSoftShadowMap, OutputPass defines) are fixed first.
|
||||
import * as THREE from 'three';
|
||||
|
||||
// three's FullScreenQuad geometry: position and uv, no normal
|
||||
const TRI = new THREE.BufferGeometry();
|
||||
TRI.setAttribute('position', new THREE.Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3));
|
||||
TRI.setAttribute('uv', new THREE.Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2));
|
||||
// a stand-in for the scene's meshes under an override material
|
||||
const MESH = new THREE.PlaneGeometry(1, 1);
|
||||
|
||||
// every material a pass holds directly or in an array (GTAOPass, UnrealBloomPass, ShaderPass, OutputPass)
|
||||
const materialsOf = (pass) => Object.values(pass).flatMap((v) => (v?.isMaterial ? [v] : Array.isArray(v) ? v.filter((m) => m?.isMaterial) : []));
|
||||
// drawn over the scene's own meshes instead of on a quad
|
||||
const isOverride = (m) => m.isMeshNormalMaterial || m.isMeshDepthMaterial || m.isMeshDistanceMaterial;
|
||||
|
||||
/**
|
||||
* jobs: [{scene, target}] or [{materials, target, lights, override}]; target null is the canvas, lights a scene whose
|
||||
* lights apply, override true for materials drawn as scene.overrideMaterial whatever their type.
|
||||
*/
|
||||
export function warmUp(renderer, camera, jobs) {
|
||||
// three swaps the removed PCFSoftShadowMap for PCFShadowMap inside its first shadow render, after any warm-up
|
||||
if (renderer.shadowMap.type === THREE.PCFSoftShadowMap) renderer.shadowMap.type = THREE.PCFShadowMap;
|
||||
const prev = renderer.getRenderTarget();
|
||||
const waits = jobs.map(({scene, materials = [], target = null, lights = null, override = false}) => {
|
||||
let root = scene;
|
||||
if (!root) {
|
||||
root = new THREE.Scene();
|
||||
for (const m of materials) root.add(new THREE.Mesh(override || isOverride(m) ? MESH : TRI, m));
|
||||
}
|
||||
renderer.setRenderTarget(target);
|
||||
return renderer.compileAsync(root, camera, lights);
|
||||
});
|
||||
renderer.setRenderTarget(prev);
|
||||
return Promise.all(waits);
|
||||
}
|
||||
|
||||
/** The scene and every enabled pass of an EffectComposer; the last pass draws to the canvas when the composer does. */
|
||||
export function warmComposer(renderer, composer, scene, camera, jobs = []) {
|
||||
const target = composer.renderTarget1;
|
||||
const passes = composer.passes.filter((p) => p.enabled);
|
||||
const last = composer.renderToScreen ? passes[passes.length - 1] : null;
|
||||
// OutputPass picks its defines from the renderer on its first render: run that part now, with the draw left out
|
||||
for (const p of passes.filter((x) => x.isOutputPass)) {
|
||||
const quad = p._fsQuad;
|
||||
p._fsQuad = {render() {}};
|
||||
p.render(renderer, composer.renderTarget2, composer.renderTarget1);
|
||||
p._fsQuad = quad;
|
||||
}
|
||||
const mats = passes.filter((p) => p !== last).flatMap(materialsOf);
|
||||
return warmUp(renderer, camera, [
|
||||
{scene, target},
|
||||
{materials: mats.filter((m) => !isOverride(m)), target},
|
||||
{materials: mats.filter(isOverride), target, lights: scene},
|
||||
{materials: last ? materialsOf(last) : [], target: null},
|
||||
...jobs,
|
||||
]);
|
||||
}
|
||||
Reference in New Issue
Block a user