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:
Nyxera0x
2026-11-06 12:57:09 +03:00
parent ca143f35f4
commit 5d8f1c6efe
93 changed files with 15705 additions and 39 deletions
+400
View File
@@ -0,0 +1,400 @@
// The Theraphos TH-8 console (the Salticus JS-8's, renamed), copied from the scorpion's (roboscorp-shared/console.js, itself after the bee's): the
// orange JS-8 badge and title with the drive load and the sim status cells; the gait with a live step diagram of the
// eight legs; the jump with its arc gauge, airtime, launch and tuck; the eight leg servos; the optics with the iris,
// its trace and both main lenses' apertures; the
// assemblies the operator isolates, the display toggles, the subsystem registry; the operation log with the
// operator's actions on its timeline; the mode word in the viewport; labels with leaders into the spider and the
// operator's pointer. update(s) redraws every live part from the frame's state.
export const C = {ink: '#24211d', mute: '#9a8f82', faint: '#e0d7ca', line: '#ece5da', panel: 'rgba(253,251,247,.95)', or: '#ff5a1f', green: '#2fa36b', track: '#efe8de'};
export const VIEWS = ['hero', 'eyes', 'leg', 'abdomen', 'head', 'jump'];
export const VIEW_LABEL = {hero: 'HERO', eyes: 'OPTICS', leg: 'LEG R1', abdomen: 'ABDOMEN', head: 'HEAD', jump: 'JUMP'};
export const DISPLAY = ['labels', 'exploded', 'turntable', 'trace'];
export const DISPLAY_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', turntable: 'TURNTABLE', trace: 'GAIT TRACE'};
// the viewport: the 3D shows between the side columns, above the flight log
export const VIEWPORT = {x0: 330, x1: 1270, y0: 108, y1: 744};
const CSS = `
#app{font-family:Inter,system-ui,sans-serif;color:${C.ink};-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}
.ui{position:absolute;inset:0;pointer-events:none}
.mo{font-family:'JetBrains Mono',ui-monospace,monospace}
.cp{position:absolute;background:${C.panel};border:1px solid ${C.line};border-radius:6px;box-shadow:0 2px 10px rgba(120,90,50,.07)}
.ph{position:absolute;display:flex;align-items:center;gap:9px;font:700 10.5px 'JetBrains Mono',monospace;letter-spacing:1.8px}
.ph i{display:block;width:3px;height:13px;background:${C.or}}
.pn{position:absolute;font:500 9.5px 'JetBrains Mono',monospace;color:${C.mute};letter-spacing:1px}
.sm{font:500 9px 'JetBrains Mono',monospace;letter-spacing:1.6px;color:${C.mute};text-transform:uppercase;white-space:nowrap}
.v{font:600 11px 'JetBrains Mono',monospace;color:${C.ink};white-space:nowrap}
.bt{position:absolute;height:23px;padding:0 10px;display:flex;align-items:center;justify-content:center;border:1px solid ${C.faint};border-radius:4px;background:#fffdf9;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink};white-space:nowrap;box-sizing:border-box}
.call{position:absolute;white-space:nowrap;padding:3px 6px 3px 5px;margin:-3px 0 0 -5px;background:rgba(253,251,247,.86);border-radius:3px}
.call b{display:flex;align-items:center;gap:6px;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink}}
.call b i{display:block;width:6px;height:6px;background:${C.or}}
.call span{display:block;font:500 7.8px 'JetBrains Mono',monospace;letter-spacing:1.2px;color:${C.mute};margin-top:2px}
.chip{position:absolute;height:15px;padding:0 6px;border-radius:3px;font:700 7.6px 'JetBrains Mono',monospace;letter-spacing:1.1px;display:flex;align-items:center;white-space:nowrap}
.cur{position:absolute;left:0;top:0;z-index:50;filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}
.ring{position:absolute;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:1.5px solid ${C.or};opacity:0;z-index:49}
`;
const el = (h) => {
const d = document.createElement('div');
d.innerHTML = h.trim();
return d.firstElementChild;
};
const SUBS = [
['OPTICS ARRAY', '2 MAIN + 6 SECONDARY LENSES'],
['HEAD SHELL', 'CARAPACE · EYE PLATE · FANGS'],
['ABDOMEN CORE', 'GLASS CAGE · GLOW COILS'],
['JUMP DRIVE', 'CROUCH · LAUNCH · TUCK'],
['LEG SERVOS', '8 LEGS × 4 JOINTS'],
['FANGS & PALPS', '2 GLOWING FANGS · 2 PEDIPALPS'],
];
const LEGS = ['L1', 'L2', 'L3', 'L4', 'R1', 'R2', 'R3', 'R4'];
// opts (all optional, the first film's console when absent): views / viewLabel / viewsTitle / viewRows for the view
// panel (the second film puts its assemblies there, in two rows), display / displayLabel for the toggles; the panels
// below move down to make room and the subsystem rows close up.
export function createConsole(app, opts = {}) {
const views = opts.views ?? VIEWS;
const viewLabel = opts.viewLabel ?? VIEW_LABEL;
const display = opts.display ?? DISPLAY;
const displayLabel = opts.displayLabel ?? DISPLAY_LABEL;
const viewRows = opts.viewRows ?? 1;
const style = document.createElement('style');
style.textContent = CSS;
document.head.appendChild(style);
const ui = el(`<div class="ui"></div>`);
app.appendChild(ui);
const add = (h) => {
const n = el(h);
ui.appendChild(n);
return n;
};
const panel = (x, y, w, h, title, n) => {
add(`<div class="cp" style="left:${x}px;top:${y}px;width:${w}px;height:${h}px"></div>`);
add(`<div class="ph" style="left:${x + 14}px;top:${y + 13}px"><i></i>${title}</div>`);
add(`<div class="pn" style="right:${1600 - x - w + 14}px;top:${y + 15}px">${n}</div>`);
};
const hr = (x, y, w) => add(`<div style="position:absolute;left:${x}px;top:${y}px;width:${w}px;height:1px;background:${C.line}"></div>`);
const L = {x: 24, w: 290};
const R = {x: 1286, w: 290};
// ------------------------------------------------------------ header: badge, title, the drive load, the status cells
add(`<div style="position:absolute;left:0;top:0;width:160px;height:88px;background:${C.or}"></div>`);
add(`<svg style="position:absolute;left:22px;top:22px" width="48" height="44" viewBox="0 0 48 44"><g fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="24" cy="12" rx="8" ry="6"/><ellipse cx="24" cy="27" rx="10" ry="9"/><circle cx="21" cy="7" r="1.4"/><circle cx="27" cy="7" r="1.4"/><path d="M16 12l-8-5-5 9M32 12l8-5 5 9M15 15l-9 1-4 10M33 15l9 1 4 10M15 22l-8 6-2 10M33 22l8 6 2 10M17 31l-6 8M31 31l6 8"/></g></svg>`);
add(`<div class="mo" style="position:absolute;left:80px;top:34px;color:#fff;font-size:16px;font-weight:600;letter-spacing:3px">TH-8</div>`);
add(`<div class="sm" style="position:absolute;left:182px;top:20px;letter-spacing:2.4px">ROBOTIC TARANTULA · HEAVY HUNTER UNIT</div>`);
add(`<div style="position:absolute;left:181px;top:35px;font-size:33px;font-weight:700;letter-spacing:-.6px;line-height:1">Theraphos TH-8 <span style="color:${C.or};font-weight:400">/</span></div>`);
add(`<div class="mo" style="position:absolute;left:182px;top:74px;font-size:11.2px;letter-spacing:2.2px;color:#6d6357">OCTOPOD HUNTER / FIELD SIMULATOR</div>`);
add(`<div class="sm" style="position:absolute;left:700px;top:22px">DRIVE LOAD</div>`);
const liftPct = add(`<div class="mo" style="position:absolute;right:${1600 - 1040}px;top:21px;font-size:10px;font-weight:700"></div>`);
const liftCells = [];
for (let i = 0; i < 40; i++) liftCells.push(add(`<div style="position:absolute;left:${700 + i * 8.5}px;top:38px;width:6px;height:13px;border-radius:1px;background:${C.track}"></div>`));
add(`<div class="sm" style="position:absolute;left:700px;top:57px;font-size:7.6px">IDLE</div>`);
add(`<div class="sm" style="position:absolute;left:846px;top:57px;font-size:7.6px">CRUISE</div>`);
add(`<div class="sm" style="position:absolute;left:1010px;top:57px;font-size:7.6px">MAX</div>`);
const cells = [
['SIM ID', 'TH8-1104'],
['RUNTIME', ''],
['STATUS', ''],
['OPERATOR', 'BAY 2 · M.V.'],
];
const cellV = cells.map(([k, v], i) => {
const x = 1086 + i * 118;
if (i) add(`<div style="position:absolute;left:${x - 12}px;top:20px;width:1px;height:44px;background:${C.faint}"></div>`);
add(`<div class="sm" style="position:absolute;left:${x}px;top:22px">${k}</div>`);
return add(`<div class="mo" style="position:absolute;left:${x}px;top:40px;font-size:12px;font-weight:600;letter-spacing:.4px">${v}</div>`);
});
{
let h = '';
for (let r = 0; r < 2; r++) for (let c = 0; c < 14; c++) h += `<path d="M${c * 25 + 4} ${r * 22}v8M${c * 25} ${r * 22 + 4}h8" stroke="${C.or}" stroke-width="1.1" opacity=".55"/>`;
add(`<svg style="position:absolute;left:640px;top:84px" width="352" height="34">${h}</svg>`);
}
// ------------------------------------------------------------ 01 gait: the stride rate, the speed, the step diagram
panel(L.x, 108, L.w, 226, 'GAIT', '01');
const fq = add(`<div style="position:absolute;left:38px;top:140px;font-size:34px;font-weight:700;letter-spacing:-1px;line-height:1"></div>`);
add(`<div class="sm" style="position:absolute;left:39px;top:178px">STRIDE RATE</div>`);
const amp = add(`<div style="position:absolute;right:${1600 - 300}px;top:146px;font-size:22px;font-weight:700;line-height:1"></div>`);
add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:178px">MM/S</div>`);
const chart = add(`<svg style="position:absolute;left:38px;top:196px" width="262" height="100"></svg>`);
hr(38, 302, 262);
add(`<div class="sm" style="position:absolute;left:38px;top:312px">PATTERN</div>`);
const pb = add(`<div class="v" style="position:absolute;left:100px;top:310px"></div>`);
const shutter = add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:312px"></div>`);
// ------------------------------------------------------------ 02 jump: the height, the arc gauge, the cells
panel(L.x, 346, L.w, 148, 'JUMP', '02');
const batt = add(`<div style="position:absolute;left:38px;top:378px;font-size:28px;font-weight:700;letter-spacing:-.8px;line-height:1"></div>`);
add(`<div class="sm" style="position:absolute;left:39px;top:410px">HEIGHT OVER STANCE</div>`);
const gauge = add(`<svg style="position:absolute;left:176px;top:366px" width="124" height="58"></svg>`);
hr(38, 428, 262);
const pw = ['AIRTIME', 'LAUNCH', 'TUCK'].map((k, i) => {
const x = 38 + i * 90;
add(`<div class="sm" style="position:absolute;left:${x}px;top:440px">${k}</div>`);
return add(`<div class="v" style="position:absolute;left:${x}px;top:458px;font-size:13px"></div>`);
});
// ------------------------------------------------------------ 03 leg servos, eight rows
panel(L.x, 506, L.w, 238, 'LEG SERVOS', '03');
const legState = add(`<div class="chip" style="right:${1600 - 300}px;top:536px"></div>`);
add(`<div class="sm" style="position:absolute;left:38px;top:540px">LOAD PER LEG · KNEE TORQUE</div>`);
const servo = LEGS.map((n, i) => {
const y = 562 + i * 21.5;
add(`<div class="mo" style="position:absolute;left:38px;top:${y}px;font-size:10px;font-weight:700">${n}</div>`);
add(`<div style="position:absolute;left:66px;top:${y + 4}px;width:170px;height:6px;background:${C.track};border-radius:3px"></div>`);
const f = add(`<div style="position:absolute;left:66px;top:${y + 4}px;height:6px;background:${C.ink};border-radius:3px"></div>`);
const v = add(`<div class="v" style="position:absolute;right:${1600 - 300}px;top:${y - 1}px"></div>`);
return {f, v};
});
// ------------------------------------------------------------ 04 optics: the iris, a trace, both lenses
panel(R.x, 108, R.w, 196, 'OPTICS', '04');
const grip = add(`<div style="position:absolute;left:1300px;top:140px;font-size:34px;font-weight:700;letter-spacing:-1px;line-height:1"></div>`);
add(`<div class="sm" style="position:absolute;left:1301px;top:178px">IRIS · MAIN LENSES</div>`);
const trace = add(`<svg style="position:absolute;left:1430px;top:136px" width="132" height="50"></svg>`);
const fl = ['LENS L', 'LENS R'].map((k, i) => {
const y = 200 + i * 24;
add(`<div class="sm" style="position:absolute;left:1300px;top:${y + 2}px">${k}</div>`);
add(`<div style="position:absolute;left:1356px;top:${y + 4}px;width:140px;height:6px;background:${C.track};border-radius:3px"></div>`);
const f = add(`<div style="position:absolute;left:1356px;top:${y + 4}px;height:6px;background:${C.ink};border-radius:3px"></div>`);
const v = add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:${y}px"></div>`);
return {f, v};
});
hr(1300, 252, 262);
add(`<div class="sm" style="position:absolute;left:1300px;top:264px">MODE</div>`);
const hold = add(`<div class="v" style="position:absolute;left:1346px;top:262px"></div>`);
add(`<div class="sm" style="position:absolute;left:1440px;top:264px">RANGE</div>`);
const air = add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:262px"></div>`);
// ------------------------------------------------------------ 05 views, 06 display
const btn = {};
const btnRow = (keys, labels, x0, y, wmax = 262, pad = 22) => {
let x = x0;
let yy = y;
for (const k of keys) {
const w = Math.round(labels[k].length * 7.1 + pad);
if (x + w > x0 + wmax) {
x = x0;
yy += 30;
}
btn[k] = add(`<div class="bt" style="left:${x}px;top:${yy}px;width:${w}px">${labels[k]}</div>`);
x += w + 6;
}
};
const viewsH = 50 + 30 * viewRows;
panel(R.x, 316, R.w, viewsH, opts.viewsTitle ?? 'VIEWS', '05');
btnRow(views, viewLabel, 1300, 353, 262, 16);
const dispY = 316 + viewsH + 12;
panel(R.x, dispY, R.w, 110, 'DISPLAY', '06');
btnRow(display, displayLabel, 1300, dispY + 37);
const subY = dispY + 122;
const subStep = Math.min(29, (744 - subY - 40) / 6);
// ------------------------------------------------------------ 07 subsystems
panel(R.x, subY, R.w, 744 - subY, 'SUBSYSTEMS', '07');
const subs = SUBS.map(([n, d], i) => {
const y = subY + 34 + i * subStep;
const bar = add(`<div style="position:absolute;left:1296px;top:${y}px;width:2px;height:22px;background:transparent"></div>`);
add(`<div class="mo" style="position:absolute;left:1304px;top:${y + 1}px;font-size:9px;color:${C.mute}">0${i + 1}</div>`);
const name = add(`<div class="mo" style="position:absolute;left:1328px;top:${y}px;font-size:9.4px;font-weight:700;letter-spacing:1.2px">${n}</div>`);
add(`<div class="sm" style="position:absolute;left:1328px;top:${y + 13}px;font-size:7.6px">${d}</div>`);
const chip = add(`<div class="chip" style="right:${1600 - 1562}px;top:${y + 3}px"></div>`);
return {bar, name, chip};
});
// ------------------------------------------------------------ 08 flight log
panel(330, 760, 940, 98, 'OPERATION LOG', '08');
add(`<div class="bt" style="left:346px;top:796px;width:44px;height:44px;border-radius:50%;border:none;background:${C.or};color:#fff;font-size:14px">❚❚</div>`);
const logMode = add(`<div class="mo" style="position:absolute;left:406px;width:780px;top:790px;text-align:center;font-size:9.6px;font-weight:700;letter-spacing:1.6px;color:${C.or}"></div>`);
add(`<div class="sm" style="position:absolute;left:406px;top:791px">DEPLOY</div>`);
add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:791px">RECALL</div>`);
const TLB = {x: 408, w: 840};
add(`<div style="position:absolute;left:${TLB.x}px;top:818px;width:${TLB.w}px;height:3px;background:${C.track};border-radius:2px"></div>`);
const tlFill = add(`<div style="position:absolute;left:${TLB.x}px;top:818px;height:3px;background:${C.or};border-radius:2px"></div>`);
const tlTicks = add(`<div style="position:absolute;inset:0"></div>`);
const tlKnob = add(`<div style="position:absolute;top:812px;width:15px;height:15px;margin-left:-7.5px;border-radius:50%;background:#fff;border:2px solid ${C.or};box-sizing:border-box"></div>`);
const tlTime = add(`<div class="mo" style="position:absolute;left:406px;top:834px;font-size:9.6px;color:${C.mute};letter-spacing:1px"></div>`);
const tlNext = add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:836px"></div>`);
// ------------------------------------------------------------ viewport notes: model, the view, the flight mode
add(`<div class="sm" style="position:absolute;left:346px;top:122px;letter-spacing:2px">MODEL TH-8 · REV A</div>`);
const viewNote = add(`<div class="sm" style="position:absolute;right:${1600 - 1254}px;top:122px;letter-spacing:2px"></div>`);
add(`<svg style="position:absolute;left:346px;top:140px" width="60" height="60"><path d="M0 60V0h60" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
add(`<svg style="position:absolute;left:1194px;top:680px" width="60" height="60"><path d="M60 0v60H0" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
add(`<div class="sm" style="position:absolute;left:346px;top:666px">OPERATION MODE</div>`);
const mode = add(`<div style="position:absolute;left:345px;top:680px;font-size:30px;font-weight:700;letter-spacing:-.4px;line-height:1;color:${C.or}"></div>`);
const modeSub = add(`<div class="sm" style="position:absolute;left:346px;top:716px"></div>`);
// ------------------------------------------------------------ footer
add(`<div class="sm" style="position:absolute;left:27px;top:878px;letter-spacing:2.2px">FIELD SIMULATOR &nbsp;·&nbsp; PROCEDURAL MODEL &nbsp;·&nbsp; 8 LEGS · 8 OPTICS · GLASS ABDOMEN</div>`);
add(`<div class="sm" style="position:absolute;right:28px;top:878px;letter-spacing:2.2px">THERAPHOS DYNAMICS · OPTICS LAB <span style="color:${C.or}">//////</span></div>`);
// ------------------------------------------------------------ labels, the pointer
const callSvg = add(`<svg style="position:absolute;inset:0;overflow:visible" width="1600" height="900"></svg>`);
const callG = add(`<div style="position:absolute;inset:0"></div>`);
const ring = add(`<div class="ring"></div>`);
const cur = add(`<div class="cur"><svg width="22" height="22" viewBox="0 0 34 34"><path d="M4 3 L30 13.5 L17.5 17.5 L13.5 30 Z" fill="#111" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/></svg></div>`);
const centre = (n) => {
const r = n.getBoundingClientRect();
return [r.left + r.width / 2, r.top + r.height / 2];
};
const spots = Object.fromEntries(Object.entries(btn).map(([k, n]) => [k, centre(n)]));
const pointer = (c) => {
cur.style.display = c.x < 0 ? 'none' : 'block';
cur.style.transform = `translate(${(c.x - 3).toFixed(2)}px, ${(c.y - 2).toFixed(2)}px) scale(${c.press ? 0.88 : 1})`;
ring.style.left = `${c.ringX}px`;
ring.style.top = `${c.ringY}px`;
ring.style.opacity = String(c.ring * 0.85);
ring.style.transform = `scale(${(0.35 + 0.9 * (1 - c.ring)).toFixed(3)})`;
};
const clock = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s) % 60).padStart(2, '0')}`;
const chipStyle = (n, kind, text) => {
const k = {ok: [C.green, '#fff'], warn: [C.or, '#fff'], idle: [C.track, C.mute]}[kind];
n.style.background = k[0];
n.style.color = k[1];
n.textContent = text;
};
let tickKey = '';
return {
spots,
btn,
root: ui,
TLB,
update(s) {
// header
const lift = Math.round(Math.min(1, s.lift) * 40);
liftCells.forEach((c, i) => (c.style.background = i < lift ? (i > 30 ? C.or : C.ink) : C.track));
liftPct.textContent = `${Math.round(s.lift * 100)}%`;
cellV[1].textContent = `00:00:${String(Math.floor(s.time)).padStart(2, '0')}`;
cellV[2].innerHTML = `<span style="color:${s.statusKind === 'ok' ? C.green : C.or}">●</span> ${s.status}`;
// gait: the stride rate, the speed, the step diagram (a dark bar per leg while it stands, orange while it
// swings, over the last 1.6 s with the now marker on the right)
fq.innerHTML = `${s.freq.toFixed(1)}<span style="font-size:14px;font-weight:600;color:${C.mute}"> HZ</span>`;
amp.textContent = `${Math.round(s.speed)}`;
{
const W = 262;
const rows = s.steps.length;
const rh = 11.2;
let g = '';
s.steps.forEach((row, r) => {
const y = 4 + r * rh;
g += `<text x="0" y="${y + 7.5}" font-size="7" fill="${C.mute}" font-family="JetBrains Mono">${LEGS[r]}</text>`;
g += `<rect x="18" y="${y + 2}" width="${W - 30}" height="5" rx="1" fill="${C.track}"/>`;
for (const [a, b, swing] of row) {
const x0 = 18 + a * (W - 30);
const x1 = 18 + b * (W - 30);
if (x1 - x0 > 0.5) g += `<rect x="${x0.toFixed(1)}" y="${y + 2}" width="${(x1 - x0).toFixed(1)}" height="5" rx="1" fill="${swing ? C.or : C.ink}" opacity="${swing ? 1 : 0.85}"/>`;
}
});
g += `<line x1="${W - 12}" x2="${W - 12}" y1="2" y2="${4 + rows * rh}" stroke="${C.ink}" stroke-width=".8" stroke-dasharray="2 2"/>`;
g += `<text x="18" y="99" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">−1.6 S</text><text x="${W - 14}" y="99" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">NOW</text>`;
chart.innerHTML = g;
}
pb.textContent = s.pattern;
shutter.textContent = `DUTY ${Math.round(s.duty * 100)}%`;
// jump: the height over the stance (negative in the crouch), a half-circle gauge from the crouch to the apex,
// the airtime, the launch speed, the tuck
batt.innerHTML = `${Math.round(s.jumpH)}<span style="font-size:13px;color:${C.mute}"> MM</span>`;
{
const cx = 62;
const cy = 54;
const r = 48;
const pt = (a, rr) => [cx + Math.cos(Math.PI - a) * rr, cy - Math.sin(Math.PI - a) * rr];
const arc = (a0, a1, rr) => {
const [x0, y0] = pt(a0, rr);
const [x1, y1] = pt(a1, rr);
return `M${x0.toFixed(1)} ${y0.toFixed(1)}A${rr} ${rr} 0 0 1 ${x1.toFixed(1)} ${y1.toFixed(1)}`;
};
const k = Math.max(0, Math.min(1, s.jumpK));
let g = `<path d="${arc(0, Math.PI, r)}" fill="none" stroke="${C.track}" stroke-width="6"/>`;
if (k > 0.005) g += `<path d="${arc(0, Math.PI * k, r)}" fill="none" stroke="${k > 0.7 ? C.or : C.ink}" stroke-width="6"/>`;
for (let i = 0; i <= 6; i++) {
const [x0, y0] = pt((i / 6) * Math.PI, r - 9);
const [x1, y1] = pt((i / 6) * Math.PI, r - 13);
g += `<line x1="${x0.toFixed(1)}" y1="${y0.toFixed(1)}" x2="${x1.toFixed(1)}" y2="${y1.toFixed(1)}" stroke="${C.mute}" stroke-width=".8"/>`;
}
const [nx, ny] = pt(Math.PI * k, r - 16);
g += `<line x1="${cx}" y1="${cy}" x2="${nx.toFixed(1)}" y2="${ny.toFixed(1)}" stroke="${C.or}" stroke-width="1.6"/><circle cx="${cx}" cy="${cy}" r="3" fill="${C.or}"/>`;
gauge.innerHTML = g;
}
pw[0].textContent = `${s.airtime.toFixed(2)} S`;
pw[1].textContent = `${s.launch.toFixed(1)} M/S`;
pw[2].textContent = `${Math.round(s.tuck * 100)}%`;
pw[2].style.color = s.tuck > 0.05 ? C.or : C.ink;
// leg servos
chipStyle(legState, s.legsFree ? 'warn' : 'ok', s.legsFree ? 'DETACHED' : s.walking ? 'STEPPING' : 'HOLDING');
servo.forEach((b, i) => {
const v = s.servos[i];
b.f.style.width = `${(v * 170).toFixed(1)}px`;
const free = s.legFreeEach ? s.legFreeEach[i] : s.legsFree;
b.f.style.background = v > 0.6 ? C.or : C.ink;
b.v.textContent = free ? 'DETACHED' : `${Math.round(v * 100)}%`;
b.v.style.color = free ? C.or : C.ink;
b.v.style.fontSize = free ? '8.6px' : '11px';
});
// optics: the iris f-stop, its trace over the last 2 s, both main lenses' apertures, the mode, the range
grip.innerHTML = `<span style="font-size:16px;font-weight:600;color:${C.mute}">F/</span>${s.fstop.toFixed(1)}`;
{
const W = 132;
const H = 50;
const Y = (v) => (H - 4 - v * (H - 10)).toFixed(1);
const tr = s.irisTrace;
const path = tr.map((v, i) => `${i ? 'L' : 'M'}${((i / (tr.length - 1)) * (W - 4)).toFixed(1)} ${Y(v)}`).join('');
trace.innerHTML = `<line x1="0" x2="${W}" y1="${H - 4}" y2="${H - 4}" stroke="${C.faint}"/><path d="${path}" fill="none" stroke="${C.or}" stroke-width="1.5"/><circle cx="${W - 4}" cy="${Y(tr[tr.length - 1])}" r="2.6" fill="${C.or}"/>`;
}
fl.forEach((b, i) => {
const v = s.lensOpen[i];
b.f.style.width = `${(v * 140).toFixed(1)}px`;
b.f.style.background = v > 0.6 ? C.or : C.ink;
const off = s.opticsOpen;
b.v.textContent = off ? 'OPEN' : `${Math.round(v * 100)}%`;
b.v.style.color = off ? C.or : C.ink;
});
hold.textContent = s.opticsMode;
air.textContent = `${Math.round(s.range)} MM`;
// views, display
const onBtn = (k, on) => {
btn[k].style.background = on ? C.or : '#fffdf9';
btn[k].style.color = on ? '#fff' : C.ink;
btn[k].style.borderColor = on ? C.or : C.faint;
};
for (const k of views) onBtn(k, s.view === k);
for (const k of display) onBtn(k, !!s.display[k]);
// subsystems: a status chip each, the row the current view looks at marked
subs.forEach((r, i) => {
const [kind, text] = s.subs[i];
chipStyle(r.chip, kind, text);
r.bar.style.background = s.focus === i ? C.or : 'transparent';
r.name.style.color = s.focus === i ? C.or : C.ink;
});
// flight log: the film's progress, a tick for every press, the mode
const kx = TLB.x + (s.time / s.dur) * TLB.w;
tlFill.style.width = `${(kx - TLB.x).toFixed(1)}px`;
tlKnob.style.left = `${kx.toFixed(1)}px`;
const key = s.events.length;
if (key !== tickKey) {
tickKey = key;
tlTicks.innerHTML = s.events.map((e) => `<div style="position:absolute;left:${(TLB.x + (e / s.dur) * TLB.w - 1).toFixed(1)}px;top:813px;width:2px;height:13px;background:${C.ink};opacity:.35"></div>`).join('');
}
tlTime.textContent = `${clock(s.time)} / ${clock(s.dur)}`;
tlNext.textContent = s.next;
logMode.textContent = s.log;
viewNote.textContent = s.viewNote ?? `VIEW · ${viewLabel[s.view]}${s.display.orbit ? ' · ORBIT' : ''}`;
mode.textContent = s.mode;
modeSub.textContent = s.modeSub;
// labels: an orange square, the name, the note, a thin leader to the part
let lh = '';
let ch = '';
for (const c of s.callouts) {
if (c.o < 0.02 || !c.at) continue;
const [ax, ay] = c.at;
const [lx, ly] = c.label;
const right = lx > ax;
const ex = right ? lx - 6 : lx + c.w + 6;
lh += `<polyline points="${ax.toFixed(1)},${ay.toFixed(1)} ${ex.toFixed(1)},${(ly + 6).toFixed(1)}" fill="none" stroke="${C.or}" stroke-width=".9" opacity="${c.o.toFixed(2)}"/><circle cx="${ax.toFixed(1)}" cy="${ay.toFixed(1)}" r="2.4" fill="${C.or}" opacity="${c.o.toFixed(2)}"/>`;
ch += `<div class="call" style="left:${lx.toFixed(1)}px;top:${(ly - 1).toFixed(1)}px;opacity:${c.o.toFixed(2)}"><b><i></i>${c.name}</b><span>${c.sub}</span></div>`;
}
callSvg.innerHTML = lh;
callG.innerHTML = ch;
pointer(s.cursor);
},
pointer,
};
}
+143
View File
@@ -0,0 +1,143 @@
// The spider's walk, copied from the scorpion's (roboscorp-shared/gait.js): a body path integrated from velocity keys and an alternating tetrapod gait for eight legs
// (L1 R2 L3 R4 against R1 L2 R3 L4), after the hexapod's (hexsim-shared/motion.js) but simpler. Pure functions of t,
// no three.js. World: y up; a yaw ψ turns the body's +x to (cos ψ, 0, -sin ψ), as three.js rotation.y does.
// keys: [[t, speed, yawRate°/s], ...] eased between; the path is moved so that at tRef the body stands at the origin
// facing +x. A step starts whenever the phase clock (∫ rate dt) crosses a group's mark; once started it always
// finishes, and it lands where the leg's home spot will be a moment after touchdown, so the feet settle home when the
// body stops. footLocal(i, t) gives a foot in the body frame of the path (the turntable turns on top of it).
import {FLOOR_Y, legHome, WHEEL_R} from './spider.js';
const smoother = (x) => {
const u = Math.min(1, Math.max(0, x));
return u * u * u * (u * (u * 6 - 15) + 10);
};
const GA = [0, 5, 2, 7];
const GB = [4, 1, 6, 3];
export const STRIDE_HZ = 2.7;
const SWING = 0.46 / STRIDE_HZ;
const LIFT = 0.12;
export function buildGait({keys, duration, tRef = 2.8, t0 = -1.5}) {
const HZ = 240;
const N = Math.ceil((duration - t0) * HZ) + 2;
const at = (t) => {
// eased velocity between keys
if (t <= keys[0][0]) return [keys[0][1], keys[0][2]];
for (let i = 0; i < keys.length - 1; i++) {
const [ta, va, wa] = keys[i];
const [tb, vb, wb] = keys[i + 1];
if (t <= tb) {
const k = smoother((t - ta) / (tb - ta));
return [va + (vb - va) * k, wa + (wb - wa) * k];
}
}
const l = keys[keys.length - 1];
return [l[1], l[2]];
};
const X = new Float64Array(N);
const Z = new Float64Array(N);
const Y = new Float64Array(N);
const RATE = new Float64Array(N);
const PH = new Float64Array(N);
const move = (t) => {
const [v, w] = at(t);
return Math.min(1, Math.abs(v) / 0.35 + Math.abs(w) / 45);
};
for (let i = 1; i < N; i++) {
const t = t0 + (i - 0.5) / HZ;
const [v, w] = at(t);
const ym = Y[i - 1] + (w * Math.PI) / 180 / HZ / 2;
X[i] = X[i - 1] + (v * Math.cos(ym)) / HZ;
Z[i] = Z[i - 1] - (v * Math.sin(ym)) / HZ;
Y[i] = Y[i - 1] + (w * Math.PI) / 180 / HZ;
// the legs keep stepping for half a second after the body stops, so they settle
RATE[i] = STRIDE_HZ * Math.max(move(t), move(t - 0.25), move(t - 0.5));
PH[i] = PH[i - 1] + RATE[i] / HZ;
}
const idx = (t) => Math.min(N - 1.000001, Math.max(0, (t - t0) * HZ));
const samp = (A, t) => {
const f = idx(t);
const i = Math.floor(f);
return A[i] + (A[i + 1] - A[i]) * (f - i);
};
// the rigid move that puts the body at the origin facing +x at tRef
const rx = samp(X, tRef);
const rz = samp(Z, tRef);
const ry = samp(Y, tRef);
const c = Math.cos(-ry);
const s = Math.sin(-ry);
const pathAt = (t) => {
const x = samp(X, t) - rx;
const z = samp(Z, t) - rz;
// rotate by -ry about y: (x, z) → (x c + z s, -x s + z c) with the three.js sense
return {x: x * c + z * s, z: -x * s + z * c, yaw: samp(Y, t) - ry};
};
const toWorld = (p, lx, lz) => [p.x + lx * Math.cos(p.yaw) + lz * Math.sin(p.yaw), p.z - lx * Math.sin(p.yaw) + lz * Math.cos(p.yaw)];
// the step schedule: every crossing of a group's mark starts a swing for its four legs
const swings = Array.from({length: 8}, () => []);
for (let i = 1; i < N; i++) {
const t = t0 + i / HZ;
for (const [grp, off] of [
[GA, 0],
[GB, 0.5],
]) {
if (Math.floor(PH[i] - off) > Math.floor(PH[i - 1] - off) && PH[i] - off > 0) {
for (const l of grp) {
const S = swings[l];
if (S.length && S[S.length - 1].t1 > t - 0.04) continue;
S.push({t0: t, t1: t + SWING});
}
}
}
}
const start = Array.from({length: 8}, (_, l) => {
const h = legHome(l);
return toWorld(pathAt(t0), h[0], h[2]);
});
swings.forEach((S, l) => {
let from = start[l];
const h = legHome(l);
for (const sw of S) {
sw.from = from;
sw.to = toWorld(pathAt(sw.t1 + 0.1), h[0], h[2]);
from = sw.to;
}
});
const footWorld = (l, t) => {
let planted = start[l];
for (const sw of swings[l]) {
if (sw.t0 > t) break;
if (t < sw.t1) {
const q = (t - sw.t0) / (sw.t1 - sw.t0);
const e = smoother((q - 0.04) / 0.9);
const y = Math.pow(Math.sin(Math.PI * q), 1.1);
return [sw.from[0] + (sw.to[0] - sw.from[0]) * e, FLOOR_Y + WHEEL_R + LIFT * y, sw.from[1] + (sw.to[1] - sw.from[1]) * e, y];
}
planted = sw.to;
}
return [planted[0], FLOOR_Y + WHEEL_R, planted[1], 0];
};
/** A foot in the body frame of the path at t, given the body's height y and its pitch and roll (radians). */
const footLocal = (l, t, body) => {
const p = pathAt(t);
const f = footWorld(l, t);
let x = f[0] - p.x;
let y = f[1] - body.y;
let z = f[2] - p.z;
// undo yaw (rotation.y = yaw): R(-yaw) about y
const cy = Math.cos(-p.yaw);
const sy = Math.sin(-p.yaw);
[x, z] = [x * cy + z * sy, -x * sy + z * cy];
// undo roll about x, then pitch about z (the root's Euler order is YXZ: R = Ry Rx Rz)
const cr = Math.cos(-body.roll);
const sr = Math.sin(-body.roll);
[y, z] = [y * cr - z * sr, y * sr + z * cr];
const cp = Math.cos(-body.pitch);
const sp = Math.sin(-body.pitch);
[x, y] = [x * cp - y * sp, x * sp + y * cp];
return [x, y, z];
};
const lifted = (l, t) => footWorld(l, t)[3];
return {pathAt, footWorld, footLocal, lifted, rateAt: (t) => samp(RATE, t), phaseAt: (t) => samp(PH, t), velAt: at, swings};
}
+141
View File
@@ -0,0 +1,141 @@
// The construction drawing around the scorpion, copied from the bee's (robobee-shared/guides.js) with a centre and a
// scale: hairline arcs and dashed circles in a few tilted planes, dots and small hollow markers riding on them, short
// ticks. All in world space round the scorpion, so a camera orbit gives them depth. Lines are fat lines with a width
// in device pixels; resize() keeps them hairline at any pixel ratio.
import * as THREE from 'three';
import {Line2} from 'three/addons/lines/Line2.js';
import {LineGeometry} from 'three/addons/lines/LineGeometry.js';
import {LineMaterial} from 'three/addons/lines/LineMaterial.js';
import {rng} from '../kit/util.js';
const V3 = THREE.Vector3;
const INK = '#8a8178';
export function buildGuides({centre = [0.05, 0.1, 0], seed = 5, scale = 1} = {}) {
const R = rng(seed);
const group = new THREE.Group();
const lines = [];
const C = new V3(...centre);
// two unit vectors spanning the plane with normal n
const basis = (n) => {
const a = Math.abs(n.y) < 0.9 ? new V3(0, 1, 0) : new V3(1, 0, 0);
const u = new V3().crossVectors(a, n).normalize();
return [u, new V3().crossVectors(n, u)];
};
const circ = (c, r, n, a) => {
const [u, v] = basis(n.clone().normalize());
return c.clone().addScaledVector(u, Math.cos(a) * r).addScaledVector(v, Math.sin(a) * r);
};
const arc = (c, r, n, a0, a1, {dashed = false, width = 1, opacity = 0.5, dash = 0.045} = {}) => {
const N = Math.max(24, Math.round(Math.abs(a1 - a0) * r * 60));
const pts = [];
for (let i = 0; i <= N; i++) {
const p = circ(c, r, n, a0 + ((a1 - a0) * i) / N);
pts.push(p.x, p.y, p.z);
}
const g = new LineGeometry();
g.setPositions(pts);
const m = new LineMaterial({color: INK, linewidth: width, transparent: true, opacity, dashed, dashSize: dash, gapSize: dash * 0.8, depthWrite: false, worldUnits: false});
const l = new Line2(g, m);
l.computeLineDistances();
l.renderOrder = 4;
group.add(l);
lines.push({m, width, opacity});
return l;
};
const seg = (a, b, opts = {}) => {
const g = new LineGeometry();
g.setPositions([a.x, a.y, a.z, b.x, b.y, b.z]);
const m = new LineMaterial({color: INK, linewidth: opts.width ?? 1, transparent: true, opacity: opts.opacity ?? 0.45, dashed: !!opts.dashed, dashSize: 0.04, gapSize: 0.035, depthWrite: false});
const l = new Line2(g, m);
l.computeLineDistances();
l.renderOrder = 4;
group.add(l);
lines.push({m, width: opts.width ?? 1, opacity: opts.opacity ?? 0.45});
};
// the rings: [radius, normal, arcs, dashed, width, opacity]
const RINGS = [
[2.75, new V3(0.35, 0.25, 1), [[0.15, 1.9], [2.4, 3.5], [4.1, 5.6]], false, 1.0, 0.42],
[2.05, new V3(0.1, 1, 0.3), [[0, Math.PI * 2]], true, 1.0, 0.45],
[1.35, new V3(1, 0.15, 0.05), [[0.3, 2.6], [3.3, 5.5]], false, 1.1, 0.5],
[3.45, new V3(0.55, 0.75, 0.35), [[0.6, 2.2], [3.6, 4.6]], false, 0.9, 0.32],
[1.7, new V3(-0.4, 0.3, 1), [[0, Math.PI * 2]], true, 0.9, 0.36],
[2.35, new V3(0.9, -0.2, 0.4), [[1.0, 2.9], [4.2, 5.9]], false, 0.9, 0.34],
];
for (const R of RINGS) R[0] *= scale;
const onRing = [];
for (const [r, n, arcs, dashed, w, o] of RINGS) {
for (const [a0, a1] of arcs) arc(C, r, n, a0, a1, {dashed, width: w, opacity: o});
onRing.push([r, n, arcs]);
}
// a small ring round the sensor head and one round the stinger, offset from the main centre
arc(new V3(1.3, 0.2, 0.0), 0.55, new V3(0.75, 0.25, 0.6), 0, Math.PI * 2, {dashed: true, width: 0.9, opacity: 0.4, dash: 0.03});
arc(new V3(-0.4, 1.7, 0), 0.8, new V3(-0.3, 0.2, 1), 0.4, 4.6, {width: 0.9, opacity: 0.38});
// dots and hollow markers riding on the rings, ticks across them
const dots = [];
const marks = new THREE.Group();
group.add(marks);
const dotGeo = new THREE.SphereGeometry(1, 10, 8);
const dotMat = new THREE.MeshBasicMaterial({color: '#5d5751', transparent: true, opacity: 0.75, depthWrite: false});
const ringGeo = new THREE.RingGeometry(0.62, 1, 28);
const ringMat = new THREE.MeshBasicMaterial({color: '#6e675f', transparent: true, opacity: 0.7, depthWrite: false, side: THREE.DoubleSide});
for (const [r, n, arcs] of onRing) {
for (const [a0, a1] of arcs) {
const k = Math.max(1, Math.round((a1 - a0) * 1.6));
for (let i = 0; i < k; i++) {
const a = a0 + (a1 - a0) * R();
const p = circ(C, r, n, a);
if (R() < 0.6) {
const d = new THREE.Mesh(dotGeo, dotMat);
d.position.copy(p);
d.scale.setScalar(0.009 + R() * 0.012);
d.renderOrder = 5;
group.add(d);
dots.push(d);
} else {
const m = new THREE.Mesh(ringGeo, ringMat);
m.position.copy(p);
m.scale.setScalar(0.022 + R() * 0.016);
m.renderOrder = 5;
marks.add(m);
}
// a short tick across the ring at some of them
if (R() < 0.35) {
const t = circ(C, r * 1.04, n, a);
const b = circ(C, r * 0.96, n, a);
seg(t, b, {width: 1, opacity: 0.5});
}
}
}
}
// a few straight dashed leaders out from the body
for (const [a, b] of [
[new V3(1.4, 0.3, 0.2), new V3(2.6, 1.2, 0.5)],
[new V3(-0.8, 0.2, 0.4), new V3(-2.2, 0.0, 1.2)],
[new V3(0.2, 0.6, -0.3), new V3(0.6, 2.2, -0.8)],
]) {
seg(a, b, {dashed: true, width: 0.9, opacity: 0.38});
}
return {
group,
resize(w, h, pr) {
for (const L of lines) {
L.m.resolution.set(w, h);
L.m.linewidth = L.width * pr;
}
},
// ops.guides 0..1 fades the whole drawing
update(camera, ops = {}) {
const k = ops.guides ?? 1;
group.userData.show = k > 0.001;
group.visible = group.userData.show;
for (const L of lines) L.m.opacity = Math.min(1, L.opacity * 1.1 * k);
dotMat.opacity = 0.75 * k;
ringMat.opacity = 0.7 * k;
for (const m of marks.children) m.quaternion.copy(camera.quaternion);
},
};
}
+43
View File
@@ -0,0 +1,43 @@
// The spider's jump: a crouch, the push, a ballistic flight with the legs tucked, the landing and its absorb. Pure
// functions of t, no three.js. J = {t0: the crouch starts, tl: lift-off, ta: touch-down, dist: the forward travel,
// h: the apex over the standing height}. The forward travel rides on the gait's path as a velocity pulse (jumpKeys,
// its integral is dist), so the gait re-plants the feet round the landing spot; jumpAt gives what goes on top of the
// path: the body's height and pitch and the tuck the legs blend toward (spider.js legTuck).
const smoother = (x) => {
const u = Math.min(1, Math.max(0, x));
return u * u * u * (u * (u * 6 - 15) + 10);
};
const ssw = (e, s, f) => smoother((e - s) / (f - s));
// how far the body sinks into its legs before the push
export const CROUCH = 0.17;
// the absorb after touch-down
export const LAND = 0.45;
/** Height offset, pitch (radians, nose up > 0), tuck 0..1 and whether the body is in the air, at t. */
export function jumpAt(t, J) {
const {t0, tl, ta, h} = J;
if (t < t0 || t > ta + LAND) return {dy: 0, pitch: 0, tuck: 0, air: 0};
if (t < tl) {
// down and a little nose-down over most of the window, then the last 0.12 s straightens the legs fast
const c = ssw(t, t0, tl - 0.12);
const push = ssw(t, tl - 0.12, tl);
return {dy: -CROUCH * c * (1 - push), pitch: -0.07 * c * (1 - push) + 0.16 * push, tuck: 0, air: 0};
}
if (t < ta) {
const q = (t - tl) / (ta - tl);
const tuck = ssw(q, 0.0, 0.28) * (1 - ssw(q, 0.7, 1.0));
return {dy: 4 * h * q * (1 - q), pitch: 0.16 * (1 - 2 * q) - 0.04 * Math.sin(Math.PI * q), tuck, air: 1};
}
// the body sinks into the legs and comes back up
const k = (t - ta) / LAND;
const s = Math.sin(Math.PI * Math.min(1, k)) * (1 - 0.35 * k);
return {dy: -0.13 * s, pitch: -0.08 * s, tuck: 0, air: 0};
}
/** The jump's forward travel as gait velocity keys [t, speed, yawRate°/s]: a pulse over the flight whose integral is
* J.dist (the gait eases between keys with the same smoother, so the area is half of peak x flight). */
export const jumpKeys = (J) => [
[J.tl, 0, 0],
[(J.tl + J.ta) / 2, (2 * J.dist) / (J.ta - J.tl), 0],
[J.ta, 0, 0],
];
+315
View File
@@ -0,0 +1,315 @@
// The robotic scorpion's kitbash shop, copied from the bee's (robobee-shared/parts.js) with the stinger's orange
// resin and a tapered tube added: the materials (gloss white shell, orange accent, graphite and black mechanism,
// steel, the lens, clear glass and the bee's unused wing films) and the geometry every part is cut from. Everything is
// built along +x and placed by the caller: sweepX turns a closed (x, r) profile round the x axis, whole or as an arc
// with capped ends, which gives rings, collars, domes, shell plates and capsules from one function; gearGeo cuts a
// toothed wheel with a bore; tube runs a cable along points.
import * as THREE from 'three';
import {RoundedBoxGeometry} from 'three/addons/geometries/RoundedBoxGeometry.js';
import {mergeGeometries} from 'three/addons/utils/BufferGeometryUtils.js';
export const V3 = THREE.Vector3;
export const D2R = Math.PI / 180;
export const PAL = {white: '#f4f2ee', orange: '#ff5a1f', graphite: '#2f3238', black: '#111214', steel: '#cdd1d6'};
export function makeMaterials() {
const phys = (o) => new THREE.MeshPhysicalMaterial(o);
const std = (o) => new THREE.MeshStandardMaterial(o);
return {
// the white plastic: a soft base under a hard clear coat, so the softboxes sit on it as crisp bars
shell: phys({color: PAL.white, roughness: 0.34, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.05}),
// inside faces of the shells, a shade darker and matte
shellIn: phys({color: '#dedad4', roughness: 0.6, metalness: 0, clearcoat: 0.2, clearcoatRoughness: 0.4, side: THREE.DoubleSide}),
orange: phys({color: PAL.orange, roughness: 0.3, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08}),
// the orange panel at a wing tip: a film on the membrane, both faces, pulled forward so it never fights it
orangeFilm: phys({color: PAL.orange, roughness: 0.32, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2}),
graphite: std({color: PAL.graphite, roughness: 0.36, metalness: 0.72}),
gunmetal: std({color: '#555a62', roughness: 0.28, metalness: 0.9}),
black: phys({color: PAL.black, roughness: 0.3, metalness: 0.15, clearcoat: 0.8, clearcoatRoughness: 0.12}),
rubber: std({color: '#1b1c1f', roughness: 0.7, metalness: 0}),
steel: std({color: PAL.steel, roughness: 0.2, metalness: 1}),
// the camera eye: a deep black inner element under a dark glass dome; its colour darkens only what shows
// through it, the highlights stay at full strength
lens: phys({color: '#020203', roughness: 0.05, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.02, envMapIntensity: 1.4}),
lensGlass: phys({color: '#6f7277', roughness: 0, metalness: 0, transmission: 1, thickness: 0, ior: 1.5, clearcoat: 1, clearcoatRoughness: 0, specularIntensity: 1, envMapIntensity: 2.4}),
amber: std({color: '#000000', emissive: '#ffa040', emissiveIntensity: 4.5}),
// circuit boards in the thorax: a dark green-black laminate
pcb: std({color: '#1b241f', roughness: 0.55, metalness: 0.1}),
// the clear abdomen window: real transmission, so the mechanism inside refracts a touch
glass: phys({color: '#ffffff', roughness: 0.0, metalness: 0, transmission: 1, thickness: 0, ior: 1.3, specularIntensity: 0.6, clearcoat: 0.5, clearcoatRoughness: 0.02}),
// the wing film: a faint grey-white sheet; the veins and the rim carry the read
membrane: phys({color: '#eef0f2', roughness: 0.38, metalness: 0, transparent: true, opacity: 0.3, depthWrite: false, side: THREE.DoubleSide, clearcoat: 1, clearcoatRoughness: 0.04, iridescence: 0.35, iridescenceIOR: 1.3}),
// the wing rim: a pale clear-ish tube
rim: phys({color: '#e4e7ea', roughness: 0.12, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.04, transparent: true, opacity: 0.55, depthWrite: false}),
vein: std({color: '#4a4d53', roughness: 0.5, metalness: 0.2, transparent: true, opacity: 0.72}),
veinCore: std({color: '#5a5d63', roughness: 0.5, metalness: 0.2}),
led: std({color: '#000000', emissive: PAL.orange, emissiveIntensity: 1.4}),
// the stinger's base and the claws' blade edges: a translucent orange resin with a hard coat
orangeGlass: phys({color: '#ff6a24', roughness: 0.12, metalness: 0, transmission: 0.55, thickness: 0.2, ior: 1.45, attenuationColor: '#ff4a10', attenuationDistance: 0.25, clearcoat: 1, clearcoatRoughness: 0.03, transparent: true, opacity: 0.92}),
};
}
// ------------------------------------------------------------ sweepX: a closed (x, r) profile turned round the x axis
// profile: [[x, r], ...] closed loop, either winding. a0..a1: the arc, angle 0 at +y, 90° at +z. Profile corners
// sharper than `smooth` degrees keep a hard edge; softer ones are shaded smooth. A partial arc gets capped ends.
export function sweepX(profile, {a0 = 0, a1 = Math.PI * 2, segs = 64, smooth = 32} = {}) {
let P = profile.map(([x, r]) => [x, Math.max(0, r)]);
let area = 0;
for (let i = 0; i < P.length; i++) {
const [x0, r0] = P[i];
const [x1, r1] = P[(i + 1) % P.length];
area += x0 * r1 - x1 * r0;
}
if (area < 0) P = P.reverse();
const n = P.length;
// outward edge normals in the (x, r) plane
const EN = [];
for (let i = 0; i < n; i++) {
const [x0, r0] = P[i];
const [x1, r1] = P[(i + 1) % n];
const l = Math.hypot(x1 - x0, r1 - r0) || 1;
EN.push([(r1 - r0) / l, -(x1 - x0) / l]);
}
const cosS = Math.cos(smooth * D2R);
const vN = (i, e) => {
// normal at vertex i as seen from edge e (e is i-1 or i)
const other = e === i ? (i - 1 + n) % n : i;
const a = EN[e];
const b = EN[other];
if (a[0] * b[0] + a[1] * b[1] < cosS) return a;
const x = a[0] + b[0];
const y = a[1] + b[1];
const l = Math.hypot(x, y) || 1;
return [x / l, y / l];
};
const full = Math.abs(a1 - a0) >= Math.PI * 2 - 1e-6;
const pos = [];
const nor = [];
const idx = [];
const cs = [];
for (let j = 0; j <= segs; j++) {
const th = a0 + ((a1 - a0) * j) / segs;
cs.push([Math.cos(th), Math.sin(th)]);
}
for (let e = 0; e < n; e++) {
const i0 = e;
const i1 = (e + 1) % n;
const [x0, r0] = P[i0];
const [x1, r1] = P[i1];
if (Math.hypot(x1 - x0, r1 - r0) < 1e-9) continue;
const n0 = vN(i0, e);
const n1 = vN(i1, e);
const base = pos.length / 3;
for (let j = 0; j <= segs; j++) {
const [c, s] = cs[j];
pos.push(x0, r0 * c, r0 * s, x1, r1 * c, r1 * s);
nor.push(n0[0], n0[1] * c, n0[1] * s, n1[0], n1[1] * c, n1[1] * s);
}
for (let j = 0; j < segs; j++) {
const a = base + j * 2;
const b = a + 1;
const c = a + 3;
const d = a + 2;
idx.push(a, b, c, a, c, d);
}
}
if (!full) {
const tri = THREE.ShapeUtils.triangulateShape(
P.map(([x, r]) => new THREE.Vector2(x, r)),
[],
);
for (const [th, flip] of [
[a0, true],
[a1, false],
]) {
const c = Math.cos(th);
const s = Math.sin(th);
// the cap's normal: -d/dθ at a0, +d/dθ at a1
const nx = 0;
const ny = flip ? s : -s;
const nz = flip ? -c : c;
const base = pos.length / 3;
for (const [x, r] of P) {
pos.push(x, r * c, r * s);
nor.push(nx, ny, nz);
}
for (const t of tri) {
if (flip) idx.push(base + t[0], base + t[2], base + t[1]);
else idx.push(base + t[0], base + t[1], base + t[2]);
}
}
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
g.setIndex(idx);
return g;
}
// a rounded rectangle profile for a ring: x0..x1 wide, r0..r1 deep, corners rounded by `round`
export function ringProfile(x0, x1, r0, r1, round = 0.01, steps = 3) {
const rr = Math.min(round, (x1 - x0) / 2.01, (r1 - r0) / 2.01);
const pts = [];
const corner = (cx, cr, a0) => {
for (let k = 0; k <= steps; k++) {
const a = a0 + (k / steps) * (Math.PI / 2);
pts.push([cx + Math.cos(a) * rr, cr + Math.sin(a) * rr]);
}
};
corner(x1 - rr, r0 + rr, -Math.PI / 2);
corner(x1 - rr, r1 - rr, 0);
corner(x0 + rr, r1 - rr, Math.PI / 2);
corner(x0 + rr, r0 + rr, Math.PI);
return pts;
}
export const ring = (x0, x1, r0, r1, round, opts) => sweepX(ringProfile(x0, x1, r0, r1, round), opts);
// a thick spherical shell from polar angle p0 to p1 (0 = +x pole), outer radius R, wall t; the rims stay sharp so
// the clear coat draws a crisp line along them
export function domeProfile(R, t, p0, p1, steps = 24) {
const out = [];
const inn = [];
for (let k = 0; k <= steps; k++) {
const p = p0 + ((p1 - p0) * k) / steps;
out.push([R * Math.cos(p), R * Math.sin(p)]);
inn.push([(R - t) * Math.cos(p), (R - t) * Math.sin(p)]);
}
return [...out, ...inn.reverse()];
}
export const dome = (R, t, p0, p1, opts) => sweepX(domeProfile(R, t, p0, p1), opts);
// a solid of revolution from a radius function: r(u) for u in 0..1 along x0..x1, closed to the axis at both ends
export function solidProfile(x0, x1, rFn, steps = 32) {
const pts = [[x0, 0]];
for (let k = 0; k <= steps; k++) {
const u = k / steps;
pts.push([x0 + (x1 - x0) * u, rFn(u)]);
}
pts.push([x1, 0]);
return pts;
}
export const solid = (x0, x1, rFn, opts, steps) => sweepX(solidProfile(x0, x1, rFn, steps), opts);
// a capsule-like rounded radius: r0 at the start, r1 at the end, ends rounded over `cap` of the length
export const capsuleR = (r0, r1, cap = 0.12) => (u) => {
const r = r0 + (r1 - r0) * u;
const e = Math.min(u, 1 - u) / cap;
return e >= 1 ? r : r * Math.sqrt(Math.max(0, 1 - (1 - e) * (1 - e)));
};
// ------------------------------------------------------------ gears, boxes, tubes
// a spur gear around +z: `teeth` teeth between rRoot and rOut, `width` thick, a bore of holeR, lightening holes
export function gearGeo(teeth, rOut, rRoot, width, holeR = 0, spokes = 0) {
const sh = new THREE.Shape();
for (let i = 0; i < teeth; i++) {
const a0 = (i / teeth) * Math.PI * 2;
const da = (Math.PI * 2) / teeth;
const pts = [
[rRoot, a0],
[rRoot, a0 + da * 0.18],
[rOut, a0 + da * 0.32],
[rOut, a0 + da * 0.6],
[rRoot, a0 + da * 0.74],
];
pts.forEach(([r, a], k) => (i === 0 && k === 0 ? sh.moveTo(r * Math.cos(a), r * Math.sin(a)) : sh.lineTo(r * Math.cos(a), r * Math.sin(a))));
}
sh.closePath();
if (holeR) {
const h = new THREE.Path();
h.absarc(0, 0, holeR, 0, Math.PI * 2, true);
sh.holes.push(h);
}
// round lightening holes between the bore and the rim
if (spokes) {
const rc = (holeR + rRoot) / 2;
const rh = Math.min((rRoot - holeR) * 0.3, (Math.PI * rc) / spokes * 0.55);
for (let k = 0; k < spokes; k++) {
const a = (k / spokes) * Math.PI * 2;
const h = new THREE.Path();
h.absarc(Math.cos(a) * rc, Math.sin(a) * rc, rh, 0, Math.PI * 2, true);
sh.holes.push(h);
}
}
const bev = Math.min(width * 0.18, (rOut - rRoot) * 0.3);
const g = new THREE.ExtrudeGeometry(sh, {depth: width - bev * 2, bevelEnabled: true, bevelThickness: bev, bevelSize: bev * 0.8, bevelSegments: 1, curveSegments: 10});
g.translate(0, 0, -(width - bev * 2) / 2);
return g;
}
// the same gear with its axis along +x
export const gearX = (...a) => gearGeo(...a).rotateY(Math.PI / 2);
export const rbox = (w, h, d, r = 0.01) => new RoundedBoxGeometry(w, h, d, 3, Math.min(r, w / 2.01, h / 2.01, d / 2.01));
export const cylX = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateZ(-Math.PI / 2);
export const cylZ = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateX(Math.PI / 2);
/** A cable or rod through points (Vector3 or arrays), radius r. */
export function tube(points, r, tubular = 64, radial = 10, closed = false) {
const pts = points.map((p) => (p.isVector3 ? p : new V3(...p)));
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts, closed, 'catmullrom', 0.5), tubular, r, radial, closed);
}
/** A tube through points whose radius runs from r0 to r1 along its length (a stinger, a finger, a tapered link). */
export function taperTube(points, r0, r1, tubular = 48, radial = 14, pow = 1) {
const pts = points.map((p) => (p.isVector3 ? p : new V3(...p)));
const curve = new THREE.CatmullRomCurve3(pts, false, 'catmullrom', 0.5);
const g = new THREE.TubeGeometry(curve, tubular, 1, radial, false);
const pos = g.attributes.position;
const nor = g.attributes.normal;
const c = new V3();
for (let i = 0; i <= tubular; i++) {
const u = i / tubular;
const r = r1 + (r0 - r1) * Math.pow(1 - u, pow);
curve.getPointAt(u, c);
for (let j = 0; j <= radial; j++) {
const k = i * (radial + 1) + j;
pos.setXYZ(k, c.x + nor.getX(k) * r, c.y + nor.getY(k) * r, c.z + nor.getZ(k) * r);
}
}
pos.needsUpdate = true;
g.computeVertexNormals();
return g;
}
/** A coil spring along +x: radius R, wire r, `turns` over len. */
export function coil(R, r, turns, len, seg = 240) {
const pts = [];
for (let i = 0; i <= seg; i++) {
const u = i / seg;
const a = u * turns * Math.PI * 2;
pts.push(new V3(u * len, Math.cos(a) * R, Math.sin(a) * R));
}
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), seg, r, 8, false);
}
export const merge = (geos) => mergeGeometries(geos.map((g) => (g.index ? g.toNonIndexed() : g)).map((g) => {
// mergeGeometries wants identical attribute sets: keep position and normal only
const o = new THREE.BufferGeometry();
o.setAttribute('position', g.attributes.position);
o.setAttribute('normal', g.attributes.normal);
return o;
}));
/** Put a mesh of geo/mat at (x, y, z) into parent; returns it. Every mesh casts and takes shadows. */
export function put(parent, geo, mat, x = 0, y = 0, z = 0) {
const m = new THREE.Mesh(geo, mat);
m.position.set(x, y, z);
m.castShadow = true;
m.receiveShadow = true;
parent.add(m);
return m;
}
/** Rotate an object so its local +x points along dir. */
export function aimX(obj, dir) {
obj.quaternion.setFromUnitVectors(new V3(1, 0, 0), dir.clone().normalize());
return obj;
}
/** Instances of one geometry at a list of matrices (casts and takes shadows). */
export function instances(parent, geo, mat, mats) {
const im = new THREE.InstancedMesh(geo, mat, mats.length);
mats.forEach((m, i) => im.setMatrixAt(i, m));
im.castShadow = true;
im.receiveShadow = true;
parent.add(im);
return im;
}
+117
View File
@@ -0,0 +1,117 @@
"""Score for the THERAPHOS TH-8 simulator film (entry tarantula-film; the SALTICUS JS-8 score, robospider-sim), after the scorpion's (roboscorp-shared/
score_sim.py): a bed for the whole film (D minor, 100 bpm, e-piano, bass, soft drums and a pad on the same changes)
at one level, a quiet click on every button press, and short quiet accents on the spider's own moves: soft servo
ticks under the steps, a tension rise in each crouch, a whoosh on each take-off and a thud on the first landing,
thread ticks as the lenses unscrew and screw back, servo blips down the front leg, a lift of air as the canopy opens
and the head's plates lift, two fang snaps, a whoosh into the explode and three clicks as it seats, and the one low
impact of the film on the last landing.
python run_sfx.py sims/tarantula-shared/score.py
Every cue comes from the script in robospider-sim/timeline.json, with the offsets inside each act taken from tour.js
(ACT, the two jumps J1 and J2, the walk keys, the explode out 0.2-1.8 s and home 0-1.0 s).
"""
import os
from sfx.score_kit import airy, bed, chords, hz # noqa: E402
from sfx.synth import blip, click, envelope, impact, pad, whoosh # noqa: E402
TIMELINE = os.environ.get("TL", "../tarantula-film/timeline.json")
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "tarantula-score.wav"))
TARGET_LUFS = -14.0
SEED = 37
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "A#maj7:A#2 D3 F3 A3/A#1", "Gm9:G2 A#2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3/A1")
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
STRIDE = 2.7
# the first jump, fixed in tour.js: crouch, lift-off, touch-down
J1 = (1.5, 1.98, 2.55)
def steps(mix, t0, t1, level=0.012):
"""Soft servo ticks, two per stride (one per group of four feet landing), panned with the stepping side."""
t = t0
i = 0
while t < t1:
mix.put(t, click(1500 + 120 * (i % 3), 0.02), level, pan=-0.25 if i % 2 else 0.25)
t += 0.5 / STRIDE
i += 1
def jump(mix, t0, tl, ta, last=False):
"""A crouch that winds up, the take-off whoosh, the landing: a soft thud, or the film's one impact."""
mix.put(t0, airy(tl - t0, 300, 1100, 0.8), 0.022)
mix.put(tl - 0.04, whoosh(0.5, 600, 2800, peak=0.45), 0.045)
for i in range(4):
mix.put(tl - 0.1 + 0.02 * i, click(1800 + 200 * i, 0.015), 0.025, pan=-0.3 + 0.2 * i)
if last:
mix.put(ta, impact(1.2), 0.22)
else:
mix.put(ta, click(900, 0.05), 0.07)
mix.put(ta + 0.005, blip(hz("D3"), 0.25, 0.08), 0.06)
for i in range(3):
mix.put(ta + 0.08 + 0.05 * i, click(2200 - 150 * i, 0.015), 0.025, pan=-0.2 + 0.2 * i)
def snap(mix, t, level=0.045, pan=0.0):
"""A fang snapping shut: a hard click with a short tonal knock under it."""
mix.put(t, click(2600, 0.03), level, pan=pan)
mix.put(t + 0.004, blip(hz("D5"), 0.12, 0.04), level * 0.35, pan=pan)
def score(mix, tl):
dur = tl["duration"]
left, right, low, drums = bed(dur, 100, CHORDS, MOTIF, motif_voice="blip", kicks=(0, 2.5), snares=(1, 3), hats=8, swing=0.08, keys_vel=0.75, keys_lp=3800)
mix.put_stereo(0, left, right, 0.13)
mix.put(0, low, 0.13)
mix.put(0, drums, 0.05)
bar = 4 * 60 / 100
changes = [(0.12 + b * bar, [f for f in CHORDS[b % len(CHORDS)][0][:4]]) for b in range(int(dur / bar) + 1)]
pl, pr = pad(dur, changes, volume=envelope([(0, 0), (1.0, 1), (dur - 1.6, 1), (dur, 0)]), detune=0.8, tremolo=0.18, xfade=0.5)
mix.put_stereo(0, pl, pr, 0.07)
acts = {e["act"]: e["t"] for e in tl["script"]}
# the run-in and the first jump at the camera
steps(mix, 0.0, 1.9)
jump(mix, *J1)
for e in tl["script"]:
t, act = e["t"], e["act"]
mix.put(t, click(2400, 0.025), 0.055, pan=0.45)
if act == "eyes":
for i, dt in enumerate((0.35, 0.5, 0.65, 0.8, 0.95)):
mix.put(t + dt, click(3300 - 180 * i, 0.016), 0.032, pan=0.1)
mix.put(t + 0.9, blip(hz("A6"), 0.2, 0.06), 0.018)
for i, dt in enumerate((1.95, 2.1, 2.25, 2.4)):
mix.put(t + dt, click(2600 + 180 * i, 0.016), 0.028, pan=0.1)
elif act == "leg":
mix.put(t + 0.05, airy(0.5, 600, 1500, 0.5), 0.016, pan=0.35)
for i, dt in enumerate((0.55, 0.75, 0.95, 1.15, 1.35)):
mix.put(t + dt, blip(hz("D6") * 2 ** (i / 6), 0.18, 0.06), 0.02, pan=0.35)
mix.put(t + 2.5, click(2000, 0.03), 0.05, pan=0.35)
elif act == "abdomen":
mix.put(t + 0.3, airy(1.1, 450, 1500, 0.6), 0.026, pan=-0.2)
for i, dt in enumerate((0.7, 0.85, 1.0)):
mix.put(t + dt, click(2800 - 200 * i, 0.018), 0.026, pan=-0.2)
mix.put(t + 2.5, click(2100, 0.03), 0.055, pan=-0.2)
elif act == "head":
mix.put(t + 0.3, airy(1.0, 500, 1700, 0.6), 0.024)
snap(mix, t + 0.95, 0.04, -0.15)
snap(mix, t + 1.45, 0.04, 0.15)
# the flared fangs snapping shut as the head closes
snap(mix, t + 2.38, 0.05, 0.0)
mix.put(t + 2.45, click(2100, 0.03), 0.05)
elif act == "exploded":
mix.put(t + 0.2, airy(1.4, 500, 2600, 0.7), 0.032, pan=-0.15)
mix.put(t + 0.25, blip(hz("D6"), 0.3, 0.1), 0.025)
elif act == "assemble":
mix.put(t, airy(1.0, 2200, 600, 0.5), 0.02, pan=0.15)
for i, dt in enumerate((0.6, 0.8, 1.0)):
mix.put(t + dt, click(2000 + 300 * i, 0.03), 0.05, pan=-0.3 + 0.3 * i)
mix.put(t + 1.15, whoosh(0.5, 800, 2200, peak=0.5), 0.022)
elif act == "hero":
steps(mix, t + 0.4, acts.get("jump", t + 3.0) + 0.4)
elif act == "jump":
jump(mix, t + 0.25, t + 0.72, t + 1.3, last=True)
+100
View File
@@ -0,0 +1,100 @@
// THERAPHOS TH-8, the approved tarantula film re-shot on the green page (entry tarantula-film). Everything that
// moves comes from tour.js unchanged (the run-in, the gait, both jumps, every assembly, every camera, the timing); what
// is new is only the look: green for orange on the spider and its glows, white paper with mint haze, and the green page
// from ../green in place of the old console, the subject shifted by SHIFT into its 3D window.
import {runSim} from '../kit/runtime.js';
import {createConsole} from '../green/console.js';
import {makeCursor, makeLabels, nice, ORANGE_TO, PAPER_GREEN, retint, SHIFT} from '../green/look.js';
import {PAL} from './parts.js';
import {buildSpider, FLOOR_Y} from './spider.js';
import {createStage, PAPER} from './stage.js';
import {makeTour, REACH} from './tour.js';
const D2R = Math.PI / 180;
Object.assign(PAL, {orange: ORANGE_TO});
Object.assign(PAPER, PAPER_GREEN);
const ACTS = [['eyes', 'Optics'], ['leg', 'Front leg'], ['abdomen', 'Abdomen'], ['head', 'Head'], ['exploded', 'Teardown'], ['hero', 'Release'], ['jump', 'Jump']];
const PAGE = {
name: 'Theraphos',
code: 'TH-8',
title: 'Robotic Tarantula, Taken Apart',
date: '2026-11-6',
nav: [['overview', 'Overview'], ...ACTS],
pills: ACTS,
sub: {
overview: ['8 legs · 32 joints', '2 main + 6 side optics'],
eyes: ['Main optic Ø 46 mm', 'Iris: 10 blades, f/1.4'],
leg: ['Coxa servo, yaw ±45°', 'Tibia piston, 60 mm'],
abdomen: ['Glass cage, 5 bands', '20 lit coils'],
head: ['Brow plate lifts 40 mm', 'Fangs flare 40°'],
exploded: ['Every part apart', 'Turntable 360°'],
hero: ['Back on 8 feet', 'Crouch armed'],
jump: ['Jump at the lens', 'Legs tucked'],
},
cards: [{k: 'Gait', kind: 'wave', unit: 'Hz'}, {k: 'Body load', kind: 'bar', unit: '%'}, {k: 'Leg servos', kind: 'bars', n: 8}, {k: 'Battery', kind: 'bar', unit: '%'}],
};
const TEXT = {'MAIN OPTIC R': ['Main optic'], 'SIDE OPTIC': ['Side optics'], 'GLOW COILS': ['Lit coils'], 'KNEE RING': ['Knee ring', 'lit ring, 2.4 N·m'], 'CLAW TIP': ['Claw tip', 'lit, 14 mm']};
const STATUS = {'RUN-IN': 'Running in', WALK: 'Walking', STANDING: 'Standing', CROUCH: 'Crouching', AIRBORNE: 'Airborne', LANDING: 'Landing', TEARDOWN: 'Teardown', REASSEMBLY: 'Reassembly', 'OPTICS OPEN': 'Optics open', 'LEG R1 APART': 'Front leg apart', 'LEG R1 LIFT': 'Front leg up', 'ABDOMEN OPEN': 'Abdomen open', 'HEAD OPEN': 'Head open'};
export function makeTarantulaGreen(TL) {
const FILM = TL.film ?? TL.duration;
const SPEED = TL.duration / FILM;
const T = makeTour(TL);
return async ({canvas, capture}) => {
const app = document.getElementById('app');
const st = createStage({canvas, floorY: FLOOR_Y, guides: {centre: [-0.3, 0.1, 0], scale: 1.3}});
const sp = buildSpider();
st.addBee(sp);
retint(sp.root);
sp.root.rotation.order = 'YXZ';
const ui = createConsole(app, PAGE);
const cursorAt = makeCursor(ui, T.SCRIPT);
const labels = makeLabels(st, sp.anchors, TEXT);
const fit = () => (app.style.transform = `scale(${Math.min(innerWidth / 1600, innerHeight / 900)})`);
const resize = () => {
fit();
st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));
};
resize();
window.SP = {st, sp, T};
return {
resize,
render(tf) {
// a demo plays the scene's timeline a little faster: TL.film seconds of film for TL.duration of scene
const t = tf * SPEED;
const s = T.stateAt(t);
const b = s.body;
sp.root.position.set(b.x, b.y, b.z);
sp.root.rotation.set(b.roll, b.yaw + s.turn * D2R, b.pitch);
sp.root.updateMatrixWorld(true);
sp.pose({explode: s.explode, spinT: s.spinT, spinA: s.spinA, t, sub: s.sub, feet: s.feet, tuck: s.tuck, palp: s.palp, reach: REACH});
retint(sp.root);
const c = s.cam;
st.frame({...c, az: c.az * D2R, el: c.el * D2R, sx: (c.sx ?? 0) + SHIFT[0], sy: (c.sy ?? 0) + SHIFT[1]}, {guides: s.guides});
const tel = T.telemetry(t, s);
const v = s.view;
const amp = tel.walking ? 0.85 : 0.12;
const wave = [];
for (let i = 0; i <= 90; i++) wave.push(amp * Math.sin(2 * Math.PI * Math.max(0.6, tel.freq) * (t - 1.2 + (i / 90) * 1.2)));
const lift = Math.min(1, tel.lift);
const bat = 0.861 - 0.0022 * t;
ui.update({
time: tf,
dur: FILM,
status: STATUS[tel.status] ?? nice(tel.status),
cards: [{v: tel.freq.toFixed(1), wave}, {v: Math.round(lift * 100), bar: lift}, {bars: tel.servos}, {v: Math.round(bat * 100), bar: bat}],
apart: Math.round(Math.max(s.open?.[v] ?? 0, s.explode) * 100),
view: v === 'intro' ? 'overview' : v,
callouts: labels(tel.labelSet),
cursor: cursorAt(t),
});
return {};
},
};
};
}
export const runTarantulaGreen = (TL, title = 'tarantula-film') =>
runSim({duration: TL.film ?? TL.duration, fps: 60, theme: 'light', hud: {enabled: false, title, subtitle: ''}, director: {enabled: false}, watermark: ''}, makeTarantulaGreen(TL));
File diff suppressed because it is too large Load Diff
+341
View File
@@ -0,0 +1,341 @@
// The robotic spider's stage, copied from the scorpion v2's (roboscorp-shared/stage.js, itself the bee's) with an optional fov per frame: a near-white product studio. A warm
// paper backdrop with no horizon, a soft shadow pooled on the floor under the scorpion (its silhouette seen from
// below, blurred wide, plus a tighter pass for what stands on the floor), a softbox environment for the clear coat to
// catch, a key with VSM self-shadows, a rim and a fill, GTAO kept off the backdrop and the clear parts, MSAA. The tone curve is linear up to 0.8 and rolls off
// above, hue preserved; the backdrop writes the inverse of that curve, so the paper lands on its exact colour and the
// floor shadow darkens it as drawn. frame(cam, ops) draws one frame; cam = {tx, ty, tz, az, el, d, sx, sy}.
import * as THREE from 'three';
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
import {GTAOPass} from 'three/addons/postprocessing/GTAOPass.js';
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
import {FullScreenQuad, Pass} from 'three/addons/postprocessing/Pass.js';
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
import {buildGuides} from './guides.js';
const V3 = THREE.Vector3;
// the paper: top, middle, the floor band (sRGB), and the shadow's tint
export const PAPER = {top: '#fefcf8', mid: '#fcf9f3', low: '#f5efe7', shadow: '#c9bcae'};
const KNEE = 0.8;
THREE.ShaderChunk.tonemapping_pars_fragment = THREE.ShaderChunk.tonemapping_pars_fragment.replace(
'vec3 CustomToneMapping( vec3 color ) { return color; }',
`vec3 CustomToneMapping( vec3 color ) {
color *= toneMappingExposure;
float p = max( color.r, max( color.g, color.b ) );
if ( p <= ${KNEE.toFixed(2)} ) return color;
float np = ${KNEE.toFixed(2)} + ${(1 - KNEE).toFixed(2)} * ( 1.0 - exp( -( p - ${KNEE.toFixed(2)} ) / ${(1 - KNEE).toFixed(2)} ) );
return color * ( np / p );
}`,
);
export const BEE_LAYER = 1;
// the scorpion is wider than the bee: the key's shadow box and the floor shadow's window grow with it
const SPAN = 4.6;
const BACK_VERT = /* glsl */ `varying vec3 vW;
void main(){
#ifdef SCREEN
vW = vec3(0.0); gl_Position = vec4(position.xy, 0.99999, 1.0);
#else
vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w;
#endif
}`;
const BACK_FRAG = /* glsl */ `uniform vec3 uTop, uMid, uLow, uTint; uniform vec2 uRes;
uniform sampler2D tSoft, tNear; uniform mat4 uVP; uniform float uSoft, uNear;
varying vec3 vW;
vec3 paper(float y){ return y > 0.42 ? mix(uMid, uTop, smoothstep(0.42, 1.0, y)) : mix(uLow, uMid, smoothstep(0.0, 0.42, y)); }
// the inverse of the tone curve's shoulder: what to write so the output lands on c
vec3 untone(vec3 c){
float p = max(c.r, max(c.g, c.b));
if (p <= ${KNEE.toFixed(2)}) return c;
float pin = ${KNEE.toFixed(2)} - ${(1 - KNEE).toFixed(2)} * log(max(1e-4, 1.0 - (p - ${KNEE.toFixed(2)}) / ${(1 - KNEE).toFixed(2)}));
return c * (pin / p);
}
float tap(sampler2D t, vec3 w){
vec4 c = uVP * vec4(w, 1.0);
vec2 uv = c.xy / c.w * 0.5 + 0.5;
if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) return 0.0;
vec2 e = smoothstep(0.0, 0.08, uv) * smoothstep(0.0, 0.08, 1.0 - uv);
return texture2D(t, uv).r * e.x * e.y;
}
void main(){
vec3 c = paper(gl_FragCoord.y / uRes.y);
#ifndef SCREEN
float s = clamp(tap(tSoft, vW) * uSoft + tap(tNear, vW) * uNear, 0.0, 1.0);
c = mix(c, c * uTint, s);
#endif
gl_FragColor = vec4(untone(c), 1.0);
}`;
const QUAD_VERT = /* glsl */ `varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
const BLUR_FRAG = /* glsl */ `uniform sampler2D tSrc; uniform vec2 uDir; varying vec2 vUv;
void main(){
float w[5]; w[0] = 0.2270270270; w[1] = 0.1945945946; w[2] = 0.1216216216; w[3] = 0.0540540541; w[4] = 0.0162162162;
vec4 c = texture2D(tSrc, vUv) * w[0];
for (int i = 1; i < 5; i++) { c += texture2D(tSrc, vUv + uDir * float(i)) * w[i]; c += texture2D(tSrc, vUv - uDir * float(i)) * w[i]; }
gl_FragColor = c;
}`;
// silhouette from below: everything counts, what hangs low counts more
const SIL_VERT = /* glsl */ `varying float vH; uniform float uFloor; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vH = w.y - uFloor; gl_Position = projectionMatrix * viewMatrix * w; }`;
const SIL_FRAG = /* glsl */ `varying float vH; uniform float uFar, uBase; void main(){ float k = 1.0 - clamp(vH / uFar, 0.0, 1.0); gl_FragColor = vec4(uBase + (1.0 - uBase) * k * k, 0.0, 0.0, 1.0); }`;
export function createStage({canvas, floorY = -1.55, guides: guideOpts = {}}) {
const renderer = new THREE.WebGLRenderer({canvas, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance'});
renderer.toneMapping = THREE.CustomToneMapping;
renderer.toneMappingExposure = 1.0;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.VSMShadowMap;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(30, 16 / 9, 0.05, 80);
const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 8}));
composer.addPass(new RenderPass(scene, camera));
const gtao = new GTAOPass(scene, camera, 4, 4);
gtao.output = GTAOPass.OUTPUT.Default;
gtao.blendIntensity = 1.0;
gtao.updateGtaoMaterial({radius: 0.13, distanceExponent: 1.6, thickness: 0.9, scale: 1.0, samples: 16, distanceFallOff: 1.0, screenSpaceRadius: false});
gtao.updatePdMaterial({lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 5, rings: 2, samples: 16});
class Toggle extends Pass {
constructor(fn) {
super();
this.needsSwap = false;
this.fn = fn;
}
render() {
this.fn();
}
}
// the backdrop, the guides and every clear part stay out of the AO pass
const skip = [];
// extra: meshes skipped only while a mode asks (the shells under x-ray)
let extra = [];
const aoSkip = (on) => {
for (const o of skip) o.visible = on && o.userData.show !== false;
for (const o of extra) o.visible = on;
};
composer.addPass(new Toggle(() => aoSkip(false)));
composer.addPass(gtao);
composer.addPass(new Toggle(() => aoSkip(true)));
composer.addPass(new OutputPass());
// ------------------------------------------------------------ the studio the clear coat reflects
{
const env = new THREE.Scene();
env.background = new THREE.Color('#d8d4ce');
const box = (w, h, pos, k, tint = [1, 0.985, 0.96]) => {
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(...tint).multiplyScalar(k), side: THREE.DoubleSide}));
m.position.copy(pos);
m.lookAt(0, 0, 0);
env.add(m);
};
box(16, 10, new V3(-4, 16, 6), 3.2); // the big top box
box(3, 16, new V3(-15, 4, 8), 2.6); // a tall strip, left front
box(3, 16, new V3(14, 5, -6), 2.0, [0.96, 0.98, 1]); // the rim strip behind
box(20, 3, new V3(2, 2, 16), 1.5); // a low card in front
box(8, 8, new V3(10, 2, 12), 1.1); // fill, right front
const g = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({color: '#e9e3da', side: THREE.DoubleSide}));
g.rotation.x = -Math.PI / 2;
g.position.y = -3;
env.add(g);
const pm = new THREE.PMREMGenerator(renderer);
scene.environment = pm.fromScene(env, 0.025).texture;
scene.environmentIntensity = 0.62;
pm.dispose();
}
const KEY = new V3(-0.3, 0.86, 0.55).normalize();
const key = new THREE.DirectionalLight('#fffaf3', 3.0);
key.castShadow = true;
Object.assign(key.shadow.camera, {left: -SPAN, right: SPAN, top: SPAN, bottom: -SPAN, near: 1, far: 18});
key.shadow.mapSize.set(4096, 4096);
key.shadow.radius = 6;
key.shadow.blurSamples = 20;
key.shadow.bias = -0.0005;
key.shadow.normalBias = 0.01;
scene.add(key, key.target);
const rim = new THREE.DirectionalLight('#f2f6ff', 1.1);
rim.position.set(3, 3, -5);
scene.add(rim);
const fill = new THREE.DirectionalLight('#fff6ec', 0.3);
fill.position.set(4, -1, 5);
scene.add(fill);
scene.add(new THREE.HemisphereLight('#ffffff', '#d9cfc2', 0.32));
// ------------------------------------------------------------ backdrop: the paper behind, the floor with its shadow
const lin = (hex) => new THREE.Color(hex);
const backU = {
uTop: {value: lin(PAPER.top)},
uMid: {value: lin(PAPER.mid)},
uLow: {value: lin(PAPER.low)},
uTint: {value: lin(PAPER.shadow)},
uRes: {value: new THREE.Vector2(1, 1)},
tSoft: {value: null},
tNear: {value: null},
uVP: {value: new THREE.Matrix4()},
uSoft: {value: 0.42},
uNear: {value: 0.55},
};
const paper = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, defines: {SCREEN: ''}, depthWrite: false, depthTest: false}));
paper.frustumCulled = false;
paper.renderOrder = -10;
scene.add(paper);
const floor = new THREE.Mesh(new THREE.PlaneGeometry(200, 200).rotateX(-Math.PI / 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, depthWrite: false}));
floor.position.y = floorY;
floor.renderOrder = -9;
scene.add(floor);
skip.push(paper, floor);
// the floor shadow: the bee from below into two targets, one blurred wide, one tight
const SR = 512;
const HALF = SPAN + 0.8;
const mkRT = () => new THREE.WebGLRenderTarget(SR, SR, {type: THREE.HalfFloatType});
const soft = [mkRT(), mkRT()];
const near = [mkRT(), mkRT()];
backU.tSoft.value = soft[0].texture;
backU.tNear.value = near[0].texture;
const shCam = new THREE.OrthographicCamera(-HALF, HALF, HALF, -HALF, 0, 6);
shCam.up.set(0, 0, -1);
shCam.layers.set(BEE_LAYER);
const silU = {uFloor: {value: floorY}, uFar: {value: 1.6}, uBase: {value: 1.0}};
const silMat = new THREE.ShaderMaterial({vertexShader: SIL_VERT, fragmentShader: SIL_FRAG, uniforms: silU, side: THREE.DoubleSide});
const blurMat = new THREE.ShaderMaterial({vertexShader: QUAD_VERT, fragmentShader: BLUR_FRAG, uniforms: {tSrc: {value: null}, uDir: {value: new THREE.Vector2()}}, depthTest: false, depthWrite: false});
const blurQuad = new FullScreenQuad(blurMat);
const blur = ([a, b], px, passes) => {
for (let i = 0; i < passes; i++) {
blurMat.uniforms.tSrc.value = a.texture;
blurMat.uniforms.uDir.value.set(px / SR, 0);
renderer.setRenderTarget(b);
blurQuad.render(renderer);
blurMat.uniforms.tSrc.value = b.texture;
blurMat.uniforms.uDir.value.set(0, px / SR);
renderer.setRenderTarget(a);
blurQuad.render(renderer);
}
};
const black = new THREE.Color(0, 0, 0);
const prevClear = new THREE.Color();
const floorShadow = (c) => {
shCam.position.set(c.x, floorY - 0.01, c.z);
shCam.lookAt(c.x, floorY + 1, c.z);
shCam.updateMatrixWorld();
shCam.updateProjectionMatrix();
renderer.getClearColor(prevClear);
const prevA = renderer.getClearAlpha();
const prevOv = scene.overrideMaterial;
const prevSh = renderer.shadowMap.autoUpdate;
renderer.shadowMap.autoUpdate = false;
renderer.setClearColor(black, 1);
scene.overrideMaterial = silMat;
for (const [rt, base, far, px, passes] of [
[soft, 1.0, 1.0, 3.2, 4],
[near, 0.0, 1.5, 1.2, 2],
]) {
silU.uBase.value = base;
silU.uFar.value = far;
renderer.setRenderTarget(rt[0]);
renderer.clear();
renderer.render(scene, shCam);
blur(rt, px, passes);
}
scene.overrideMaterial = prevOv;
renderer.shadowMap.autoUpdate = prevSh;
renderer.setRenderTarget(null);
renderer.setClearColor(prevClear, prevA);
backU.uVP.value.multiplyMatrices(shCam.projectionMatrix, shCam.matrixWorldInverse);
};
// a dark studio for the camera lenses only: black all round with a few hard softboxes, so the glass reads deep
// black with crisp highlights instead of mirroring the pale studio as a grey haze
const lensEnv = (() => {
const env = new THREE.Scene();
env.background = new THREE.Color('#050506');
const box = (w, h, dir, k) => {
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(1, 0.98, 0.95).multiplyScalar(k), side: THREE.DoubleSide}));
m.position.copy(new V3(...dir).normalize().multiplyScalar(15));
m.lookAt(0, 0, 0);
env.add(m);
};
box(10, 6, [-0.2, 1, 0.2], 6); // overhead
box(1.6, 12, [-0.85, 0.3, 0.45], 7); // a tall strip, left
box(3.2, 2.2, [0.42, 0.62, 0.66], 9); // a small box above the camera: the hot spot on the dome
box(1.2, 10, [0.75, 0.2, -0.6], 3); // a rim strip behind
const pm = new THREE.PMREMGenerator(renderer);
const tex = pm.fromScene(env, 0.01).texture;
pm.dispose();
return tex;
})();
// ------------------------------------------------------------ the scorpion and the guides
let bee = null;
const addBee = (b) => {
bee = b;
scene.add(b.root);
b.root.traverse((o) => {
if (o.isMesh && !b.clear.includes(o)) o.layers.enable(BEE_LAYER);
});
skip.push(...b.clear);
for (const m of [b.M.lens, b.M.lensGlass]) {
if (!m) continue;
m.envMap = lensEnv;
m.needsUpdate = true;
}
};
const guides = buildGuides(guideOpts);
scene.add(guides.group);
skip.push(guides.group);
const size = {w: 1920, h: 1080, pr: 1};
const resize = (w, h, pr) => {
Object.assign(size, {w, h, pr});
renderer.setPixelRatio(pr);
renderer.setSize(w, h, false);
composer.setPixelRatio(pr);
composer.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
backU.uRes.value.set(Math.round(w * pr), Math.round(h * pr));
guides.resize(Math.round(w * pr), Math.round(h * pr), pr);
};
// cam: target (tx, ty, tz), azimuth from +z toward +x, elevation, distance, screen shift sx/sy in CSS px, fov (30)
const frame = (cam, ops = {}) => {
const {tx, ty, tz, az, el, d} = cam;
const fov = cam.fov ?? 30;
if (camera.fov !== fov) {
camera.fov = fov;
camera.updateProjectionMatrix();
}
camera.position.set(tx + d * Math.cos(el) * Math.sin(az), ty + d * Math.sin(el), tz + d * Math.cos(el) * Math.cos(az));
camera.lookAt(tx, ty, tz);
camera.setViewOffset(size.w, size.h, -(cam.sx ?? 0), -(cam.sy ?? 0), size.w, size.h);
camera.updateMatrixWorld();
const c = bee ? bee.root.position : new V3();
key.target.position.set(c.x + 0.1, c.y, c.z);
key.position.copy(key.target.position).addScaledVector(KEY, 9);
key.target.updateMatrixWorld();
guides.update(camera, ops);
floorShadow(c);
composer.render();
};
const pv = new V3();
/** World point to CSS px, or null behind the camera. Call after frame(). */
const project = (p) => {
pv.copy(p).project(camera);
if (pv.z > 1) return null;
return [(pv.x * 0.5 + 0.5) * size.w, (-pv.y * 0.5 + 0.5) * size.h];
};
const setAOSkip = (list) => {
extra = list;
};
// a live page's quality knobs: MSAA samples, the AO pass, the key's shadow map
const setQuality = ({samples, ao, shadow}) => {
if (samples !== undefined) {
for (const t of [composer.renderTarget1, composer.renderTarget2]) {
t.samples = samples;
t.dispose();
}
}
if (ao !== undefined) gtao.enabled = ao;
if (shadow !== undefined && shadow !== key.shadow.mapSize.x) {
key.shadow.mapSize.set(shadow, shadow);
key.shadow.map?.dispose();
key.shadow.map = null;
}
};
return {renderer, scene, camera, composer, gtao, key, resize, frame, addBee, size, floorY, project, setAOSkip, setQuality};
}
+502
View File
@@ -0,0 +1,502 @@
// The JS-8 simulator tour, after the scorpion's (roboscorp-shared/tour.js) under the camera rules of
// 2026-10-31: frame 0 is already the low front 3/4 hero view with the spider big and running; every teardown is shot
// from that hero side (within about ±35°, the eyes toward the camera, a little above, pushing in on the part); the
// variety lives in the transitions, the explode's turntable and the final jump. The camera rides a smoothed copy of
// the body's path, never the stride bob or the jump.
// The film: the spider runs in, brakes, crouches and jumps at the camera; then the operator opens one assembly after
// another: the main lenses unscrew and the side lenses swivel, the near front leg lifts and comes apart segment by
// segment with its piston out of the glass, the abdomen's canopy swings open and the gears lift out spinning fast, the
// head's plates lift and the fangs and palps work; then it explodes on a turntable, snaps back together, walks a few
// steps and jumps at the camera again.
// Script: the entry's timeline.json, {duration, script: [{t, act}]}; act is an assembly (eyes, leg, abdomen, head),
// 'exploded', 'assemble', 'hero' (the walk) or 'jump' (the final jump). Everything is a pure function of film time t.
import * as THREE from 'three';
import {VIEWPORT} from './console.js';
import {buildGait, STRIDE_HZ} from './gait.js';
import {CROUCH, jumpAt, jumpKeys} from './jump.js';
import {FLOOR_Y, LEG_NAMES} from './spider.js';
const smoother = (x) => {
const u = Math.min(1, Math.max(0, x));
return u * u * u * (u * (u * 6 - 15) + 10);
};
const ss = (a, b, t) => smoother((t - a) / (b - a));
const lerp = (a, b, k) => a + (b - a) * k;
const D2R = Math.PI / 180;
// a fast in, eased out pulse: 0 before a, up to 1 at b, back to 0 by c
const pulse = (a, b, c, t) => ss(a, b, t) * (1 - ss(b, c, t));
// millimetres per scene unit, for the readouts
const MM = 220;
export const REACH = 0.7;
export const ASSEMBLIES = ['hero', 'eyes', 'leg', 'abdomen', 'head', 'jump'];
export const ASSEMBLY_LABEL = {hero: 'HERO', eyes: 'OPTICS', leg: 'LEG R1', abdomen: 'ABDOMEN', head: 'HEAD', jump: 'JUMP'};
export const DISPLAY2 = ['labels', 'exploded', 'turntable', 'trace'];
export const DISPLAY2_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', turntable: 'TURNTABLE', trace: 'GAIT TRACE'};
const BUTTON = {eyes: 'eyes', leg: 'leg', abdomen: 'abdomen', head: 'head', exploded: 'exploded', assemble: 'exploded', hero: 'hero', jump: 'jump'};
// each act's own clock (seconds after its click): when its parts open and when they close
const ACT = {
eyes: {open: [0.3, 1.3], close: [1.95, 2.45]},
leg: {open: [0.5, 1.45], close: [2.05, 2.5]},
abdomen: {open: [0.3, 1.35], close: [2.0, 2.5]},
head: {open: [0.3, 1.3], close: [1.95, 2.45]},
};
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy, fov] in the
// frame of the smoothed body path (az from the spider's right toward its face: 90 is straight at the face, the hero
// side is about 66), u = seconds into the view
const H = 66;
export const CAMS = {
intro: (u) => {
const k = ss(0, 3.2, u);
return [lerp(H + 8, H - 4, k), lerp(10, 8, k), lerp(7.6, 6.8, k), lerp(-0.2, 0.4, k), lerp(0.0, -0.06, k), 0.0, 0, -14, 36];
},
eyes: (u) => [lerp(H + 4, H + 12, ss(0, 2.6, u)), lerp(12, 8, ss(0, 2.6, u)), lerp(6.0, 5.3, ss(0, 1.8, u)), 0.62, 0.04, 0.0, 0, -14, 36],
leg: (u) => [lerp(H - 16, H - 26, ss(0, 2.6, u)), lerp(16, 12, ss(0, 2.6, u)), lerp(6.6, 6.0, ss(0, 1.8, u)), 0.8, 0.06, 0.56, 0, -14, 36],
abdomen: (u) => [lerp(H - 4, H - 14, ss(0, 2.6, u)), lerp(36, 31, ss(0, 2.6, u)), lerp(8.2, 7.6, ss(0, 1.8, u)), -0.7, 0.4, 0.0, 0, -14, 36],
head: (u) => [lerp(H + 22, H + 14, ss(0, 2.6, u)), lerp(18, 14, ss(0, 2.6, u)), lerp(6.5, 5.9, ss(0, 1.8, u)), 0.45, 0.08, 0.0, 0, -14, 36],
exploded: (u) => [H + 10 * u, lerp(16, 22, ss(0, 2.0, u)), lerp(11.0, 12.2, ss(0, 1.6, u)), -0.25, 0.3, 0.0, 0, -14, 36],
hero: (u) => [lerp(H - 30, H + 26, ss(0, 3.0, u)), lerp(14, 7, ss(0, 3.0, u)), lerp(8.4, 7.2, ss(0, 3.0, u)), 0.3, -0.04, 0.0, 0, -14, 36],
jump: (u) => [lerp(H + 24, H + 18, ss(0, 3.0, u)), lerp(7, 5, ss(0, 1.6, u)), lerp(7.4, 6.9, ss(0, 1.2, u)) - 0.25 * ss(1.4, 3.3, u), 0.5, lerp(-0.04, 0.02, ss(0.4, 1.8, u)), 0.0, 0, -14, 36],
};
export function makeTour(TL) {
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
const DURATION = TL.duration;
const EVENTS = SCRIPT.map((e) => e.t);
const at = (act) => SCRIPT.filter((e) => e.act === act).map((e) => e.t);
const T_EXP = at('exploded')[0] ?? 999;
const T_ASM = at('assemble')[0] ?? 999;
const T_HERO = at('hero')[0] ?? 999;
const T_JUMP = at('jump')[0] ?? 999;
const T_LEG = at('leg')[0] ?? 999;
// the two jumps: at the camera out of the run-in, and the last one
const J1 = {t0: 1.5, tl: 1.98, ta: 2.55, dist: 1.1, h: 0.52};
const J2 = {t0: T_JUMP + 0.25, tl: T_JUMP + 0.72, ta: T_JUMP + 1.3, dist: 1.35, h: 0.6};
const jumpBoth = (t) => {
const a = jumpAt(t, J1);
const b = jumpAt(t, J2);
return {dy: a.dy + b.dy, pitch: a.pitch + b.pitch, tuck: Math.max(a.tuck, b.tuck), air: Math.max(a.air, b.air)};
};
const openOf = (act, t) => {
let v = 0;
for (const t0 of at(act)) {
const A = ACT[act];
v = Math.max(v, ss(t0 + A.open[0], t0 + A.open[1], t) * (1 - ss(t0 + A.close[0], t0 + A.close[1], t)));
}
return v;
};
const explodeAt = (t) => ss(T_EXP + 0.2, T_EXP + 1.8, t) * (1 - ss(T_ASM, T_ASM + 1.0, t));
// the turntable: one full turn from the explode to just after the spider is whole again, eased at both ends
const TT = [T_EXP + 0.2, T_ASM + 1.3];
const turnAt = (t) => {
const [a, b] = TT;
if (t <= a) return 0;
const R = 0.6;
const span = b - a;
const v = 360 / (span - R);
const x = Math.min(t, b) - a;
if (x < R) return (v * x * x) / (2 * R);
if (x < span - R) return v * (x - R / 2);
const y = x - (span - R);
return v * (span - 1.5 * R) + v * y - (v * y * y) / (2 * R);
};
const activity = (t) => Math.max(...Object.keys(ACT).map((a) => openOf(a, t)), explodeAt(t));
// the busy clocks: every gear turns on spinT, six times faster while an assembly is open; the abdomen's own gears
// on spinA, five times faster again while the canopy is up
const DT = 1 / 240;
const SPIN = [0];
const SPINA = [0];
for (let i = 1; i * DT <= DURATION + 1; i++) {
const tm = (i - 0.5) * DT;
const r = 1 + 5 * activity(tm);
SPIN.push(SPIN[i - 1] + r * DT);
SPINA.push(SPINA[i - 1] + (r + 5 * openOf('abdomen', tm)) * DT);
}
const look = (A, t) => {
const u = Math.max(0, Math.min(A.length - 2, t / DT));
const i = Math.floor(u);
return A[i] + (A[i + 1] - A[i]) * (u - i);
};
const spinAt = (t) => (t < 0 ? t : look(SPIN, t));
const spinAAt = (t) => (t < 0 ? t : look(SPINA, t));
// the walk: the run-in on a gentle curve to a stop, the first jump's travel, still through the acts, a short walk
// on a curve after the reassembly, a stop, the last jump's travel
const gait = buildGait({
duration: DURATION + 0.5,
tRef: 1.42,
keys: [
[-1.5, 1.05, 12],
[0.7, 1.0, 9],
[1.42, 0, 0],
...jumpKeys(J1),
[T_HERO + 0.3, 0, 0],
[T_HERO + 0.8, 0.62, -16],
[T_JUMP - 0.55, 0.55, -16],
[T_JUMP - 0.05, 0, 0],
...jumpKeys(J2),
],
});
// the camera's path: the body's path low-passed (gaussian, sigma 0.4 s), so the camera follows the spider without
// picking up the jump's dash or the stride
const CHZ = 60;
const C0 = -1.5;
const CN = Math.ceil((DURATION + 1 - C0) * CHZ);
const raw = Array.from({length: CN}, (_, i) => gait.pathAt(C0 + i / CHZ));
const SIG = 0.4 * CHZ;
const KR = Math.ceil(3 * SIG);
const KW = Array.from({length: 2 * KR + 1}, (_, j) => Math.exp(-0.5 * Math.pow((j - KR) / SIG, 2)));
const CX = new Float64Array(CN);
const CZ = new Float64Array(CN);
const CY = new Float64Array(CN);
for (let i = 0; i < CN; i++) {
let sx = 0;
let sz = 0;
let sy = 0;
let sw = 0;
for (let j = -KR; j <= KR; j++) {
const p = raw[Math.max(0, Math.min(CN - 1, i + j))];
const w = KW[j + KR];
sx += p.x * w;
sz += p.z * w;
sy += p.yaw * w;
sw += w;
}
CX[i] = sx / sw;
CZ[i] = sz / sw;
CY[i] = sy / sw;
}
const camPath = (t) => {
const u = Math.max(0, Math.min(CN - 1.000001, (t - C0) * CHZ));
const i = Math.floor(u);
const f = u - i;
return {x: CX[i] + (CX[i + 1] - CX[i]) * f, z: CZ[i] + (CZ[i + 1] - CZ[i]) * f, yaw: CY[i] + (CY[i + 1] - CY[i]) * f};
};
// the near front leg (R1): lifted off the floor and held up in front before it comes apart
const legLiftAt = (t) => {
let v = 0;
for (const t0 of at('leg')) v = Math.max(v, ss(t0 + 0.05, t0 + 0.45, t) * (1 - ss(t0 + 2.2, t0 + 2.65, t)));
return v;
};
// the body: the path, the jumps, a bob with the stride, a slow breath, a lean off the lifted leg
const bodyAt = (t) => {
const p = gait.pathAt(t);
const rate = gait.rateAt(t) / STRIDE_HZ;
const ph = gait.phaseAt(t);
const [, w] = gait.velAt(t);
const j = jumpBoth(t);
const run = Math.min(1, rate) * (1 - j.air);
let y = j.dy + 0.014 * Math.sin(ph * Math.PI * 4) * run + 0.006 * Math.sin(t * 1.7);
let roll = -w * 0.001 + 0.01 * Math.sin(ph * Math.PI * 2) * run;
const pitch = j.pitch + 0.008 * Math.sin(t * 1.3 + 1);
const kl = legLiftAt(t);
roll -= 0.05 * kl;
y += 0.02 * kl;
return {x: p.x, z: p.z, y, yaw: p.yaw, roll, pitch, rate, jump: j};
};
const feetAt = (t, b) => {
const F = [];
for (let l = 0; l < 8; l++) {
const f = gait.footLocal(l, t, b);
if (l === 4) {
const k = legLiftAt(t);
f[0] -= 0.3 * k;
f[1] += 0.62 * k;
f[2] -= 0.12 * k;
}
F.push(f);
}
return F;
};
// the palps: up in front of the face for the jumps and the head act, otherwise hanging and twitching
const palpAt = (t, j) => 0.35 + 0.55 * j.tuck + 0.35 * pulse(J1.t0, J1.tl, J1.ta + 0.3, t) + 0.35 * pulse(J2.t0, J2.tl, J2.ta + 0.3, t) + 0.5 * pulse(J2.ta + 0.35, J2.ta + 0.8, J2.ta + 1.8, t);
// the close: after the last landing the main lenses focus on the camera (their rings run out a little and back)
const focusAt = (t) => 0.38 * pulse(J2.ta + 0.4, J2.ta + 0.85, J2.ta + 1.75, t);
// the camera: each act's view, blended over 0.9 s with a short dolly out, on the smoothed path
const VIEWS = [{t: -1, key: 'intro'}, ...SCRIPT.map((e) => ({t: e.t, key: e.act === 'assemble' ? 'exploded' : e.act}))];
const viewIdx = (t) => {
let i = 0;
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= t) i++;
return i;
};
const camFn = (V, t) => CAMS[V.key](t - (V.key === 'intro' ? 0 : V.t));
// the follow time: the camera follows the smoothed path, except into a jump, where its follow eases to a stop
// just before take-off (the speed falls from 1 to 0 over a..b), so the spider leaps toward a camera that holds
const ease = (t, a, b) => {
if (t <= a) return t;
const u = Math.min(1, (t - a) / (b - a));
return a + (b - a) * (u - (u * u) / 2);
};
const followT = (V, t) => (V.key === 'intro' ? ease(t, 0.8, 1.95) : V.key === 'jump' ? ease(t, J2.t0 - 0.6, J2.tl) : t);
// a view's camera in the world: its framing turned with the path's heading and put on the path
const world = (V, t) => {
const o = camFn(V, t);
const p = camPath(followT(V, t));
const cy = Math.cos(p.yaw);
const sy = Math.sin(p.yaw);
return [o[0] + p.yaw / D2R, o[1], o[2], p.x + o[3] * cy + o[5] * sy, o[4], p.z - o[3] * sy + o[5] * cy, o[6], o[7], o[8]];
};
// each view blended from the last one over 0.9 s in world space, with a short dolly out
const camAt = (t) => {
const i = viewIdx(t);
let o = world(VIEWS[i], t);
if (VIEWS[i].key === 'exploded' && i > 0 && VIEWS[i - 1].key === 'exploded') o = world(VIEWS[i - 1], t);
else if (i > 0) {
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.9, t);
if (k < 1) {
const a = world(VIEWS[i - 1], t);
const dAz = ((((o[0] - a[0]) % 360) + 540) % 360) - 180;
const b = o.map((v, n) => lerp(a[n], v, k));
b[0] = a[0] + dAz * k;
b[2] += 0.6 * Math.sin(Math.PI * k);
o = b;
}
}
return {az: o[0], el: o[1], d: o[2], tx: o[3], ty: o[4], tz: o[5], sx: o[6], sy: o[7], fov: o[8]};
};
const actAt = (t) => VIEWS[viewIdx(t)].key;
const stateAt = (t) => {
const ex = explodeAt(t);
const open = Object.fromEntries(Object.keys(ACT).map((a) => [a, openOf(a, t)]));
const body = bodyAt(t);
return {
t,
spinT: spinAt(t),
spinA: spinAAt(t),
explode: ex,
sub: {eyes: Math.max(open.eyes, focusAt(t)), leg: open.leg, abdomen: open.abdomen, head: open.head},
body,
feet: feetAt(t, body),
tuck: body.jump.tuck,
palp: palpAt(t, body.jump),
open,
cam: camAt(t),
view: actAt(t),
guides: 0.35 + 0.65 * Math.min(1, ex * 2.5 + activity(t)),
turn: turnAt(t),
};
};
// labels: on while an act's parts are moving apart and while they hang open, gone before they close
const LABELS = {
eyes: [['lens', 'MAIN OPTIC R', 'Ø 46 MM · 9 ELEMENTS'], ['iris', 'IRIS', '10 BLADES · F/1.4'], ['eyeGlass', 'DOME GLASS', 'SAPPHIRE · AR COAT'], ['ale', 'SIDE OPTIC', '6 SECONDARY · SWIVEL']],
leg: [['hipR1', 'COXA SERVO', 'YAW ±45°'], ['femR1', 'FEMUR PLATES', 'RIVETED · 52 BRISTLES'], ['kneeR1', 'KNEE RING', 'GLOW RING · 2.4 N·M'], ['pistonR1', 'TIBIA PISTON', 'PLATED · 60 MM'], ['footR1', 'CLAW TIP', 'GLOW · 14 MM']],
abdomen: [['canopy', 'GLASS CAGE', '5 BANDS · HINGED'], ['gears', 'FLANK GEARS', '7 PER SIDE · 5× SPEED'], ['core', 'GLOW COILS', '20 COILS · 5× SPEED']],
head: [['visor', 'BROW PLATE', 'LIFT 40 MM'], ['channel', 'SPINE CHANNEL', '8 GEARS'], ['face', 'EYE PLATE', '8 LENSES'], ['chel', 'FANG', 'FLARE 40° · GLOW TIP'], ['jaw', 'JAW BLOCK', '4 LINES · 2 GEARS']],
exploded: [['lens', 'OPTICS', '2 + 6 LENSES'], ['core', 'GLOW COILS', 'SPINNING FREE'], ['canopy', 'CAGE', 'GLASS · 5 BANDS'], ['kneeR1', 'LEG RINGS', '8 × 4 JOINTS']],
};
const labelAt = (t, s) => {
const v = s.view;
if (ACT[v]) {
const t0 = at(v).filter((x) => x <= t).pop();
const A = ACT[v];
return {set: LABELS[v], o: ss(t0 + A.open[0] + 0.1, t0 + A.open[0] + 0.45, t) * (1 - ss(t0 + A.close[0] - 0.25, t0 + A.close[0], t))};
}
if (v === 'exploded') return {set: LABELS.exploded, o: ss(T_EXP + 0.4, T_EXP + 0.8, t) * (1 - ss(T_EXP + 2.3, T_EXP + 2.6, t))};
return {set: [], o: 0};
};
// the optics: the iris opens wide for the eye act, stops down for the jumps; the focus range follows the camera
const irisAt = (t) => {
const j = jumpBoth(t);
return Math.max(0.05, Math.min(1, 0.35 + 0.6 * Math.max(openOf('eyes', t), focusAt(t)) - 0.25 * j.air + 0.06 * Math.sin(t * 2.1)));
};
const telemetry = (t, s) => {
const b = s.body;
const j = b.jump;
const ex = s.explode > 0.04;
const walking = b.rate > 0.05;
// the step diagram: stance and swing spans of every leg over the last 1.6 s, as fractions of the window
const W0 = t - 1.6;
const steps = [0, 1, 2, 3, 4, 5, 6, 7].map((l) => {
const row = [];
let x = W0;
for (const sw of gait.swings[l]) {
if (sw.t1 < W0) continue;
if (sw.t0 > t) break;
const a = Math.max(W0, sw.t0);
const c = Math.min(t, sw.t1);
if (a > x) row.push([(x - W0) / 1.6, (a - W0) / 1.6, false]);
row.push([(a - W0) / 1.6, (c - W0) / 1.6, true]);
x = c;
}
if (x < t) row.push([(x - W0) / 1.6, 1, false]);
return row;
});
const legOpen = s.open.leg > 0.08;
const free = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => ex || (i === 4 && legOpen));
const lifts = [0, 1, 2, 3, 4, 5, 6, 7].map((l) => gait.lifted(l, t));
const nLift = lifts.reduce((a, v) => a + v, 0);
// the crouch loads every knee, the flight unloads them
const crouch = Math.max(0, -j.dy) / CROUCH;
const servos = lifts.map((v, i) => (free[i] ? 0 : Math.max(0.04, Math.min(1, (j.air ? 0.1 : (v > 0.05 ? 0.16 : 0.34 + (0.22 * nLift) / 4) + 0.55 * crouch) + [0.06, 0.1, 0.04, 0.0, 0.08, 0.02, 0.09, 0.05][i] + 0.04 * Math.sin(t * 6 + i) - (i === 4 ? 0.3 * legLiftAt(t) : 0)))));
const v = s.view;
const opening = ACT[v] ? s.open[v] : 0;
const NAME = {eyes: 'OPTICS OPEN', leg: 'LEG R1 APART', abdomen: 'ABDOMEN OPEN', head: 'HEAD OPEN'};
let status = 'STANDING';
let kind = 'ok';
const jumpState = j.air ? 'AIRBORNE' : (t > J1.t0 && t < J1.tl) || (t > J2.t0 && t < J2.tl) ? 'CROUCH' : (t > J1.ta && t < J1.ta + 0.45) || (t > J2.ta && t < J2.ta + 0.45) ? 'LANDING' : null;
if (walking && !jumpState) status = t < 3 ? 'RUN-IN' : 'WALK';
if (ACT[v] && opening > 0.05) [status, kind] = [NAME[v], 'warn'];
if (v === 'leg' && legLiftAt(t) > 0.05 && opening <= 0.05) status = 'LEG R1 LIFT';
if (v === 'exploded') [status, kind] = t < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['STANDING', 'ok'];
if (jumpState) [status, kind] = [jumpState, 'warn'];
const ROW = {eyes: 0, head: 1, abdomen: 2, jump: 3, leg: 4};
const sub = (i) => {
if (ex) return ['warn', 'DETACHED'];
if (ROW[v] === i && opening > 0.05) return ['warn', i === 4 ? 'DETACHED' : 'OPEN'];
if (i === 3) return j.air ? ['warn', 'AIRBORNE'] : jumpState === 'CROUCH' ? ['warn', 'ARMED'] : ['ok', 'READY'];
if (i === 4) return walking ? ['ok', 'STEPPING'] : ['ok', 'HOLDING'];
if (i === 5) return s.open.head > 0.05 ? ['warn', 'ACTIVE'] : ['ok', 'FOLDED'];
if (i === 0) return ['ok', 'TRACKING'];
return ['ok', 'SEALED'];
};
const last = SCRIPT.filter((e) => e.t <= t).pop();
const say = (e) => (e.act === 'exploded' ? 'EXPLODED ON' : e.act === 'assemble' ? 'EXPLODED OFF · REASSEMBLE' : e.act === 'hero' ? 'HERO · WALK' : e.act === 'jump' ? 'JUMP · ARMED' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
const labels = labelAt(t, s);
// the jump readouts: the height over the stance (negative in the crouch), the last flight's airtime, the launch
// speed, the tuck
const Jl = t >= J2.t0 ? J2 : J1;
const air = j.air ? t - Jl.tl : t >= Jl.ta ? Jl.ta - Jl.tl : 0;
const launch = (2 * Jl.dist) / (Jl.ta - Jl.tl) * (MM / 1000) + 0.0;
const iris = irisAt(t);
const trace = [];
for (let i = 0; i <= 40; i++) trace.push(irisAt(t - 2 + (i / 40) * 2));
const [vv] = gait.velAt(t);
return {
time: t,
dur: DURATION,
lift: 0.18 + 0.45 * b.rate + 0.4 * crouch + 0.35 * j.air + 0.15 * activity(t),
status,
statusKind: kind,
freq: gait.rateAt(t) * (1 - j.air),
speed: Math.abs(vv) * MM,
steps,
pattern: j.air ? 'BALLISTIC · TUCKED' : walking ? 'ALT TETRAPOD' : 'STANCE · 8 FEET',
duty: walking && !j.air ? 0.54 : j.air ? 0 : 1,
jumpH: j.dy * MM,
jumpK: Math.max(0, Math.min(1, (j.dy + CROUCH) / (J2.h + CROUCH))),
airtime: air,
launch: t >= Jl.tl ? launch : 0,
tuck: j.tuck,
servos,
legsFree: ex,
legFreeEach: free,
walking,
iris,
fstop: 1.4 / Math.sqrt(Math.max(0.05, iris)) ,
irisTrace: trace,
lensOpen: [iris * (0.96 + 0.04 * Math.sin(t * 3)), iris],
opticsOpen: s.open.eyes > 0.05,
opticsMode: s.open.eyes > 0.05 ? 'OPEN' : j.air || jumpState === 'CROUCH' ? 'LOCK' : walking ? 'TRACK' : 'SCAN',
range: s.cam.d * MM,
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
display: {labels: labels.o > 0.5, exploded: t >= T_EXP && t < T_ASM, turntable: s.turn > 0 && t < TT[1], trace: walking},
subs: [0, 1, 2, 3, 4, 5].map(sub),
focus: jumpState ? 3 : ROW[v] ?? (v === 'exploded' ? 2 : -1),
events: EVENTS,
next: `${EVENTS.length} OPERATOR ACTIONS`,
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · RUN-IN · 8 LEGS',
mode: status,
modeSub: j.air
? `${Math.round(j.dy * MM)} MM UP · TUCK ${Math.round(j.tuck * 100)}%`
: status === 'CROUCH'
? `${Math.round(-j.dy * MM)} MM DOWN · KNEES LOADED`
: status === 'RUN-IN' || status === 'WALK'
? `${(Math.abs(vv) * MM).toFixed(0)} MM/S · YAW ${((((b.yaw / D2R) % 360) + 360) % 360).toFixed(0)}°`
: status === 'TEARDOWN' || status === 'REASSEMBLY'
? `TURNTABLE ${Math.round(s.turn)}° · ${Math.round(s.explode * 100)}% APART`
: ACT[v] && opening > 0.05
? `${ASSEMBLY_LABEL[v]} · ${Math.round(opening * 100)}% APART`
: `8 FEET DOWN · ${((0 - FLOOR_Y) * MM).toFixed(0)} MM CLEARANCE`,
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' || v === 'jump' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
labelSet: labels,
legNames: LEG_NAMES,
};
};
return {SCRIPT, DURATION, stateAt, telemetry, camAt, gait};
}
/** Labels in two columns at the viewport's edges, from a set of anchors (as the bee's makeLabels2). */
export function makeLabels(st, sc) {
const p = new THREE.Vector3();
return ({set, o}) => {
if (o < 0.02) return [];
const pts = [];
for (const [key, name, sub] of set) {
const A = sc.anchors[key];
if (!A) continue;
A.obj.updateWorldMatrix(true, false);
const at = st.project(A.obj.localToWorld(p.copy(A.at)));
if (at && at[0] > VIEWPORT.x0 + 30 && at[0] < VIEWPORT.x1 - 30 && at[1] > VIEWPORT.y0 + 40 && at[1] < VIEWPORT.y1 - 70) pts.push({name, sub, at});
}
const mid = (VIEWPORT.x0 + VIEWPORT.x1) / 2;
const out = [];
const stack = (col, x, w) => {
let y = Math.max(VIEWPORT.y0 + 48, Math.min(col.length ? col[0].at[1] - 10 : 0, VIEWPORT.y1 - 110 - 34 * col.length));
for (const c of col) {
y = Math.max(y, Math.min(VIEWPORT.y1 - 110, c.at[1] - 10));
out.push({name: c.name, sub: c.sub, at: c.at, label: [x, y], w, o});
y += 34;
}
};
stack(pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x0 + 16, 168);
stack(pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x1 - 160, 150);
return out;
};
}
// ------------------------------------------------------------ the operator's pointer, on the act buttons (the bee's)
const GUTTER_X = 1262;
export function makeCursor(ui, SCRIPT) {
// Timeline actions without a visible button still run; the pointer skips them.
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[BUTTON[e.act]]})).filter((e) => e.spot);
if (!EV.length) return () => ({x: -1, y: 0, press: false, ring: 0, ringX: 0, ringY: 0});
const WP = [[0, GUTTER_X, EV[0].spot[1] + 60]];
let [px, py, pt] = [GUTTER_X, EV[0].spot[1] + 60, 0];
EV.forEach((e, n) => {
const [x, y] = e.spot;
const travel = Math.min(0.7, 0.3 + Math.hypot(x - px, y - py) / 900);
const arrive = e.t - 0.1;
if (arrive - travel - pt > 1.4) {
const rest = [GUTTER_X, Math.max(170, Math.min(720, y + 40))];
WP.push([pt + 0.7, ...rest]);
WP.push([arrive - travel, ...rest]);
} else WP.push([Math.max(pt + 0.01, arrive - travel), px, py]);
WP.push([arrive, x, y], [e.t + 0.18, x, y]);
[px, py, pt] = [x, y, e.t + 0.18];
const next = EV[n + 1];
if (!next || next.t - 0.1 - 0.7 - pt > 0.8) {
[px, py, pt] = [GUTTER_X, y + 12, pt + 0.55];
WP.push([pt, px, py]);
}
});
WP.push([pt + 0.9, GUTTER_X, Math.min(720, py + 50)]);
return (t) => {
let i = 0;
while (i < WP.length - 2 && t > WP[i + 1][0]) i++;
const [t0, x0, y0] = WP[i];
const [t1, x1, y1] = WP[i + 1];
const k = ss(t0, t1, t);
const len = Math.hypot(x1 - x0, y1 - y0);
const bow = Math.sin(Math.PI * k) * Math.min(22, len * 0.07);
let press = false;
let ring = 0;
let rx = 0;
let ry = 0;
for (const e of EV) {
if (t >= e.t - 0.07 && t < e.t + 0.09) press = true;
if (t >= e.t && t < e.t + 0.55) {
ring = 1 - (t - e.t) / 0.55;
[rx, ry] = e.spot;
}
}
return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};
};
}