// spacebeam: Beam's 49 MoE layers (3..51) drawn three ways. Each word of a passage makes one pass
// through all 49 layers, lighting the experts it picked; trails of earlier words fade behind it,
// and the passage loops forever.
//
// Every lit point is a real pick of a public expert, placed by its cell on the layer's 16x16 Space
// sheet (public cells 0..127 = sheet rows 0..7). Picks of withheld experts exist in routes.json only
// as a per-layer count "h"; here they only dim that layer's mark (a rim segment, an arm edge, a
// ring). They are never given a position. Loom's star comes from its layout, not from Beam.
const L = 49, ROWS = 8, COLS = 16, SUB = 6;
const HUE = { "code": 172, "maths": 40, "French": 222, "prose": 18, "tool call": 330 };
const SAT = { "code": 70, "maths": 85, "French": 85, "prose": 35, "tool call": 75 };
const LABEL = { "tool call": "tool calls" };
const NOTE = {
"code": "Python source", "maths": "a word problem and its worked answer", "French": "French Wikipedia",
"prose": "English Wikipedia", "tool call": "one of Beam's own tool calls in an agent run",
};
const $ = id => document.getElementById(id);
const canvas = $("orbit"), ctx = canvas.getContext("2d");
const S = {
routes: null, cards: null, grid: false, ex: 0, view: 2, p: 0, clock: 0, wps: 1, trail: 105, paused: false, last: null,
g: null, bg: null, cache: new Map(), hover: null, cellPts: null, markPts: null,
};
// ---- the three views ---------------------------------------------------------------------------
// v = (sheet row + 0.5) / 8, w = sheet column / 15: a public cell's place on its layer's sheet
const param = cell => [(Math.floor(cell / COLS) + 0.5) / ROWS, (cell % COLS) / (COLS - 1)];
const polar = (th, r) => [S.g.c + r * Math.cos(th), S.g.c + r * Math.sin(th)];
const A = 2 * Math.PI / L;
const STAR = 20; // Loom: each next layer sits 20 wedges on round the circle (49 and 20 share no factor)
const VIEWS = [
{
name: "Orbit", centreWord: true, spin: 0, strongest: true,
line: "Orbit: the 49 layers as one ring, clockwise from layer 3 at the top; each word goes round once, its line passing through its strongest public pick in each layer.",
mark: "rim",
setup(g) { g.R0 = g.size * 0.17; g.R1 = g.size * 0.425; g.Rr = g.size * 0.446; },
pos(t, v, w) { const g = S.g; return polar(-Math.PI / 2 + A * (t + 0.08 + 0.84 * v), g.R0 + (g.R1 - g.R0) * w); },
markLine(i) { return arcPts(-Math.PI / 2 + A * (i + 0.08), -Math.PI / 2 + A * (i + 0.92), S.g.Rr, 6); },
labels: [0, 12, 24, 36, 48],
label(i) { return polar(-Math.PI / 2 + A * (i + 0.5), S.g.Rr + 15 * S.g.u); },
},
{
name: "Rings", centreWord: false, spin: 0, markBase: 0.04, perWord: true, thin: true,
line: "Rings: one ring per layer, layer 3 innermost; each word is one spoke, the passage goes round like a clock hand.",
mark: "ring",
setup(g) { g.Q0 = g.size * 0.075; g.Q1 = g.size * 0.455; g.bw = (g.Q1 - g.Q0) / L; },
// a word's slot is its place in the passage; inside the slot and the layer's band, a pick sits by its sheet cell
pos(t, v, w, f, k) {
const g = S.g, slot = 2 * Math.PI / S.routes.excerpts[S.ex].n;
return polar(-Math.PI / 2 + slot * (k + 0.5 + 0.8 * (v - 0.5)), g.Q0 + g.bw * (t + 0.1 + 0.8 * w));
},
markLine(i) { return arcPts(-Math.PI / 2, 1.5 * Math.PI, S.g.Q0 + S.g.bw * (i + 0.95), 128); },
labels: [0, 48],
label(i) { return i ? polar(-Math.PI / 2, S.g.Q1 + 12 * S.g.u) : [S.g.c, S.g.c]; },
},
{
name: "Loom", centreWord: false, spin: 0, chord: true, strongest: true,
line: "Loom: the star shape comes from the layout, not from Beam: each next layer is placed 20 wedges further round, so every word's line is a 49-point star; only the points inside each wedge come from Beam. Each thread passes through the layer's strongest public pick.",
mark: "rim",
setup(g) { g.R0 = g.size * 0.30; g.R1 = g.size * 0.425; g.Rr = g.size * 0.446; },
slot(i) { return (i * STAR) % L; },
pos(t, v, w) { const g = S.g; return polar(-Math.PI / 2 + A * (this.slot(t) + 0.08 + 0.84 * v), g.R0 + (g.R1 - g.R0) * w); },
markLine(i) { const j = this.slot(i); return arcPts(-Math.PI / 2 + A * (j + 0.08), -Math.PI / 2 + A * (j + 0.92), S.g.Rr, 6); },
labels: [0, 1, 2, 24, 48],
label(i) { return polar(-Math.PI / 2 + A * (this.slot(i) + 0.5), S.g.Rr + 15 * S.g.u); },
},
];
function arcPts(a0, a1, r, n) { const p = []; for (let k = 0; k <= n; k++) p.push(polar(a0 + (a1 - a0) * k / n, r)); return p; }
function fillGaps(arr, dflt) {
for (let i = 0; i < arr.length; i++) if (arr[i] == null) {
let a = i - 1; while (a >= 0 && arr[a] == null) a--;
let b = i + 1; while (b < arr.length && arr[b] == null) b++;
arr[i] = a >= 0 ? arr[a] : b < arr.length ? arr[b] : dflt(i);
}
}
const view = () => VIEWS[S.view];
const cellXY = (i, cell, k = 0) => view().pos(i, ...param(cell), 0, k);
// the word's line through each layer's weighted centre (in sheet coordinates) of its public picks;
// a layer whose picks all went to withheld experts has no centre, the line passes between neighbours
function paramPath(tok, k) {
const strongest = view().strongest; // Orbit and Loom thread through each layer's strongest public pick (ties: lowest cell), so every vertex is a real dot
const vw = tok.L.map(l => {
if (!l.p.length) return null;
if (strongest) { let best = l.p[0]; for (const q of l.p) if (q[1] > best[1]) best = q; return param(best[0]); }
let v = 0, w = 0, s = 0;
for (const [cell, wt] of l.p) { const [a, b] = param(cell); v += a * wt; w += b * wt; s += wt; }
return [v / s, w / s];
});
for (let i = 0; i < L; i++) if (!vw[i]) {
let a = i - 1; while (a >= 0 && !vw[a]) a--;
let b = i + 1; while (b < L && !vw[b]) b++;
const pa = a >= 0 ? vw[a] : null, pb = b < L ? vw[b] : null;
vw[i] = pa && pb ? [(pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2] : (pa || pb || [0.5, 0.5]).slice();
}
const poly = [], V = view();
for (let i = 0; i < L; i++) {
const n = i + 1 < L ? SUB : 1, a = vw[i], j = Math.min(L - 1, i + 1), b = vw[j];
if (V.chord) { // a straight thread from one layer's centre to the next
const p = V.pos(i, ...a, 0, k), q = V.pos(j, ...b, 0, k);
for (let s = 0; s < n; s++) { const f = s / SUB; poly.push([p[0] + (q[0] - p[0]) * f, p[1] + (q[1] - p[1]) * f]); }
} else for (let s = 0; s < n; s++) { const f = s / SUB; poly.push(V.pos(i + f, a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, f, k)); }
}
return poly;
}
// ---- data and controls ------------------------------------------------------------------------
Promise.all([fetch("routes.json").then(r => r.json()), fetch("cards.json").then(r => r.json())]).then(([r, c]) => {
S.routes = r; S.cards = c;
VIEWS.forEach((v, i) => {
const b = document.createElement("button");
b.textContent = v.name; b.title = `${v.name} (${i + 1})`; b.onclick = () => pickView(i);
$("views").appendChild(b);
});
r.excerpts.forEach((e, i) => {
const b = document.createElement("button");
b.textContent = LABEL[e.kind] || e.kind; b.onclick = () => pickExcerpt(i);
$("kinds").appendChild(b);
});
window.addEventListener("resize", layout);
pickExcerpt(0);
pickView(VIEWS.findIndex(v => v.name === "Loom")); // Loom opens first
$("text").onclick = ev => { const s = ev.target.closest("span[data-k]"); if (s) { S.p = +s.dataset.k; S.cache.clear(); } };
requestAnimationFrame(frame);
});
function speedFromSlider() {
S.wps = 0.1 * Math.pow(6.25, +$("speed").value / 100); // 10 s/word .. 1.6 s/word at the fastest
$("speedv").textContent = S.wps < 1 ? `${(1 / S.wps).toFixed(1)} s/word` : `${S.wps.toFixed(1)} words/s`;
}
function trailFromSlider() {
const e = S.routes.excerpts[S.ex];
S.trail = Math.max(1, Math.min(e.n, +$("trail").value));
$("trailv").textContent = S.trail >= e.n ? "whole passage" : `${S.trail} word${S.trail > 1 ? "s" : ""}`;
}
$("speed").oninput = speedFromSlider;
$("trail").oninput = trailFromSlider;
$("pause").onclick = togglePause;
$("save").onclick = savePNG;
// the timeline: one stop per layer of every word; dragging or stepping pauses the loop and puts you there
function setPause(p) { S.paused = p; $("pause").textContent = p ? "Play" : "Pause"; $("pause").classList.toggle("on", p); }
function seek(pos) { // pos in words, within this pass of the passage
const n = S.routes.excerpts[S.ex].n, loop = Math.floor(S.p / n) * n;
S.p = loop + Math.max(0, Math.min(n - 1e-6, pos));
}
function stepLayer(d) {
if (!S.routes) return; setPause(true);
const n = S.routes.excerpts[S.ex].n, q = Math.floor(((S.p % n) + n) % n * L + 1e-6) + d; // in layer steps: the layer now showing, plus d
seek(((q % (n * L)) + n * L) % (n * L) / L + 0.5 / (L * 8));
}
$("scrub").addEventListener("input", () => { setPause(true); seek(+$("scrub").value); S.scrubbing = true; });
$("scrub").addEventListener("change", () => { S.scrubbing = false; });
$("tstep0").onclick = () => stepLayer(-1);
$("tstep1").onclick = () => stepLayer(1);
function toggleGrid() { S.grid = !S.grid; $("grid").classList.toggle("on", S.grid); if (S.g) S.bg = drawBackground(); }
$("grid").onclick = toggleGrid;
function togglePause() { S.paused = !S.paused; $("pause").textContent = S.paused ? "Play" : "Pause"; $("pause").classList.toggle("on", S.paused); }
window.addEventListener("keydown", ev => {
if (ev.metaKey || ev.ctrlKey || ev.altKey) return;
if (ev.key === " ") { ev.preventDefault(); togglePause(); }
else if (ev.key === "s") savePNG();
else if (ev.key === "g") toggleGrid();
else if (ev.key === "ArrowLeft") { ev.preventDefault(); stepLayer(-1); }
else if (ev.key === "ArrowRight") { ev.preventDefault(); stepLayer(1); }
else if (/^[1-3]$/.test(ev.key) && S.routes) pickView(+ev.key - 1);
});
speedFromSlider();
function pickView(i) {
S.view = i; S.guide = null; S.detailKey = null;
[...$("views").children].forEach((b, k) => b.classList.toggle("on", k === i));
layout();
caption();
}
function pickExcerpt(i) {
const wasWhole = +$("trail").value >= +$("trail").max;
S.ex = i; S.p = 0; S.cache.clear();
const e = S.routes.excerpts[i];
[...$("kinds").children].forEach((b, k) => b.classList.toggle("on", k === i));
$("trail").max = e.n;
if (wasWhole || +$("trail").value > e.n) $("trail").value = e.n;
trailFromSlider();
caption();
if (S.g) S.bg = drawBackground();
$("ptitle").textContent = `${LABEL[e.kind] || e.kind} · ${e.n} words`;
$("psrc").textContent = `${e.source} · ${e.licence}`;
$("text").innerHTML = e.tokens.map((t, k) => `${esc(t.t)}`).join("");
S.lit = -1;
}
function caption() {
if (!S.routes) return;
const e = S.routes.excerpts[S.ex], V = view();
const src = e.origin.includes("/wiki/") ? decodeURIComponent(e.origin.split("/wiki/")[1]) : `${e.source}, ${e.origin}`;
const text = `${V.line} Every point is an expert the word really picked, at its place on the layer's map, brighter where words agree; ` +
`colour shows word order, from the passage's first word to its last; ` +
`the ${V.mark} dims by picks that went to withheld experts, counted, never placed.`;
$("caption").innerHTML = `spacebeam · ${esc(text)} · ${LABEL[e.kind] || e.kind}: ${e.n} words of ${NOTE[e.kind]} (${esc(src)}, ${e.licence})`;
$("caption").title = $("caption").textContent;
$("legend").innerHTML = [ // the same caption, listed in the panel
`${esc(V.name)}: ${esc(V.line.replace(/^[A-Za-z]+: /, ""))}`,
"Every point is an expert the word really picked, at its place on the layer's map, brighter where words agree.",
"Colour shows word order, from the passage's first word to its last.",
`The ${esc(V.mark)} dims by picks that went to withheld experts: counted, never placed.`,
`${esc(LABEL[e.kind] || e.kind)}: ${e.n} words of ${esc(NOTE[e.kind])} (${esc(src)}, ${esc(e.licence)})`,
].map(s => `
${s}`).join("");
}
// ---- geometry -----------------------------------------------------------------------------------
function layout() {
const st = $("stage"), w = st.clientWidth || 900, h = st.clientHeight || 800;
const size = Math.max(320, Math.min(w, h) - 8), dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(size * dpr); canvas.height = Math.round(size * dpr);
canvas.style.width = size + "px"; canvas.style.height = size + "px";
S.g = { size, dpr, c: size / 2, u: size / 800 };
view().setup(S.g);
S.cache.clear();
S.cellPts = []; // every public cell's place, for the faint background and for hover; Rings places by word, so none
if (!view().perWord) for (let i = 0; i < L; i++) for (let c = 0; c < 128; c++) S.cellPts.push([i, c, ...cellXY(i, c)]);
S.markPts = []; for (let i = 0; i < L; i++) S.markPts.push(view().markLine(i));
S.bg = drawBackground();
}
// along a word's pass, opacity rises from layer 3 to a peak mid-model and falls to layer 51, so one word's
// end fades as the next word's start rises: one continuous movement from token to token
const NB = 14, env = s => Math.pow(Math.sin(Math.PI * Math.min(1, Math.max(0, s))), 0.9);
function wordGeom(k) {
let g = S.cache.get(k);
if (g) return g;
const tok = S.routes.excerpts[S.ex].tokens[k], u = S.g.u, V = view();
const poly = paramPath(tok, k);
const line = new Path2D(), dots = new Path2D(), picks = [];
poly.forEach(([x, y], j) => (j ? line.lineTo(x, y) : line.moveTo(x, y)));
tok.L.forEach((l, i) => {
for (const [cell, w] of l.p) {
const [x, y] = cellXY(i, cell, k), r = V.perWord ? Math.min(u * (0.5 + 4 * w), 0.45 * S.g.bw) : u * (1.0 + 7 * w);
if (V.streak) { // a star streak, along the direction of the galaxy's turn
const tan = Math.atan2(y - S.g.c, x - S.g.c) + Math.PI / 2;
dots.moveTo(x + Math.cos(tan) * r * 3, y + Math.sin(tan) * r * 3); dots.ellipse(x, y, r * 3, r * 0.55, tan, 0, 2 * Math.PI);
} else { dots.moveTo(x + r, y); dots.arc(x, y, r, 0, 2 * Math.PI); }
picks.push({ i, cell, w, x, y, r });
}
});
const bands = Array.from({ length: NB }, () => new Path2D()), last = poly.length - 1;
for (let j = 0; j < last; j++) { const b = bands[Math.min(NB - 1, Math.floor(NB * j / last))]; b.moveTo(...poly[j]); b.lineTo(...poly[j + 1]); }
g = { poly, line, bands, dots, picks, hid: tok.L.map(l => l.h) };
S.cache.set(k, g);
return g;
}
function colour(k, a, light = 62) {
const e = S.routes.excerpts[S.ex], t = e.tokens[k];
const hue = HUE[e.kind] + 36 * (k / Math.max(1, e.n - 1) - 0.5); // drifts from the first word to the last
return `hsla(${hue.toFixed(1)},${t.s ? 8 : SAT[e.kind]}%,${light}%,${Math.max(0, a).toFixed(3)})`;
}
// ---- drawing ------------------------------------------------------------------------------------
function strokePts(x, pts) { x.beginPath(); pts.forEach(([a, b], j) => (j ? x.lineTo(a, b) : x.moveTo(a, b))); x.stroke(); }
function drawBackground() {
const { dpr, u } = S.g, off = document.createElement("canvas");
off.width = canvas.width; off.height = canvas.height;
const x = off.getContext("2d");
x.setTransform(dpr, 0, 0, dpr, 0, 0);
x.fillStyle = "rgba(232,232,227,0.07)";
const d = Math.max(0.8, u);
for (const [, , px, py] of S.cellPts) x.fillRect(px - d / 2, py - d / 2, d, d);
if (S.grid) {
const g = S.g, V = view();
x.strokeStyle = "rgba(232,232,227,0.09)"; x.lineWidth = 0.6 * u; x.beginPath();
if (V.perWord) {
const n = S.routes.excerpts[S.ex].n;
for (let i = 0; i <= L; i++) { x.moveTo(g.c + g.Q0 + g.bw * i, g.c); x.arc(g.c, g.c, g.Q0 + g.bw * i, 0, 2 * Math.PI); }
for (let k = 0; k < n; k++) { const th = -Math.PI / 2 + 2 * Math.PI * k / n; x.moveTo(...polar(th, g.Q0)); x.lineTo(...polar(th, g.Q1)); }
} else {
for (let s = 0; s < L; s++) { const th = -Math.PI / 2 + A * s; x.moveTo(...polar(th, g.R0)); x.lineTo(...polar(th, g.R1)); }
for (let q = 0; q <= 4; q++) { const r = g.R0 + (g.R1 - g.R0) * q / 4; x.moveTo(g.c + r, g.c); x.arc(g.c, g.c, r, 0, 2 * Math.PI); }
}
x.stroke();
}
x.lineWidth = (view().thin ? 0.6 : 2) * u; x.strokeStyle = "rgba(232,232,227,0.06)";
for (const pts of S.markPts) strokePts(x, pts);
x.font = `${Math.max(9, 10 * u)}px ui-monospace, Menlo, monospace`;
x.fillStyle = "rgba(232,232,227,0.3)"; x.textAlign = "center"; x.textBaseline = "middle";
for (const i of view().labels) x.fillText(`L${S.routes.meta.layers[i]}`, ...view().label(i));
return off;
}
function fadeOf(age) {
// age in words since the word finished its pass; the trail slider sets how long it stays
const T = S.trail, whole = T >= S.routes.excerpts[S.ex].n;
if (age >= T) return 0;
const f = Math.exp(-2.5 * age / T);
return whole ? 0.45 + 0.55 * f : f * (1 - age / T) ** 0.5; // 1 at hand-over, 0 at the trail's end, no step
}
function frame(now) {
if (S.last == null) S.last = now;
const dt = Math.min(0.1, (now - S.last) / 1000); S.last = now;
if (!S.paused) { S.p += dt * S.wps; S.clock += dt; }
draw();
requestAnimationFrame(frame);
}
function draw() {
if (!S.g || !S.routes) return;
const { size, dpr, c, u } = S.g, V = view();
const e = S.routes.excerpts[S.ex], n = e.n;
const whole = Math.floor(S.p), k = ((whole % n) + n) % n, phase = (S.p - whole) * L; // 0..49
const rot = V.spin * S.clock;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "#0b0b0c"; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.save();
if (rot) { ctx.translate(c, c); ctx.rotate(rot); ctx.translate(-c, -c); }
ctx.drawImage(S.bg, 0, 0, size, size);
// trail: earlier words, oldest first
ctx.globalCompositeOperation = "lighter";
const mark = new Float32Array(L), markW = new Float32Array(L);
// where many words overlap, each is fainter, so the bright places are where words agree
const dim = V.perWord ? 1 : Math.pow(Math.min(1, 8 / Math.min(S.trail, n)), 0.6);
for (let a = whole - Math.min(S.trail, n - 1); a < whole; a++) {
if (a < 0) continue;
const kk = ((a % n) + n) % n, f = fadeOf(whole - a - 1 + phase / L);
if (f <= 0.003) continue;
const g = wordGeom(kk);
ctx.lineWidth = 0.8 * u;
for (let b = 0; b < NB; b++) { ctx.strokeStyle = colour(kk, (0.12 + 0.78 * env((b + 0.5) / NB)) * f * Math.sqrt(dim), 70 - 12 * (1 - f)); ctx.stroke(g.bands[b]); }
ctx.fillStyle = colour(kk, 0.65 * f * dim, 62); ctx.fill(g.dots);
for (let i = 0; i < L; i++) { mark[i] += f * (8 - g.hid[i]) / 8; markW[i] += f; }
}
// the current word, revealed layer by layer
const g = wordGeom(k), upto = Math.min(L - 1, Math.floor(phase));
const head = Math.min(g.poly.length - 1, Math.floor(phase * SUB));
ctx.lineWidth = 1.4 * u;
for (let j = 0; j < head; j++) { // the same rise and fall along the pass, drawn up to the head
ctx.strokeStyle = colour(k, 0.12 + 0.78 * env((j + 0.5) / (g.poly.length - 1)), 70);
ctx.beginPath(); ctx.moveTo(...g.poly[j]); ctx.lineTo(...g.poly[j + 1]); ctx.stroke();
}
for (const pk of g.picks) {
if (pk.i > upto) continue;
const flash = Math.max(0, 1 - (phase - pk.i) / 3); // bright as the word arrives
ctx.fillStyle = colour(k, 0.65 + 0.35 * flash, 62 + 30 * flash);
ctx.beginPath(); ctx.arc(pk.x, pk.y, pk.r * (1 + 1.2 * flash), 0, 2 * Math.PI); ctx.fill();
if (pk.i === upto) { // spokes from the word to this layer's picks
ctx.strokeStyle = colour(k, 0.35 * flash + 0.1, 80); ctx.lineWidth = 0.7 * u;
ctx.beginPath(); ctx.moveTo(...g.poly[head]); ctx.lineTo(pk.x, pk.y); ctx.stroke();
}
}
// each layer's mark: bright where its picks were public, dimmed by the count that went to withheld experts
ctx.lineCap = "round";
const thin = V.thin;
for (let i = 0; i < L; i++) {
if (markW[i] > 0) {
ctx.strokeStyle = `rgba(232,232,227,${((thin ? 0.08 : 0.22) * mark[i] / markW[i] * Math.min(1, markW[i] / 3)).toFixed(3)})`;
ctx.lineWidth = (thin ? 0.8 : 2) * u; strokePts(ctx, S.markPts[i]);
}
if (i <= upto) {
const share = (8 - g.hid[i]) / 8, flash = Math.max(0, 1 - (phase - i) / 4);
ctx.strokeStyle = colour(k, ((V.markBase ?? 0.15) + 0.6 * flash) * share, 70);
ctx.lineWidth = ((thin ? 0.8 : 2) + (thin ? 1.5 : 3) * flash) * u; strokePts(ctx, S.markPts[i]);
}
}
// the travelling word's head
const [hx, hy] = g.poly[head], hr = 14 * u;
const grad = ctx.createRadialGradient(hx, hy, 0, hx, hy, hr);
grad.addColorStop(0, "rgba(255,255,255,0.9)"); grad.addColorStop(0.3, colour(k, 0.5, 70)); grad.addColorStop(1, colour(k, 0, 70));
ctx.fillStyle = grad; ctx.beginPath(); ctx.arc(hx, hy, hr, 0, 2 * Math.PI); ctx.fill();
ctx.globalCompositeOperation = "source-over";
if (S.hover && S.hover.cell != null) {
const [px, py] = cellXY(S.hover.i, S.hover.cell, S.hover.k ?? 0);
ctx.strokeStyle = "rgba(255,255,255,0.85)"; ctx.lineWidth = 1;
ctx.beginPath(); ctx.arc(px, py, Math.max(5 * u, (S.hover.r ?? 0) * 2.2) + 3, 0, 2 * Math.PI); ctx.stroke();
}
drawGuide();
ctx.restore();
detail(k, upto);
// the word now travelling: in the empty centre of Orbit, in the corner elsewhere
const word = show(e.tokens[k].t), small = `${Math.max(9, 10 * u)}px ui-monospace, Menlo, monospace`;
if (V.centreWord) {
ctx.textAlign = "center"; ctx.textBaseline = "middle";
const fs = Math.max(12, Math.min(34 * u, (S.g.R0 * 2.7) / Math.max(3, word.length)));
ctx.font = `${fs}px ui-monospace, Menlo, monospace`; ctx.fillStyle = colour(k, 0.95, 82);
ctx.fillText(word, c, c - 6 * u);
ctx.font = small; ctx.fillStyle = "rgba(232,232,227,0.4)";
ctx.fillText(`word ${k + 1} of ${n} · layer ${S.routes.meta.layers[upto]}`, c, c + fs * 0.75);
} else {
ctx.textAlign = "left"; ctx.textBaseline = "top";
const fs = Math.max(12, 20 * u);
ctx.font = `${fs}px ui-monospace, Menlo, monospace`; ctx.fillStyle = colour(k, 0.95, 82);
ctx.fillText(word.length > 28 ? word.slice(0, 27) + "…" : word, 10 * u, 10 * u);
ctx.font = small; ctx.fillStyle = "rgba(232,232,227,0.4)";
ctx.fillText(`word ${k + 1} of ${n} · layer ${S.routes.meta.layers[upto]}`, 10 * u, 14 * u + fs);
}
// quiet signature, so a saved PNG says what it is
ctx.font = small; ctx.textAlign = "left"; ctx.textBaseline = "alphabetic"; ctx.fillStyle = "rgba(232,232,227,0.26)";
ctx.fillText(`spacebeam · ${V.name} · Beam-1.0-501B-A23B · ${LABEL[e.kind] || e.kind} · every point is a real expert pick`, 10 * u, size - 10 * u);
if (S.hover) showTip();
// the timeline follows the loop; its label names the word and the layer the word has reached
const sc = $("scrub"); if (+sc.max !== n) sc.max = n;
if (!S.scrubbing) sc.value = ((S.p % n) + n) % n;
$("tpos").textContent = `word ${k + 1} of ${n} · layer ${S.routes.meta.layers[upto]}`;
if (S.lit !== k) { // light the word now travelling in the passage panel
const box = $("text"), old = box.querySelector("span.now"), cur = box.querySelector(`span[data-k="${k}"]`);
if (old) old.classList.remove("now");
if (cur) { cur.classList.add("now"); const top = cur.offsetTop - box.offsetTop; if (top < box.scrollTop || top > box.scrollTop + box.clientHeight - 30) box.scrollTop = top - box.clientHeight / 3; }
S.lit = k;
}
}
function show(t) { return t.replace(/\n/g, "⏎").replace(/\t/g, "⇥").replace(/^ /, "·").replace(/^\s+$/, s => "·".repeat(s.length)); }
function esc(s) { return String(s).replace(/[&<>"]/g, ch => ({ "&": "&", "<": "<", ">": ">", '"': """ })[ch]); }
// ---- hover: name the expert and the words that picked it -------------------------------------
function hit(ev) {
if (!S.g || !S.cellPts) return null;
const r = canvas.getBoundingClientRect(), mx = ev.clientX - r.left, my = ev.clientY - r.top, { c, u } = S.g;
const rot = view().spin * S.clock, cs = Math.cos(-rot), sn = Math.sin(-rot);
const x = c + (mx - c) * cs - (my - c) * sn, y = c + (mx - c) * sn + (my - c) * cs; // undo the turn
let best = null, bd = (8 * u + 3) ** 2;
for (const v of visibleWords()) for (const pk of wordGeom(v.k).picks) { // lit points first
if (pk.i > v.upto) continue;
const d = (pk.x - x) ** 2 + (pk.y - y) ** 2; if (d < bd) { bd = d; best = { i: pk.i, cell: pk.cell, k: v.k, r: pk.r }; }
}
if (!best) for (const [i, cell, px, py] of S.cellPts) { const d = (px - x) ** 2 + (py - y) ** 2; if (d < bd) { bd = d; best = { i, cell }; } }
if (!best) {
bd = (6 * u + 3) ** 2;
S.markPts.forEach((pts, i) => {
for (let j = 0; j + 1 < pts.length; j++) { const d = segDist2(x, y, pts[j], pts[j + 1]); if (d < bd) { bd = d; best = { i, mark: true }; } }
});
}
if (best && best.mark && view().perWord) { const la = layerAt(mx, my); if (la) best.i = la.i; }
return best && { ...best, x: mx, y: my };
}
// the layer under the mouse, and the guide line across every layer: in Orbit and Loom a circle at the
// mouse's radius through all 49 wedges, in Rings a spoke at the mouse's angle through all 49 rings;
// each view draws the other direction too, so the mouse sits at a crossing
const LOOM_LAYER = (() => { const m = []; for (let i = 0; i < L; i++) m[(i * STAR) % L] = i; return m; })();
function layerAt(mx, my) {
const g = S.g, V = view(), dx = mx - g.c, dy = my - g.c, r = Math.hypot(dx, dy);
const th = Math.atan2(dy, dx), turn = ((th + Math.PI / 2) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI);
if (V.perWord) {
if (r < g.Q0 || r > g.Q1) return null;
return { i: Math.min(L - 1, Math.floor((r - g.Q0) / g.bw)), th, r, r0: g.Q0, r1: g.Q1 };
}
if (r < g.R0 * 0.85 || r > g.Rr * 1.06) return null;
const slot = Math.floor(turn / A) % L;
return { i: V.slot ? LOOM_LAYER[slot] : slot, th, r: Math.max(g.R0, Math.min(g.R1, r)), r0: g.R0, r1: g.Rr };
}
function drawGuide() {
const m = S.guide; if (!m) return;
const g = S.g, V = view(), u = g.u;
ctx.globalCompositeOperation = "source-over";
ctx.strokeStyle = "rgba(232,232,227,0.28)"; ctx.lineWidth = 0.8 * u; ctx.setLineDash([2 * u, 4 * u]);
ctx.beginPath(); // both directions: a circle at the mouse's radius and a spoke at its angle
ctx.arc(g.c, g.c, m.r, 0, 2 * Math.PI);
ctx.moveTo(...polar(m.th, m.r0)); ctx.lineTo(...polar(m.th, m.r1));
ctx.stroke(); ctx.setLineDash([]);
ctx.strokeStyle = "rgba(255,255,255,0.75)"; ctx.lineWidth = (V.thin ? 1.6 : 3) * u; strokePts(ctx, S.markPts[m.i]);
}
// the second panel: the layer under the mouse (or the layer the word is at), for the word now travelling
function detail(k, upto) {
const i = S.guide ? S.guide.i : upto, key = `${S.ex}:${k}:${i}:${S.view}`;
if (S.detailKey === key) return; S.detailKey = key;
const e = S.routes.excerpts[S.ex], tok = e.tokens[k], l = tok.L[i], n = S.routes.meta.layers[i];
const picks = l.p.slice().sort((a, b) => b[1] - a[1]).map(([cell, w]) => {
const id = S.cards.cells[n][cell], card = id && S.cards.cards[id];
return `${esc(id || "")} ${w.toFixed(3)}
${card ? card.top_tokens.slice(0, 5).map(t => `${esc(show(t))}`).join("") : ""}`;
}).join("");
$("dlayer").textContent = `Layer ${n}`;
$("dword").innerHTML = `word ${k + 1} of ${e.n}: ${esc(show(tok.t))}` + (S.guide ? "" : ` (follows the word; point at a layer to hold one)`);
$("dpicks").innerHTML = picks || `no public pick at this layer`;
$("dhid").textContent = `${l.h} of its 8 picks went to withheld experts: counted, never named or placed.` + (i > upto ? " The word has not reached this layer yet on screen." : "");
}
function segDist2(x, y, [ax, ay], [bx, by]) {
const dx = bx - ax, dy = by - ay, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / l)) : 0;
return (ax + t * dx - x) ** 2 + (ay + t * dy - y) ** 2;
}
function visibleWords() {
// the words now on screen: the current word up to its head, then the trail, newest first
const n = S.routes.excerpts[S.ex].n, whole = Math.floor(S.p), phase = (S.p - whole) * L;
const out = [{ k: ((whole % n) + n) % n, upto: Math.floor(phase) }];
for (let a = whole - 1; a >= Math.max(0, whole - Math.min(S.trail, n)); a--) {
const kk = ((a % n) + n) % n;
if (fadeOf(whole - a - 1 + phase / L) > 0.003 && !out.some(o => o.k === kk)) out.push({ k: kk, upto: L - 1 });
}
return out;
}
function showTip() {
const h = S.hover, tip = $("tip"), e = S.routes.excerpts[S.ex], n = S.routes.meta.layers[h.i];
let html;
if (h.mark) {
const cur = visibleWords()[0], hid = e.tokens[cur.k].L[h.i].h;
html = `layer ${n}
` + (h.i <= cur.upto
? `«${esc(show(e.tokens[cur.k].t))}» sent ${hid} of its 8 picks here to withheld experts: counted, never placed. This ${view().mark} dims by that share.`
: `The word has not reached this layer yet.`);
} else {
const key = S.cards.cells[n][h.cell], card = key && S.cards.cards[key];
if (!card) { tip.style.display = "none"; return; }
const by = [];
for (const v of visibleWords()) {
if (h.i > v.upto) continue;
const pk = e.tokens[v.k].L[h.i].p.find(p => p[0] === h.cell);
if (pk) by.push(`«${esc(show(e.tokens[v.k].t))}» ${pk[1].toFixed(2)}`);
}
html = `${key} layer ${n}, expert ${key.split("E")[1]}
` +
`handles most: ${card.top_tokens.slice(0, 6).map(t => `${esc(show(t))}`).join("")}
` +
(by.length ? `picked on screen by ${by.slice(0, 8).join(", ")}${by.length > 8 ? `, and ${by.length - 8} more` : ""}`
: `no word on screen picked it`);
}
tip.innerHTML = html; tip.style.display = "block";
const cr = canvas.getBoundingClientRect(), sr = $("stage").getBoundingClientRect();
tip.style.left = Math.min((sr.width || 900) - 310, cr.left - sr.left + h.x + 14) + "px";
tip.style.top = (cr.top - sr.top + h.y + 14) + "px";
}
canvas.addEventListener("mousemove", ev => {
const cr = canvas.getBoundingClientRect();
S.guide = S.g ? layerAt(ev.clientX - cr.left, ev.clientY - cr.top) : null;
S.hover = hit(ev);
canvas.style.cursor = S.hover ? "crosshair" : "default";
if (!S.hover) $("tip").style.display = "none";
});
canvas.addEventListener("mouseleave", () => { S.hover = null; S.guide = null; $("tip").style.display = "none"; });
canvas.addEventListener("click", ev => { if (!hit(ev)) togglePause(); });
function savePNG() {
if (!S.routes) return;
const name = `spacebeam-${view().name.toLowerCase()}-${S.routes.excerpts[S.ex].kind.replace(/\s+/g, "-")}.png`;
const go = url => { const a = document.createElement("a"); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); };
draw(); // the frame on screen, freshly drawn
if (canvas.toBlob) canvas.toBlob(b => { const url = URL.createObjectURL(b); go(url); setTimeout(() => URL.revokeObjectURL(url), 4000); }, "image/png");
else go(canvas.toDataURL("image/png"));
}