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
+4
View File
@@ -0,0 +1,4 @@
node_modules/
cutaway-out/
__pycache__/
*.pyc
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2026 Nyxera0x
Copyright (c) 2026 whaleyxbt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+69 -39
View File
@@ -1,46 +1,76 @@
# Cutaway # cutaway
A cutaway is a machine drawn with its shell opened, so you see the mechanism inside. This is the method for building one as a live 3D film from a single reference image: Claude Code writes every shell, gear and part as three.js code, checks the result against the picture, and films the object taking itself apart. It works for anything with a dense core: robotic animals, engines, drones, devices. A Claude Code skill that turns one picture into a 3D object that takes itself apart.
This repository holds the method, not the output: Give Claude an image of a robotic animal, a machine or a device. It rebuilds it in three.js, every shell, gear and fang written as code, checks the build against the picture line by line, and films it: a cursor presses a button, that part comes apart under its own camera, then the whole object explodes and snaps back together.
- the job description Claude reads before every animal; ![Theraphos TH-8 robotic tarantula](docs/tarantula.gif)
- the checklist format and a full example;
- every prompt, step by step;
- the corrections that made it work.
There is no code here and no renders. Claude writes the code on your machine from these files. | Serrasal PX-7 robotic piranha | Vespion VX-9 robotic wasp |
## What you need
- **Claude Code** on Opus.
- **An image model** (ChatGPT works) for the reference picture.
- **Node.js 20 or newer**, **ffmpeg** and **Python 3** for the video and the sound. Claude Code installs them if you ask.
## How it runs
1. **Generate the reference.** One picture sets the look and nothing else. See [PROMPTS.md](PROMPTS.md), step 1.
2. **Add the job description.** Copy [JOB_DESCRIPTION.md](JOB_DESCRIPTION.md) into your project and point Claude at it before every animal.
3. **Write a checklist for this picture.** 10 to 12 numbered lines on what this one image stands on. See [CHECKLIST.md](CHECKLIST.md).
4. **Run the still loop.** Claude renders a still, stacks it next to the reference and grades every line. It stops after round 2 and waits for you.
5. **Measure.** Dark-pixel share against the reference, and the proportions in numbers. Eyeballing lets a tidy diagram through.
6. **Save every correction** into the job description. [LESSONS.md](LESSONS.md) lists ours.
7. **Film it.** Port the approved film of the animal with the closest body 1:1 and change the body only. Every beat gets its own camera.
8. **Write the short version.** A 10-second version is its own script, never a montage of the long one.
9. **Render frame by frame** and score the sound on the same script.
## Files
| File | What it is |
|---|---| |---|---|
| [JOB_DESCRIPTION.md](JOB_DESCRIPTION.md) | The brief Claude reads before every animal: the look, the order of work, the camera, the film | | ![Serrasal PX-7 robotic piranha](docs/piranha.gif) | ![Vespion VX-9 robotic wasp](docs/wasp.gif) |
| [CHECKLIST.md](CHECKLIST.md) | How to write a checklist for one picture, a template and a full 12-line example |
| [PROMPTS.md](PROMPTS.md) | Every prompt, from the reference image to the sound |
| [LESSONS.md](LESSONS.md) | Each mistake, what it looked like, and the line it added to the job description |
## What it costs ## Install
- A still runs about 400,000 tokens over 3 rounds. ```
- A film runs another 150,000 to 400,000. npx skills add Nyxera0x/cutaway -g -a claude-code
- Run 2 animals at a time, not 4, and look at both after round 2. A note there still changes the outcome; after round 6 it only costs tokens. ```
- An animal whose body is unlike anything you have filmed costs about twice as much. Pick one close to an approved body, or know the price first.
Then, once, in the installed folder:
```
npm install && npx playwright install chromium
```
You need Node.js 20 or newer. For the video you also need `ffmpeg`, and for the sound Python 3.
## Use
Give Claude Code a picture and ask in plain words:
> Here is a robotic mantis. Build it as a 3D object I can take apart, and stop at the still so I can check it.
> Turn this image of a robot crab into a 20-second film where every part comes apart.
> I approved the still. Film it the way the piranha example is filmed.
No picture yet? `docs/PROMPTS.md` has the prompt that generated ours.
Or open one of the 3 examples first:
```
node sims/build.mjs tarantula-film # cutaway-out/dist/tarantula-film.html
node sims/build.mjs piranha-film
node sims/build.mjs wasp-film
```
## How it works
1. **One reference picture** sets the look. Claude reads it and rebuilds it; it never imports it.
2. **A checklist for that picture**: 10 to 12 numbered lines Claude grades yes, partial or no every round.
3. **Measured, not eyeballed**: the share of dark mechanism and the proportions, both against the picture.
4. **A still first.** Claude stops after round 2 and waits for your yes. Nothing gets filmed before it.
5. **The film** reuses the example with the closest body 1:1 and changes the body only. Every part gets its own camera.
6. **A 10-second version** gets its own script, its own opening and its own exit.
The whole method is in `docs/`, written so you can follow it with or without the code.
## What is inside
| | |
|---|---|
| `SKILL.md` | What Claude reads: the order of work, the rules that make it look right, the review loop. |
| `docs/JOB_DESCRIPTION.md` | The brief Claude reads before every object. Your corrections go into it. |
| `docs/CHECKLIST.md`, `docs/PROMPTS.md`, `docs/LESSONS.md` | The checklist format with a full example, every prompt, every mistake and the line it added. |
| `sims/tarantula-*`, `sims/piranha-*`, `sims/wasp-*` | 3 complete objects. `-shared` is the object, `-film` the full film, `-demo` the 10-second version. |
| `sims/green/` | The page around every object and the green look, plus 3 review tools: leftover-colour probe, camera track, part anchors. |
| `sims/kit/` | Runtime, stage, shader warm-up. |
| `sims/build.mjs` | Bundles an object into one HTML file, three.js and fonts inlined. |
| `sims/capture.mjs` | Renders the film frame by frame to a 60 fps mp4, or to review sheets of stills. |
| `sfx/`, `run_sfx.py` | Procedural sound on the film's timeline, mastered to −14 LUFS. |
## Credits
Built on [whaleyxbt/claude-motion](https://github.com/whaleyxbt/claude-motion) (MIT): the runtime, frame capture, sound engine and review rules come from there. Recorded samples are CC0 from Freesound, prepared by [Barty-Bart/motion-graphics](https://github.com/Barty-Bart/motion-graphics); sources in `sfx/samples/SOURCES.md`.
MIT licence.
+172
View File
@@ -0,0 +1,172 @@
---
name: cutaway
description: Build a robotic cutaway of any object or creature from one reference image - a three.js scene written entirely in code that takes itself apart on camera, a page with a button for every part, and a 60 fps film with a synced procedural score. Claude matches the build to the picture, grades it line by line, measures its density and proportions, and films it only after the user approves the still. Use when someone hands over a picture of a robotic animal, machine or device and wants it built in 3D, opened up part by part, or recorded; or asks for a "cutaway", an "exploded view", a "robot animal simulator" or "make this image a 3D model that comes apart".
---
# Cutaway
One picture in, one object out: built from code, opened part by part, filmed. The visitor sees the object move, a cursor presses a button, and that part comes apart under its own camera while live cards around it react. The same code records the film frame by frame, with a score built on the same timeline.
`SKILL_DIR` below is the folder this file lives in. Builds and renders go to `./cutaway-out` of the folder you run from.
## First run
```
cd "$SKILL_DIR" && npm install && npx playwright install chromium
```
The pages need nothing else. The video needs `ffmpeg` on PATH and the score needs Python 3 (standard library only). Set `FFMPEG`, `PYTHON` or `CHROMIUM` to point at other binaries.
## The 3 examples
Build one, open the HTML, watch it take itself apart. Start a new object from the example whose body is closest.
| | The object | Its parts | Worth stealing |
|---|---|---|---|
| `tarantula-*` | A robotic tarantula on 8 bristled legs, a glass abdomen full of lit coils. | Optics, a front leg coming apart on its servos, the abdomen cage opening, the head plates lifting; two jumps. | A walking body: an alternating tetrapod gait integrated from velocity keys, a jump with a crouch and a tuck. |
| `piranha-*` | A deep-bodied robotic piranha with 2 rows of glass fangs and a glass flank over drive gears. | The eye unscrewing in macro, the tail stalk telescoping, the glass flank opening from above, the jaw dropping from below. | One camera per beat aimed at its own part; a mirrored scene; a lunge at the lens. |
| `wasp-*` | A robotic wasp with frosted wings, a telescoping abdomen and a glass stinger. | Optics, a wing pulled out of its hinge and turned over, thorax gears, the abdomen telescoping. | A slow-motion explode as a warp of film time into scene time; a dive in from above and a climb out of the frame. |
Each comes in 3 folders: `<name>-shared/` holds the object, `<name>-film/` the full film (it also opens as a looping page), `<name>-demo/` a 10-second version with its own script.
```
node "$SKILL_DIR/sims/build.mjs" piranha-film # → cutaway-out/dist/piranha-film.html, offline, ~900 KB
node "$SKILL_DIR/sims/build.mjs" # all of them
```
## The method
The 4 files in `docs/` are the method. Read them before the first object, and keep `docs/JOB_DESCRIPTION.md` open the whole time.
| File | What it holds |
|---|---|
| `docs/JOB_DESCRIPTION.md` | The brief: the look, the order of work, the camera, the film, the short version. Every correction the user gives goes into it, one line per mistake. |
| `docs/CHECKLIST.md` | How to write 10 to 12 numbered lines on what one picture stands on, a template and a full example. |
| `docs/PROMPTS.md` | Every prompt, from the reference image to the sound. |
| `docs/LESSONS.md` | Every mistake so far and the line it added to the brief. |
The order, every time:
1. **The reference.** One picture. If the user has none, generate one with the prompt in `docs/PROMPTS.md`. It sets the look and nothing else: never import it, rebuild it.
2. **Measure the picture.** Body height, head length, jaw or limb length as shares of the body length. Dark-pixel share (luma under 80) in its bounding box.
3. **Write the checklist** for this picture before the first line of code.
4. **The still loop.** Build, render a still posed like the reference, stack reference | still | an approved still, plus the stack at 900 px wide, grade every line yes / partial / no against the picture. **Stop after round 2 and show the user.** Nothing gets filmed until they say yes.
5. **The film.** Port the example with the closest body 1:1: its tour, its beat times, its moves, distances scaled. Change the body only. Give every part its own camera.
6. **The short version.** Its own script, never pieces of the long film.
7. **Render and score.**
## How an object is built
One folder per object, split by job. The examples follow this exactly:
| File | Job |
|---|---|
| `spider.js` / `piranha.js` / `bee.js` | The body, built from code: shells, gears, pistons, hoses, lenses, membranes. Every part that comes apart is its own group with a named anchor; `pose(state)` sets the whole object for one moment. |
| `parts.js` | The shop: materials (gloss white shell, accent, graphite, black, steel, lens, glass) and shape helpers. `PAL` holds the colours. |
| `stage.js` | The studio: paper backdrop, lights, soft floor shadow, post. `frame(cam)` draws one frame. |
| `tour.js` / `tour_bee.js` / `tour_v2.js` | The film as functions of time: each act's clock, the flight or walk, the explode, every camera, the telemetry for the page. |
| `sim_green.js` | The wiring: state for t → pose, flight, camera, page. Applies the green look. |
| `../green/` | The page around every object (title, pill buttons the cursor presses, a section list, 4 cards, labels with leaders) and the green look (`look.js`). |
| `score.py` | The sound on the film's timeline. |
For an object outside `SKILL_DIR`, make a folder with a `main.js` and import the kit by name: `import {runSim} from 'cutaway-kit/runtime.js'`. Build it with `node "$SKILL_DIR/sims/build.mjs" ./my-object`.
## Rules that decide whether it works
1. **Start from the picture, never from imagination.** Asked for a robot animal with nothing to match, the model returns a generic toy. With a picture and a checklist it rebuilds what is in front of it.
2. **Port the closest approved film.** A new body on an existing choreography works; a new body on a new choreography is twice the rounds. Flag an object with no close body before starting.
3. **Measure, don't eyeball.** Features pass the checklist while the whole reads as a tidy white diagram. Dark share must reach 0.8 of the reference's; proportions must match within a few hundredths.
4. **One main set of limbs.** Legs, or wings, or tentacles. Two systems fighting for the same half second is noise.
5. **Dense core, plates with gaps.** Break white surfaces into separate curved plates in 3 sizes with gaps over the mechanism. A long smooth shell reads as a toy however many rounds it gets.
6. **Every beat its own camera.** Aim at the part itself, from its own side and height, and push in while it hangs open. Check with `sims/green/cam_track.mjs`: if az, el and distance barely move between beats, the film looks parked.
7. **Review after round 2, 2 objects at a time.** A note after round 2 changes the outcome; after round 6 it only costs tokens.
## The green look
`sims/green/look.js` turns any object green without touching its code: set `PAL.orange` and the paper before the build, then call `retint(root)` after the build and after every pose. It handles material colours, emissive glows, HDR glow colours above 1, colours a pose rewrites every frame, lights and vertex colours. `SHIFT` moves the subject into the page's 3D window. Before a render, run `node sims/green/probe_warm.mjs <entry> <t> <global>`: it lists any warm colour left.
## render(t) contract
```js
import {runSim} from '../kit/runtime.js';
const DEFAULTS = {duration: 20, fps: 60, hud: {enabled: false}, director: {enabled: false}};
runSim(DEFAULTS, async ({cfg, canvas, capture}) => {
// build the scene, precompute anything stateful
return {render(t) { /* draw frame t from scratch */ return {}; }, resize() {}};
});
```
- `render(t)` is pure: no `Math.random` (use `rng(seed)` from `kit/util.js` at setup), no `Date`, no state carried between frames. Capture calls it at arbitrary times.
- Anything integrated over time (a gait, the gears' busy clock, a speed ramp) is tabulated at load; `render` only reads the tables.
- Every beat goes into `<name>-film/timeline.json` in seconds. The score reads the same file.
- A short version may run its scene faster than the film: `{"duration": 11.3, "film": 10.0}` plays 11.3 s of scene in 10 s.
- Frame 0 is the thumbnail. It must already show the object big, front 3/4, moving.
## Commands
```
node "$SKILL_DIR/sims/build.mjs" piranha-film
node "$SKILL_DIR/sims/capture.mjs" piranha-film --size 1600x900 --dpr 1.2 --stills beats --cols 4 --out cutaway-out/piranha-beats.png
node "$SKILL_DIR/sims/capture.mjs" piranha-film --size 1600x900 --dpr 1.2 --still 9.4 --out cutaway-out/piranha-9.4.png
node "$SKILL_DIR/sims/capture.mjs" piranha-film --size 1600x900 --dpr 2.4 --out cutaway-out/piranha-4k.mp4
python "$SKILL_DIR/run_sfx.py" "$SKILL_DIR/sims/piranha-shared/score.py"
ffmpeg -y -i cutaway-out/piranha-4k.mp4 -i cutaway-out/piranha-score.wav -map 0:v -map 1:a -vf scale=1920:1080:flags=lanczos -c:v libx264 -crf 16 -pix_fmt yuv420p -c:a aac -b:a 256k -shortest -movflags +faststart cutaway-out/piranha.mp4
```
For a demo whose scene runs faster than its film, score the scene and stretch the sound by the same factor:
```
TL="$SKILL_DIR/sims/piranha-demo/timeline.json" OUT=cutaway-out/piranha-demo-scene.wav python "$SKILL_DIR/run_sfx.py" "$SKILL_DIR/sims/piranha-shared/score.py"
ffmpeg -y -i cutaway-out/piranha-demo-scene.wav -af atempo=1.12 cutaway-out/piranha-demo-score.wav
```
`--size` is the CSS layout and `--dpr` multiplies it: 1600 x 900 at 1.2 gives 1920 x 1080, at 2.4 gives 4K to bring down to 1080p (thin veins stay sharp). Capture prints the GPU it got; a software renderer means the GPU flags in `paths.mjs` did not take.
## Review loop
You cannot watch the video; you can look at frames. Never report an object as done without reading sheets of the current render.
1. `--stills beats`: one tile per timeline beat, 0.3 s after it, each labelled `t=`.
2. Read every tile against the checklist below.
3. Zoom in: `--stills every:0.2 --from A --to B` for a transition, `--still T` for one full frame.
4. `node sims/green/cam_track.mjs <entry> <global>` prints the camera every 0.5 s; `node sims/green/anchors_dump.mjs <entry> <global>` prints the parts' rest points to aim cameras at.
5. Fix, rebuild, go back to 1. Stop when a full pass finds nothing.
6. Final: `node "$SKILL_DIR/sheet.mjs" --video <final.mp4> --timeline <timeline.json>` and read that too.
Checklist:
- **The object.** Every part that comes apart goes back where it was; nothing passes through anything; the cards match the motion.
- **Composition.** The opening part fills the frame; the rest may run off. Labels never cover the part they name.
- **The look.** No warm colour left (`probe_warm.mjs`). Green only as lines and glows, never dots.
- **Camera.** A new side, height or distance at every beat. No beat parked.
- **Timing.** A part opens in about 1 s, holds, closes in 0.5 s; a new beat every 2 to 3 s.
## three.js traps the examples already hit
- A glow colour above 1 (an HDR `MeshBasicMaterial`) breaks `getHSL`: read and write it at unit peak.
- A colour the pose rewrites every frame comes back each frame: retint whatever changed since the last write.
- Colours baked into vertex attributes ignore the material: retint the `color` attribute too.
- `smoothstep(a, b, x)` with `a > b` returns 0 on Windows (ANGLE/D3D). Write `1.0 - smoothstep(b, a, x)`.
- One NaN pixel blacks out the whole frame through bloom. Clamp every `pow()` base in a shader.
## Sound
`sfx/` synthesises every sound in pure Python (48 kHz, reproducible) and reads the film's timeline, so sound cannot drift out of sync. `python "$SKILL_DIR/run_sfx.py" --list` shows the generators. `sfx/score_kit.py` has the bed and accents the 3 scores use: a chord bed with soft drums, a pad, airy whooshes, clicks and ticks.
- Every time comes from the timeline, never a typed number.
- Mastering is automatic: −14 LUFS, true peak ≤ −2 dBFS.
- Accent, never narrate: a quiet click per button, a short accent on every part that moves, continuous motion silent.
## Taste, with numbers
- Frame 0: the front 3/4 hero view, the object big and already moving.
- A beat every 2 to 3 s. Visible wing beats 1.5 to 2.5 Hz; faster only as a motion-blurred fan.
- Bristles and spikes 0.15 to 0.25 of the limb's thickness.
- The object fills 60-70% of the 3D window at rest; the opening part fills the frame.
- One accent colour, and it marks what is moving right now.
## Credits
The kit, frame capture, sfx engine and review rules come from [whaleyxbt/claude-motion](https://github.com/whaleyxbt/claude-motion) (MIT). The recorded samples are CC0 from Freesound, trimmed by [Barty-Bart/motion-graphics](https://github.com/Barty-Bart/motion-graphics) (MIT); sources in `sfx/samples/SOURCES.md`.
View File
View File
View File
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 MiB

+545
View File
@@ -0,0 +1,545 @@
{
"name": "cutaway",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cutaway",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"@fontsource-variable/inter": "5.3.0",
"@fontsource/jetbrains-mono": "5.3.0",
"esbuild": "0.28.1",
"playwright": "1.58.2",
"three": "0.186.1"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/jetbrains-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",
"integrity": "sha512-fqDfB5I9f1p1TV486aUgB9t8zP84P0O1FtQR5Ol9vjwPy+S+EIGlVYm1cvj2W5shcZMTg2nZFdVMoH5wFu8a1A==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/playwright": {
"version": "1.58.2",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz",
"integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==",
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.58.2"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.58.2",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",
"integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/three": {
"version": "0.186.1",
"resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",
"integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",
"license": "MIT"
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "cutaway",
"version": "1.0.0",
"private": true,
"description": "A Claude Code skill that builds a robotic cutaway of any object from one reference image: a 3D simulator that takes itself apart, recorded to 60 fps video.",
"license": "MIT",
"scripts": {
"setup": "npm install && npx playwright install chromium",
"build": "node sims/build.mjs"
},
"dependencies": {
"@fontsource-variable/inter": "5.3.0",
"@fontsource/jetbrains-mono": "5.3.0",
"esbuild": "0.28.1",
"playwright": "1.58.2",
"three": "0.186.1"
}
}
+30
View File
@@ -0,0 +1,30 @@
// Paths and browser flags for the kit. Everything resolves from this folder, so the skill runs wherever it is installed.
// Override any of them with an environment variable.
import {createRequire} from 'node:module';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
const ROOT = path.dirname(fileURLToPath(import.meta.url));
export const FFMPEG = process.env.FFMPEG || 'ffmpeg';
export const FFPROBE = process.env.FFPROBE || 'ffprobe';
export const PYTHON = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
// three, esbuild, fonts and playwright: `npm install` in this folder puts them here.
export const DEPS = process.env.CUTAWAY_DEPS || path.join(ROOT, 'node_modules');
// Unset: playwright uses the Chromium that `npx playwright install chromium` downloaded.
export const CHROMIUM = process.env.CHROMIUM || undefined;
// Real GPU WebGL instead of a software rasteriser. On Windows d3d11 plus --force_high_performance_gpu keeps ANGLE off
// an integrated GPU when a discrete one exists. capture.mjs prints the GPU it got on every run.
export const CHROMIUM_ARGS = [
...(process.platform === 'win32' ? ['--use-angle=d3d11'] : []),
'--force_high_performance_gpu', '--ignore-gpu-blocklist', '--enable-gpu-rasterization', '--enable-webgl', '--hide-scrollbars',
];
// Builds and renders land in ./cutaway-out of the folder you run from.
export const OUT = path.resolve(process.env.CUTAWAY_OUT || 'cutaway-out');
export const DIST = path.join(OUT, 'dist');
export const fromDeps = (id) => createRequire(path.join(DEPS, 'x.js'))(id);
export const playwright = () => fromDeps('playwright');
+10
View File
@@ -0,0 +1,10 @@
"""Render a cue sheet to a mastered WAV from any folder: python run_sfx.py <cues.py> | --list"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sfx.__main__ import main # noqa: E402
main()
+10
View File
@@ -0,0 +1,10 @@
"""Procedural sound design for motion graphics. Pure Python stdlib, 48 kHz stereo.
python run_sfx.py sfx/cues/effort.py render a cue sheet to WAV
python run_sfx.py --list list the sound generators
"""
from .mix import Mix
from .synth import SR
__all__ = ["Mix", "SR"]
+64
View File
@@ -0,0 +1,64 @@
"""CLI: render a cue sheet, or list the available generators."""
import argparse
import importlib.util
import inspect
import json
import os
import sys
from . import synth
from .mix import Mix
def list_generators():
for name, fn in inspect.getmembers(synth, inspect.isfunction):
if fn.__module__ != synth.__name__ or name.startswith("_"):
continue
doc = (fn.__doc__ or "").strip().splitlines()[0] if fn.__doc__ else ""
print(f"{name}{inspect.signature(fn)}\n {doc}")
def load_cues(path):
spec = importlib.util.spec_from_file_location("cues", path)
cues = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cues)
if not hasattr(cues, "score"):
sys.exit(f"{path} needs a score(mix, tl) function")
return cues
def main():
ap = argparse.ArgumentParser(prog="python run_sfx.py", description="Render a cue sheet to a mastered WAV.")
ap.add_argument("cues", nargs="?", help="cue sheet: a .py file with score(mix, tl)")
ap.add_argument("--timeline", help="timeline JSON (default: the cue sheet's TIMELINE, else timeline.json)")
ap.add_argument("--out", help="output WAV (default: the cue sheet's OUT, else cutaway-out/<cue>.wav, or $CUTAWAY_OUT)")
ap.add_argument("--list", action="store_true", help="list sound generators and exit")
args = ap.parse_args()
if args.list:
list_generators()
return
if not args.cues:
ap.error("pass a cue sheet, or --list")
cues = load_cues(args.cues)
# A relative TIMELINE in the cue sheet is read next to the cue sheet, so it runs from any folder.
timeline = args.timeline or os.path.join(os.path.dirname(os.path.abspath(args.cues)), getattr(cues, "TIMELINE", "timeline.json"))
stem = os.path.splitext(os.path.basename(args.cues))[0]
out = args.out or getattr(cues, "OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), f"{stem}.wav"))
with open(timeline, encoding="utf8") as f:
tl = json.load(f)
mix = Mix(tl["duration"], seed=getattr(cues, "SEED", 11))
cues.score(mix, tl)
stats = mix.master(target_lufs=getattr(cues, "TARGET_LUFS", -14.0))
mix.write(out)
print(
f"wrote {out}: {tl['duration']}s, {mix.count} sounds, "
f"{stats['lufs']:.1f} LUFS, true peak {stats['peak_db']:.1f} dBFS, drive {stats['drive']}"
)
if __name__ == "__main__":
main()
+453
View File
@@ -0,0 +1,453 @@
"""DSP building blocks (oscillators, filters, delays, reverb), pure Python stdlib at 48 kHz.
Used by sound scripts that need more than the one-shot generators in synth.py,
e.g. sims/engine/sound.py.
Signals are plain lists of floats. Speed comes from two tricks:
- A Python per-sample loop costs about 0.3 µs/sample and a list comprehension
about 0.05 µs. So constant-pitch oscillators are one comprehension (the naive
ramp) plus a sparse PolyBLEP fix-up at each wrap. Feedback delays and the
reverb combs/allpasses run one block at a time, where the block is no longer
than the delay, so every block depends only on earlier blocks and is a single
comprehension.
- Filters whose state really is sequential (SVF, biquad, ladder) are tight
loops, run only on short one-shots or on the few full-length buses that need
them.
"""
import math
from .synth import SR
TAU = 2.0 * math.pi
_tanh = math.tanh
# ---------------------------------------------------------------- buffers
def zeros(n):
return [0.0] * n
def add(dst, src, at=0, gain=1.0):
"""dst[at:] += gain * src, in place, clipped to dst."""
if at < 0:
src = src[-at:]
at = 0
end = min(len(dst), at + len(src))
if end <= at:
return
seg = dst[at:end]
if gain == 1.0:
dst[at:end] = [a + b for a, b in zip(seg, src)]
else:
dst[at:end] = [a + b * gain for a, b in zip(seg, src)]
def scaled(x, g):
return [v * g for v in x]
def mul(x, y):
return [a * b for a, b in zip(x, y)]
def summed(a, b):
return [p + q for p, q in zip(a, b)]
def rms(x):
return math.sqrt(sum(v * v for v in x) / len(x)) if x else 0.0
def peak(x):
return max(max(x), -min(x)) if x else 0.0
def pan_gains(pan):
"""Equal-power pan, -1 left .. +1 right."""
ang = (pan + 1.0) * math.pi / 4.0
return math.cos(ang), math.sin(ang)
def fade(x, fin=0, fout=0):
"""Linear fade in/out over fin/fout samples, in place."""
n = len(x)
fin, fout = min(fin, n), min(fout, n)
for i in range(fin):
x[i] *= i / fin
for i in range(fout):
x[n - 1 - i] *= i / fout
return x
# ------------------------------------------------------------ oscillators
def _blep(out, phase, dt, n, h=1.0):
"""Subtract the PolyBLEP residual at every wrap of the ramp phase + i*dt (downward jump 2h)."""
k = 1
while True:
j = math.ceil((k - phase) / dt)
# float guard: make j the first sample whose wrapped phase is small
if j < n and (phase + j * dt) % 1.0 > 0.5:
j += 1
if j >= 1 and (phase + (j - 1) * dt) % 1.0 < 0.5:
j -= 1
if j - 1 >= n:
break
if 0 <= j < n:
u = ((phase + j * dt) % 1.0) / dt
if u < 1.0:
out[j] -= h * (u + u - u * u - 1.0)
if 1 <= j <= n:
u = (((phase + (j - 1) * dt) % 1.0) - 1.0) / dt
if u > -1.0:
out[j - 1] -= h * (u * u + u + u + 1.0)
k += 1
def saw(freq, n, phase=0.0):
"""Band-limited sawtooth (PolyBLEP) at constant freq, -1..1."""
dt = freq / SR
phase %= 1.0
out = [2.0 * ((phase + i * dt) % 1.0) - 1.0 for i in range(n)]
if 0.0 < dt < 0.5:
_blep(out, phase, dt, n)
return out
def pulse(freq, n, width=0.5, phase=0.0):
"""Band-limited pulse as the difference of two PolyBLEP saws; zero mean."""
a = saw(freq, n, phase)
b = saw(freq, n, phase + width)
return [p - q for p, q in zip(a, b)]
def sine(freq, n, phase=0.0):
w = TAU * freq / SR
ph = TAU * phase
sin = math.sin
return [sin(ph + w * i) for i in range(n)]
def noise(rng, n):
r = rng.random
return [2.0 * r() - 1.0 for _ in range(n)]
# ---------------------------------------------------------------- filters
def _norm(b0, b1, b2, a0, a1, a2):
return (b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0)
def lp(fc, q=0.7071):
w = TAU * min(fc, 0.45 * SR) / SR
c, al = math.cos(w), math.sin(w) / (2 * q)
return _norm((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + al, -2 * c, 1 - al)
def hp(fc, q=0.7071):
w = TAU * min(fc, 0.45 * SR) / SR
c, al = math.cos(w), math.sin(w) / (2 * q)
return _norm((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + al, -2 * c, 1 - al)
def bp(fc, q=1.0):
w = TAU * min(fc, 0.45 * SR) / SR
c, al = math.cos(w), math.sin(w) / (2 * q)
return _norm(al, 0.0, -al, 1 + al, -2 * c, 1 - al)
def peaking(fc, q, db):
a = 10 ** (db / 40)
w = TAU * min(fc, 0.45 * SR) / SR
c, al = math.cos(w), math.sin(w) / (2 * q)
return _norm(1 + al * a, -2 * c, 1 - al * a, 1 + al / a, -2 * c, 1 - al / a)
def shelf(fc, db, high=True):
a = 10 ** (db / 40)
w = TAU * min(fc, 0.45 * SR) / SR
c, s = math.cos(w), math.sin(w)
al = s / 2 * math.sqrt(2)
sa = 2 * math.sqrt(a) * al
if high:
return _norm(
a * ((a + 1) + (a - 1) * c + sa), -2 * a * ((a - 1) + (a + 1) * c), a * ((a + 1) + (a - 1) * c - sa),
(a + 1) - (a - 1) * c + sa, 2 * ((a - 1) - (a + 1) * c), (a + 1) - (a - 1) * c - sa,
)
return _norm(
a * ((a + 1) - (a - 1) * c + sa), 2 * a * ((a - 1) - (a + 1) * c), a * ((a + 1) - (a - 1) * c - sa),
(a + 1) + (a - 1) * c + sa, -2 * ((a - 1) + (a + 1) * c), (a + 1) + (a - 1) * c - sa,
)
def biquad(x, c):
"""Static biquad (transposed direct form II); c from lp/hp/bp/peaking/shelf."""
b0, b1, b2, a1, a2 = c
z1 = z2 = 0.0
out = [0.0] * len(x)
i = 0
for v in x:
y = b0 * v + z1
z1 = b1 * v - a1 * y + z2
z2 = b2 * v - a2 * y
out[i] = y
i += 1
return out
def svf(x, fc, q=0.7071, mode="lp", ctrl=32):
"""Zero-delay-feedback state-variable filter (Cytomic/Simper), stable under fast modulation.
fc: Hz, or a function of the sample index evaluated every `ctrl` samples.
mode: 'lp', 'bp' or 'hp'.
"""
n = len(x)
out = [0.0] * n
k = 1.0 / q
ic1 = ic2 = 0.0
const = not callable(fc)
if const:
ctrl = max(n, 1)
tan = math.tan
pis = math.pi / SR
for s in range(0, n, ctrl):
f = fc if const else fc(s)
f = 10.0 if f < 10.0 else 20000.0 if f > 20000.0 else f
g = tan(pis * f)
a1 = 1.0 / (1.0 + g * (g + k))
a2 = g * a1
a3 = g * a2
e = s + ctrl if s + ctrl < n else n
if mode == "lp":
for i in range(s, e):
v3 = x[i] - ic2
v1 = a1 * ic1 + a2 * v3
v2 = ic2 + a2 * ic1 + a3 * v3
ic1 = v1 + v1 - ic1
ic2 = v2 + v2 - ic2
out[i] = v2
elif mode == "bp":
for i in range(s, e):
v3 = x[i] - ic2
v1 = a1 * ic1 + a2 * v3
v2 = ic2 + a2 * ic1 + a3 * v3
ic1 = v1 + v1 - ic1
ic2 = v2 + v2 - ic2
out[i] = v1
else:
for i in range(s, e):
xi = x[i]
v3 = xi - ic2
v1 = a1 * ic1 + a2 * v3
v2 = ic2 + a2 * ic1 + a3 * v3
ic1 = v1 + v1 - ic1
ic2 = v2 + v2 - ic2
out[i] = xi - k * v1 - v2
return out
def onepole_hp(x, fc):
"""Gentle 6 dB/oct high-pass; used as a DC blocker."""
a = math.exp(-TAU * fc / SR)
out = [0.0] * len(x)
px = py = 0.0
i = 0
for v in x:
py = a * (py + v - px)
px = v
out[i] = py
i += 1
return out
def sweep(x, start, end, f0, f1, mode="lp", q=0.9, wet_in=0.0, wet_out=0.0):
"""Filter x[start:end] in place, cutoff gliding exponentially f0 -> f1.
wet_in / wet_out (fractions of the region) crossfade from / back to the
dry signal, so the region's edges are seamless.
"""
start, end = max(0, start), min(len(x), end)
n = end - start
if n <= 0:
return
seg = x[start:end]
r = f1 / f0
y = svf(seg, lambda i: f0 * r ** (i / n), q, mode, 32)
a = max(1, int(wet_in * n))
b = max(1, int(wet_out * n))
out = []
for i in range(n):
w = 1.0
if wet_in and i < a:
w = i / a
if wet_out and i > n - b:
w = min(w, (n - i) / b)
out.append(seg[i] + (y[i] - seg[i]) * w)
x[start:end] = out
# ------------------------------------------------------- delay and reverb
_COMBS = (1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617)
_ALLPASSES = (556, 441, 341, 225)
def _comb(x, m, fb, damp):
"""Freeverb comb, block-vectorized; the in-loop damping is a 2-tap low-pass."""
n = len(x)
a = fb * (1.0 - damp)
b = fb * damp
w = [0.0] * (n + m + 1) # w[i + m + 1] = W(i)
for s in range(0, n, m):
e = min(s + m, n)
w[s + m + 1:e + m + 1] = [xi + a * p + b * q for xi, p, q in zip(x[s:e], w[s + 1:e + 1], w[s:e])]
return w[1:n + 1]
def _allpass(x, m, g=0.5):
n = len(x)
v = [0.0] * (n + m) # v[i + m] = V(i)
for s in range(0, n, m):
e = min(s + m, n)
v[s + m:e + m] = [xi + g * p for xi, p in zip(x[s:e], v[s:e])]
return [p - xi for xi, p in zip(x, v)]
def reverb(x, size=0.7, damp=0.45, scale=1.0, spread=23):
"""Freeverb (8 combs + 4 allpasses per side): mono in, (left, right) wet out.
size 0..1 maps to comb feedback 0.7..0.98; scale stretches every delay
(0.3 = small room, 1.5 = hall). Output is roughly level-matched to input.
"""
fb = 0.7 + 0.28 * size
r = SR / 44100 * scale
outs = []
for off in (0, spread):
acc = None
for m in _COMBS:
c = _comb(x, max(8, int((m + off) * r)), fb, damp)
acc = c if acc is None else [p + q for p, q in zip(acc, c)]
for m in _ALLPASSES:
acc = _allpass(acc, max(8, int((m + off) * r)))
outs.append(acc)
g = math.sqrt((1 - fb * fb) / 8.0) * 1.4
return [v * g for v in outs[0]], [v * g for v in outs[1]]
def pingpong(x, d, fb=0.5, damp=0.35):
"""Ping-pong delay, mono in -> (left, right) wet; first echo left at d samples, then alternating."""
n = len(x)
xp = [0.0] * d + x
a = [0.0] * (n + d + 1) # a[i + d + 1] = A(i)
b = [0.0] * (n + d + 1)
c0 = fb * (1.0 - damp)
c1 = fb * damp
for s in range(0, n, d):
e = min(s + d, n)
av = [xi + c0 * p + c1 * q for xi, p, q in zip(xp[s:e], b[s + 1:e + 1], b[s:e])]
bv = [c0 * p + c1 * q for p, q in zip(a[s + 1:e + 1], a[s:e])]
a[s + d + 1:e + d + 1] = av
b[s + d + 1:e + d + 1] = bv
return a[d + 1:], b[d + 1:]
# --------------------------------------------------------------- dynamics
def softclip(x, drive=1.5):
norm = 1.0 / _tanh(drive)
return [_tanh(drive * v) * norm for v in x]
def compress(left, right, thresh_db=-12.0, ratio=2.0, attack=0.01, release=0.15, knee_db=6.0, block=64):
"""Stereo-linked RMS bus compressor at control rate (one gain per block, interpolated)."""
n = len(left)
pw = [a * a + b * b for a, b in zip(left, right)]
ca = math.exp(-block / (attack * SR))
cr = math.exp(-block / (release * SR))
slope = 1.0 / ratio - 1.0
half = knee_db / 2
gr = 0.0
gains = []
# warm the detector on the first second so the start isn't uncompressed
for warm in (True, False):
for s in range(0, n if not warm else min(n, SR), block):
p = sum(pw[s:s + block]) / (2 * block)
db = 10 * math.log10(p + 1e-12)
over = db - thresh_db
if over <= -half:
want = 0.0
elif over < half:
want = slope * (over + half) ** 2 / (2 * knee_db)
else:
want = slope * over
c = ca if want < gr else cr
gr = c * gr + (1 - c) * want
if not warm:
gains.append(10 ** (gr / 20))
ramp = [k / block for k in range(block)]
g = []
prev = gains[0]
for cur in gains:
d = cur - prev
g.extend([prev + d * r for r in ramp])
prev = cur
return [a * b for a, b in zip(left, g)], [a * b for a, b in zip(right, g)]
def mono_below(left, right, fc=120.0):
"""Collapse the side signal below fc (24 dB/oct), so the low end is mono."""
mid = [(a + b) * 0.5 for a, b in zip(left, right)]
side = [(a - b) * 0.5 for a, b in zip(left, right)]
c = hp(fc)
side = biquad(biquad(side, c), c)
return [m + s for m, s in zip(mid, side)], [m - s for m, s in zip(mid, side)]
# --------------------------------------------------------- glitch effects
def crush(x, bits=8, hold=2):
"""Bit and sample-rate reduction (intentionally aliasing)."""
q = float(2 ** (bits - 1))
return [round(x[i - i % hold] * q) / q for i in range(len(x))]
def stutter(x, start, slice_n, repeats, decay=0.9, edge=48):
"""Beat-repeat in place: x[start:start+slice_n] repeated `repeats` times."""
sl = x[start:start + slice_n]
if len(sl) < slice_n:
return
sl = fade(sl[:], edge, edge)
for r in range(repeats):
a = start + r * slice_n
if a + slice_n > len(x):
break
x[a:a + slice_n] = [v * decay ** r for v in sl]
def tapestop(x, start, n, curve=1.6):
"""Tape stop in place over x[start:start+n]: playback slows to zero."""
seg = x[start:start + n]
n = len(seg)
if n < 2:
return
out = []
pos = 0.0
for i in range(n):
j = int(pos)
if j + 1 >= n:
out.append(0.0)
else:
f = pos - j
out.append(seg[j] + (seg[j + 1] - seg[j]) * f)
pos += (1 - i / n) ** curve
fade(out, 0, min(n, 480))
x[start:start + n] = out
+72
View File
@@ -0,0 +1,72 @@
"""Integrated loudness (ITU-R BS.1770-4, EBU R128 gating) for 48 kHz stereo."""
import math
# K-weighting at 48 kHz: high shelf, then high-pass (coefficients from BS.1770).
_SHELF = ((1.53512485958697, -2.69169618940638, 1.19839281085285), (-1.69065929318241, 0.73248077421585))
_HIGHPASS = ((1.0, -2.0, 1.0), (-1.99004745483398, 0.99007225036621))
def _biquad(x, coeffs):
(b0, b1, b2), (a1, a2) = coeffs
y = [0.0] * len(x)
x1 = x2 = y1 = y2 = 0.0
for i, xi in enumerate(x):
yi = b0 * xi + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2
x2, x1, y2, y1 = x1, xi, y1, yi
y[i] = yi
return y
def _kernels(taps=8):
out = []
for frac in (0.25, 0.5, 0.75):
k = []
for j in range(-taps + 1, taps + 1):
d = j - frac
k.append((j, math.sin(math.pi * d) / (math.pi * d) * 0.5 * (1 + math.cos(math.pi * d / taps))))
out.append(k)
return out
_TP_KERNELS = _kernels()
def true_peak(x, near=0.7):
"""Linear true peak: 4x windowed-sinc interpolation around samples above near × sample peak."""
peak = max(map(abs, x)) or 0.0
lim = near * peak
tp = peak
for i in range(8, len(x) - 8):
if abs(x[i]) < lim and abs(x[i + 1]) < lim:
continue
for kernel in _TP_KERNELS:
v = abs(sum(c * x[i + j] for j, c in kernel))
if v > tp:
tp = v
return tp
def integrated_lufs(left, right, sr=48000):
"""Integrated loudness in LUFS; -inf for silence."""
if sr != 48000:
raise ValueError("K-weighting coefficients here are for 48 kHz")
kl = _biquad(_biquad(left, _SHELF), _HIGHPASS)
kr = _biquad(_biquad(right, _SHELF), _HIGHPASS)
cs = [0.0]
acc = 0.0
for a, b in zip(kl, kr):
acc += a * a + b * b
cs.append(acc)
block, hop = int(0.4 * sr), int(0.1 * sr)
z = [(cs[i + block] - cs[i]) / block for i in range(0, len(kl) - block + 1, hop)]
lufs = lambda power: -0.691 + 10 * math.log10(power)
above_abs = [p for p in z if p > 0 and lufs(p) > -70]
if not above_abs:
return float("-inf")
relative = lufs(sum(above_abs) / len(above_abs)) - 10
gated = [p for p in above_abs if lufs(p) > relative]
return lufs(sum(gated) / len(gated))
+111
View File
@@ -0,0 +1,111 @@
"""Mixer: place sounds in time, master to a loudness target, write a WAV."""
import math
import os
import random
import struct
import wave
from .loudness import integrated_lufs, true_peak
from .synth import SR, key
DRIVES = (1.2, 1.5, 1.8, 2.0, 2.2, 2.5, 3.0, 4.0)
class Mix:
def __init__(self, duration, seed=11):
random.seed(seed)
self.duration = duration
self.n = int(SR * duration)
self.left = [0.0] * self.n
self.right = [0.0] * self.n
self.count = 0
self._out = None
def put(self, t, samples, gain=1.0, pan=0.0):
"""Place mono samples at t seconds. pan: -1 left, 0 centre, +1 right (equal power)."""
ang = (pan + 1) * math.pi / 4
gl, gr = gain * math.cos(ang), gain * math.sin(ang)
i0 = int(t * SR)
for k, s in enumerate(samples):
i = i0 + k
if 0 <= i < self.n:
self.left[i] += s * gl
self.right[i] += s * gr
self.count += 1
def put_stereo(self, t, left, right, gain=1.0):
"""Place a stereo pair (e.g. from synth.pad) at t seconds."""
i0 = int(t * SR)
for k, (a, b) in enumerate(zip(left, right)):
i = i0 + k
if 0 <= i < self.n:
self.left[i] += a * gain
self.right[i] += b * gain
self.count += 1
def typing(self, start, end, chars, gain=(0.16, 0.26), jitter=0.006, spread=0.3):
"""One keystroke per character, evenly spaced from start to end, humanized."""
for k in range(chars):
tk = start + (end - start) * k / chars
self.put(tk + random.uniform(-jitter, jitter), key(), random.uniform(*gain), random.uniform(-spread, spread))
def master(self, target_lufs=-14.0, ceiling_db=-2.0, fade_out=0.25):
"""Soft-clip and set gain so the mix hits target_lufs with true peak <= ceiling_db.
Drive only rises when the ceiling would otherwise be crossed. The ceiling
leaves room for AAC overshoot, so the muxed MP4 stays under -1 dBTP. If no
drive reaches the target within the ceiling, the mix comes out quieter
rather than crushed.
"""
peak = max(max(map(abs, self.left)), max(map(abs, self.right))) or 1.0
fade_n = int(fade_out * SR)
fade = [1.0 if i < self.n - fade_n else (self.n - i) / fade_n for i in range(self.n)]
ceiling = 10 ** (ceiling_db / 20)
best = None
for drive in DRIVES:
norm = math.tanh(drive)
left = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.left, fade)]
right = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.right, fade)]
gain = 10 ** ((target_lufs - integrated_lufs(left, right)) / 20)
if gain > ceiling:
continue
tp = max(true_peak(left), true_peak(right))
fit = min(gain, ceiling / tp)
if best is None or fit / gain > best[0]:
best = (fit / gain, drive, left, right, fit, tp)
if gain * tp <= ceiling:
break
if best is None:
drive = DRIVES[0]
norm = math.tanh(drive)
left = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.left, fade)]
right = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.right, fade)]
tp = max(true_peak(left), true_peak(right))
best = (0, drive, left, right, ceiling / tp, tp)
_, drive, left, right, gain, tp = best
self._out = ([x * gain for x in left], [x * gain for x in right])
lufs = integrated_lufs(*self._out)
if lufs < target_lufs - 0.5:
print(
f"warning: {lufs:.1f} LUFS, short of {target_lufs}: the mix is too sparse to get louder "
"without clipping. Add sustained sound (a pad, longer tails) or accept it quieter."
)
return {"lufs": lufs, "peak_db": 20 * math.log10(gain * tp), "drive": drive}
def write(self, path):
"""Write 16-bit stereo WAV; masters with defaults first if master() wasn't called."""
if self._out is None:
self.master()
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
left, right = self._out
with wave.open(path, "wb") as wf:
wf.setnchannels(2)
wf.setsampwidth(2)
wf.setframerate(SR)
frames = bytearray()
for a, b in zip(left, right):
frames += struct.pack("<hh", int(a * 32767), int(b * 32767))
wf.writeframes(bytes(frames))
+23
View File
@@ -0,0 +1,23 @@
# Recorded samples
Real recordings for what synthesis does badly: keyboards, room tone, a mouth pop, a tape eject.
All 12 are CC0 1.0. Each Freesound page was checked for the CC0 licence on 2026-10-18.
Taken from the `sound-effects` skill of github.com/Barty-Bart/motion-graphics (MIT), which had already trimmed them, normalised them (one-shots to -3 dBFS peak, ambience to -35 LUFS) and encoded them as OGG.
Load one in a cue sheet with `sample("<file>")` from `sfx.synth`.
| File | Use | Author | Source |
|---|---|---|---|
| fs-447909-keyboard-typing.ogg | keyboard, 3.8 s | Breviceps | https://freesound.org/people/Breviceps/sounds/447909/ |
| fs-323432-typing.ogg | keyboard, 4 s | Alivvie | https://freesound.org/people/Alivvie/sounds/323432/ |
| fs-79388-keyboard-typing-wav.ogg | keyboard, 4 s | j1987 | https://freesound.org/people/j1987/sounds/79388/ |
| fs-416777-digital-typing-wav.ogg | digital typing, 1 s | Sky_Motion | https://freesound.org/people/Sky_Motion/sounds/416777/ |
| fs-329533-room-tone-in-an-apartment-livi.ogg | room tone, 17 s | leonelmail | https://freesound.org/people/leonelmail/sounds/329533/ |
| fs-426767-apartment-room-tone-wav.ogg | room tone, 20 s | cMilan | https://freesound.org/people/cMilan/sounds/426767/ |
| fs-329569-roomtone-bedroom-yew.ogg | room tone, 20 s | leonelmail | https://freesound.org/people/leonelmail/sounds/329569/ |
| fs-258269-mouth-pop.ogg | mouth pop | jcallison | https://freesound.org/people/jcallison/sounds/258269/ |
| fs-447910-plop.ogg | plop | Breviceps | https://freesound.org/people/Breviceps/sounds/447910/ |
| fs-824189-pop-in-sfx.ogg | pop-in | Sadiquecat | https://freesound.org/people/Sadiquecat/sounds/824189/ |
| fs-349504-triangle-open-04.ogg | triangle ding, 4 s | cabled_mess | https://freesound.org/people/cabled_mess/sounds/349504/ |
| fs-339521-vhs-rewind-forward-and-eject.ogg | VHS rewind and eject, 4 s | lucaslima | https://freesound.org/people/lucaslima/sounds/339521/ |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+206
View File
@@ -0,0 +1,206 @@
"""Shared pieces for the figure scores: a parameterised lo-fi bed and a handful of accents.
A figure's score.py imports this (it sits next to the sfx engine on sys.path when run through
run_sfx.py) and adds its own accents on the tour's seconds.
"""
import math
import os
import random
from sfx.dsp import add, reverb, svf, zeros
from sfx.synth import SR, bandnoise, bass, blip, epiano, hat, kick, snare
def env_fade(x, fin, fout):
n = len(x)
a = max(1, int(fin * SR))
b = max(1, int(fout * SR))
for i in range(min(a, n)):
x[i] *= i / a
for i in range(min(b, n)):
x[n - 1 - i] *= i / b
return x
def bed(dur, bpm, chords, motif=(), motif_voice="epiano", bass_pattern=((0, 1.15, 0.9), (2.5, 0.85, 0.6)),
kicks=(0, 2.75), snares=(1, 3), hats=8, swing=0.12, drums_from=1, keys_lp=4200, crackle_level=0.0, keys_vel=0.9):
"""A looping bed: e-piano chords (one per bar), a bass line, soft drums and an optional motif every other bar.
chords: [([note Hz, ...], root Hz), ...]. bass_pattern: (beat, length in beats, velocity). Returns stereo keys
plus mono bass and drum stems, all faded in and out.
"""
if os.environ.get("FIG_VARIANT"):
# the second-upload variant: three semitones up, a touch faster, the other motif voice
up = 2 ** (3 / 12)
chords = [([f * up for f in notes], root * up) for notes, root in chords]
motif = [(bt, f * up) for bt, f in motif]
motif_voice = "blip" if motif_voice == "epiano" else "epiano"
bpm *= 1.06
beat = 60 / bpm
bar = 4 * beat
n = int(dur * SR)
keys, low, drums = zeros(n), zeros(n), zeros(n)
bars = int(dur / bar) + 1
for b in range(bars):
t = 0.12 + b * bar
notes, root = chords[b % len(chords)]
for i, f in enumerate(notes):
add(keys, epiano(f, 2.9 * 84 / bpm + 0.4, keys_vel), int((t + 0.012 * i) * SR))
if i >= 2:
add(keys, epiano(f, 1.3, keys_vel * 0.5), int((t + 1.5 * beat + 0.01 * i) * SR))
if b % 2 == 1:
for bt, f in motif:
v = epiano(f, 1.1, 0.34, 0.6) if motif_voice == "epiano" else blip(f, 0.32, 0.11)
add(keys, v, int((t + bt * beat) * SR), 1.0 if motif_voice == "epiano" else 0.5)
for bt, length, vel in bass_pattern:
add(low, bass(root, length * beat, vel), int((t + bt * beat) * SR))
if drums_from <= b < bars - 2:
for bt in kicks:
add(drums, kick(1.0 if bt == 0 else 0.75), int((t + bt * beat) * SR))
for bt in snares:
add(drums, snare(0.55), int((t + bt * beat) * SR))
for e in range(hats):
sw = swing * beat if (hats == 8 and e % 2) else 0.0
add(drums, hat(0.5 if e % 2 == 0 else 0.32), int((t + e * 4 * beat / hats + sw) * SR))
keys = svf(keys, keys_lp, 0.6, "lp")
wl, wr = reverb(keys, size=0.6, damp=0.5, scale=0.9)
left = [k * 0.8 + w * 0.36 for k, w in zip(keys, wl)]
right = [k * 0.8 + w * 0.36 for k, w in zip(keys, wr)]
low = svf(low, 900, 0.7, "lp")
drums = svf(drums, 7000, 0.6, "lp")
for buf in (left, right, low, drums):
env_fade(buf, 1.0, 2.2)
return left, right, low, drums
def thud(f=95, decay=0.12, dur=0.4):
"""A soft body hitting something: a plush toy landing, a knock."""
n = int(dur * SR)
return [math.sin(2 * math.pi * f * k / SR) * math.exp(-k / (decay * SR)) * min(1, k / 40) for k in range(n)]
def motor(dur, f0=220, grit_hz=1400, wobble=17):
"""A small electric motor: a buzzy tone plus brush noise, faded at both ends."""
n = int(dur * SR)
grit = bandnoise(n, lambda k: grit_hz, q=0.8)
out = []
for k in range(n):
t = k / SR
m = 1 + 0.15 * math.sin(2 * math.pi * wobble * t)
s = sum(math.sin(2 * math.pi * f0 * h * t) / h for h in (1, 2, 3, 4))
out.append(m * (0.35 * s + 0.5 * grit[k]))
return env_fade(out, 0.06, 0.1)
def airy(dur, f0, f1, level=1.0):
"""Moving air: band noise sweeping from f0 to f1 with a soft swell."""
n = int(dur * SR)
x = bandnoise(n, lambda k: f0 * (f1 / f0) ** (k / n), q=0.7)
return [x[k] * level * 1.4 * math.sin(math.pi * k / n) for k in range(n)]
def bang(level=1.0, seed=0):
"""A small explosion: a low punch and a burst of dark noise."""
rnd = random.Random(seed)
n = int(0.42 * SR)
noise = bandnoise(n, lambda k: 700 + 1600 * math.exp(-k / (0.03 * SR)), q=0.5)
out = []
ph = 0.0
for k in range(n):
t = k / SR
f = 48 + 90 * math.exp(-t / 0.03)
ph += 2 * math.pi * f / SR
s = math.sin(ph) * math.exp(-t / 0.12) * 1.1 + noise[k] * 1.8 * math.exp(-t / 0.05)
out.append(level * math.tanh(1.5 * s) * (0.92 + 0.08 * rnd.random()))
return out
def puff(level=1.0):
"""A breath of gas out of a pipe."""
n = int(0.3 * SR)
x = bandnoise(n, lambda k: 900, q=0.6)
return [level * x[k] * 1.6 * math.sin(math.pi * min(1, k / (0.06 * SR)) / 2) * math.exp(-k / (0.09 * SR)) for k in range(n)]
def rumble(dur, f_at, level=1.0):
"""An engine's low hum whose pitch follows f_at(t)."""
n = int(dur * SR)
out = []
ph = 0.0
for k in range(n):
f = f_at(k / SR)
ph += 2 * math.pi * f / SR
out.append(level * (math.sin(ph) + 0.4 * math.sin(2 * ph) + 0.2 * math.sin(3 * ph)))
return env_fade(out, 0.3, 0.4)
_SEMI = {"C": -9, "D": -7, "E": -5, "F": -4, "G": -2, "A": 0, "B": 2}
def hz(name):
"""Note name to frequency: "A4" = 440, "F#3", "Bb2"."""
base, rest = name[0], name[1:]
shift = 0
while rest and rest[0] in "#b":
shift += 1 if rest[0] == "#" else -1
rest = rest[1:]
return 440.0 * 2 ** ((_SEMI[base] + shift + 12 * (int(rest) - 4)) / 12)
def chords(*specs):
"""chords("Fmaj7:F3 A3 C4 E4/F2", ...) -> bed() chord list; the part after / is the bass root."""
out = []
for spec in specs:
notes, root = spec.split(":", 1)[1].split("/")
out.append(([hz(n) for n in notes.split()], hz(root.strip())))
return out
def beep(freq, dur=0.12, level=1.0):
"""A clean electronic beep: a keypad, a timer, a piezo horn."""
n = int(dur * SR)
a = max(1, int(0.004 * SR))
return [level * math.sin(2 * math.pi * freq * k / SR) * min(1, k / a, (n - k) / a) for k in range(n)]
def rattle(dur, rate=18.0, f=3200, seed=0, level=1.0):
"""Many small hard things settling: coins in a box, shavings, capsules."""
rnd = random.Random(seed)
n = int(dur * SR)
out = zeros(n)
t = 0.0
while t < dur:
k = int(t * SR)
tick = [math.sin(2 * math.pi * f * (0.7 + 0.6 * rnd.random()) * j / SR) * math.exp(-j / (0.004 * SR)) for j in range(int(0.03 * SR))]
add(out, tick, k, level * (0.4 + 0.6 * rnd.random()) * math.sin(math.pi * min(1.0, t / dur)))
t += rnd.expovariate(rate)
return out
def hiss(dur, fc=5200, level=1.0):
"""Steam or air escaping: bright band noise with a soft swell."""
n = int(dur * SR)
x = bandnoise(n, lambda k: fc, q=0.5)
return [x[k] * level * 1.3 * min(1, k / (0.15 * SR), (n - k) / (0.25 * SR)) for k in range(n)]
def spans(tl, field, pred):
"""Intervals (t0, t1) in seconds where pred(sampled value of field) holds, from a timeline made with --sample."""
i = tl["fields"].index(field)
rate, out, start = tl["rate"], [], None
for k, row in enumerate(tl["samples"]):
on = bool(pred(row[i]))
if on and start is None:
start = k / rate
elif not on and start is not None:
out.append((start, k / rate))
start = None
if start is not None:
out.append((start, len(tl["samples"]) / rate))
return out
def rising(tl, field, pred):
"""Moments where pred(sampled value) turns true."""
return [a for a, _ in spans(tl, field, pred)]
+294
View File
@@ -0,0 +1,294 @@
"""Sound generators.
Every generator returns mono samples (a list of floats, roughly -1..1) at SR.
The first line of each docstring says what it's for; `python run_sfx.py --list`
prints them. To add a sound, write a function here in the same shape.
Use the module-level `random` for noise so renders stay reproducible.
"""
import array
import bisect
import math
import os
import random
import subprocess
SR = 48000
FFMPEG = r"C:\Users\user_\.claude\bin\ffmpeg.exe"
SAMPLES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "samples")
def sample(name, start=0.0, dur=None):
"""Recorded sound from sfx/samples (or any path): keyboards, room tone. start/dur trim it in seconds."""
path = name if os.path.isabs(name) else os.path.join(SAMPLES, name)
cmd = [FFMPEG, "-v", "error", "-ss", str(start), "-i", path]
if dur is not None:
cmd += ["-t", str(dur)]
cmd += ["-ac", "1", "-ar", str(SR), "-f", "s16le", "-"]
raw = subprocess.run(cmd, check=True, capture_output=True).stdout
pcm = array.array("h")
pcm.frombytes(raw[: len(raw) // 2 * 2])
return [x / 32768 for x in pcm]
def bandnoise(n, fc_at, q=0.8):
"""Building block: white noise through a band-pass, fc_at(k) is the cutoff in Hz at sample k."""
low = band = 0.0
out = []
for k in range(n):
f = 2 * math.sin(math.pi * min(fc_at(k), SR / 6) / SR)
x = random.uniform(-1, 1)
low += f * band
high = x - low - q * band
band += f * high
out.append(band)
return out
def click(freq=1800, dur=0.05):
"""UI click: a control snapping to a step, a toggle, a tick. Higher freq sounds smaller."""
n = int(dur * SR)
out = []
for k in range(n):
tt = k / SR
s = math.sin(2 * math.pi * freq * tt) * math.exp(-tt / 0.012)
s += random.uniform(-1, 1) * math.exp(-tt / 0.0015) * 0.6
out.append(s)
return out
def key():
"""One keystroke; every call is slightly different. For typing use Mix.typing()."""
n = int(0.018 * SR)
fc = random.uniform(2400, 4200)
noise = bandnoise(n, lambda k: fc, q=0.5)
thock = random.uniform(160, 220)
return [
noise[k] * math.exp(-k / (0.0025 * SR)) * 2.2
+ math.sin(2 * math.pi * thock * k / SR) * math.exp(-k / (0.006 * SR)) * 0.5
for k in range(n)
]
def blip(freq, dur=0.35, tau=0.12):
"""Soft tonal blip: a word or element landing, one note of a sequence. Keep freq in key."""
n = int(dur * SR)
out = []
ph = 0.0
for k in range(n):
tt = k / SR
ph += 2 * math.pi * freq / SR
a = min(1, tt / 0.003) * math.exp(-tt / tau)
out.append(a * (math.sin(ph) + 0.25 * math.sin(2 * ph) + 0.08 * math.sin(3 * ph)))
return out
def pop(f0, f1, dur=0.16):
"""Pitched pop: a badge, chip or callout popping in. Sweeps f0 to f1; raise f0 across a sequence."""
n = int(dur * SR)
out = []
ph = 0.0
for k in range(n):
tt = k / SR
f = f0 * (f1 / f0) ** min(1, tt / 0.06)
ph += 2 * math.pi * f / SR
a = min(1, tt / 0.002) * math.exp(-tt / 0.045)
out.append(a * math.sin(ph))
return out
def chime(freqs, dur=1.8, tau=0.7):
"""Bell chord: success, arrival, a payoff. Pass freqs from the video's key."""
n = int(dur * SR)
out = [0.0] * n
for j, f in enumerate(freqs):
ph1 = ph2 = 0.0
g = 1.0 / (1 + j * 0.35)
for k in range(n):
tt = k / SR
ph1 += 2 * math.pi * f / SR
ph2 += 2 * math.pi * f * 2.76 / SR
a = min(1, tt / 0.004) * math.exp(-tt / tau)
out[k] += g * a * (math.sin(ph1) + 0.18 * math.sin(ph2) * math.exp(-tt / 0.15))
return out
def whoosh(dur, f0, f1, peak=0.6, q=0.9):
"""Air whoosh: movement, reveals, transitions. f0 to f1 sets direction, peak (0..1) where it's loudest."""
n = int(dur * SR)
p = math.log(0.5) / math.log(peak)
noise = bandnoise(n, lambda k: f0 * (f1 / f0) ** (k / n), q=q)
return [noise[k] * math.sin(math.pi * (k / n) ** p) ** 2 * 1.6 for k in range(n)]
def riser(dur, f0=260, f1=5200):
"""Build-up into a payoff. End it exactly on the hit; one big riser per video."""
n = int(dur * SR)
noise = bandnoise(n, lambda k: f0 * (f1 / f0) ** (k / n), q=0.6)
out = []
ph = 0.0
for k in range(n):
x = k / n
ph += 2 * math.pi * (180 * (4.0 ** x)) / SR
tail = min(1, (n - k) / (0.02 * SR))
out.append((noise[k] * 1.3 + 0.35 * math.sin(ph)) * x ** 2.2 * tail)
return out
def impact(dur=1.2):
"""Low impact for the hero moment. One per video."""
n = int(dur * SR)
out = []
ph = 0.0
lp = 0.0
for k in range(n):
tt = k / SR
f = 38 + 60 * math.exp(-tt / 0.07)
ph += 2 * math.pi * f / SR
lp += 0.08 * (random.uniform(-1, 1) - lp)
s = math.sin(ph) * math.exp(-tt / 0.38)
s += lp * math.exp(-tt / 0.05) * 3.0
out.append(math.tanh(1.6 * s))
return out
def scratch(dur):
"""Pencil on paper: a sketch or line drawing itself on."""
n = int(dur * SR)
noise = bandnoise(n, lambda k: 3800 + 1400 * math.sin(k / SR * 23), q=0.35)
out = []
for k in range(n):
tt = k / SR
stroke = max(0.0, math.sin(tt * 2 * math.pi * 7.5)) ** 3
env = math.sin(math.pi * k / n)
out.append(noise[k] * stroke * env * 1.4)
return out
def envelope(points):
"""Helper: piecewise-linear gain curve from [(t, value), ...], for pad volume and ducking."""
pts = sorted(points)
ts = [p[0] for p in pts]
def at(t):
i = bisect.bisect_right(ts, t)
if i == 0:
return pts[0][1]
if i == len(pts):
return pts[-1][1]
(t0, v0), (t1, v1) = pts[i - 1], pts[i]
return v0 + (v1 - v0) * (t - t0) / (t1 - t0)
return at
def pad(duration, chords, volume=None, detune=0.6, tremolo=0.23, xfade=0.35):
"""Music bed under everything; returns (left, right) for Mix.put_stereo. chords = [(start_s, [freqs]), ...]."""
n = int(duration * SR)
left = [0.0] * n
right = [0.0] * n
for ci, (t0, freqs) in enumerate(chords):
t_next = chords[ci + 1][0] if ci + 1 < len(chords) else None
i0 = int(t0 * SR)
i1 = n if t_next is None else min(n, int((t_next + xfade) * SR))
phl = [0.0] * len(freqs)
phr = [0.0] * len(freqs)
for i in range(i0, i1):
t = i / SR
w = 1.0 if ci == 0 else min(1.0, (t - t0) / xfade)
if t_next is not None and t > t_next:
w *= max(0.0, 1 - (t - t_next) / xfade)
v = w * (volume(t) if volume else 1.0) * (0.85 + 0.15 * math.sin(2 * math.pi * tremolo * t))
sl = sr = 0.0
for j, f in enumerate(freqs):
phl[j] += 2 * math.pi * (f - detune) / SR
phr[j] += 2 * math.pi * (f + detune) / SR
g = 1 / (1 + j * 0.5)
sl += g * math.sin(phl[j])
sr += g * math.sin(phr[j])
left[i] += sl * v
right[i] += sr * v
return left, right
# ---------------------------------------------------------------- a small band, for music beds
# Added 2026-10-18 for the coffee-machine film. Soft, warm, low in the mix: the bed sits under the picture,
# the accents (clicks, hiss) sit on top of it.
def epiano(freq, dur=2.6, vel=1.0, decay=1.1):
"""Electric-piano note (tine and warm body), for lo-fi chords. Keep freq in key; vel 0..1."""
n = int(dur * SR)
out = [0.0] * n
w1 = 2 * math.pi * freq / SR
w2 = 2 * w1
wt = 2 * math.pi * freq * 6.98 / SR
wtrem = 2 * math.pi * 4.6 / SR
sin = math.sin
exp = math.exp
for k in range(n):
t = k / SR
a = (t / 0.006 if t < 0.006 else 1.0) * exp(-t / decay)
body = sin(w1 * k) + 0.28 * sin(w2 * k) * exp(-t / 0.5)
tine = 0.16 * sin(wt * k) * exp(-t / 0.09)
out[k] = vel * a * (body + tine) * (1 + 0.1 * sin(wtrem * k))
tail = min(n, int(0.08 * SR))
for i in range(tail):
out[n - 1 - i] *= i / tail
return out
def bass(freq, dur=0.9, vel=1.0):
"""Round bass note: sine plus a little second harmonic, gently saturated. Roots under the chords."""
n = int(dur * SR)
out = [0.0] * n
w = 2 * math.pi * freq / SR
sin = math.sin
exp = math.exp
for k in range(n):
t = k / SR
a = (t / 0.012 if t < 0.012 else 1.0) * exp(-t / 0.45)
out[k] = math.tanh(1.4 * vel * a * (sin(w * k) + 0.22 * sin(2 * w * k)))
tail = min(n, int(0.05 * SR))
for i in range(tail):
out[n - 1 - i] *= i / tail
return out
def kick(vel=1.0):
"""Soft kick: a sine dropping from 110 to 46 Hz. Lo-fi, not club."""
n = int(0.32 * SR)
out = [0.0] * n
ph = 0.0
for k in range(n):
t = k / SR
f = 46 + 64 * math.exp(-t / 0.035)
ph += 2 * math.pi * f / SR
out[k] = vel * math.sin(ph) * math.exp(-t / 0.11) * min(1.0, t / 0.002)
return out
def snare(vel=1.0):
"""Brushed snare: band-passed noise with a short body tone, for beats 2 and 4."""
n = int(0.22 * SR)
noise = bandnoise(n, lambda k: 2100, q=0.55)
return [vel * (noise[k] * 1.6 * math.exp(-k / (0.06 * SR)) + 0.25 * math.sin(2 * math.pi * 190 * k / SR) * math.exp(-k / (0.025 * SR))) for k in range(n)]
def hat(vel=1.0):
"""Closed hat tick: high band noise, very short. Swing the off-beats."""
n = int(0.05 * SR)
noise = bandnoise(n, lambda k: 7600, q=0.4)
return [vel * noise[k] * 1.8 * math.exp(-k / (0.011 * SR)) for k in range(n)]
def crackle(dur, density=7.0, hiss=0.012):
"""Vinyl crackle bed: sparse clicks over a faint hiss. density is clicks per second."""
n = int(dur * SR)
out = [random.uniform(-1, 1) * hiss for _ in range(n)]
for _ in range(int(dur * density)):
at = random.randrange(n)
g = random.uniform(0.05, 0.35) * random.choice((-1, 1))
for i in range(min(40, n - at)):
out[at + i] += g * math.exp(-i / 6.0)
return out
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env node
// Contact sheets from any rendered video: the review loop's eyes, and the way to
// read a clip before writing timecodes about it.
//
// node sheet.mjs --video f.mp4 --timeline timeline.json every beat, settled (+0.3s)
// node sheet.mjs --video f.mp4 2.3 4.5 6.9 exact timestamps
// node sheet.mjs --video f.mp4 --every 1 one frame per second
// node sheet.mjs --video f.mp4 --from 3 --to 5 --every 0.2 scrub a transition
//
// Options: --offset 0.3 --cols 4 --rows 2 --size 540 --name beats
// Sheets land next to the video in <video>_sheets/. Every tile is labelled t=.
import {execFileSync} from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import {FFMPEG, FFPROBE} from './paths.mjs';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(`--${name}`);
if (i === -1) return fallback;
const v = argv[i + 1];
argv.splice(i, 2);
return v;
};
const video = path.resolve(opt('video', ''));
const timelinePath = opt('timeline', null);
const offset = Number(opt('offset', '0.3'));
const every = opt('every', null);
const from = Number(opt('from', '0'));
const to = opt('to', null);
const cols = Number(opt('cols', '4'));
const rows = Number(opt('rows', '2'));
const size = Number(opt('size', '540'));
let name = opt('name', null);
if (!video || !fs.existsSync(video)) {
console.error('pass --video <file.mp4>');
process.exit(1);
}
const probe = (args) =>
execFileSync(FFPROBE, ['-v', 'error', ...args, '-of', 'csv=p=0', video]).toString().trim();
const duration = Number(probe(['-show_entries', 'format=duration']));
const beats = () => {
if (!timelinePath) {
console.error('pass timestamps, --every, or --timeline <file.json>');
process.exit(1);
}
const tl = JSON.parse(fs.readFileSync(timelinePath, 'utf8'));
const out = [];
const walk = (v, key) => {
if (key === 'fps' || key === 'duration') return;
if (typeof v === 'number') out.push(v);
else if (Array.isArray(v)) v.forEach((x) => walk(x));
else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x]) => walk(x, k));
};
walk(tl);
return out.map((t) => t + offset);
};
let times;
if (argv.length) {
times = argv.map(Number);
name ??= 'picked';
} else if (every) {
const end = to === null ? duration : Number(to);
times = [];
for (let t = from; t <= end + 1e-6; t += Number(every)) times.push(Number(t.toFixed(3)));
name ??= `every${every}`;
} else {
times = beats();
name ??= 'beats';
}
// ffmpeg returns no frame for a seek this close to the end of the file, so keep 50 ms off it
const eps = 0.05;
times = [...new Set(times.map((t) => Math.min(Math.max(t, 0), duration - eps).toFixed(2)))]
.map(Number)
.sort((a, b) => a - b);
const base = video.replace(/\.[^.]+$/, '') + '_sheets';
const dir = path.join(base, name);
fs.rmSync(dir, {recursive: true, force: true});
fs.mkdirSync(dir, {recursive: true});
const ffmpeg = (args) => execFileSync(FFMPEG, ['-loglevel', 'error', '-y', ...args], {stdio: 'pipe'});
let labels = true;
times.forEach((t, i) => {
const file = path.join(dir, `${String(i).padStart(3, '0')}.png`);
const scale = `scale=${size}:-2`;
// Consolas ships with Windows; the colon in the drive letter is escaped for the filter parser.
const label = `drawtext=fontfile='C\\:/Windows/Fonts/consola.ttf':text='t=${t.toFixed(2)}':x=10:y=10:fontsize=${Math.round(
size / 24,
)}:fontcolor=white:box=1:boxcolor=black@0.6:boxborderw=6`;
const grab = (vf) => ffmpeg(['-ss', String(t), '-i', video, '-frames:v', '1', '-vf', vf, file]);
if (labels) {
try {
grab(`${scale},${label}`);
return;
} catch {
labels = false;
console.warn('drawtext unavailable in this ffmpeg build; sheets will have no timestamps.');
}
}
grab(scale);
});
const perSheet = cols * rows;
const sheets = [];
for (let s = 0; s * perSheet < times.length; s++) {
const out = path.join(base, `${name}-${s + 1}.png`);
ffmpeg([
'-framerate', '1',
'-start_number', String(s * perSheet),
'-i', path.join(dir, '%03d.png'),
'-vf', `tile=${cols}x${rows}:padding=6:color=0x333333`,
'-frames:v', '1',
out,
]);
sheets.push(out);
}
console.log(`${times.length} frames from ${video} → ${sheets.length} sheet(s):`);
sheets.forEach((s) => console.log(` ${s}`));
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python
"""Beat map for a music track, so a sim can cut and hit on the music.
python sims/beats.py music/track.mp3 [--duration 30] [--start auto|SECONDS] [-o out.json]
Decodes with ffmpeg, then in pure Python:
- tempo from the autocorrelation of the onset envelope (prefers 100-160 BPM),
- the beat grid, aligned to the onsets,
- downbeats (the beat phase with the most low-band attack),
- kicks (low-band onset peaks, with strength 0..1),
- energy per bar, and the drop (the biggest sustained jump in energy).
With --start auto the 30 s window is placed so the drop lands at ~40 % of the
clip, snapped to a bar. All times in the output are relative to the window start.
"""
import argparse
import json
import math
import os
import subprocess
import sys
from array import array
FFMPEG = os.environ.get('FFMPEG', 'ffmpeg')
SR = 11025
HOP = 256
FPS = SR / HOP # envelope frames per second (~43)
def decode(path, filt=None):
cmd = [FFMPEG, '-v', 'error', '-i', path, '-ac', '1', '-ar', str(SR)]
if filt:
cmd += ['-af', filt]
cmd += ['-f', 's16le', '-']
raw = subprocess.run(cmd, check=True, capture_output=True).stdout
a = array('h')
a.frombytes(raw[: len(raw) // 2 * 2])
return a
def frame_energy(samples):
n = len(samples) // HOP
out = array('d', bytes(8 * n))
for i in range(n):
s = 0
for x in samples[i * HOP:(i + 1) * HOP]:
s += x * x
out[i] = s / HOP
return out
def onset(env):
"""Positive change of log energy, lightly smoothed."""
lg = [math.log(1e-3 + e) for e in env]
d = [0.0] + [max(0.0, lg[i] - lg[i - 1]) for i in range(1, len(lg))]
return [0.5 * d[i] + 0.25 * (d[i - 1] if i else 0) + 0.25 * (d[i + 1] if i + 1 < len(d) else 0)
for i in range(len(d))]
def tempo(nov):
"""Best period in frames from the autocorrelation, weighted toward ~126 BPM."""
n = len(nov)
mean = sum(nov) / n
x = [v - mean for v in nov]
best, best_lag = -1e18, None
scores = {}
lo = int(FPS * 60 / 190)
hi = int(FPS * 60 / 70) + 1
for lag in range(lo, hi):
s = 0.0
for i in range(n - lag):
s += x[i] * x[i + lag]
bpm = 60 * FPS / lag
w = math.exp(-0.5 * (math.log2(bpm / 126) / 0.6) ** 2)
scores[lag] = s
if s * w > best:
best, best_lag = s * w, lag
# parabolic refinement
l = best_lag
if l - 1 in scores and l + 1 in scores:
a, b, c = scores[l - 1], scores[l], scores[l + 1]
den = a - 2 * b + c
if den:
l = l + 0.5 * (a - c) / den
return l
def beat_grid(nov, period):
"""Phase of the grid that sits on the most onset energy, then local snapping."""
n = len(nov)
best, best_off = -1, 0
for off in range(int(period) + 1):
s, k = 0.0, 0
while True:
i = int(round(off + k * period))
if i >= n:
break
s += nov[i]
k += 1
if s > best:
best, best_off = s, off
beats = []
while best_off - period >= 0: # grid back to the very start
best_off -= period
k = 0
while True:
c = best_off + k * period
if c >= n:
break
i = int(round(c))
lo, hi = max(0, i - 2), min(n - 1, i + 2)
j = max(range(lo, hi + 1), key=lambda q: nov[q])
# only snap if the peak is clearly there, else keep the grid
beats.append(j if nov[j] > 1.5 * nov[i] + 1e-9 else i)
k += 1
return beats
def main():
ap = argparse.ArgumentParser()
ap.add_argument('track')
ap.add_argument('--duration', type=float, default=30)
ap.add_argument('--start', default='auto')
ap.add_argument('-o', '--out')
args = ap.parse_args()
full = decode(args.track)
low = decode(args.track, 'lowpass=f=140,lowpass=f=140')
total = len(full) / SR
env = frame_energy(full)
envl = frame_energy(low)
nov = onset(env)
novl = onset(envl)
comb = [a + 1.5 * b for a, b in zip(nov, novl)]
period = tempo(comb)
bpm = 60 * FPS / period
beats = beat_grid(comb, period)
# downbeat phase: most low-band attack
phase = max(range(4), key=lambda p: sum(novl[b] for b in beats[p::4]))
downs = beats[phase::4]
# kicks: low-band onset peaks above an adaptive threshold
srt = sorted(novl)
thr = srt[int(len(srt) * 0.9)]
peak = max(novl) or 1
kicks = []
for i in range(1, len(novl) - 1):
if novl[i] > thr and novl[i] >= novl[i - 1] and novl[i] > novl[i + 1]:
if not kicks or i - kicks[-1][0] > FPS * 0.18:
kicks.append((i, novl[i] / peak))
# energy per bar
bar_e = []
for b in range(len(downs) - 1):
seg = env[downs[b]:downs[b + 1]]
bar_e.append(math.sqrt(sum(seg) / max(1, len(seg))))
mx = max(bar_e) or 1
bar_e = [e / mx for e in bar_e]
# drop: biggest jump vs the previous 4 bars that holds for the next 2
drop_bar, best = None, 0
for b in range(4, len(bar_e) - 2):
before = sum(bar_e[b - 4:b]) / 4
after = min(bar_e[b:b + 2])
j = after - before
if j > best:
best, drop_bar = j, b
drop_t = downs[drop_bar] / FPS if drop_bar is not None else None
D = args.duration
if args.start == 'auto':
if drop_t is not None and best > 0.12:
want = drop_t - 0.4 * D
else:
# loudest window
nb = max(1, int(D / (240 / bpm)))
want_bar = max(range(max(1, len(bar_e) - nb)), key=lambda b: sum(bar_e[b:b + nb]))
want = downs[want_bar] / FPS
want = min(max(0.0, want), max(0.0, total - D))
start = min((d / FPS for d in downs), key=lambda d: abs(d - want))
if start + D > total:
start = max(0.0, total - D)
else:
start = float(args.start)
end = start + D
rel = lambda f: round(f / FPS - start, 3)
inwin = lambda f: start - 1e-6 <= f / FPS < end
bar_starts = [d for d in downs if inwin(d)]
out = {
'track': os.path.abspath(args.track),
'start': round(start, 3),
'duration': D,
'bpm': round(bpm, 2),
'beats': [rel(b) for b in beats if inwin(b)],
'downbeats': [rel(d) for d in bar_starts],
'kicks': [[rel(i), round(s, 3)] for i, s in kicks if inwin(i)],
'barEnergy': [round(bar_e[downs.index(d)], 3) for d in bar_starts if downs.index(d) < len(bar_e)],
'drop': round(drop_t - start, 3) if drop_t is not None and start <= drop_t < end else None,
}
path = args.out or os.path.splitext(args.track)[0] + f'.beats-{int(round(start))}.json'
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, 'w') as f:
json.dump(out, f)
print(f'{os.path.basename(args.track)}: {out["bpm"]} bpm, window {start:.2f}-{end:.2f} s, '
f'drop {"%.2f" % out["drop"] if out["drop"] is not None else "none"} (clip time), '
f'{len(out["beats"])} beats, {len(out["kicks"])} kicks -> {path}')
if __name__ == '__main__':
sys.exit(main())
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env node
// Bundles every sims/<name>/main.js into one self-contained HTML file:
// cutaway-out/dist/<name>.html (three.js, fonts, CSS inlined). Opens from file://,
// works offline, can be published as-is.
//
// node sims/build.mjs every example in sims/
// node sims/build.mjs v8-live one example
// node sims/build.mjs ./my-machine your own sim: any folder with a main.js. Import the kit as
// 'cutaway-kit/runtime.js', 'cutaway-kit/util.js' and so on.
//
// An entry may carry build.json with {"swap": {"heavy.glb": "light.glb"}}: every import of a file named heavy.glb is
// served from light.glb in the same folder (a site page with lighter models than its film). {"external": {...}} does
// the same but leaves the model out of the page: the import becomes the string "url:light.glb", the file is copied
// next to the page and listed in <name>.assets.json (the site build copies those too). The page stays small enough
// for link crawlers (X reads the share card from it). {"files": [...]} copies more files from node_modules next to the
// page the same way (decoders a loader fetches at runtime).
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {DEPS, DIST, fromDeps} from '../paths.mjs';
const esbuild = fromDeps('esbuild');
const HERE = path.dirname(fileURLToPath(import.meta.url));
fs.mkdirSync(DIST, {recursive: true});
const font = (weight) => {
const file = path.join(
DEPS,
`@fontsource/jetbrains-mono/files/jetbrains-mono-latin-${weight}-normal.woff2`,
);
const b64 = fs.readFileSync(file).toString('base64');
return `@font-face{font-family:'JetBrains Mono';font-weight:${weight};font-style:normal;font-display:block;src:url(data:font/woff2;base64,${b64}) format('woff2');}`;
};
const inter = fs.readFileSync(path.join(DEPS, '@fontsource-variable/inter/files/inter-latin-wght-normal.woff2')).toString('base64');
const FONTS = [400, 600, 700].map(font).join('\n') +
`\n@font-face{font-family:'Inter';font-weight:100 900;font-style:normal;font-display:block;src:url(data:font/woff2;base64,${inter}) format('woff2');}`;
const KIT_CSS = fs.readFileSync(path.join(HERE, 'kit/style.css'), 'utf8');
const names = process.argv.slice(2).length
? process.argv.slice(2)
: fs
.readdirSync(HERE)
.filter((d) => fs.existsSync(path.join(HERE, d, 'main.js')));
// `cutaway-kit/x.js` resolves to sims/kit/x.js, so a sim outside this folder can use the kit.
const kitPlugin = {
name: 'cutaway-kit',
setup(b) {
b.onResolve({filter: /^cutaway-kit\//}, (args) => ({path: path.join(HERE, 'kit', args.path.slice('cutaway-kit/'.length))}));
},
};
for (const arg of names) {
const dir = fs.existsSync(path.join(HERE, arg, 'main.js')) ? path.join(HERE, arg) : path.resolve(arg);
if (!fs.existsSync(path.join(dir, 'main.js'))) {
console.error(`no main.js in ${dir}`);
process.exit(1);
}
const name = path.basename(dir);
const t0 = Date.now();
const cfgFile = path.join(dir, 'build.json');
const bcfg = fs.existsSync(cfgFile) ? JSON.parse(fs.readFileSync(cfgFile, 'utf8')) : {};
const swap = bcfg.swap || {};
const external = bcfg.external || {};
const assets = [];
const plugins = Object.keys(external).length
? [
{
name: 'external',
setup(b) {
b.onResolve({filter: /\.glb$/}, (args) => {
const base = path.basename(args.path);
if (!external[base]) return undefined;
const src = path.join(args.resolveDir, path.dirname(args.path), external[base]);
if (!assets.includes(src)) assets.push(src);
return {path: external[base], namespace: 'ext'};
});
b.onLoad({filter: /.*/, namespace: 'ext'}, (args) => ({contents: `export default ${JSON.stringify('url:' + args.path)};`, loader: 'js'}));
},
},
]
: Object.keys(swap).length
? [
{
name: 'swap',
setup(b) {
b.onResolve({filter: /\.glb$/}, (args) => {
const base = path.basename(args.path);
if (!swap[base]) return undefined;
return {path: path.join(args.resolveDir, path.dirname(args.path), swap[base])};
});
},
},
]
: [];
const res = await esbuild.build({
plugins: [kitPlugin, ...plugins],
entryPoints: [path.join(dir, 'main.js')],
bundle: true,
nodePaths: [DEPS],
format: 'esm',
minify: !process.env.SIMS_DEBUG,
write: false,
target: 'es2022',
legalComments: 'none',
loader: {'.glb': 'base64', '.woff2': 'base64'},
logLevel: 'warning',
});
const js = res.outputFiles[0].text.replace(/<\/script/g, '<\\/script');
const css = fs.existsSync(path.join(dir, 'style.css')) ? fs.readFileSync(path.join(dir, 'style.css'), 'utf8') : '';
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>${name}</title>
<style>
${FONTS}
${KIT_CSS}
${css}
</style>
</head>
<body>
<div id="app"></div>
<script type="module">
${js}
</script>
</body>
</html>
`;
const out = path.join(DIST, `${name}.html`);
fs.writeFileSync(out, html);
const listFile = path.join(DIST, `${name}.assets.json`);
assets.push(...(bcfg.files || []).map((f) => path.join(DEPS, f)));
if (assets.length) {
for (const a of assets) fs.copyFileSync(a, path.join(DIST, path.basename(a)));
fs.writeFileSync(listFile, JSON.stringify(assets.map((a) => path.basename(a))));
} else if (fs.existsSync(listFile)) fs.rmSync(listFile);
console.log(`${out} ${(html.length / 1024).toFixed(0)} KB ${Date.now() - t0} ms`);
}
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env node
// Frame-accurate capture of a sim page to mp4: steps window.SIM.render(t) for
// every frame in headless Chromium, screenshots, pipes to ffmpeg, then muxes
// a music track if given.
//
// node sims/capture.mjs <name> [--config post.json] [--out cutaway-out/x.mp4]
// [--size 1080x1350] [--dpr 1.3333] [--fps 60] [--from 0] [--to <duration>]
// (--size is the layout in CSS px; --dpr multiplies the output: 1080x1350
// at the default 4/3 gives a 1440x1800 video. Default 60 fps, crf 16.)
// [--music music/track.mp3 [--music-start auto|SEC] [--no-sync] [--lufs -21]] [--crf 21]
// [--still 12.5] (--still: one PNG, no video)
// [--stills 0,4,9,14 --cols 3] (tiled review sheet, every tile labelled t=)
// [--stills beats [--timeline f.json]] (one tile per timeline beat, +0.3 s so motion settles)
// [--stills every:0.2 --from 3 --to 5] (scrub a transition)
//
// <name> is a sim built into cutaway-out/dist, or a path to any .html
// that exposes window.seek(seconds) and freezes its clock on ?render
// (motion-effects, vox-explainer, milestone-reveal, model-showdown). An .html
// needs --to <seconds> unless it sets window.DURATION.
import {spawn} from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
import {CHROMIUM, CHROMIUM_ARGS, DIST, FFMPEG, OUT, PYTHON, playwright} from '../paths.mjs';
const {chromium} = playwright();
const HERE = path.dirname(fileURLToPath(import.meta.url));
const argv = process.argv.slice(2);
const name = argv[0];
const opt = (k, d) => {
const i = argv.indexOf(`--${k}`);
return i === -1 ? d : argv[i + 1];
};
if (!name) {
console.error('usage: node sims/capture.mjs <name|file.html> [--config f.json] [--out f.mp4] [--music f.wav]');
process.exit(1);
}
const SEEK = name.endsWith('.html');
const html = SEEK ? path.resolve(name) : path.join(DIST, `${name}.html`);
const label = SEEK ? path.basename(name, '.html') : name;
if (!fs.existsSync(html)) {
console.error(SEEK ? `missing ${html}` : `missing ${html}; run node sims/build.mjs ${name}`);
process.exit(1);
}
const [W, H] = opt('size', '1080x1350').split('x').map(Number);
const config = opt('config') ? JSON.parse(fs.readFileSync(opt('config'), 'utf8')) : {};
// --music <file> [--music-start auto|SECONDS]: analyse the track (sims/beats.py),
// cut the window so the drop lands ~40% in, and give the beat map to the director.
const music = opt('music');
let beats = null;
if (music) {
const dur = Number(opt('to', config.duration ?? 30)) - Number(opt('from', 0));
const ms = opt('music-start', 'auto');
const cache = path.join(OUT, 'beats', `${path.basename(music).replace(/\.[^.]+$/, '')}-${ms}-${dur}.json`);
fs.mkdirSync(path.dirname(cache), {recursive: true});
const {execFileSync} = await import('node:child_process');
if (!fs.existsSync(cache) || fs.statSync(cache).mtimeMs < fs.statSync(music).mtimeMs) {
execFileSync(PYTHON, ['-I', path.join(HERE, 'beats.py'), music, '--duration', String(dur), '--start', ms, '-o', cache], {stdio: 'inherit'});
}
beats = JSON.parse(fs.readFileSync(cache, 'utf8'));
if (!opt('no-sync')) config.beats = beats;
}
const still = opt('still');
const stamp = new Date().toISOString().slice(5, 16).replace(/[-:T]/g, '');
const out = path.resolve(opt('out', path.join(OUT, still ? `${label}-${still}.png` : `${label}-${stamp}.mp4`)));
fs.mkdirSync(path.dirname(out), {recursive: true});
// Browser and GPU flags come from ../paths.mjs.
const exe = CHROMIUM;
const browser = await chromium.launch({
executablePath: exe,
args: CHROMIUM_ARGS,
});
const dpr = Number(opt('dpr', 4 / 3));
const page = await browser.newPage({viewport: {width: W, height: H}, deviceScaleFactor: dpr});
page.on('console', (m) => m.type() === 'error' && console.error('[page]', m.text()));
page.on('pageerror', (e) => console.error('[page error]', e.message));
await page.addInitScript((cfg) => {
window.__CAPTURE = true;
window.__SIM_CONFIG = cfg;
}, config);
await page.goto(pathToFileURL(html).href + (SEEK ? '?render' : ''));
await page.waitForFunction(
(seek) => (seek ? typeof window.seek === 'function' : window.SIM && window.SIM.ready),
SEEK,
{timeout: 60000},
);
await page.evaluate(() => document.fonts.ready);
const info = await page.evaluate((seek) => {
const gl = document.createElement('canvas').getContext('webgl2');
const ext = gl && gl.getExtension('WEBGL_debug_renderer_info');
return {
duration: seek ? window.DURATION : window.SIM.duration,
fps: seek ? window.FPS : window.SIM.fps,
gpu: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : 'unknown',
};
}, SEEK);
console.log(`gpu: ${info.gpu}`);
// One entry point for both contracts: a sim's SIM.render(t) or a page's seek(t).
const draw = (t) => page.evaluate(([x, seek]) => (seek ? window.seek(x) : window.SIM.render(x)), [t, SEEK]);
const end = Number(opt('to', info.duration));
if (!Number.isFinite(end)) {
console.error('no duration: pass --to <seconds> or set window.DURATION in the page');
process.exit(1);
}
// --stills: a list, `beats` (every number in the timeline, +0.3 s), or `every:<step>`.
const stillTimes = (arg) => {
if (arg === 'beats') {
const file = opt('timeline', path.join(HERE, name, 'timeline.json'));
const tl = JSON.parse(fs.readFileSync(file, 'utf8'));
const ts = [];
const walk = (v, key) => {
if (key === 'fps' || key === 'duration') return;
if (typeof v === 'number') ts.push(v + 0.3);
else if (Array.isArray(v)) v.forEach((x) => walk(x));
else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x]) => walk(x, k));
};
walk(tl);
return [0, ...ts];
}
if (arg.startsWith('every:')) {
const step = Number(arg.slice(6));
const ts = [];
for (let t = Number(opt('from', 0)); t <= end + 1e-6; t += step) ts.push(t);
return ts;
}
return arg.split(',').map(Number);
};
const stills = opt('stills');
if (stills) {
const ts = [...new Set(stillTimes(stills).map((t) => Math.min(Math.max(t, 0), end - 1 / 120).toFixed(2)))]
.map(Number)
.sort((a, b) => a - b);
const dir = out.replace(/\.(png|mp4)$/, '') + '-frames';
fs.mkdirSync(dir, {recursive: true});
for (const [i, t] of ts.entries()) {
await draw(t);
// The t= label goes into the DOM for the screenshot only, so no ffmpeg font setup is needed.
await page.evaluate((txt) => {
const el = document.createElement('div');
el.id = '__t';
el.textContent = txt;
el.style.cssText =
'position:fixed;right:12px;top:12px;z-index:2147483647;font:600 28px monospace;color:#fff;background:rgba(0,0,0,.65);padding:4px 10px;border-radius:4px';
document.body.appendChild(el);
}, `t=${t.toFixed(2)}`);
await page.screenshot({path: path.join(dir, `${String(i).padStart(3, '0')}.png`)});
await page.evaluate(() => document.getElementById('__t')?.remove());
}
await browser.close();
const cols = Math.min(ts.length, Number(opt('cols', 3)));
const sheet = out.endsWith('.png') ? out : out.replace(/\.mp4$/, '') + '-sheet.png';
const tw = Math.round(W * 0.4);
const th = Math.round(H * 0.4);
await new Promise((r) =>
spawn(FFMPEG, ['-loglevel', 'error', '-y', '-framerate', '1', '-i', path.join(dir, '%03d.png'),
'-vf', `scale=${tw}:${th},tile=${cols}x${Math.ceil(ts.length / cols)}:padding=4:color=0x333333`, '-frames:v', '1', sheet],
{stdio: 'inherit'}).on('close', r),
);
console.log(`→ ${sheet} (full frames in ${dir})`);
process.exit(0);
}
if (still !== undefined) {
await draw(Number(still));
await page.screenshot({path: out});
await browser.close();
console.log(`→ ${out}`);
process.exit(0);
}
const fps = Number(opt('fps', 60));
const from = Number(opt('from', 0));
const to = end;
const frames = Math.round((to - from) * fps);
const silent = music ? out.replace(/\.mp4$/, '-silent.mp4') : out;
const ff = spawn(
FFMPEG,
['-loglevel', 'error', '-y', '-f', 'image2pipe', '-framerate', String(fps), '-i', '-',
'-c:v', 'libx264', '-preset', 'slow', '-crf', String(opt('crf', 16)), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', silent],
{stdio: ['pipe', 'inherit', 'inherit']},
);
const t0 = Date.now();
for (let i = 0; i < frames; i++) {
await draw(from + i / fps);
const buf = await page.screenshot({type: 'jpeg', quality: 97});
if (!ff.stdin.write(buf)) await new Promise((r) => ff.stdin.once('drain', r));
if (i % fps === 0) process.stdout.write(`\r${i}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);
}
ff.stdin.end();
await new Promise((r) => ff.on('close', r));
await browser.close();
console.log(`\r${frames}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);
if (music) {
await new Promise((r, j) =>
spawn(
FFMPEG,
['-loglevel', 'error', '-y', '-i', silent, '-ss', String(beats.start), '-i', music, '-map', '0:v', '-map', '1:a',
'-c:v', 'copy', '-c:a', 'aac', '-b:a', '256k', '-af', `loudnorm=I=${opt('lufs', -21)}:TP=-3,afade=t=in:d=0.04,afade=t=out:st=${(to - from - 0.6).toFixed(2)}:d=0.6`,
'-shortest', '-movflags', '+faststart', out],
{stdio: 'inherit'},
).on('close', (c) => (c === 0 ? r() : j(new Error('mux failed')))),
);
fs.rmSync(silent);
}
console.log(`→ ${out}`);
+18
View File
@@ -0,0 +1,18 @@
// print a film's anchor table A, the parts' rest points the close-up cameras aim at (node sims/green/anchors_dump.mjs <entry> <global>)
import {pathToFileURL} from 'node:url';
import path from 'node:path';
import {CHROMIUM, CHROMIUM_ARGS, DIST, playwright} from '../../paths.mjs';
const [entry, glob] = process.argv.slice(2);
const {chromium} = playwright();
const browser = await chromium.launch({executablePath: CHROMIUM, args: CHROMIUM_ARGS});
const page = await browser.newPage({viewport: {width: 1600, height: 900}, deviceScaleFactor: 1});
await page.addInitScript(() => {
window.__CAPTURE = true;
window.__SIM_CONFIG = {};
});
await page.goto(pathToFileURL(path.join(DIST, `${entry}.html`)).href);
await page.waitForFunction(() => window.SIM && window.SIM.ready, null, {timeout: 60000});
const out = await page.evaluate((g) => JSON.stringify(Object.fromEntries(Object.entries(window[g].A).map(([k, v]) => [k, v.map((x) => +x.toFixed(2))]))), glob);
console.log(out);
await browser.close();
+23
View File
@@ -0,0 +1,23 @@
// print a film's camera every 0.5 s (node sims/green/cam_track.mjs <entry> <global> [step])
import {pathToFileURL} from 'node:url';
import path from 'node:path';
import {CHROMIUM, CHROMIUM_ARGS, DIST, playwright} from '../../paths.mjs';
const [entry, glob, step = '0.5'] = process.argv.slice(2);
const {chromium} = playwright();
const browser = await chromium.launch({executablePath: CHROMIUM, args: CHROMIUM_ARGS});
const page = await browser.newPage({viewport: {width: 1600, height: 900}, deviceScaleFactor: 1});
await page.addInitScript(() => { window.__CAPTURE = true; window.__SIM_CONFIG = {}; });
await page.goto(pathToFileURL(path.join(DIST, `${entry}.html`)).href);
await page.waitForFunction(() => window.SIM && window.SIM.ready, null, {timeout: 60000});
const rows = await page.evaluate(([glob, step]) => {
const T = window[glob].T;
const out = [];
for (let t = 0; t <= window.SIM.duration + 1e-6; t += Number(step)) {
const s = T.stateAt(t);
const c = s.cam;
out.push(`${t.toFixed(1).padStart(5)} ${String(s.view).padEnd(9)} az ${c.az.toFixed(0).padStart(4)} el ${c.el.toFixed(0).padStart(3)} d ${c.d.toFixed(1)}`);
}
return out;
}, [glob, step]);
console.log(rows.join('\n'));
await browser.close();
+187
View File
@@ -0,0 +1,187 @@
// The green page around a creature, in the look of a model-launch blog (first made for longcat/wasp, Vespera-07): white
// paper with mint haze in the top corners, a wordmark, a centred title with a green rule and a row of pill buttons the
// operator's cursor presses, a section list on the left that follows the act, white metric cards on the right, labels
// as soft cards with leader lines. Shared by every creature's green film; what changes per creature (name, title, the
// acts and their notes) comes in as options. 1600 x 900 layout px. update(s) redraws every live part from one frame.
export const VIEWPORT = {x0: 250, x1: 1320, y0: 236, y1: 836};
export const REST = [1250, 272];
export const GREEN = '#16b364';
const CSS = `
#app{width:1600px!important;height:900px!important;inset:auto!important;left:0;top:0;transform-origin:0 0;background:#fff}
.vp{position:absolute;inset:0;pointer-events:none;font-family:'Inter',system-ui,sans-serif;color:#0f172a;-webkit-font-smoothing:antialiased}
.vp *{box-sizing:border-box}
.vp .haze{position:absolute;inset:0;mix-blend-mode:multiply;background:
radial-gradient(520px 360px at 60px -40px, rgba(22,179,100,.16), rgba(22,179,100,0) 70%),
radial-gradient(620px 420px at 1600px 20px, rgba(22,179,100,.14), rgba(22,179,100,0) 70%)}
.vp .dots{position:absolute;right:0;top:0;width:420px;height:300px;opacity:.5;mix-blend-mode:multiply;
background-image:radial-gradient(rgba(22,179,100,.35) 1px, transparent 1.4px);background-size:9px 9px;
-webkit-mask-image:radial-gradient(360px 240px at 100% 0%, #000, transparent 75%);mask-image:radial-gradient(360px 240px at 100% 0%, #000, transparent 75%)}
.vp .logo{position:absolute;left:46px;top:22px;display:flex;align-items:center;gap:10px;font:800 23px/1 'Inter',sans-serif;letter-spacing:-.3px}
.vp .logo i{width:30px;height:30px;border-radius:9px;background:linear-gradient(135deg,#22c55e,#0e9f55);position:relative;display:block}
.vp .logo i:after{content:'';position:absolute;left:8px;top:8px;width:14px;height:14px;border:3px solid #fff;border-radius:50%;border-right-color:transparent}
.vp .lang{position:absolute;right:46px;top:20px;height:32px;padding:0 14px;border:1px solid #e2e8f0;border-radius:16px;display:flex;align-items:center;gap:8px;font:600 13px/1 'Inter',sans-serif;background:#fff}
.vp .lang b{width:8px;height:8px;border-radius:50%;background:${GREEN};display:block;box-shadow:0 0 0 4px rgba(22,179,100,.15)}
.vp .head{position:absolute;left:0;right:0;top:52px;text-align:center}
.vp .head .ver{font:800 22px/1 'Inter',sans-serif;letter-spacing:-.3px}
.vp .head .ver em{font-style:normal;color:${GREEN}}
.vp .head h1{margin:10px 0 0;font:800 36px/1.05 'Inter',sans-serif;letter-spacing:-.8px}
.vp .head .rule{width:84px;height:4px;border-radius:3px;margin:12px auto 0;background:linear-gradient(90deg,rgba(22,179,100,0),${GREEN} 30%,${GREEN} 70%,rgba(22,179,100,0))}
.vp .head .date{margin-top:9px;font:500 13px/1 'Inter',sans-serif;color:#64748b}
.vp .pills{position:absolute;left:0;right:0;top:180px;display:flex;justify-content:center;gap:10px}
.vp .pill{height:34px;padding:0 15px;border:1px solid #e2e8f0;border-radius:17px;background:#fff;display:flex;align-items:center;gap:8px;font:600 13px/1 'Inter',sans-serif;color:#334155;transition:none}
.vp .pill i{width:15px;height:15px;border-radius:50%;border:1.6px solid #94a3b8;display:block;position:relative}
.vp .pill i:after{content:'';position:absolute;left:4px;top:3px;border-left:5px solid #94a3b8;border-top:3.5px solid transparent;border-bottom:3.5px solid transparent}
.vp .pill.on{border-color:${GREEN};background:#effbf4;color:#0b7a43}
.vp .pill.on i{border-color:${GREEN}}
.vp .pill.on i:after{border-left-color:${GREEN}}
.vp .pill.press{transform:scale(.95)}
.vp .nav{position:absolute;left:58px;top:300px;width:190px;border-left:1.5px solid #e2e8f0;padding-left:0}
.vp .nav div{position:relative;padding:7px 0 7px 18px;font:500 15px/1.2 'Inter',sans-serif;color:#94a3b8}
.vp .nav div.on{color:#0f172a;font-weight:700}
.vp .nav div.on:before{content:'';position:absolute;left:-2px;top:7px;bottom:7px;width:3px;border-radius:2px;background:#0f172a}
.vp .nav div.sub{padding:4px 0 4px 30px;font:500 12.5px/1.2 'Inter',sans-serif;color:#64748b}
.vp .cards{position:absolute;left:1340px;top:290px;width:220px;display:flex;flex-direction:column;gap:12px}
.vp .card{background:rgba(255,255,255,.92);border:1px solid #e8edf3;border-radius:14px;padding:14px 16px;box-shadow:0 1px 2px rgba(15,23,42,.04),0 6px 18px rgba(15,23,42,.05)}
.vp .card .k{font:600 11px/1 'Inter',sans-serif;letter-spacing:.6px;text-transform:uppercase;color:#64748b}
.vp .card .v{margin-top:8px;font:800 28px/1 'Inter',sans-serif;letter-spacing:-.5px;font-variant-numeric:tabular-nums}
.vp .card .v small{font-size:14px;font-weight:600;color:#64748b;margin-left:4px}
.vp .card svg{display:block;margin-top:8px}
.vp .bar{height:6px;border-radius:3px;background:#edf2f7;margin-top:10px;overflow:hidden}
.vp .bar b{display:block;height:100%;background:${GREEN};border-radius:3px}
.vp .servos{display:flex;gap:6px;align-items:flex-end;height:46px;margin-top:10px}
.vp .servos b{flex:1;background:${GREEN};border-radius:3px 3px 1px 1px;opacity:.9}
.vp .foot{position:absolute;left:262px;right:280px;top:852px;display:flex;align-items:center;gap:14px}
.vp .foot .st{height:28px;padding:0 12px;border-radius:14px;background:#effbf4;color:#0b7a43;font:600 12.5px/28px 'Inter',sans-serif;white-space:nowrap;display:flex;align-items:center;gap:7px}
.vp .foot .st b{width:7px;height:7px;border-radius:50%;background:${GREEN};display:block}
.vp .foot .track{flex:1;height:3px;border-radius:2px;background:#e2e8f0;position:relative}
.vp .foot .track b{position:absolute;left:0;top:0;bottom:0;background:${GREEN};border-radius:2px}
.vp .foot .tm{font:600 12.5px/1 'Inter',sans-serif;color:#64748b;font-variant-numeric:tabular-nums}
.vp svg.lines{position:absolute;left:0;top:0;width:1600px;height:900px;overflow:visible}
.vp .lab{position:absolute;padding:8px 12px;background:#fff;border:1px solid #e2e8f0;border-radius:10px;box-shadow:0 4px 14px rgba(15,23,42,.08);white-space:nowrap}
.vp .lab b{display:block;font:700 13.5px/1.15 'Inter',sans-serif;color:#0f172a}
.vp .lab span{display:block;margin-top:3px;font:500 11.5px/1.1 'Inter',sans-serif;color:#64748b}
.vp .cur{position:absolute;left:0;top:0;width:26px;height:26px}
.vp .ring{position:absolute;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;border:2px solid ${GREEN}}
`;
export function createConsole(app, opts) {
const {name, code, title, date} = opts;
// the 4 cards: a value with a trace ('wave'), a value with a bar ('bar') or a row of load bars ('bars'); a plain
// title string keeps the flying creatures' set (wingbeat, lift, servo load, battery)
const KIND = ['wave', 'bar', 'bars', 'bar'];
const UNIT = ['Hz', '%', '', '%'];
const CARDS = (opts.cards ?? ['Wingbeat', 'Lift', 'Servo load', 'Battery']).map((c, i) => (typeof c === 'string' ? {k: c, kind: KIND[i], unit: UNIT[i], n: 6} : {n: 6, unit: '', ...c}));
const cardHtml = (c, i) =>
c.kind === 'wave'
? `<div class="card"><div class="k">${c.k}</div><div class="v" data-c="${i}">0<small>${c.unit}</small></div><svg width="188" height="38" viewBox="0 0 188 38"><path data-w="${i}" fill="none" stroke="${GREEN}" stroke-width="2" stroke-linejoin="round"/></svg></div>`
: c.kind === 'bars'
? `<div class="card"><div class="k">${c.k}</div><div class="servos" data-s="${i}">${'<b></b>'.repeat(c.n)}</div></div>`
: `<div class="card"><div class="k">${c.k}</div><div class="v" data-c="${i}">0<small>${c.unit}</small></div><div class="bar"><b data-b="${i}"></b></div></div>`;
const NAV = opts.nav;
const SUB = opts.sub;
const PILLS = opts.pills;
const st = document.createElement('style');
st.textContent = CSS;
document.head.appendChild(st);
const root = document.createElement('div');
root.className = 'vp';
root.innerHTML = `
<div class="haze"></div><div class="dots"></div>
<div class="logo"><i></i>${name}</div>
<div class="lang"><b></b>Live sim</div>
<div class="head"><div class="ver">${name} <em>${code}</em></div><h1>${title}</h1><div class="rule"></div><div class="date">${date}</div></div>
<div class="pills">${PILLS.map(([k, t]) => `<div class="pill" data-p="${k}"><i></i>${t}</div>`).join('')}</div>
<div class="nav"></div>
<div class="cards">${CARDS.map(cardHtml).join('')}
</div>
<div class="foot"><div class="st"><b></b><span data-v="status">Banking in</span></div><div class="track"><b data-v="prog"></b></div><div class="tm" data-v="time">00:00.0</div></div>
<svg class="lines"></svg>
<div class="labs"></div>
<div class="ring" style="opacity:0"></div>
<svg class="cur" viewBox="0 0 26 26" style="display:none"><path d="M3 2 L3 22 L8.5 17 L12.5 25 L16 23.4 L12 15.5 L19 15.5 Z" fill="#0f172a" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg>`;
app.appendChild(root);
const $ = (q) => root.querySelector(q);
const V = Object.fromEntries([...root.querySelectorAll('[data-v]')].map((e) => [e.dataset.v, e]));
const pills = Object.fromEntries([...root.querySelectorAll('[data-p]')].map((e) => [e.dataset.p, e]));
const cardV = CARDS.map((c, i) => root.querySelector(`[data-c="${i}"]`));
const cardW = CARDS.map((c, i) => root.querySelector(`[data-w="${i}"]`));
const cardB = CARDS.map((c, i) => root.querySelector(`[data-b="${i}"]`));
const cardS = CARDS.map((c, i) => [...root.querySelectorAll(`[data-s="${i}"] b`)]);
const nav = $('.nav');
const lines = $('svg.lines');
const labs = $('.labs');
const cur = $('.cur');
const ring = $('.ring');
const spots = Object.fromEntries(Object.entries(pills).map(([k, e]) => [k, [e.offsetLeft + e.parentElement.offsetLeft + e.offsetWidth * 0.42, e.offsetTop + e.parentElement.offsetTop + e.offsetHeight * 0.58]]));
let lastNav = '';
const pool = [];
const pad = (n) => String(Math.floor(n)).padStart(2, '0');
return {
root,
spots,
pills,
update(s) {
// pills and the section list follow the act
for (const [k, e] of Object.entries(pills)) e.classList.toggle('on', k === s.view);
if (s.view !== lastNav) {
lastNav = s.view;
nav.innerHTML = NAV.map(([k, t]) => (k === s.view ? `<div class="on">${t}</div>${(SUB[k] ?? []).map((x) => `<div class="sub">${x}</div>`).join('')}` : `<div>${t}</div>`)).join('');
}
// cards: s.cards [{v, wave (-1..1) | bar (0..1) | bars (0..1 each)}], or the flying creatures' fields
const cards = s.cards ?? [
{v: s.freq.toFixed(1), wave: s.stroke.map((a) => a / 32)},
{v: Math.round(Math.min(1, s.lift) * 100), bar: Math.min(1, s.lift)},
{bars: s.servos},
{v: Math.round(s.battery * 100), bar: s.battery},
];
cards.forEach((c, i) => {
if (cardV[i]) cardV[i].innerHTML = `${c.v}<small>${CARDS[i].unit}</small>`;
if (cardW[i] && c.wave) cardW[i].setAttribute('d', `M${c.wave.map((a, j) => `${((j / (c.wave.length - 1)) * 188).toFixed(1)},${(19 - Math.max(-1, Math.min(1, a)) * 15).toFixed(1)}`).join(' L')}`);
if (cardB[i]) cardB[i].style.width = `${Math.round(Math.max(0, Math.min(1, c.bar ?? 0)) * 100)}%`;
cardS[i].forEach((e, j) => (e.style.height = `${Math.round(8 + 38 * Math.max(0, Math.min(1, c.bars?.[j] ?? 0)))}px`));
});
V.status.textContent = s.status + (s.apart > 2 && s.status !== 'Hovering' ? ` · ${s.apart}% apart` : '');
V.prog.style.width = `${Math.min(100, (s.time / s.dur) * 100)}%`;
V.time.textContent = `00:${pad(s.time)}.${Math.floor((s.time % 1) * 10)}`;
// labels
let path = '';
(s.callouts || []).forEach((c, i) => {
let el = pool[i];
if (!el) {
el = document.createElement('div');
el.className = 'lab';
labs.appendChild(el);
pool[i] = el;
}
el.style.display = 'block';
el.style.opacity = String(c.o);
el.innerHTML = `<b>${c.name}</b><span>${c.sub}</span>`;
const w = el.offsetWidth;
const left = c.w === 'l' ? c.label[0] : c.label[0] - w;
el.style.left = `${left}px`;
el.style.top = `${c.label[1]}px`;
const ex = c.w === 'l' ? left + w : left;
const ey = c.label[1] + 21;
const k = Math.min(1, c.o * 1.2);
const ax = ex + (c.at[0] - ex) * k;
const ay = ey + (c.at[1] - ey) * k;
path += `<path d="M${ex} ${ey} L${(ex + ax) / 2} ${ey} L${ax} ${ay}" stroke="rgba(100,116,139,${0.8 * c.o})" stroke-width="1.3" fill="none"/><circle cx="${c.at[0]}" cy="${c.at[1]}" r="${4.5 * k}" fill="${GREEN}" fill-opacity="${c.o}" stroke="#fff" stroke-width="1.5"/>`;
});
for (let i = (s.callouts || []).length; i < pool.length; i++) pool[i].style.display = 'none';
lines.innerHTML = path;
// cursor
const c = s.cursor;
if (c) {
cur.style.display = 'block';
cur.style.transform = `translate(${c.x - 3}px, ${c.y - 2}px) scale(${c.press ? 0.86 : 1})`;
ring.style.opacity = String(c.ring * 0.9);
ring.style.left = `${c.ringX}px`;
ring.style.top = `${c.ringY}px`;
ring.style.transform = `scale(${0.45 + (1 - c.ring) * 0.9})`;
for (const [k, e] of Object.entries(pills)) e.classList.toggle('press', c.press && Math.hypot(spots[k][0] - c.x, spots[k][1] - c.y) < 40);
} else cur.style.display = 'none';
},
};
}
+158
View File
@@ -0,0 +1,158 @@
// The green look for any creature film (first made for longcat/wasp and longcat/tarantula): the palette swap, the warm
// glows turned green, the labels as two columns of soft cards inside the green page's viewport, and the operator's
// pointer on its pill buttons. A creature's own film keeps its tour (movement, cameras, timing) and only routes its
// state through these.
import * as THREE from 'three';
import {REST, VIEWPORT} from './console.js';
export const HUE = 0.405;
export const ORANGE_TO = '#17b865';
export const PAPER_GREEN = {top: '#ffffff', mid: '#fcfefd', low: '#f0f6f2', shadow: '#b4c6bd'};
// the old consoles centre the subject in a 3D window at (800, 426); the green page's window centres at (785, 536)
export const SHIFT = [-15, 110];
const ss = (a, b, t) => {
const u = Math.min(1, Math.max(0, (t - a) / (b - a)));
return u * u * u * (u * (u * 6 - 15) + 10);
};
/** Every warm accent left in a creature's materials and lights (glows, tints, rims) turned to the same green. */
export function retint(root) {
const hsl = {};
const fix = (c, minS = 0.4) => {
if (!c?.isColor) return;
// a glow colour above 1 (an HDR basic material, the octopus's coils and rings) is read and written at unit peak
const k = Math.max(1, c.r, c.g, c.b);
c.multiplyScalar(1 / k);
c.getHSL(hsl);
if ((hsl.h < 0.15 || hsl.h > 0.96) && hsl.s > minS) c.setHSL(HUE, Math.min(0.85, hsl.s), hsl.l);
c.multiplyScalar(k);
};
const vc = new THREE.Color();
root.traverse((o) => {
// colours baked into a geometry's vertices (the shark's fang tips), turned once per geometry
const ca = o.geometry?.attributes?.color;
if (ca && !o.geometry.userData.tinted && [].concat(o.material || []).some((m) => m.vertexColors)) {
o.geometry.userData.tinted = true;
for (let i = 0; i < ca.count; i++) {
vc.setRGB(ca.getX(i), ca.getY(i), ca.getZ(i));
fix(vc);
ca.setXYZ(i, vc.r, vc.g, vc.b);
}
ca.needsUpdate = true;
}
if (o.isLight && !o.userData.tinted) {
o.userData.tinted = true;
fix(o.color, 0.3);
}
for (const m of [].concat(o.material || [])) {
// a colour the creature's pose rewrites every frame (the octopus's pulsing core) is turned again whenever it no
// longer matches what was last written here
const done = (m.userData.tinted ??= {});
for (const key of ['color', 'emissive', 'attenuationColor']) {
const c = m[key];
if (!c?.isColor || done[key]?.equals(c)) continue;
fix(c);
done[key] = c.clone();
}
const u = m.uniforms?.uColor?.value;
if (u?.isColor && !done.u?.equals(u)) {
fix(u, 0.2);
done.u = u.clone();
}
}
});
}
// the old consoles' capitals in the page's voice: units, axes and part codes keep their case
const fixCase = (x) =>
x
.replace(/ø/g, 'Ø')
.replace(/\bn·m\b/g, 'N·m')
.replace(/\b(cpu|imu|ar|dof|led)\b/g, (m) => m.toUpperCase())
.replace(/\b([lr])(\d)\b/g, (m, a, d) => a.toUpperCase() + d)
.replace(/(\d) k\b/g, '$1 K');
/** A part name in capitals, in sentence case. */
export const nice = (s) => {
const x = fixCase(s.toLowerCase());
return x.charAt(0).toUpperCase() + x.slice(1);
};
/** A part's note in capitals, lower case with commas. */
export const niceSub = (s) => fixCase(s.toLowerCase().replace(/ · /g, ', '));
/** Labels in two columns at the green viewport's edges; text: old capital name -> [name, sub] (or [name] to keep the
* converted note) in the page's voice, anything missing converted by nice / niceSub. */
export function makeLabels(st, anchors, text = {}) {
const p = new THREE.Vector3();
return ({set, o}) => {
if (o < 0.02) return [];
const pts = [];
for (const [key, name, sub] of set) {
const A = anchors[key];
if (!A) continue;
// an anchor is {obj, at} (a point on a part) or a function giving the world point (the octopus's)
let w;
if (typeof A === 'function') w = A();
else {
A.obj.updateWorldMatrix(true, false);
w = A.obj.localToWorld(p.copy(A.at));
}
const at = st.project(w);
const n2 = text[name]?.[0] ?? nice(name);
const s2 = text[name]?.[1] ?? niceSub(sub);
if (at && at[0] > VIEWPORT.x0 + 30 && at[0] < VIEWPORT.x1 - 30 && at[1] > VIEWPORT.y0 + 30 && at[1] < VIEWPORT.y1 - 60) pts.push({name: n2, sub: s2, at});
}
const mid = (VIEWPORT.x0 + VIEWPORT.x1) / 2;
const out = [];
const stack = (col, x, w) => {
let y = Math.max(VIEWPORT.y0 + 30, Math.min(col.length ? col[0].at[1] - 10 : 0, VIEWPORT.y1 - 90 - 44 * col.length));
for (const c of col) {
y = Math.max(y, Math.min(VIEWPORT.y1 - 90, c.at[1] - 10));
out.push({name: c.name, sub: c.sub, at: c.at, label: [x, y], w, o});
y += 44;
}
};
stack(pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x0 + 8, 'l');
stack(pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x1 - 8, 'r');
return out;
};
}
/** The operator's pointer on the pill buttons; button maps an act to its pill. */
export function makeCursor(ui, SCRIPT, button = (act) => (act === 'assemble' ? 'exploded' : act)) {
const EV = SCRIPT.filter((e) => e.t > 0 && ui.spots[button(e.act)]).map((e) => ({t: e.t, spot: ui.spots[button(e.act)]}));
const [RX, RY] = REST;
const WP = [[0, RX, RY + 40]];
let [px, py, pt] = [RX, RY + 40, 0];
EV.forEach((e) => {
const [x, y] = e.spot;
const travel = Math.min(0.6, 0.28 + Math.hypot(x - px, y - py) / 1000);
const arrive = e.t - 0.08;
WP.push([Math.max(pt + 0.01, arrive - travel), px, py]);
WP.push([arrive, x, y], [e.t + 0.16, x, y]);
[px, py, pt] = [x + 30, y + 46, e.t + 0.5];
WP.push([pt, px, py]);
});
WP.push([pt + 0.8, RX, RY + 60]);
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(20, 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.5) {
ring = 1 - (t - e.t) / 0.5;
[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};
};
}
+42
View File
@@ -0,0 +1,42 @@
// list the warm colours left on a green film's creature at time t (node sims/green/probe_warm.mjs <entry> <t> <global>)
import {pathToFileURL} from 'node:url';
import path from 'node:path';
import {CHROMIUM, CHROMIUM_ARGS, DIST, playwright} from '../../paths.mjs';
const [entry, t, glob] = process.argv.slice(2);
const {chromium} = playwright();
const browser = await chromium.launch({executablePath: CHROMIUM, args: CHROMIUM_ARGS});
const page = await browser.newPage({viewport: {width: 1600, height: 900}, deviceScaleFactor: 1});
await page.addInitScript(() => { window.__CAPTURE = true; window.__SIM_CONFIG = {}; });
await page.goto(pathToFileURL(path.join(DIST, `${entry}.html`)).href);
await page.waitForFunction(() => window.SIM && window.SIM.ready, null, {timeout: 60000});
const res = await page.evaluate(([t, glob]) => {
window.SIM.render(Number(t));
const out = {};
const warm = (c) => {
if (!c?.isColor) return false;
const k = Math.max(1e-6, c.r, c.g, c.b);
const r = c.r / k, g = c.g / k, b = c.b / k;
return r > 0.9 && b < 0.6 && g < 0.85 && r - b > 0.3;
};
const hex = (c) => [c.r, c.g, c.b].map((v) => v.toFixed(2)).join(',');
const scene = window[glob].st.scene ?? null;
const roots = [window[glob].oc?.root ?? window[glob].sp?.root ?? window[glob].fish?.root ?? window[glob].bee?.root];
if (scene) roots.push(scene);
for (const [ri, r] of roots.entries()) r.traverse((o) => {
if (o.isLight && warm(o.color)) out[`${ri} light ${o.type} ${hex(o.color)}`] = (out[`${ri} light ${o.type} ${hex(o.color)}`] ?? 0) + 1;
for (const m of [].concat(o.material || [])) for (const key of ['color', 'emissive', 'attenuationColor', 'sheenColor', 'specularColor']) if (warm(m[key])) { const id = `${ri} ${m.type} ${key} ${hex(m[key])} map:${!!m.map} emap:${!!m.emissiveMap} vc:${!!m.vertexColors}`; out[id] = (out[id] ?? 0) + 1; }
for (const [nm, at] of [['vertex', o.geometry?.attributes?.color], ['instance', o.instanceColor]]) {
if (!at) continue;
let n = 0;
const c = {isColor: true, r: 0, g: 0, b: 0};
for (let i = 0; i < at.count; i++) {
c.r = at.getX(i); c.g = at.getY(i); c.b = at.getZ(i);
if (warm(c)) n++;
}
if (n) out[`${ri} ${nm} colours warm: ${n} of ${at.count}`] = (out[`${ri} ${nm} colours warm: ${n} of ${at.count}`] ?? 0) + 1;
}
});
return out;
}, [t, glob]);
console.log(JSON.stringify(res, null, 1));
await browser.close();
+300
View File
@@ -0,0 +1,300 @@
import {clamp01, easeOutExpo, fmt, hash, smooth} from './util.js';
/**
* The director edits a sim to the music: hard cuts between wide and tight
* shots on bar lines, punch-ins on kicks, a shake and flash on the drop,
* glitches on stage changes, and big readable story captions on the beat.
*
* Beats come from cfg.beats (sims/beats.py output, injected by capture.mjs).
* Without music it runs on a synthetic grid (cfg.director.bpm) so live pages
* still feel edited.
*
* Shots crop the 3D render (crisp re-render of a sub-rectangle) when the sim
* uses kit/stage3d; otherwise they scale the target element with CSS.
* Sims can return `foci: [{x, y}]` (screen px) in their render info: tight
* shots frame those points.
*
* Story: cfg.story = [{at | bar | drop, text, sub, kind: 'hero'|'num', hold,
* from, to, prefix, suffix, tag}]. `drop` is in bars relative to the drop,
* `bar` counts bars from the clip start, `hold` is in beats. *word* gets the
* accent box.
*/
export const DIRECTOR = {
enabled: true,
bpm: 128,
drop: null,
hero: null,
// cut every N beats before / after the drop
cutBeats: [4, 2],
shots: [
{z: 1},
{z: 1.75, f: 0},
{z: 1.3, f: 1},
{z: 2.2, f: 2},
{z: 1.12, f: 0},
{z: 1.6, f: 1},
],
punch: [0.03, 0.07],
shake: 1,
flash: 1,
glitch: 1,
target: '#gl',
};
const before = (arr, t) => {
let lo = 0;
let hi = arr.length;
while (lo < hi) {
const m = (lo + hi) >> 1;
if (arr[m] <= t) lo = m + 1;
else hi = m;
}
return lo - 1;
};
export function createDirector(app, cfg) {
const d = {...DIRECTOR, ...(cfg.director || {})};
const D = cfg.duration;
const music = cfg.beats && cfg.beats.beats && cfg.beats.beats.length > 4;
const spb = music ? 60 / cfg.beats.bpm : 60 / d.bpm;
const beats = music ? cfg.beats.beats : Array.from({length: Math.ceil(D / spb) + 8}, (_, i) => i * spb);
// pad the grid past both ends so lookups never fall off
while (beats[0] > 0) beats.unshift(beats[0] - spb);
while (beats[beats.length - 1] < D + 4 * spb) beats.push(beats[beats.length - 1] + spb);
let downs = music && cfg.beats.downbeats.length ? cfg.beats.downbeats.slice() : beats.filter((_, i) => i % 4 === 0);
while (downs[0] > 0) downs.unshift(downs[0] - 4 * spb);
while (downs[downs.length - 1] < D + 8 * spb) downs.push(downs[downs.length - 1] + 4 * spb);
const kicks = music ? cfg.beats.kicks : beats.map((b) => [b, 0.8]);
const kickT = kicks.map((k) => k[0]);
const energy = music ? cfg.beats.barEnergy : null;
const drop = (music && cfg.beats.drop) ?? d.drop ?? Math.round((0.4 * D) / (4 * spb)) * 4 * spb;
const dropBar = before(downs, drop + 0.01);
const barTime = (b) => downs[Math.max(0, Math.min(downs.length - 1, b))];
// ---- time warp: the sim's hero moment lands on the drop
const warp = (t) => {
if (d.hero == null || !d.enabled) return t;
const h = d.hero;
if (t <= drop) return (t / drop) * h;
return h + ((t - drop) / (D - drop)) * (D - h);
};
const beat = (t) => {
const sh = shotAt(t);
const bi = before(beats, t);
const b0 = beats[Math.max(0, bi)];
const b1 = beats[bi + 1] ?? b0 + spb;
const ri = before(downs, t);
const r0 = downs[Math.max(0, ri)];
const r1 = downs[ri + 1] ?? r0 + 4 * spb;
const ki = before(kickT, t);
const kick = ki >= 0 ? kicks[ki][1] * Math.exp(-(t - kicks[ki][0]) / 0.11) : 0;
const down = Math.exp(-(t - r0) / 0.18);
return {
music,
bpm: 60 / spb,
beat: bi,
beatPhase: clamp01((t - b0) / (b1 - b0)),
bar: ri,
barPhase: clamp01((t - r0) / (r1 - r0)),
kick,
down,
energy: energy ? energy[Math.max(0, Math.min(energy.length - 1, ri))] ?? 1 : 1,
drop,
sinceDrop: t - drop,
isDrop: t >= drop,
// current shot: sims may change camera angle per shot index
shot: sh.k,
shotZ: sh.shot.z || 1,
};
};
// ---- story timing
const story = (cfg.story || []).map((s, i) => {
const start = s.at ?? (s.bar != null ? barTime(s.bar) : s.drop != null ? barTime(dropBar + s.drop) : 0);
const b0 = before(beats, start + 0.02);
const hold = s.hold ?? 8;
const end = s.end ?? beats[Math.min(beats.length - 1, b0 + hold)] ?? start + hold * spb;
return {...s, i, start, end, b0};
});
// ---- DOM layers
app.insertAdjacentHTML(
'beforeend',
`<canvas class="dir-glitch"></canvas><div class="dir-flash"></div><div class="dir-story"></div>`,
);
const gcv = app.querySelector('.dir-glitch');
const gctx = gcv.getContext('2d');
const flash = app.querySelector('.dir-flash');
const storyEl = app.querySelector('.dir-story');
let foci = [];
let crop = {z: 1, x0: 0, y0: 0};
let built = -1;
let parts = null;
const stageCuts = (cfg.stages || []).map((s) => s.at).filter((a) => a > 0.2);
const dropBeat = before(beats, drop + 0.01);
function shotAt(t) {
const bi = before(beats, t);
const isDrop = t >= drop;
const every = isDrop ? d.cutBeats[1] : d.cutBeats[0];
// the first beats of the drop always open wide
if (isDrop && bi - dropBeat < every) return {shot: d.shots[0], k: 0};
const rel = isDrop ? bi - dropBeat : bi - before(beats, 0.01);
const k = Math.floor(rel / every) + (isDrop ? 1000 : 0);
return {shot: d.shots[((k % d.shots.length) + d.shots.length) % d.shots.length], k};
}
const target = () => document.querySelector(d.target);
return {
warp,
beat,
/** Before the sim renders: set this frame's crop. */
pre(t) {
if (!d.enabled) return;
const {shot} = shotAt(t);
const b = beat(t);
const punch = 1 + (b.isDrop ? d.punch[1] : d.punch[0]) * b.kick;
const drift = 1 + 0.035 * b.barPhase;
let z = (shot.z || 1) * punch * (shot.z > 1 ? drift : 1);
const vw = innerWidth;
const vh = innerHeight;
let f = {x: vw / 2, y: vh / 2};
if (shot.z > 1 && foci.length) f = foci[(shot.f ?? 0) % foci.length];
else if (window.__STAGE) {
const vp = window.__STAGE.hudViewport();
f = {x: vw / 2, y: (vp.top + vh - vp.bottom) / 2};
}
// drop shake (decays over ~0.6 s)
const sk = d.shake * (b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.25) : 0);
const sx = sk * (hash(t * 91.7) - 0.5) * 26;
const sy = sk * (hash(t * 53.3 + 7) - 0.5) * 26;
const st = window.__STAGE;
if (st) {
crop = st.setCrop(z, f.x + sx, f.y + sy);
} else {
const el = target();
if (el) {
el.style.transformOrigin = `${f.x}px ${f.y}px`;
el.style.transform = `translate(${sx}px, ${sy}px) scale(${z})`;
}
crop = {z: 1, x0: 0, y0: 0};
}
},
/** After the sim renders: remember its foci, draw overlays and the story. */
post(t, info = {}) {
if (!d.enabled) return;
if (info.foci && info.foci.length) {
// convert from this frame's cropped screen back to base screen coords
foci = info.foci.map((p) => ({x: crop.x0 + p.x / crop.z, y: crop.y0 + p.y / crop.z}));
}
const b = beat(t);
const vw = innerWidth;
const vh = innerHeight;
// flash: accent bloom on downbeats after the drop, white hit on the drop
const dropHit = b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.22) : 0;
const onBar = b.isDrop ? 0.16 * b.down * b.energy : 0;
flash.style.opacity = String(d.flash * Math.min(0.85, dropHit * 0.7 + onBar));
// glitch: 3 frames around each stage change and the drop
const gl = [...stageCuts, b.drop].some((c) => t >= c - 0.03 && t < c + 0.1);
if (gcv.width !== vw || gcv.height !== vh) {
gcv.width = vw;
gcv.height = vh;
}
gctx.clearRect(0, 0, vw, vh);
const src = document.getElementById('gl');
if (gl && d.glitch && src && src.width) {
const n = 7;
for (let i = 0; i < n; i++) {
const y = Math.floor(hash(t * 13 + i) * vh);
const h = 6 + Math.floor(hash(t * 7 + i * 3) * 60);
const dx = (hash(t * 31 + i * 5) - 0.5) * 120;
const sx = src.width / vw;
gctx.globalAlpha = 0.9;
gctx.drawImage(src, 0, y * sx, src.width, h * sx, dx, y, vw, h);
}
gctx.globalAlpha = 0.25;
gctx.fillStyle = cfg.accent;
gctx.fillRect(0, Math.floor(hash(t * 3.3) * vh), vw, 3 + hash(t) * 10);
gctx.globalAlpha = 1;
}
// ---- story
const cur = story.find((s) => t >= s.start && t < s.end);
if (!cur) {
storyEl.style.opacity = '0';
return;
}
if (built !== cur.i) {
built = cur.i;
const words = (cur.text || '').split(/\s+/).filter(Boolean);
storyEl.innerHTML = `<div class="cap ${cur.kind || 'hero'}">
${cur.tag ? `<div class="cap-tag">${cur.tag}</div>` : ''}
<div class="cap-main">${
cur.kind === 'num'
? `<span class="w"><span class="n"></span></span>`
: (() => {
// *several words* → each word gets the accent box
let on = false;
return words
.map((w) => {
const open = w.startsWith('*');
const close = w.endsWith('*') && (w.length > 1 || on);
if (open) on = true;
const hl = on;
if (close) on = false;
return `<span class="w${hl ? ' hl' : ''}">${w.replace(/^\*|\*$/g, '')}</span>`;
})
.join(' ');
})()
}</div>
${cur.sub ? `<div class="cap-sub"></div>` : ''}
</div>`;
parts = {
words: [...storyEl.querySelectorAll('.w')],
num: storyEl.querySelector('.n'),
sub: storyEl.querySelector('.cap-sub'),
main: storyEl.querySelector('.cap-main'),
};
}
const vp = window.__HUDVP ? window.__HUDVP() : {top: 0, bottom: 0};
storyEl.style.top = `${vp.top}px`;
storyEl.style.bottom = `${vp.bottom}px`;
storyEl.style.opacity = '1';
const ex = clamp01((t - (cur.end - 0.18)) / 0.18);
// words slam in on successive beats (half-beats if the text is long)
const step = parts.words.length > 4 ? 0.5 : 1;
let lastIn = cur.start;
parts.words.forEach((w, i) => {
const bi = cur.b0 + i * step;
const wt = Math.floor(bi) === bi ? beats[bi] : (beats[Math.floor(bi)] + beats[Math.ceil(bi)]) / 2;
const k = cur.start <= 0.001 ? 1 : clamp01((t - wt) / 0.12);
lastIn = Math.max(lastIn, wt);
const s = 1 + 0.35 * (1 - easeOutExpo(k)) + 0.03 * b.kick;
w.style.opacity = String(k > 0 ? 1 : 0);
w.style.transform = `scale(${s}) translateY(${ex * -0.25}em)`;
w.style.filter = k < 1 ? `blur(${(1 - k) * 8}px)` : 'none';
});
if (cur.kind === 'num' && parts.num) {
const roll = cur.roll ?? 6;
const k = easeOutExpo(clamp01((t - cur.start) / (roll * spb)));
const v = cur.from + (cur.to - cur.from) * k;
parts.num.textContent = `${cur.prefix ?? ''}${fmt(v, cur.decimals ?? 0)}${cur.suffix ?? ''}`;
lastIn = cur.start + roll * spb * 0.6;
}
if (parts.sub) {
const n = Math.floor(Math.max(0, t - lastIn - 0.15) / 0.022);
parts.sub.textContent = cur.sub.slice(0, n);
}
parts.main.style.opacity = String(1 - ex);
if (parts.sub) parts.sub.style.opacity = String(1 - ex);
storyEl.firstElementChild.style.transform = `translateX(${ex * (hash(t * 41) - 0.5) * 40}px)`;
},
};
}
+194
View File
@@ -0,0 +1,194 @@
import {clamp01, pad} from './util.js';
/**
* Instrument-style HUD: header with stage/command/clock, annotations over the
* viewport, a terminal log and a side panel (minimap + stats) at the bottom.
* Everything is derived from `t` and the config's stages, so it's deterministic.
*
* cfg.stages: [{at, name, cmd, logs: [string]}]. A log line starting with "!"
* is highlighted in the accent. {key} tokens are replaced from `facts`.
*/
export function createHud(root, cfg) {
const h = cfg.hud;
root.insertAdjacentHTML(
'beforeend',
`<div class="hud">
<div class="ann"></div>
<div class="wm"></div>
<div class="hdr">
<div class="row row1">
<div class="title"><i class="bar"></i><span class="t"></span></div>
<div class="sub"></div>
<div class="right"></div>
</div>
<div class="row row2">
<div class="stage accent"></div>
<div class="cmd"></div>
<div class="time accent"></div>
</div>
<div class="prog"><i></i></div>
</div>
<div class="bot">
<div class="term">
<div class="thead">
<span class="host accent"></span><span class="path"></span>
<span class="status accent"><i></i><span></span></span>
</div>
<div class="prompt"></div>
<div class="logs"></div>
<div class="tfoot"></div>
</div>
<div class="side">
<div class="shead accent"></div>
<canvas class="mini"></canvas>
<div class="stats"></div>
<div class="sfoot"></div>
</div>
<div class="baseline"><i></i></div>
</div>
</div>`,
);
const $ = (s) => root.querySelector(s);
const el = {
hud: $('.hud'),
ann: $('.ann'),
stage: $('.row2 .stage'),
cmd: $('.row2 .cmd'),
time: $('.row2 .time'),
prog: $('.prog i'),
prompt: $('.prompt'),
logs: $('.logs'),
tfoot: $('.tfoot'),
status: $('.thead .status span'),
stats: $('.stats'),
sfoot: $('.sfoot'),
base: $('.baseline i'),
mini: $('.mini'),
};
$('.title .t').textContent = h.title;
$('.sub').textContent = h.subtitle;
$('.right').textContent = h.right;
$('.wm').textContent = cfg.watermark;
$('.thead .host').textContent = h.host;
$('.thead .path').textContent = h.path;
$('.shead').textContent = h.sideTitle;
const stages = cfg.stages;
const D = cfg.duration;
const TYPE_CMD = 0.028;
const TYPE_LOG = 0.011;
// Log line schedule: each stage types its command, then its lines spread
// over the stage.
const lines = [];
stages.forEach((s, i) => {
const end = i + 1 < stages.length ? stages[i + 1].at : D;
const t0 = s.at + 0.25 + s.cmd.length * TYPE_CMD + 0.2;
const n = s.logs.length;
const gap = Math.min(0.8, Math.max(0.22, (end - t0 - 0.4) / Math.max(1, n)));
s.logs.forEach((text, j) => lines.push({at: t0 + j * gap, text, stage: i}));
});
const stageAt = (t) => {
let i = 0;
while (i + 1 < stages.length && stages[i + 1].at <= t) i++;
return i;
};
const fill = (text, facts) => text.replace(/\{(\w+)\}/g, (m, k) => (k in facts ? facts[k] : m));
const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
let lastStats = '';
let lastLogs = '';
const annPool = [];
return {
minimap: el.mini,
stageAt,
setVisible(v) {
el.hud.classList.toggle('hidden', !v);
},
/** Viewport between header and bottom panel, in CSS px. */
viewport() {
const fs = parseFloat(getComputedStyle(document.documentElement).fontSize);
return {top: 13.4 * fs, bottom: 30.5 * fs};
},
render(t, frame, info = {}) {
const facts = {...cfg.facts, ...(info.facts || {})};
const si = stageAt(t);
const s = stages[si];
const dt = t - s.at;
const typed = Math.floor(Math.max(0, dt - 0.15) / TYPE_CMD);
const cmd = fill(s.cmd, facts);
const typing = typed < cmd.length;
const caretOn = typing || Math.floor(t * 2.4) % 2 === 0;
el.stage.textContent = `${pad(si + 1, 2)} / ${s.name}`;
el.cmd.textContent = cmd.slice(0, typed);
el.time.textContent = `${t.toFixed(2).padStart(5, '0')} / ${D}`;
el.prog.style.width = `${(clamp01(t / D) * 100).toFixed(2)}%`;
el.base.style.width = `${(clamp01(dt / ((stages[si + 1]?.at ?? D) - s.at)) * 100).toFixed(2)}%`;
el.prompt.innerHTML = `<span class="accent">&gt;</span> ${esc(cmd.slice(0, typed))}${
caretOn ? '<i class="caret"></i>' : ''
}`;
const shown = lines.filter((l) => l.at <= t);
const rows = shown.slice(-h.logRows);
const offset = shown.length - rows.length;
const html = rows
.map((l, j) => {
const full = fill(l.text, facts);
const hl = full.startsWith('!');
const text = hl ? full.slice(1) : full;
const n = Math.floor((t - l.at) / TYPE_LOG);
const isLast = j === rows.length - 1 && n < text.length;
return `<div><span class="ln">${pad(offset + j, 3)}</span><span class="${hl ? 'hl' : ''}">${esc(
text.slice(0, n),
)}</span>${isLast ? '<i class="caret"></i>' : ''}</div>`;
})
.join('');
if (html !== lastLogs) {
el.logs.innerHTML = html;
lastLogs = html;
}
el.tfoot.textContent = `frame ${pad(frame, 4)} delta ${pad((dt * 7.3) % 100, 2)} / ${s.name.toLowerCase()}`;
el.status.textContent = info.status ?? (t >= D - 0.05 ? 'DONE' : 'RUNNING');
el.sfoot.textContent = `view ${pad(si + 1, 2)} / ${pad(h.views, 2)} seed ${cfg.seed} · t+${dt.toFixed(2)}s`;
const stats = (info.stats || []).map((x) => `<div>${esc(x.label)}<b>${esc(String(x.value))}</b></div>`).join('');
if (stats !== lastStats) {
el.stats.innerHTML = stats;
lastStats = stats;
}
const anns = info.annotations || [];
while (annPool.length < anns.length) {
const d = document.createElement('div');
el.ann.appendChild(d);
annPool.push(d);
}
annPool.forEach((d, i) => {
const a = anns[i];
if (!a) {
d.style.display = 'none';
return;
}
d.style.display = '';
d.className = a.cls || '';
d.style.left = `${a.x}px`;
d.style.top = `${a.y}px`;
d.style.opacity = a.opacity ?? 1;
if (a.html !== undefined) d.innerHTML = a.html;
else d.textContent = a.text;
// keep labels inside the viewport (between header and bottom panel)
const vp = this.viewport();
const w = d.offsetWidth;
const hh = d.offsetHeight;
const x = Math.min(Math.max(a.x, 8), innerWidth - w - 40);
const y = Math.min(Math.max(a.y, vp.top + hh / 2 + 8), innerHeight - vp.bottom - hh / 2 - 8);
d.style.left = `${x}px`;
d.style.top = `${y}px`;
});
},
};
}
+168
View File
@@ -0,0 +1,168 @@
import {createDirector, DIRECTOR} from './director.js';
import {createHud} from './hud.js';
import {merge} from './util.js';
/** Config every sim starts from; a sim's defaults and the post config merge over it. */
export const BASE = {
duration: 30,
fps: 30,
seed: 746337560,
theme: 'dark',
accent: '#f2b632',
watermark: '',
hud: {
title: 'AGENT MESH',
subtitle: '/ SIMULATION',
right: 'VISUAL SIMULATION',
host: 'agent@local',
path: '~/session-01',
sideTitle: 'LOCAL VIEW',
logRows: 5,
views: 10,
},
stages: [{at: 0, name: 'RUN', cmd: 'run', logs: []}],
facts: {},
director: DIRECTOR,
story: [],
beats: null,
};
const fromBase64 = (s) => decodeURIComponent(escape(atob(s.replace(/-/g, '+').replace(/_/g, '/'))));
/**
* Config sources, later wins: BASE, the sim's defaults, window.__SIM_CONFIG
* (injected by the capture script), ?config=<base64 json>, and a few plain
* query params (?title= ?accent= ?seed= ?theme= ?duration=).
*/
export function loadConfig(defaults) {
let cfg = merge(BASE, defaults);
if (window.__SIM_CONFIG) cfg = merge(cfg, window.__SIM_CONFIG);
const q = new URLSearchParams(location.search);
if (q.get('config')) {
try {
cfg = merge(cfg, JSON.parse(fromBase64(q.get('config'))));
} catch (e) {
console.warn('bad ?config', e);
}
}
if (q.get('title')) cfg = merge(cfg, {hud: {title: q.get('title')}});
if (q.get('accent')) cfg.accent = '#' + q.get('accent').replace('#', '');
if (q.get('seed')) cfg.seed = Number(q.get('seed'));
if (q.get('theme')) cfg.theme = q.get('theme');
if (q.get('duration')) cfg.duration = Number(q.get('duration'));
if (q.has('nodirector')) cfg.director = {...cfg.director, enabled: false};
return cfg;
}
/**
* Boots a sim. `setup({cfg, canvas, hud, capture})` returns (or resolves to)
* `{render(t) -> hudInfo, resize()}`. render must be a pure function of t.
*
* Live mode loops in real time. Keys: space pause, h hide HUD, f fullscreen,
* r restart, ←/→ seek 2 s, 1–9 jump to a stage.
* Capture mode (?capture or window.__CAPTURE) exposes window.SIM.render(t).
*/
export async function runSim(defaults, setup) {
const cfg = loadConfig(defaults);
const q = new URLSearchParams(location.search);
const capture = !!window.__CAPTURE || q.has('capture');
const root = document.documentElement;
root.dataset.theme = cfg.theme;
root.style.setProperty('--accent', cfg.accent);
document.title = `${cfg.hud.title} ${cfg.hud.subtitle}`.trim();
const scale = () => {
root.style.fontSize = `${10 * Math.min(innerWidth / 1080, innerHeight / 1350)}px`;
};
scale();
const app = document.getElementById('app');
const canvas = document.createElement('canvas');
canvas.id = 'gl';
app.appendChild(canvas);
// cfg.hud.enabled === false: no instrument chrome (UI demos, infographics).
const hud =
cfg.hud.enabled === false
? {minimap: null, stageAt: () => 0, setVisible() {}, viewport: () => ({top: 0, bottom: 0}), render() {}}
: createHud(app, cfg);
await Promise.all([
document.fonts.load('400 20px "JetBrains Mono"'),
document.fonts.load('600 20px "JetBrains Mono"'),
document.fonts.load('800 20px "Inter"'),
]).catch(() => {});
window.__HUDVP = () => hud.viewport();
const sim = await setup({cfg, canvas, hud, capture});
if (!capture && sim.warm) await sim.warm();
const dir = createDirector(app, cfg);
// The sim and HUD run on warped time (hero lands on the drop); the
// director's cuts, punches and story run on real (music) time.
const draw = (t) => {
const tw = dir.warp(t);
dir.pre(t);
const info = sim.render(tw, dir.beat(t)) || {};
hud.render(tw, Math.round(t * cfg.fps), info);
dir.post(t, info);
};
let cur = 0;
let paused = false;
const resize = () => {
scale();
sim.resize?.();
if (paused || capture) draw(cur);
};
addEventListener('resize', resize);
resize();
window.SIM = {
cfg,
duration: cfg.duration,
fps: cfg.fps,
ready: true,
render: (t) => {
cur = t;
draw(t);
},
};
if (capture) {
draw(0);
return;
}
let start = performance.now();
const seek = (t) => {
cur = ((t % cfg.duration) + cfg.duration) % cfg.duration;
start = performance.now() - cur * 1000;
};
let hudOn = true;
addEventListener('keydown', (e) => {
if (e.key === ' ') {
paused = !paused;
if (!paused) seek(cur);
} else if (e.key === 'h') {
hudOn = !hudOn;
hud.setVisible(hudOn);
} else if (e.key === 'f') {
if (document.fullscreenElement) document.exitFullscreen();
else document.documentElement.requestFullscreen();
} else if (e.key === 'r') seek(0);
else if (e.key === 'ArrowRight') seek(cur + 2);
else if (e.key === 'ArrowLeft') seek(cur - 2);
else if (/^[1-9]$/.test(e.key) && cfg.stages[+e.key - 1]) seek(Math.max(0, cfg.stages[+e.key - 1].at));
else return;
e.preventDefault();
});
const loop = (now) => {
if (!paused) cur = Math.max(0, (now - start) / 1000) % cfg.duration;
draw(cur);
// the site page swaps its poster for the canvas on this
if (!window.SIM_SHOWN) {
window.SIM_SHOWN = true;
dispatchEvent(new Event('simframe'));
}
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);
}
+114
View File
@@ -0,0 +1,114 @@
import * as THREE from 'three';
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
import {UnrealBloomPass} from 'three/addons/postprocessing/UnrealBloomPass.js';
/**
* Renderer + scene + camera + bloom. The camera's projection centre is shifted
* to the middle of the HUD viewport (between header and bottom panel), so the
* subject is centred in the visible area, not behind the terminal.
*/
export function createStage(canvas, hud, opts = {}) {
const {
bg = '#09090a',
fov = 38,
bloom = {strength: 0.85, radius: 0.55, threshold: 0.62},
capture = false,
exposure = 1,
} = opts;
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: false,
preserveDrawingBuffer: true,
powerPreference: 'high-performance',
});
renderer.setClearColor(new THREE.Color(bg), 1);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = exposure;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
scene.background = new THREE.Color(bg);
const camera = new THREE.PerspectiveCamera(fov, 1, 0.5, 6000);
const target = new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 4});
const composer = new EffectComposer(renderer, target);
composer.addPass(new RenderPass(scene, camera));
const bloomPass = new UnrealBloomPass(new THREE.Vector2(4, 4), bloom.strength, bloom.radius, bloom.threshold);
composer.addPass(bloomPass);
composer.addPass(new OutputPass());
const size = {w: 1, h: 1, centre: 0.5};
// Director crop: render a sub-rectangle of the base view (crisp punch-ins).
const crop = {z: 1, fx: 0, fy: 0, x0: 0, y0: 0};
const applyView = () => {
const {w, h, centre} = size;
const offY = h / 2 - centre;
if (crop.z <= 1.0001) {
crop.x0 = 0;
crop.y0 = 0;
camera.setViewOffset(w, h, 0, offY, w, h);
} else {
const cw = w / crop.z;
const ch = h / crop.z;
crop.x0 = Math.min(Math.max(crop.fx - cw / 2, 0), w - cw);
crop.y0 = Math.min(Math.max(crop.fy - ch / 2, 0), h - ch);
camera.setViewOffset(w, h, crop.x0, offY + crop.y0, cw, ch);
}
camera.updateProjectionMatrix();
};
// opts.pr fixes the pixel ratio (a capture that wants the 3D at the output resolution, a page that adapts it)
let prFixed = opts.pr;
const resize = () => {
const w = canvas.clientWidth || innerWidth;
const h = canvas.clientHeight || innerHeight;
const pr = prFixed ?? (capture ? 1 : Math.min(devicePixelRatio || 1, 2));
size.w = w;
size.h = h;
renderer.setPixelRatio(pr);
renderer.setSize(w, h, false);
composer.setPixelRatio(pr);
composer.setSize(w, h);
const vp = hud.viewport();
size.centre = (vp.top + (h - vp.bottom)) / 2;
camera.aspect = w / h;
applyView();
};
/** Zoom z around base-screen point (fx, fy); returns {z, x0, y0} for mapping back. */
const setCrop = (z, fx, fy) => {
crop.z = Math.max(1, z);
crop.fx = fx;
crop.fy = fy;
applyView();
return {z: crop.z, x0: crop.x0, y0: crop.y0};
};
const v = new THREE.Vector3();
/** World point → CSS px on screen, plus whether it's in front of the camera. */
const project = (p) => {
v.set(p[0] ?? p.x, p[1] ?? p.y, p[2] ?? p.z).project(camera);
return {x: (v.x * 0.5 + 0.5) * size.w, y: (-v.y * 0.5 + 0.5) * size.h, visible: v.z < 1};
};
const st = {
THREE,
renderer,
scene,
camera,
composer,
bloomPass,
size,
resize,
setPixelRatio: (v) => {
prFixed = v;
resize();
},
project,
render: () => composer.render(),
setCrop,
hudViewport: () => hud.viewport(),
};
window.__STAGE = st;
return st;
}
+137
View File
@@ -0,0 +1,137 @@
/* HUD chrome shared by every sim. 1rem = 10px at the 1080x1350 reference
size; runtime sets html font-size from the viewport so it scales. */
:root {
--bg: #09090a;
--fg: #ece6d6;
--dim: rgba(236, 230, 214, 0.64);
--mute: rgba(236, 230, 214, 0.38);
--faint: rgba(236, 230, 214, 0.16);
--line: rgba(236, 230, 214, 0.14);
--panel: rgba(9, 9, 10, 0.9);
--accent: #f2b632;
--top: 13.4rem;
--bot: 30.5rem;
}
:root[data-theme='light'] {
--bg: #f3f2ee;
--fg: #151515;
--dim: rgba(21, 21, 21, 0.66);
--mute: rgba(21, 21, 21, 0.42);
--faint: rgba(21, 21, 21, 0.16);
--line: rgba(21, 21, 21, 0.16);
--panel: rgba(243, 242, 238, 0.93);
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; background: var(--bg); overflow: hidden; }
#app {
position: fixed; inset: 0; color: var(--fg);
font-family: 'JetBrains Mono', ui-monospace, monospace;
font-variant-ligatures: none; -webkit-font-smoothing: antialiased;
}
#gl { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.hud { position: absolute; inset: 0; pointer-events: none; }
.hud.hidden { display: none; }
.accent { color: var(--accent); }
/* header */
.hdr {
position: absolute; left: 0; right: 0; top: 0; height: var(--top);
padding: 2.4rem 2.8rem 0;
background: linear-gradient(var(--bg) 0%, var(--bg) 78%, transparent 100%);
}
.row { display: flex; align-items: baseline; white-space: nowrap; }
.row1 { gap: 5.6rem; }
.title { display: flex; align-items: center; gap: 1.3rem; font-size: 3.6rem; font-weight: 600; letter-spacing: 0.04em; }
.title .bar { display: inline-block; width: 0.75rem; height: 3.6rem; background: var(--accent); }
.sub { font-size: 1.75rem; color: var(--dim); letter-spacing: 0.08em; }
.right { margin-left: auto; font-size: 1.6rem; color: var(--dim); letter-spacing: 0.1em; }
.row2 { margin-top: 2rem; font-size: 1.95rem; }
.row2 .stage { width: 21rem; letter-spacing: 0.05em; }
.row2 .cmd { color: var(--fg); }
.row2 .time { margin-left: auto; letter-spacing: 0.05em; }
.prog { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 1.2rem; height: 0.35rem; }
.prog i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
/* viewport overlays */
.ann { position: absolute; inset: 0; overflow: hidden; }
.ann div {
position: absolute; transform: translate(1.4rem, -50%); white-space: nowrap;
font-size: 1.7rem; letter-spacing: 0.04em; color: var(--fg);
text-shadow: 0 0 0.6rem var(--bg), 0 0 1.2rem var(--bg);
}
.ann div.a { color: var(--accent); }
.ann div.box {
padding: 0.8rem 1.1rem; border: 1px solid var(--line); background: var(--panel);
text-shadow: none; line-height: 1.45; font-size: 1.55rem;
}
.ann div.box b { color: var(--accent); font-weight: 600; }
.wm {
position: absolute; right: 3rem; bottom: calc(var(--bot) + 1.6rem);
font-size: 2.3rem; letter-spacing: 0.06em; color: var(--fg); opacity: 0.3;
}
/* bottom panel */
.bot {
position: absolute; left: 0; right: 0; bottom: 0; height: var(--bot);
display: flex; border-top: 1px solid var(--line); background: var(--panel);
padding: 2rem 2.8rem 1.6rem;
}
.term { flex: 1; min-width: 0; display: flex; flex-direction: column; padding-right: 2.6rem; }
.thead { display: flex; align-items: baseline; gap: 2.4rem; font-size: 1.75rem; white-space: nowrap; }
.thead .host { font-size: 2.1rem; }
.thead .path { color: var(--dim); }
.thead .status { margin-left: auto; font-size: 1.5rem; letter-spacing: 0.1em; display: flex; align-items: center; gap: 0.9rem; }
.thead .status i { width: 1rem; height: 1rem; border-radius: 50%; background: var(--accent); display: inline-block; }
.prompt { margin-top: 1.9rem; font-size: 2.2rem; white-space: nowrap; overflow: hidden; }
.logs { margin-top: 1.1rem; font-size: 1.85rem; line-height: 1.52; flex: 1; overflow: hidden; }
.logs div { white-space: nowrap; overflow: hidden; text-overflow: clip; }
.logs .ln { color: var(--mute); display: inline-block; width: 6.4rem; }
.logs .hl { color: var(--accent); }
.caret { display: inline-block; width: 0.95em; height: 1.05em; vertical-align: -0.15em; background: var(--accent); margin-left: 0.15em; }
.tfoot { font-size: 1.35rem; color: var(--mute); white-space: nowrap; letter-spacing: 0.04em; }
.side {
width: 31%; border-left: 1px solid var(--line); padding-left: 2.2rem;
display: flex; flex-direction: column;
}
.shead { font-size: 1.45rem; letter-spacing: 0.12em; }
.mini { width: 100%; flex: 1; min-height: 0; display: block; margin: 0.8rem 0; }
.stats { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem 1.4rem; font-size: 1.35rem; color: var(--mute); }
.stats b { display: block; font-size: 2rem; color: var(--fg); font-weight: 600; letter-spacing: 0.02em; }
.sfoot { margin-top: 0.8rem; font-size: 1.3rem; color: var(--mute); letter-spacing: 0.05em; }
.baseline { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 0.9rem; height: 0.25rem; background: var(--line); }
.baseline i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
/* director layers */
.dir-glitch { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
.dir-flash {
position: absolute; inset: 0; pointer-events: none; opacity: 0; mix-blend-mode: screen;
background: radial-gradient(ellipse 75% 55% at 50% 45%, var(--accent) 0%, transparent 70%), rgba(255,255,255,0.18);
}
.dir-story {
position: absolute; left: 0; right: 0; top: 0; bottom: 0; pointer-events: none;
display: flex; align-items: flex-end; justify-content: center; padding: 0 4.5rem 6rem; opacity: 0;
}
.cap { text-align: center; max-width: 96rem; position: relative; }
.cap::before {
content: ''; position: absolute; inset: -6rem -10rem; z-index: -1;
background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(0,0,0,0.62) 0%, rgba(0,0,0,0) 100%);
}
:root[data-theme='light'] .cap::before { background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(243,242,238,0.8) 0%, rgba(243,242,238,0) 100%); }
.cap-main {
font-family: 'Inter', 'Inter Variable', system-ui, sans-serif; font-weight: 800;
font-size: 11.5rem; line-height: 0.98; letter-spacing: -0.035em; color: var(--fg);
text-shadow: 0 0.4rem 2.4rem rgba(0,0,0,0.55);
}
.cap.num .cap-main { font-size: 15rem; font-variant-numeric: tabular-nums; letter-spacing: -0.045em; }
.cap-main .w { display: inline-block; transform-origin: 50% 70%; }
.cap-main .w.hl { background: var(--accent); color: #0a0a0a; padding: 0 0.14em; text-shadow: none; border-radius: 0.06em; }
.cap-sub {
margin-top: 2rem; font-size: 2.7rem; letter-spacing: 0.08em; text-transform: uppercase;
color: var(--fg); opacity: 0.85; min-height: 1.3em;
}
.cap-tag {
display: inline-block; margin-bottom: 1.8rem; padding: 0.5rem 1.2rem; font-size: 2.2rem; letter-spacing: 0.12em;
border: 1px solid var(--accent); color: var(--accent); background: rgba(0,0,0,0.5);
}
+79
View File
@@ -0,0 +1,79 @@
// Small pure helpers shared by every sim. Everything animated must be a pure
// function of `t` (seconds) so live playback and frame capture match.
export const clamp01 = (x) => Math.min(1, Math.max(0, x));
export const lerp = (a, b, k) => a + (b - a) * k;
export const smooth = (x) => {
const k = clamp01(x);
return k * k * (3 - 2 * k);
};
export const easeOutCubic = (x) => 1 - Math.pow(1 - clamp01(x), 3);
export const easeInOutCubic = (x) => {
const k = clamp01(x);
return k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;
};
export const easeOutExpo = (x) => (x >= 1 ? 1 : 1 - Math.pow(2, -10 * clamp01(x)));
export const easeOutBack = (x, s = 1.7) => {
const k = clamp01(x) - 1;
return 1 + (s + 1) * k * k * k + s * k * k;
};
/** 0..1 progress of t between t0 and t1, eased. */
export const prog = (t, t0, t1, ease = easeInOutCubic) => ease((t - t0) / (t1 - t0));
/** Seeded PRNG (mulberry32). Same seed → same sequence. */
export const rng = (seed) => {
let s = seed >>> 0;
return () => {
s = (s + 0x6d2b79f5) >>> 0;
let x = s;
x = Math.imul(x ^ (x >>> 15), x | 1);
x ^= x + Math.imul(x ^ (x >>> 7), x | 61);
return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
};
};
/** Stateless hash noise in [0,1). */
export const hash = (n) => {
const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;
return x - Math.floor(x);
};
/** Random unit vector from a PRNG. */
export const randDir = (r) => {
const u = r() * 2 - 1;
const a = r() * Math.PI * 2;
const s = Math.sqrt(1 - u * u);
return [s * Math.cos(a), u, s * Math.sin(a)];
};
/**
* Keyframed value: keys = [[t, value], ...] with numbers or arrays of numbers.
* Eased between keys, held outside.
*/
export const keyed = (keys, t, ease = easeInOutCubic) => {
if (t <= keys[0][0]) return keys[0][1];
for (let i = 0; i < keys.length - 1; i++) {
const [t0, v0] = keys[i];
const [t1, v1] = keys[i + 1];
if (t <= t1) {
const k = ease((t - t0) / (t1 - t0));
return Array.isArray(v0) ? v0.map((v, j) => lerp(v, v1[j], k)) : lerp(v0, v1, k);
}
}
return keys[keys.length - 1][1];
};
export const fmt = (n, d = 0) =>
Number(n).toLocaleString('en-US', {minimumFractionDigits: d, maximumFractionDigits: d});
export const pad = (n, w) => String(Math.max(0, Math.floor(n))).padStart(w, '0');
/** Deep merge plain objects; arrays and scalars from `b` replace `a`. */
export const merge = (a, b) => {
if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b;
const out = {...a};
for (const k of Object.keys(b)) {
out[k] =
a && typeof a[k] === 'object' && !Array.isArray(a[k]) && a[k] !== null ? merge(a[k], b[k]) : b[k];
}
return out;
};
+66
View File
@@ -0,0 +1,66 @@
// Shader warm-up before a live page's first frame. three.js links a program the first time something draws with it,
// and the frame waits on every one in turn: 1-2 s on a phone or an integrated GPU, and a frozen page meanwhile. Here
// all of them start at once and the page awaits them without blocking (renderer.compileAsync, KHR_parallel_shader_compile):
// the scene's materials and the ones held by post passes (GTAO, bloom, ink, output), which compileAsync never meets
// on its own because they only reach the renderer inside composer.render().
//
// A warmed program only helps when its cache key matches the one the frame asks for, so everything here mirrors the
// frame: each set compiles against the target it draws into (tone mapping, colour space), pass quads have no normals
// like three's fullscreen triangle, override materials (GTAO's normals) see the scene's lights and shadows, and the
// two settings three only fixes on its first render (PCFSoftShadowMap, OutputPass defines) are fixed first.
import * as THREE from 'three';
// three's FullScreenQuad geometry: position and uv, no normal
const TRI = new THREE.BufferGeometry();
TRI.setAttribute('position', new THREE.Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3));
TRI.setAttribute('uv', new THREE.Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2));
// a stand-in for the scene's meshes under an override material
const MESH = new THREE.PlaneGeometry(1, 1);
// every material a pass holds directly or in an array (GTAOPass, UnrealBloomPass, ShaderPass, OutputPass)
const materialsOf = (pass) => Object.values(pass).flatMap((v) => (v?.isMaterial ? [v] : Array.isArray(v) ? v.filter((m) => m?.isMaterial) : []));
// drawn over the scene's own meshes instead of on a quad
const isOverride = (m) => m.isMeshNormalMaterial || m.isMeshDepthMaterial || m.isMeshDistanceMaterial;
/**
* jobs: [{scene, target}] or [{materials, target, lights, override}]; target null is the canvas, lights a scene whose
* lights apply, override true for materials drawn as scene.overrideMaterial whatever their type.
*/
export function warmUp(renderer, camera, jobs) {
// three swaps the removed PCFSoftShadowMap for PCFShadowMap inside its first shadow render, after any warm-up
if (renderer.shadowMap.type === THREE.PCFSoftShadowMap) renderer.shadowMap.type = THREE.PCFShadowMap;
const prev = renderer.getRenderTarget();
const waits = jobs.map(({scene, materials = [], target = null, lights = null, override = false}) => {
let root = scene;
if (!root) {
root = new THREE.Scene();
for (const m of materials) root.add(new THREE.Mesh(override || isOverride(m) ? MESH : TRI, m));
}
renderer.setRenderTarget(target);
return renderer.compileAsync(root, camera, lights);
});
renderer.setRenderTarget(prev);
return Promise.all(waits);
}
/** The scene and every enabled pass of an EffectComposer; the last pass draws to the canvas when the composer does. */
export function warmComposer(renderer, composer, scene, camera, jobs = []) {
const target = composer.renderTarget1;
const passes = composer.passes.filter((p) => p.enabled);
const last = composer.renderToScreen ? passes[passes.length - 1] : null;
// OutputPass picks its defines from the renderer on its first render: run that part now, with the draw left out
for (const p of passes.filter((x) => x.isOutputPass)) {
const quad = p._fsQuad;
p._fsQuad = {render() {}};
p.render(renderer, composer.renderTarget2, composer.renderTarget1);
p._fsQuad = quad;
}
const mats = passes.filter((p) => p !== last).flatMap(materialsOf);
return warmUp(renderer, camera, [
{scene, target},
{materials: mats.filter((m) => !isOverride(m)), target},
{materials: mats.filter(isOverride), target, lights: scene},
{materials: last ? materialsOf(last) : [], target: null},
...jobs,
]);
}
+7
View File
@@ -0,0 +1,7 @@
// SERRASAL PX-7, the 10-second demo for the article (2026-11-06), green: the swim-in, the jaw dropping with its glass
// fangs shot from below, the explode with the camera swinging round the parts and the lunge at the lens. 11.2 s of the
// tour played at 1.12x.
import {runPiranhaGreen} from '../piranha-shared/sim_green.js';
import TL from './timeline.json';
runPiranhaGreen(TL, 'piranha-demo');
+1
View File
@@ -0,0 +1 @@
{"duration": 11.2, "film": 10.0, "push": 0.72, "opt": 0.88, "pills": ["optics", "leg", "thorax", "abdomen", "exploded", "hero"], "script": [{"t": 2.6, "act": "abdomen"}, {"t": 5.0, "act": "exploded"}, {"t": 6.9, "act": "assemble"}, {"t": 7.9, "act": "hero"}]}
+6
View File
@@ -0,0 +1,6 @@
// SERRASAL PX-7, the robotic piranha's film on the green page (2026-11-06): the angler's approved tour with the piranha
// body, the hammerhead cut's beats (eye, tail stalk, glass flank, jaw, explode, lunge). Code: ../piranha-shared/sim_green.js.
import {runPiranhaGreen} from '../piranha-shared/sim_green.js';
import TL from './timeline.json';
runPiranhaGreen(TL);
+1
View File
@@ -0,0 +1 @@
{"duration": 21.2, "push": 0.72, "opt": 0.88, "pills": ["optics", "leg", "thorax", "abdomen", "exploded", "hero"], "script": [{"t": 3.0, "act": "optics"}, {"t": 5.7, "act": "leg"}, {"t": 8.2, "act": "thorax"}, {"t": 10.8, "act": "abdomen"}, {"t": 13.3, "act": "exploded"}, {"t": 16.5, "act": "assemble"}, {"t": 17.7, "act": "hero"}]}
+360
View File
@@ -0,0 +1,360 @@
// The Vesper AX-6 console, copied from the hummingbird's (robohum-shared/console.js, itself the bee's) and laid out the
// same at 1600 x 900: the orange AX-6 badge and title with the sim status cells, the fin stroke with its live chart of
// the tail and the pectorals, power, the six fin, tail, jaw, lure and dorsal servos, dive telemetry with an attitude
// ball and the bank, the assemblies, the display toggles, the subsystem registry, the dive log with the operator's
// actions on its timeline, the swim-mode word in the viewport, the labels with leaders into the fish and the
// operator's pointer. Panels are light paper over the near-white studio; the fish's orange is the one accent.
// 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', 'front', 'side', 'wing', 'legs'];
export const VIEW_LABEL = {hero: 'HERO', front: 'FRONT', side: 'SIDE', wing: 'WING', legs: 'LEGS'};
export const DISPLAY = ['labels', 'xray', 'exploded', 'blur', 'orbit'];
export const DISPLAY_LABEL = {labels: 'LABELS', xray: 'X-RAY', exploded: 'EXPLODED', blur: 'MOTION BLUR', orbit: 'ORBIT'};
// 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 = [
['OPTIC HEAD', '2 × 60 MM DOME · IRIS'],
['LURE ARRAY', '7-LINK STALK · CAGED LAMP'],
['RIBCAGE DRIVE', '2 DRIVE RINGS · 16 PISTONS'],
['PECTORAL FINS', '2 × 10 RAYS · QUICK RELEASE'],
['JAW & FANGS', 'HINGED JAW · 64 GLASS FANGS'],
['HULL', '12 SHIELDS · 2,140 PARTS'],
];
const SERVOS = ['FIN R', 'FIN L', 'TAIL', 'JAW', 'LURE', 'DORSAL'];
// 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 lift bar, 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:20px;top:22px" width="52" height="44" viewBox="0 0 52 44"><g fill="none" stroke="#fff" stroke-width="2.1" stroke-linejoin="round" stroke-linecap="round"><path d="M8 30c4-9 13-13 22-11l9 4-9 3 9 3-9 4c-9 2-18-1-22-3z"/><path d="M8 30L1 24v13z"/><path d="M24 19c-2-7 2-14 10-16 7-1 12 4 11 10"/><circle cx="45" cy="17" r="3.4"/><circle cx="24" cy="26" r="1.6"/></g></svg>`);
add(`<div class="mo" style="position:absolute;left:80px;top:34px;color:#fff;font-size:16px;font-weight:600;letter-spacing:3px">AX-6</div>`);
add(`<div class="sm" style="position:absolute;left:182px;top:20px;letter-spacing:2.4px">ROBOTIC ANGLERFISH · DEEP-WATER SURVEY DRONE</div>`);
add(`<div style="position:absolute;left:181px;top:35px;font-size:33px;font-weight:700;letter-spacing:-.6px;line-height:1">Vesper AX-6 <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">BIOLUMINESCENT LURE PLATFORM / FIELD SIMULATOR</div>`);
add(`<div class="sm" style="position:absolute;left:700px;top:22px">THRUST 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:852px;top:57px;font-size:7.6px">CRUISE</div>`);
add(`<div class="sm" style="position:absolute;left:1010px;top:57px;font-size:7.6px">LUNGE</div>`);
const cells = [
['SIM ID', 'AX6-1101'],
['RUNTIME', ''],
['STATUS', ''],
['OPERATOR', 'LAB 4 · 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 wing beat
panel(L.x, 108, L.w, 226, 'FIN STROKE', '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">STROKE FREQUENCY</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">AMPLITUDE</div>`);
const chart = add(`<svg style="position:absolute;left:38px;top:198px" width="262" height="96"></svg>`);
hr(38, 302, 262);
add(`<div class="sm" style="position:absolute;left:38px;top:312px">PLAYBACK</div>`);
const pb = add(`<div class="v" style="position:absolute;left:104px;top:310px"></div>`);
const shutter = add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:312px"></div>`);
// ------------------------------------------------------------ 02 power
panel(L.x, 346, L.w, 148, 'POWER', '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">BATTERY</div>`);
const battCells = [];
for (let i = 0; i < 10; i++) battCells.push(add(`<div style="position:absolute;left:${150 + i * 15}px;top:383px;width:11px;height:20px;border-radius:2px;background:${C.track}"></div>`));
hr(38, 428, 262);
const pw = [['DRAW', 444], ['CELL', 444], ['MOTOR', 444]].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 servos: the wings, the fans, the tail, the neck
panel(L.x, 506, L.w, 238, '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 JOINT · TORQUE</div>`);
const servo = SERVOS.map((n, i) => {
const y = 566 + i * 27;
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:94px;top:${y + 4}px;width:150px;height:6px;background:${C.track};border-radius:3px"></div>`);
const f = add(`<div style="position:absolute;left:94px;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 flight
panel(R.x, 108, R.w, 196, 'DIVE', '04');
const ball = add(`<svg style="position:absolute;left:1300px;top:142px" width="96" height="96"></svg>`);
const fl = [['DEPTH', 0], ['CLIMB', 1], ['PITCH', 2], ['BANK', 3]].map(([k], i) => {
const y = 142 + i * 24;
add(`<div class="sm" style="position:absolute;left:1412px;top:${y + 2}px">${k}</div>`);
return add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:${y}px"></div>`);
});
hr(1300, 252, 262);
add(`<div class="sm" style="position:absolute;left:1300px;top:264px">TRIM</div>`);
const hold = add(`<div class="v" style="position:absolute;left:1350px;top:262px"></div>`);
add(`<div class="sm" style="position:absolute;left:1440px;top:264px">SPEED</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, 'DIVE 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">DESCENT</div>`);
add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:791px">SURFACE</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 AX-6 · 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">SWIM 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; 64 GLASS FANGS · 7-LINK LURE · 2 OPTICS</div>`);
add(`<div class="sm" style="position:absolute;right:28px;top:878px;letter-spacing:2.2px">VESPER MARINE · ABYSS 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(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}`;
// wing beat: the frequency, the amplitude, the stroke of the near wing (orange) and the far one (grey) over the
// last 1.2 s of playback, with the now marker on the right
fq.innerHTML = `${s.freq.toFixed(2)}<span style="font-size:14px;font-weight:600;color:${C.mute}"> HZ</span>`;
amp.textContent = `±${Math.round(s.amp)}°`;
{
const W = 262;
const H = 96;
const Y = (a) => H / 2 - (a / (s.chartMax ?? 62)) * (H / 2 - 8);
let g = `<line x1="0" x2="${W}" y1="${H / 2}" y2="${H / 2}" stroke="${C.faint}" stroke-width="1"/>`;
for (const a of s.chartTicks ?? [-55, 55]) g += `<line x1="0" x2="${W}" y1="${Y(a)}" y2="${Y(a)}" stroke="${C.line}" stroke-width="1" stroke-dasharray="2 3"/><text x="${W - 2}" y="${Y(a) - 3}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono">${a > 0 ? '+' : ''}${a}°</text>`;
const path = (k) => s.stroke.map((p, i) => `${i ? 'L' : 'M'}${((i / (s.stroke.length - 1)) * (W - 10)).toFixed(1)} ${Y(p[k]).toFixed(1)}`).join('');
g += `<path d="${path(1)}" fill="none" stroke="${C.mute}" stroke-width="1" opacity=".7"/><path d="${path(0)}" fill="none" stroke="${C.or}" stroke-width="1.6"/>`;
const last = s.stroke[s.stroke.length - 1];
g += `<line x1="${W - 10}" x2="${W - 10}" y1="4" y2="${H - 4}" stroke="${C.ink}" stroke-width=".8" stroke-dasharray="2 2"/><circle cx="${W - 10}" cy="${Y(last[0]).toFixed(1)}" r="3.4" fill="${C.or}"/>`;
g += `<text x="0" y="${H - 1}" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">${s.chartSpan ?? '−1.2 S'}</text><text x="${W - 14}" y="${H - 1}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">NOW</text>`;
chart.innerHTML = g;
}
pb.textContent = `${s.playback.toFixed(1)}×`;
shutter.textContent = s.shutter ?? (s.blur > 0.5 ? 'SHUTTER 1/60' : 'HI-SPEED 1/2000');
// power
batt.innerHTML = `${Math.round(s.battery * 100)}<span style="font-size:13px;color:${C.mute}">%</span>`;
const bc = Math.round(s.battery * 10);
battCells.forEach((c, i) => (c.style.background = i < bc ? (i < 2 ? C.or : C.green) : C.track));
pw[0].textContent = `${s.power.toFixed(1)} W`;
pw[1].textContent = `${s.volt.toFixed(2)} V`;
pw[2].textContent = `${s.motorT.toFixed(0)} °C`;
// servos
chipStyle(legState, s.legsFree ? 'warn' : 'ok', s.legsFree ? 'DETACHED' : 'HOLDING');
servo.forEach((b, i) => {
const v = s.servos[i];
b.f.style.width = `${(v * 150).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';
});
// flight: the attitude ball (the horizon tilts with roll and slides with pitch) and the numbers
{
const r = 44;
const off = s.pitch * 2.2;
ball.innerHTML = `<defs><clipPath id="bc"><circle cx="48" cy="48" r="${r}"/></clipPath></defs><circle cx="48" cy="48" r="${r}" fill="#fbf8f3" stroke="${C.faint}"/><g clip-path="url(#bc)"><g transform="rotate(${(-s.roll).toFixed(2)} 48 48) translate(0 ${off.toFixed(2)})"><rect x="-20" y="48" width="136" height="70" fill="${C.track}"/><line x1="-20" x2="116" y1="48" y2="48" stroke="${C.ink}" stroke-width="1"/>${[-20, -10, 10, 20].map((p) => `<line x1="${48 - (Math.abs(p) > 10 ? 12 : 7)}" x2="${48 + (Math.abs(p) > 10 ? 12 : 7)}" y1="${48 - p * 2.2}" y2="${48 - p * 2.2}" stroke="${C.mute}" stroke-width=".8"/>`).join('')}</g></g><path d="M26 48h14l4 5 4-5h22" fill="none" stroke="${C.or}" stroke-width="2"/><circle cx="48" cy="48" r="2" fill="${C.or}"/>`;
fl[0].textContent = `${s.depth.toFixed(1)} M`;
fl[1].textContent = `${s.vs >= 0 ? '+' : '−'}${Math.abs(s.vs).toFixed(2)} M/S`;
fl[2].textContent = `${s.pitch >= 0 ? '+' : '−'}${Math.abs(s.pitch).toFixed(2)}°`;
fl[3].textContent = `${s.roll >= 0 ? '+' : '−'}${Math.abs(s.roll).toFixed(2)}°`;
hold.textContent = s.trim ?? 'NEUTRAL';
air.textContent = `${s.airspeed.toFixed(2)} M/S`;
}
// 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,
};
}
+139
View File
@@ -0,0 +1,139 @@
// The construction drawing around the bee: 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 bee, 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} = {}) {
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],
];
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 eye and one round the tail, offset from the main centre
arc(new V3(1.2, 0.14, 0.1), 0.62, new V3(0.55, 0.05, 0.85), 0, Math.PI * 2, {dashed: true, width: 0.9, opacity: 0.4, dash: 0.03});
arc(new V3(-1.15, -0.25, 0), 0.75, new V3(-0.9, -0.3, 0.3), 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(0.9, 0.55, 0.2), new V3(1.9, 1.6, 0.4)],
[new V3(-0.6, -0.4, 0.3), new V3(-1.9, -1.1, 0.9)],
[new V3(0.2, 0.5, -0.3), new V3(0.6, 1.9, -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);
},
};
}
+416
View File
@@ -0,0 +1,416 @@
// The robotic anglerfish's kitbash shop, copied from the bee's (robobee-shared/parts.js): the materials (gloss white
// shell, orange accent, graphite and black mechanism, steel, the lens, clear glass and the fin membrane) and the
// geometry every part is cut from. Added here: taperTube (from the scorpion) and plate, a thick panel cut out of any
// parametric surface, which the skull and the jaws are made of. 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}),
};
}
// ------------------------------------------------------------ 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 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;
}
/** A tube through points whose radius runs from r0 to r1 along its length (a fang, a fin ray, 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 thick panel cut from a parametric surface. S(u, v) -> Vector3 is the outer face over [u0, u1] x [v0, v1]; nrm(p)
* gives the outward normal there (or null: taken from the surface's partials). t: the wall, nu x nv: the grid. The
* outer and inner faces are smooth; the four edge walls are flat, and the outer face's border row leans its normal
* toward the wall (bevel), so the clear coat draws a crisp line along every edge of the panel.
*/
export function plate(S, [u0, u1], [v0, v1], t, nu, nv, nrm = null, bevel = 0.55) {
const P = [];
const N = [];
const e = 1e-4;
for (let i = 0; i <= nu; i++) {
for (let j = 0; j <= nv; j++) {
const u = u0 + ((u1 - u0) * i) / nu;
const v = v0 + ((v1 - v0) * j) / nv;
const p = S(u, v);
let n = nrm ? nrm(p) : null;
if (!n) {
const du = S(u + e, v).sub(S(u - e, v));
const dv = S(u, v + e).sub(S(u, v - e));
n = new V3().crossVectors(du, dv).normalize();
}
P.push(p);
N.push(n);
}
}
const id = (i, j) => i * (nv + 1) + j;
// the orientation: the grid's own winding against the outward normal, at the middle of the panel
const mi = Math.max(0, Math.floor(nu / 2) - (nu > 1 ? 0 : 0));
const mj = Math.floor(nv / 2);
const ia = Math.min(mi, nu - 1);
const ja = Math.min(mj, nv - 1);
const w = new V3().crossVectors(P[id(ia + 1, ja)].clone().sub(P[id(ia, ja)]), P[id(ia, ja + 1)].clone().sub(P[id(ia, ja)]));
const ccw = w.dot(N[id(ia, ja)]) > 0;
// bevel: the border row of the outer face leans toward the wall
const NO = N.map((n) => n.clone());
const lean = (i, j, d) => NO[id(i, j)].addScaledVector(d.normalize(), bevel).normalize();
if (bevel > 0) {
for (let i = 0; i <= nu; i++) {
lean(i, 0, P[id(i, 0)].clone().sub(P[id(i, 1)]));
lean(i, nv, P[id(i, nv)].clone().sub(P[id(i, nv - 1)]));
}
for (let j = 0; j <= nv; j++) {
lean(0, j, P[id(0, j)].clone().sub(P[id(1, j)]));
lean(nu, j, P[id(nu, j)].clone().sub(P[id(nu - 1, j)]));
}
}
const pos = [];
const nor = [];
const idx = [];
const V = (nGrid) => (nGrid + 1) * (nv + 1);
// outer
for (let k = 0; k < P.length; k++) {
pos.push(P[k].x, P[k].y, P[k].z);
nor.push(NO[k].x, NO[k].y, NO[k].z);
}
// inner
for (let k = 0; k < P.length; k++) {
pos.push(P[k].x - N[k].x * t, P[k].y - N[k].y * t, P[k].z - N[k].z * t);
nor.push(-N[k].x, -N[k].y, -N[k].z);
}
const off = V(nu);
for (let i = 0; i < nu; i++) {
for (let j = 0; j < nv; j++) {
const a = id(i, j);
const b = id(i + 1, j);
const c = id(i, j + 1);
const d = id(i + 1, j + 1);
if (ccw) idx.push(a, b, c, c, b, d, off + a, off + c, off + b, off + c, off + d, off + b);
else idx.push(a, c, b, c, d, b, off + a, off + b, off + c, off + c, off + b, off + d);
}
}
const face = new THREE.BufferGeometry();
face.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
face.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
face.setIndex(idx);
// the walls: a strip between the outer border and the inner one, flat shaded, facing away from the panel
const wp = [];
const edge = (list, outDir) => {
for (let k = 0; k < list.length - 1; k++) {
const [ka, kb] = [list[k], list[k + 1]];
const oa = P[ka];
const ob = P[kb];
if (oa.distanceTo(ob) < 1e-7) continue;
const ia2 = oa.clone().addScaledVector(N[ka], -t);
const ib2 = ob.clone().addScaledVector(N[kb], -t);
const fn = new V3().crossVectors(ob.clone().sub(oa), ia2.clone().sub(oa));
const tri = fn.dot(outDir(k)) > 0 ? [oa, ob, ia2, ob, ib2, ia2] : [oa, ia2, ob, ob, ia2, ib2];
for (const p of tri) wp.push(p.x, p.y, p.z);
}
};
const row = (j) => [...Array(nu + 1).keys()].map((i) => id(i, j));
const col = (i) => [...Array(nv + 1).keys()].map((j) => id(i, j));
edge(row(0), (k) => P[id(k, 0)].clone().sub(P[id(k, 1)]));
edge(row(nv), (k) => P[id(k, nv)].clone().sub(P[id(k, nv - 1)]));
edge(col(0), (k) => P[id(0, k)].clone().sub(P[id(1, k)]));
edge(col(nu), (k) => P[id(nu, k)].clone().sub(P[id(nu - 1, k)]));
const walls = new THREE.BufferGeometry();
walls.setAttribute('position', new THREE.Float32BufferAttribute(wp, 3));
walls.computeVertexNormals();
return wp.length ? merge([face, walls]) : face;
}
File diff suppressed because it is too large Load Diff
+104
View File
@@ -0,0 +1,104 @@
"""Score for the VESPER AX-6 film cut 1:1 on the bee's (entry roboangler-film, tour_bee.js), mixed like the
hummingbird's (robohum-shared/score_bee.py): a bed in D minor (Dm9, Bbmaj7, Gm9, A7sus at 92 bpm: e-piano, bass, soft
drums and a pad on the same changes) at one level the whole way, a quiet click on every button press, and for every act
short quiet accents on its own moves: a slow wash for the swim-in and a snap as the jaw shuts at its end, thread ticks
as the lens rings unscrew and screw back, a swish as the fin leaves its root, air through its turn and a snap as it
seats, a servo tick per lure link, a run of glass ticks as the cage blooms and a soft rising tone for the flare, a
hinge click per rib shield and servo blips as the drive rings slide out, a drop and a run of glass ticks along the fang
rows and a snap as the jaw seats, a whoosh into the explode and three clicks as the fish seats again, a rising air on
the wind-up and a snap and a rush for the lunge. No drones.
python run_sfx.py sims/piranha-shared/score.py
Every cue comes from the script in roboangler-film/timeline.json, with the offsets inside each act taken from
tour_bee.js (the bee's ACT clocks, WING_FLIP, CAGE, FLARE, the snap at 2.3 s, the explode out 0.2-1.8 s and home
0-1.0 s, the lunge 1.0 s after HERO).
"""
import os
from sfx.score_kit import airy, bed, chords, hz, thud # noqa: E402
from sfx.synth import blip, click, envelope, pad # noqa: E402
# TL / OUT in the environment score another cut of the film (roboangler-cut) without touching this one
TIMELINE = os.environ.get("TL", "../piranha-film/timeline.json")
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "piranha-score.wav"))
TARGET_LUFS = -14.0
SEED = 41
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "Bbmaj7:Bb2 D3 F3 A3 D4/Bb1", "Gm9:G2 Bb2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3 C4/A1")
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
SNAP_IN = 2.3
DEP = 1.0
def snap(mix, t, level=0.06, pan=0.0):
"""The jaw shutting: a short click on a soft low knock."""
mix.put(t, click(1500, 0.03), level, pan=pan)
mix.put(t, thud(110, 0.06, 0.25), level * 0.5, pan=pan)
def score(mix, tl):
dur = tl["duration"]
left, right, low, drums = bed(dur, 92, CHORDS, MOTIF, motif_voice="blip", kicks=(0, 2.5), snares=(1, 3), hats=8, swing=0.08, keys_vel=0.75, keys_lp=3600)
mix.put_stereo(0, left, right, 0.13)
mix.put(0, low, 0.13)
mix.put(0, drums, 0.05)
bar = 4 * 60 / 92
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)
# the swim-in and the snap at its end
mix.put(0.0, airy(2.4, 400, 1200, 0.6), 0.02, pan=-0.3)
snap(mix, SNAP_IN + 0.12, 0.05, pan=0.2)
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 == "optics":
mix.put(t + 0.35, airy(0.6, 1200, 2600, 0.5), 0.012, pan=-0.15)
for i, dt in enumerate((0.45, 0.62, 0.79, 0.96, 1.13)):
mix.put(t + dt, click(3200 - 180 * i, 0.018), 0.033, pan=-0.1)
for i, dt in enumerate((2.2, 2.34, 2.48, 2.6)):
mix.put(t + dt, click(2500 + 180 * i, 0.018), 0.03, pan=-0.1)
elif act == "wing":
mix.put(t + 0.45, airy(0.8, 600, 2000, 0.6), 0.024, pan=-0.3)
mix.put(t + 0.9, airy(1.4, 800, 1400, 0.5), 0.016, pan=-0.2)
mix.put(t + 2.35, airy(0.35, 1800, 800, 0.5), 0.012, pan=-0.3)
mix.put(t + 2.68, click(1800, 0.03), 0.06, pan=-0.2)
elif act == "leg":
for k in range(7):
mix.put(t + 0.35 + 0.07 * k, click(2800 + 90 * k, 0.016), 0.028, pan=0.3)
for j in range(12):
mix.put(t + 0.78 + 0.05 * (j % 4) + 0.012 * j, click(3600 + 60 * j, 0.012), 0.018, pan=0.35)
mix.put(t + 1.05, blip(hz("D6"), 0.6, 0.25), 0.014, pan=0.35)
mix.put(t + 1.05, airy(0.8, 900, 2400, 0.5), 0.012, pan=0.35)
for k in range(4):
mix.put(t + 2.15 + 0.09 * k, click(2600 - 120 * k, 0.016), 0.026, pan=0.3)
mix.put(t + 2.55, click(1900, 0.03), 0.05, pan=0.3)
elif act == "thorax":
for k in range(5):
mix.put(t + 0.3 + 0.077 * k, click(2300 - 90 * k, 0.022), 0.034, pan=0.1)
for i, dt in enumerate((0.6, 0.85, 1.1)):
mix.put(t + dt, blip(hz("A5") * 2 ** (i / 6), 0.18, 0.06), 0.016)
mix.put(t + 2.1, airy(0.4, 1600, 800, 0.5), 0.011)
mix.put(t + 2.6, click(2100, 0.03), 0.055)
elif act == "abdomen":
mix.put(t + 0.3, airy(0.7, 1400, 500, 0.6), 0.02, pan=0.15)
for j in range(12):
mix.put(t + 0.38 + 0.045 * j, click(3300 + 70 * j, 0.012), 0.02, pan=0.1 + 0.03 * j)
mix.put(t + 2.0, airy(0.4, 600, 1600, 0.5), 0.012, pan=0.15)
snap(mix, t + 2.42, 0.06, pan=0.15)
elif act == "exploded":
mix.put(t + 0.2, airy(1.4, 450, 2400, 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 + 0.9, airy(0.6, 400, 1300, 0.6), 0.016)
elif act == "hero":
mix.put(t + 0.1, airy(0.9, 500, 1500, 0.5), 0.016, pan=0.2)
snap(mix, t + DEP + 0.12, 0.065, pan=0.3)
mix.put(t + DEP, airy(2.2, 450, 2600, 0.7), 0.032, pan=0.45)
+129
View File
@@ -0,0 +1,129 @@
// SERRASAL PX-7, the robotic piranha's film on the green page (entry piranha-film), made 2026-11-06: the approved
// angler film's tour (tour_bee.js, the cut's beats as the hammerhead ran them) with the piranha's body (piranha.js,
// round 3 of its still). The beats: the eye, the tail stalk telescoping out, the glass flank opening over its gears, the
// jaw dropping with its glass fangs, the explode on a turntable and the lunge at the lens. The scene is mirrored across
// x (the fish and every camera, not the lights or the page) as its still was shot, head on the left, near side to the
// key. Green look and page from ../green; TL.film plays the scene's timeline faster for a demo.
import * as THREE from 'three';
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 {buildPiranha, FLOOR_Y} from './piranha.js';
import {createStage, PAPER} from './stage.js';
import {makeBeeTour} from './tour_bee.js';
const D2R = Math.PI / 180;
Object.assign(PAL, {orange: ORANGE_TO});
Object.assign(PAPER, PAPER_GREEN);
const ACTS = [['optics', 'Eye'], ['wing', 'Fin'], ['leg', 'Tail'], ['thorax', 'Glass flank'], ['abdomen', 'Jaw'], ['exploded', 'Teardown'], ['hero', 'Release']];
const PAGE = {
name: 'Serrasal',
code: 'PX-7',
title: 'Robotic Piranha, Taken Apart',
date: '2026-11-6',
sub: {
overview: ['2 rows of glass fangs', 'Glass flank, 2 drive gears'],
optics: ['Lens under the brow', 'Iris: 10 blades'],
wing: ['Pectoral fin, frosted', 'Root: pivot drum'],
leg: ['Tail stalk, 4 segments', 'Telescopes on servos'],
thorax: ['Glass barrel, 2 big gears', '2 lit coils'],
abdomen: ['Jaw drops off the hinge', 'Glass fangs fly out'],
exploded: ['Every part apart', 'Turntable 330°'],
hero: ['Tail to full stroke', 'Lunge at the lens'],
},
cards: [{k: 'Tail beat', kind: 'wave', unit: 'Hz'}, {k: 'Thrust', kind: 'bar', unit: '%'}, {k: 'Servo load', kind: 'bars', n: 6}, {k: 'Battery', kind: 'bar', unit: '%'}],
};
const STATUS = {BANKING: 'Banking in', CRUISE: 'Cruising', 'OPTICS OPEN': 'Eye open', 'FIN OFF': 'Fin off', 'TAIL OUT': 'Tail out', 'FLANK OPEN': 'Flank open', 'JAW DROPPED': 'Jaw dropped', TEARDOWN: 'Teardown', REASSEMBLY: 'Reassembly', 'WIND-UP': 'Winding up', LUNGE: 'Lunging'};
export function makePiranhaGreen(TL) {
const FILM = TL.film ?? TL.duration;
// the angler's camera distances, scaled by TL.push; the eye shot pushes in by TL.opt
const PUSH = TL.push ?? 1;
const OPT = TL.opt ?? 0.9;
const SPEED = TL.duration / FILM;
// only the acts this cut runs get a pill and a line in the list (a demo names its set in TL.pills)
const used = new Set(TL.pills ?? TL.script.map((e) => (e.act === 'assemble' ? 'exploded' : e.act)));
const acts = ACTS.filter(([k]) => used.has(k));
return async ({canvas, capture}) => {
const app = document.getElementById('app');
const st = createStage({canvas, floorY: FLOOR_Y, span: 3.8});
const fish = buildPiranha();
fish.pose({t: 0, idle: 0});
fish.root.updateMatrixWorld(true);
const at = (k) => fish.anchorAt(k).toArray();
const mid = (...ps) => ps.reduce((a, p) => a.map((v, i) => v + p[i] / ps.length), [0, 0, 0]);
const A = {
lens: at('lens'),
eyeAxis: new THREE.Vector3(1, 0, 0).transformDirection(fish.anchors.lens.obj.matrixWorld).toArray(),
finHub: at('finHub'),
lureMid: mid(at('stalk'), at('joint'), at('bulb')),
core: at('core'),
jaw: at('jaw'),
};
const T = makeBeeTour(TL, A);
st.addBody(fish);
retint(fish.root);
fish.root.rotation.order = 'YXZ';
fish.root.scale.x = -1;
const m = -1;
const ui = createConsole(app, {...PAGE, nav: [['overview', 'Overview'], ...acts], pills: acts});
const cursorAt = makeCursor(ui, T.SCRIPT);
const labels = makeLabels(st, fish.anchors);
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.PIRANHA = {st, fish, T, A};
const sm = (x) => {
const u = Math.min(1, Math.max(0, x));
return u * u * u * (u * (u * 6 - 15) + 10);
};
const SCR = [...TL.script].sort((a, b) => a.t - b.t);
const optWin = (t) => {
let w = 0;
SCR.forEach((e, i) => {
if (e.act !== 'optics') return;
const t1 = SCR[i + 1]?.t ?? TL.duration;
w = Math.max(w, sm((t - e.t) / 0.85) * (1 - sm((t - t1) / 0.85)));
});
return w;
};
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);
fish.pose({t, idle: 1, gape: s.gape, swim: s.swim, eye: s.eye, fin: s.fin, finFlip: s.finFlip, lure: s.lure, cage: s.cage, flare: s.flare, rib: s.rib, drop: s.drop, explode: s.explode, spinT: s.spinT, bend: s.bend});
retint(fish.root);
const f = s.flight;
fish.root.position.set(m * f.pos.x, f.pos.y, f.pos.z);
fish.root.rotation.set(f.roll * D2R, m * f.yaw * D2R, m * f.pitch * D2R);
const c = s.cam;
st.frame({...c, az: m * c.az * D2R, el: c.el * D2R, d: c.d * PUSH * (1 - (1 - OPT) * optWin(t)), tx: m * c.tx, sx: m * (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 lift = Math.min(1, tel.lift);
ui.update({
time: tf,
dur: FILM,
status: STATUS[tel.status] ?? nice(tel.status),
cards: [{v: tel.freq.toFixed(1), wave: tel.stroke.map((p) => p[0] / 40)}, {v: Math.round(lift * 100), bar: lift}, {bars: tel.servos}, {v: Math.round(tel.battery * 100), bar: tel.battery}],
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 runPiranhaGreen = (TL, title = 'piranha-film') =>
runSim({duration: TL.film ?? TL.duration, fps: 60, theme: 'light', hud: {enabled: false, title, subtitle: ''}, director: {enabled: false}, watermark: ''}, makePiranhaGreen(TL));
+345
View File
@@ -0,0 +1,345 @@
// The robotic anglerfish's stage, copied from the bee's (robobee-shared/stage.js); the key's shadow box and the floor
// shadow's window take a span (the fish is longer than the bee). A near-white product studio. A warm paper backdrop with no horizon, a soft shadow pooled
// on the floor under the bee (the bee's silhouette seen from below, blurred wide, plus a tighter pass for what hangs
// close to 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;
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, span = 3.4}) {
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();
// floor: 'full' (a wide pass and a tight one), 'one' (the wide pass only), 'half' / 'quarter' (that, every 2nd / 4th
// frame)
let floorMode = 'full';
let floorTick = 0;
const floorShadow = (c) => {
if ((floorMode === 'half' && floorTick++ % 2) || (floorMode === 'quarter' && floorTick++ % 4)) return;
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;
const passes = floorMode === 'full' ? [
[soft, 1.0, 1.0, 3.2, 4],
[near, 0.0, 1.5, 1.2, 2],
] : [[soft, 1.0, 1.0, 3.2, 3]];
backU.uNear.value = floorMode === 'full' ? 0.55 : 0;
for (const [rt, base, far, px, passes2] of passes) {
silU.uBase.value = base;
silU.uFar.value = far;
renderer.setRenderTarget(rt[0]);
renderer.clear();
renderer.render(scene, shCam);
blur(rt, px, passes2);
}
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 bee 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();
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
const frame = (cam, ops = {}) => {
const {tx, ty, tz, az, el, d} = cam;
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, 8);
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, floor, self, blur}) => {
if (blur !== undefined) key.shadow.blurSamples = blur;
if (floor !== undefined) floorMode = floor;
if (self !== undefined) key.castShadow = self;
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, addBody: addBee, size, floorY, project, setAOSkip, setQuality};
}
+481
View File
@@ -0,0 +1,481 @@
// The Vesper AX-6 tour cut 1:1 on the bee's (robobee-shared/tour_v2.js, robobee-sim2/timeline.json), the way the
// hummingbird's was (robohum-shared/tour_bee.js): the same beat times in the same order, the same push-ins and orbits,
// the same 330° explode turntable with the fast reassembly, distances scaled to the fish. The bee's banking fly-in is
// the fish swimming in with a bank and a roll, its tail sweeping and its jaw snapping once near the end of the 3 s; the
// bee's fly-off is a lunge (the jaw snaps and it shoots past the camera). The five assemblies map beat for beat:
// OPTICS = the eye (the bubble lifts, the lens rings unscrew out along the axis, the iris opens), WING = the near
// pectoral fin (it leaves its root and turns over in the air), LEG = the lure (the stalk comes apart link by link with
// a servo spinning in each joint, the cage blooms and the light flares), THORAX = the ribcage (the shields swing off
// and the drive rings slide out spinning 5× faster), ABDOMEN = the jaw (it drops away, the fang rows fly out along their
// rims and snap back).
// The camera rules on top: frame 0 is already the front three-quarter hero view of the still (the eye side and
// the open mouth toward the camera, the fish big and moving); every teardown is shot from that side within about ±35°
// and pushed in on the part; sides change only in the orbits, the turntable and the exit; the camera rides smooth
// splines and follows only the fish's path, never its sway. Labels show only while parts move.
// Script: the entry's timeline.json, {duration, script: [{t, act}]}; act is optics, wing, leg, thorax, abdomen,
// 'exploded', 'assemble' or 'hero' (the lunge). Everything is a pure function of film time t.
import * as THREE from 'three';
import {GAPE_LO} from './piranha.js';
import {VIEWPORT} from './console.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;
// the bee's distances scaled to the fish (tail tip to lure bulb about 5.3 units against the bee's 3)
const S = 1.6;
// the tail's stroke: radians per second of its sweep while swimming (about 0.5 Hz, heavy), and the cruise level
const STROKE_W = 3.1;
export const STROKE_HZ = STROKE_W / (2 * Math.PI);
const CRUISE = 0.65;
// fish units to metres for the dive panel (the fish is a 1.6 m drone)
const M_PER = 0.3;
const DEPTH0 = 412.6;
export const ASSEMBLIES = ['hero', 'optics', 'wing', 'leg', 'thorax', 'abdomen'];
export const ASSEMBLY_LABEL = {hero: 'HERO', optics: 'OPTICS', wing: 'FIN', leg: 'TAIL', thorax: 'FLANK', abdomen: 'JAW'};
export const DISPLAY2 = ['labels', 'exploded', 'flare', 'turntable'];
export const DISPLAY2_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', flare: 'COIL FLARE', turntable: 'TURNTABLE'};
const BUTTON = {optics: 'optics', wing: 'wing', leg: 'leg', thorax: 'thorax', abdomen: 'abdomen', exploded: 'exploded', assemble: 'exploded', hero: 'hero'};
// each act's own clock, the bee's (seconds after its click): when it opens, when it closes, whether the swim eases off
// (only the ribcage: the fish keeps its slow stroke through the others, its own motion between the beats)
const ACT = {
optics: {open: [0.35, 1.5], close: [2.2, 2.65], stop: false},
wing: {open: [0.45, 1.25], close: [2.35, 2.7], stop: false},
leg: {open: [0.35, 1.45], close: [2.15, 2.55], stop: false},
thorax: {open: [0.3, 1.4], close: [2.1, 2.6], stop: true},
abdomen: {open: [0.3, 1.3], close: [2.0, 2.45], stop: false},
};
// the fin: the bee's full turn over 0.9-2.3 s; the lure's cage blooms behind the stalk and the light flares in it
const WING_FLIP = [0.9, 2.3];
const CAGE = {open: [0.75, 1.6], close: [2.05, 2.5]};
const FLARE = {open: [1.05, 1.5], close: [1.95, 2.4]};
// the jaw's snaps: the one at the end of the swim-in and the one that starts the lunge (start of the shut, seconds)
const SNAP_IN = 2.3;
const DEP = 1.0;
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy], u = seconds on
// az from +z (the fish's right flank, the near side) toward +x (its face): the still's hero view is az 30. The bee's
// angles map onto the hero side: every teardown sits between az -5 and 65. A = the world points of the parts at rest.
export function makeBeeCams(A) {
const add = (p, d) => p.map((v, i) => v + d[i]);
const mid = (a, b, k = 0.5) => a.map((v, i) => v + (b[i] - v) * k);
// the fish's middle at rest (the bulb to the tail, the lure's top to the fins): every close-up aims between it and
// its part, so the push-in lands on the part and the whole fish stays inside the viewport
const C0 = [0.15, 0.3, 0.1];
const lens = mid(C0, add(A.lens, A.eyeAxis.map((v) => v * 0.45)), 0.45).map((v, i) => (i === 1 ? C0[1] + 0.2 : v));
const wing = mid(C0, add(A.finHub, [0.9, -0.35, 1.0]), 0.35).map((v, i) => (i === 1 ? 0.2 : v));
const lure = add(mid(C0, A.lureMid, 0.3), [0.1, 0.06, 0]);
const rib = mid(C0, A.core, 0.4).map((v, i) => (i === 1 ? C0[1] - 0.1 : i === 0 ? v + 0.25 : v));
const jaw = mid(C0, A.jaw, 0.4).map((v, i) => (i === 1 ? -0.03 : v));
// the piranha's close-up targets sit on the parts themselves
const eye = mid(add(A.lens, A.eyeAxis.map((v) => v * 0.3)), C0, 0.15);
const stalk = add(A.lureMid, [0.18, -0.05, 0.05]);
const flank = add(A.core, [0, 0.05, 0.15]);
const mouth = add(A.jaw, [-0.1, 0.25, 0]);
// every close-up keeps pushing in through its whole act and keeps orbiting about 14°/s, so a hold never parks
const push = (a, b, u) => lerp(a, b, ss(0, 2.5, u));
// the explode: wide while it is apart, pushing in through the reassembly toward the hero distance
const ASM = A.asm ?? 3.2;
return {
intro: (u) => {
const k = ss(0, 3.0, u);
return [lerp(2, 32, k), lerp(13, 8, k), lerp(11.2, 10.4, k), C0[0], C0[1] + 0.08, C0[2], 0, -24];
},
// 2026-11-06, the piranha's own cameras: the angler's ones parked the shot (az
// 20-50, el 6-10, the same distance in every beat). Every beat now sits on its part from its own side and height
// and pushes in while the part hangs open: the eye in macro from the face side, the tail stalk from behind, the
// glass flank from above, the jaw from below, the explode passing low round the parts.
optics: (u) => [72 - 8 * u, lerp(10, 18, ss(0, 2.5, u)), push(6.2, 5.0, u), ...eye, 0, -24],
wing: (u) => [10 + 14 * u, 13, push(12.6, 11.1, u), ...wing, 0, -24],
leg: (u) => [-42 + 9 * u, 14, push(8.0, 6.8, u), ...stalk, 0, -24],
thorax: (u) => [4 + 8 * u, 40 - 3 * u, push(8.2, 6.9, u), ...flank, 0, -24],
abdomen: (u) => [56 - 7 * u, -4 + 2 * u, push(8.8, 7.4, u), ...mouth, 0, -24],
// the explode: while the parts fly the camera swings 38° toward the face and drops under them to look up, then
// through the reassembly swings back against the turntable onto the hero side, rises and pushes in, so the whole
// fish turns into the hero view as it snaps together
exploded: (u) => {
const go = ss(0.3, 2.8, u);
const back = ss(ASM, ASM + 1.5, u);
return [34 + 38 * go - 67 * back, lerp(16, 0, go) + 9 * back, lerp(lerp(16.8, 14.8, go), 11.0, ss(ASM + 0.1, ASM + 1.2, u)), 0.1, lerp(0.58, 0.3, ss(ASM, ASM + 1.0, u)) - 0.22 * Math.sin(Math.PI * ss(1.8, 3.0, u)), 0.0, 0, -24];
},
// the turntable stops at 330°, so the fish comes out of it turned -30°: the hero view after it sits 30° lower in
// the world to land on the same side of the fish
hero: (u) => [-2 + 12 * u, 8, 10.3, ...C0, 0, -24],
};
}
export function makeBeeTour(TL, A) {
const CAM2 = makeBeeCams(A);
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
const DURATION = TL.duration;
const EVENTS = SCRIPT.map((e) => e.t);
const AT = {};
for (const e of SCRIPT) (AT[e.act] ??= []).push(e.t);
const at = (act) => AT[act] ?? [];
const T_EXP = at('exploded')[0] ?? 999;
const T_ASM = at('assemble')[0] ?? 999;
const T_END = at('hero')[0] ?? 999;
const T_LUNGE = T_END + DEP;
const win = (act, W, t) => {
let v = 0;
for (const t0 of at(act)) v = Math.max(v, ss(t0 + W.open[0], t0 + W.open[1], t) * (1 - ss(t0 + W.close[0], t0 + W.close[1], t)));
return v;
};
const openOf = (act, t) => win(act, ACT[act], t);
// the full explode: out 0.2-1.8 s after EXPLODED, home 0-1.0 s after it goes off (fast, it snaps)
const explodeAt = (t) => ss(T_EXP + 0.2, T_EXP + 1.8, t) * (1 - ss(T_ASM, T_ASM + 1.0, t));
// the turntable: 330° from the explode to just after the fish is whole again, steady in the middle
const TT = [T_EXP + 0.2, T_ASM + 1.5];
const turnAt = (t) => {
const [a, b] = TT;
if (t <= a) return 0;
const R = 0.6;
const span = b - a;
const v = 330 / (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 stopAt = (t) => {
let v = 0;
for (const act of Object.keys(ACT)) {
if (!ACT[act].stop) continue;
for (const t0 of at(act)) v = Math.max(v, ss(t0, t0 + 0.45, t) * (1 - ss(t0 + ACT[act].close[1], t0 + ACT[act].close[1] + 0.5, t)));
}
return Math.max(v, ss(T_EXP, T_EXP + 0.45, t) * (1 - ss(T_ASM + 0.9, T_ASM + 1.5, t)));
};
const activity = (t) => Math.max(...Object.keys(ACT).map((a) => openOf(a, t)), explodeAt(t));
const DT = 1 / 240;
const SPIN = [0];
for (let i = 1; i * DT <= DURATION + 1; i++) SPIN.push(SPIN[i - 1] + (1 + 5 * activity((i - 0.5) * DT)) * DT);
const look = (A2, t) => {
const u = Math.max(0, Math.min(A2.length - 2, t / DT));
const i = Math.floor(u);
return A2[i] + (A2[i + 1] - A2[i]) * (u - i);
};
const spinAt = (t) => (t < 0 ? t : look(SPIN, t));
// the swim stroke: heavy while it swims in, a cruise between the beats, held still while a part is off, the full
// stroke again for the wind-up and the lunge
const swimAt = (t) => Math.max(1 - ss(2.5, 3.6, t), CRUISE * (1 - 0.6 * stopAt(t) - 0.4 * Math.min(1, explodeAt(t) * 3)), ss(T_END + 0.1, T_END + 0.8, t));
// the jaw: its gape in degrees, with the snap at the end of the swim-in, the wide wind-up before the lunge and the
// snap that starts it
const snap = (t, t0) => ss(t0, t0 + 0.12, t) * (1 - ss(t0 + 0.2, t0 + 0.55, t));
const gapeAt = (t) => GAPE_LO + 9 * ss(T_END + 0.15, T_END + 0.85, t) * (1 - ss(T_LUNGE, T_LUNGE + 0.12, t)) - 22 * snap(t, SNAP_IN) - 24 * snap(t, T_LUNGE);
// the swim: in from behind-left banking through a turn toward the camera, the cruise, the turntable, the wind-up and
// the lunge past the camera. path is the smooth part the camera follows; the stroke's sway rides on top for the fish
// alone.
const flightAt = (t) => {
const kIn = ss(-0.3, 2.6, t);
const ex = explodeAt(t);
const calm = 1 - Math.min(1, ex * 2.5);
const sw = swimAt(t);
const path = new THREE.Vector3(lerp(-1.3 * S, 0, kIn), lerp(0.4 * S, 0, kIn), lerp(-1.7 * S, 0, kIn));
let yaw = lerp(-48, 0, kIn) + 12 * Math.sin(Math.PI * kIn);
let roll = -22 * Math.sin(Math.PI * Math.min(1, kIn * 1.05)) + (2.2 * Math.sin(t * 1.3 + 1.1) + 3.2 * Math.sin(t * 0.85 + 0.4)) * calm;
let pitch = 5 * Math.sin(Math.PI * kIn) + (1.6 * Math.sin(t * 1.9 + 0.6) + 2.4 * Math.sin(t * 1.2 + 2.0)) * calm;
yaw += turnAt(t);
// the wind-up: it draws back along its heading and turns its head a little toward the camera; the lunge turns it
// back onto the hero line, so it shoots forward and toward the lens and passes the camera on the right
const wind = ss(T_END + 0.1, T_END + 0.9, t);
yaw -= 9 * wind;
pitch += 4 * wind;
{
const h0 = new THREE.Vector3(Math.cos(yaw * D2R), 0, -Math.sin(yaw * D2R));
path.addScaledVector(h0, -0.4 * wind * (1 - ss(T_LUNGE, T_LUNGE + 0.3, t)));
}
if (t > T_LUNGE) {
const u = t - T_LUNGE;
const k = ss(0, 0.8, u);
yaw += 6 * k;
roll += 16 * k;
pitch -= 5 * k;
const h = new THREE.Vector3(Math.cos(yaw * D2R), 0, -Math.sin(yaw * D2R));
path.addScaledVector(h, 1.15 * S * u * u + 0.4 * S * u).add(new THREE.Vector3(0, 0.05 * S * u * u, 0));
}
// the stroke sways the head against the tail; the camera never sees it
const sway = 3.4 * sw * Math.sin(t * STROKE_W + Math.PI) * calm;
const pos = path.clone().add(new THREE.Vector3(0, 0.07 * S * Math.sin(t * 1.1) * calm, 0));
return {pos, path, yaw: yaw + sway, roll, pitch, calm, swim: sw, heading: yaw};
};
// the lure lags the turns: each joint takes the turn the fish made a moment earlier
const LAG = 0.085;
const bendAt = (t) => {
const out = [];
let a = flightAt(t);
for (let k = 0; k < 7; k++) {
const b = flightAt(t - LAG * (k + 1));
out.push([0.55 * D2R * (b.pitch - a.pitch), 0.55 * D2R * (b.yaw - a.yaw) + 0.25 * D2R * (b.roll - a.roll)]);
a = b;
}
return out;
};
// the camera: each act's view, blended over 0.85 s with a short dolly out, tracking the fish's 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) => CAM2[V.key](t - (V.key === 'intro' ? 0 : V.t));
// the reassembly keeps the explode's camera running on the explode's clock, also while the next view blends in
const runOf = (j) => {
while (j > 0 && VIEWS[j].key === 'exploded' && VIEWS[j - 1].key === 'exploded') j--;
return VIEWS[j];
};
const camAt = (t) => {
const i = viewIdx(t);
let o = camFn(runOf(i), t);
if (i > 0 && runOf(i) === VIEWS[i]) {
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.85, t);
if (k < 1) {
const a = camFn(runOf(i - 1), t);
const dAz = ((o[0] - a[0] + 540) % 360) - 180;
const b = o.map((v, j) => lerp(a[j], v, k));
b[0] = a[0] + dAz * k;
b[2] += 0.9 * Math.sin(Math.PI * k);
o = b;
}
}
const f = flightAt(t);
const track = 0.85 - 0.5 * ss(T_LUNGE, T_LUNGE + 1.0, t);
return {az: o[0], el: o[1], d: o[2], tx: o[3] + f.path.x * track, ty: o[4] + f.path.y * track, tz: o[5] + f.path.z * track, sx: o[6], sy: o[7]};
};
const actAt = (t) => VIEWS[viewIdx(t)].key;
const stateAt = (t) => {
const ex = explodeAt(t);
const f = flightAt(t);
const open = Object.fromEntries(Object.keys(ACT).map((a) => [a, openOf(a, t)]));
let finFlip = 0;
for (const t0 of at('wing')) finFlip = Math.max(finFlip, ss(t0 + WING_FLIP[0], t0 + WING_FLIP[1], t));
if (finFlip >= 1) finFlip = 0;
const cage = win('leg', CAGE, t);
// the light flares in the lure act, glows up through the explode and flashes on the wind-up
const flare = Math.max(win('leg', FLARE, t), 0.55 * ss(T_END + 0.2, T_END + 0.8, t) * (1 - ss(T_LUNGE + 0.6, T_LUNGE + 1.4, t)));
const view = actAt(t);
return {
t,
spinT: spinAt(t),
explode: ex,
swim: f.swim,
gape: gapeAt(t),
eye: open.optics,
fin: open.wing,
finFlip,
lure: open.leg,
cage,
flare,
rib: open.thorax,
drop: open.abdomen,
open,
flight: f,
bend: bendAt(t),
cam: camAt(t),
view,
guides: 0.45 + 0.55 * Math.min(1, ex * 2.5 + activity(t)),
turn: turnAt(t),
};
};
const LABELS = {
optics: [['eyeGlass', 'EYE RING', 'LIT · UNDER THE BROW'], ['lensRing', 'LENS RINGS', '3 × THREADED'], ['iris', 'IRIS', '10 BLADES · OPENS 4×'], ['barrel', 'LENS BARREL', 'SLIDES OUT']],
wing: [['fin', 'PECTORAL FIN', 'FROSTED FILM'], ['finHub', 'FIN ROOT', 'PIVOT DRUM']],
leg: [['stalk', 'TAIL STALK', '4 SEGMENTS · TELESCOPING'], ['joint', 'SEGMENT SERVO', 'SPINNING FREE'], ['tailHub', 'TAIL HUB', 'BRACKET · 2 LOBES'], ['tail', 'TAIL FIN', '11 RAYS · FROSTED FILM']],
thorax: [['flank', 'GLASS BARREL', 'CLEAR · LIFTS OFF'], ['rib', 'RIB BANDS', 'HINGED · SWING UP'], ['gear', 'DRIVE GEARS', '2 BIG · 5× SPEED'], ['coil', 'LIT COILS', '2 · GREEN']],
abdomen: [['jaw', 'LOWER JAW', 'DROPS · UNDERBITE'], ['fang', 'LOWER FANGS', 'GLASS · 2 ROWS'], ['upfang', 'UPPER FANGS', 'GLASS · 2 ROWS']],
exploded: [['lens', 'OPTIC HEAD', '2 × LENS'], ['tailHub', 'TAIL', '4 SEGMENTS'], ['gear', 'DRIVE GEARS', 'SPINNING FREE'], ['fin', 'PECTORAL FIN', 'FROSTED FILM'], ['jaw', 'LOWER JAW', 'GLASS FANGS']],
};
const labelAt = (t, s) => {
const v = s.view;
if (ACT[v]) {
const t0 = at(v).filter((x) => x <= t).pop();
const A2 = ACT[v];
return {set: LABELS[v], o: ss(t0 + A2.open[0] + 0.1, t0 + A2.open[0] + 0.45, t) * (1 - ss(t0 + A2.close[0] - 0.25, t0 + A2.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 tail's and the near pectoral's angles in degrees, as pose() draws them
const tailDeg = (tt) => (0.14 * Math.sin(tt * 1.6) + 0.4 * swimAt(tt) * Math.sin(tt * STROKE_W)) / D2R;
const finDeg = (tt) => ((0.12 + 0.2 * swimAt(tt)) * Math.sin(tt * 2.2)) / D2R;
const telemetry = (t, s) => {
const f = s.flight;
const stroke = [];
for (let i = 0; i <= 90; i++) {
const tt = t - 4 + (i / 90) * 4;
stroke.push([tailDeg(tt), finDeg(tt)]);
}
const ex = s.explode > 0.04;
const sw = s.swim;
// the servos: FIN R, FIN L, TAIL, JAW, TAIL STALK, DORSAL; a part that is off its mount reads DETACHED
const free = [ex || s.fin > 0.08, ex, ex, ex || s.drop > 0.08, ex || s.lure > 0.08, ex];
const gapeLoad = Math.abs(s.gape - GAPE_LO) / 24;
const base = [0.3 + 0.4 * sw, 0.28 + 0.4 * sw, 0.22 + 0.62 * sw, 0.24 + 0.6 * gapeLoad, 0.3 + 0.08 * Math.abs(s.bend[3][1]) * 40, 0.2 + 0.2 * sw];
const servos = base.map((b, i) => (free[i] ? 0 : Math.max(0, Math.min(1, b + 0.04 * Math.sin(t * 7 + i) + 0.1 * Math.abs(f.roll) / 30))));
const v = s.view;
const opening = ACT[v] ? s.open[v] : 0;
const NAME = {optics: 'OPTICS OPEN', wing: 'FIN OFF', leg: 'TAIL OUT', thorax: 'FLANK OPEN', abdomen: 'JAW DROPPED'};
let status = 'CRUISE';
let kind = 'ok';
if (t < 2.6) status = 'BANKING';
if (ACT[v] && opening > 0.05) [status, kind] = [NAME[v], 'warn'];
if (v === 'exploded') [status, kind] = t < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['CRUISE', 'ok'];
if (t > T_END + 0.1 && t <= T_LUNGE) status = 'WIND-UP';
if (t > T_LUNGE) [status, kind] = ['LUNGE', 'warn'];
const ROW = {optics: 0, leg: 1, thorax: 2, wing: 3, abdomen: 4};
const sub = (i) => {
if (ex) return ['warn', 'DETACHED'];
if (ROW[v] === i && opening > 0.05) return ['warn', i === 3 || i === 4 ? 'DETACHED' : 'OPEN'];
if (i === 3) return sw > 0.05 ? ['ok', `${(STROKE_HZ * 60).toFixed(0)} SPM`] : ['idle', 'FEATHERED'];
if (i === 2) return sw > 0.05 ? ['ok', 'RUNNING'] : ['idle', 'IDLE'];
if (i === 1) return s.flare > 0.1 ? ['warn', 'FLARE'] : ['ok', 'LIT 18%'];
return ['ok', ['TRACKING', '', '', '', 'ARMED', 'SEALED'][i]];
};
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 · RELEASE' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
const lungeV = t > T_LUNGE ? (2.3 * S * (t - T_LUNGE) + 0.4 * S) * M_PER : 0;
const speed = lungeV + M_PER * (0.9 * (1 - ss(1.5, 3.0, t)) + 0.35 * sw);
const labels = labelAt(t, s);
const amp = (0.14 + 0.4 * sw) / D2R;
return {
time: t,
dur: DURATION,
lift: Math.max(0, Math.min(1, 0.18 + 0.55 * sw + 0.25 * ss(T_LUNGE, T_LUNGE + 0.4, t) + 0.05 * Math.sin(t * STROKE_W))),
status,
statusKind: kind,
freq: STROKE_HZ * Math.min(1, 0.4 + sw),
amp,
stroke,
chartMax: 40,
chartTicks: [-30, 30],
chartSpan: '−4 S',
playback: 1,
blur: 1,
shutter: 'TAIL · R PECTORAL',
battery: 0.912 - 0.0021 * t,
power: 41 + 120 * Math.pow(sw, 1.4) + 60 * activity(t) + 8 * Math.sin(t * STROKE_W),
volt: 48.2,
motorT: 22 + 0.35 * t,
servos,
legsFree: free.some((x) => x),
legFreeEach: free,
depth: DEPTH0 - M_PER * f.pos.y * 4,
vs: -M_PER * 0.07 * S * 1.1 * Math.cos(t * 1.1) * f.calm,
pitch: f.pitch,
roll: f.roll,
airspeed: speed,
trim: s.explode > 0.04 ? 'FREE' : t > T_LUNGE ? 'STRIKE' : 'NEUTRAL',
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
display: {labels: labels.o > 0.5, exploded: t >= T_EXP && t < T_ASM, flare: s.flare > 0.2, turntable: s.turn > 0 && t < TT[1]},
subs: [0, 1, 2, 3, 4, 5].map(sub),
focus: ROW[v] ?? (v === 'exploded' ? 5 : -1),
events: EVENTS,
next: `${EVENTS.length} OPERATOR ACTIONS`,
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · BANKING IN',
mode: status,
modeSub:
status === 'BANKING'
? `BANK ${f.roll.toFixed(0)}° · INBOUND`
: status === 'TEARDOWN' || status === 'REASSEMBLY'
? `TURNTABLE ${Math.round(s.turn)}° · ${Math.round(s.explode * 100)}% APART`
: status === 'LUNGE'
? `STRIKE · ${speed.toFixed(1)} M/S`
: status === 'WIND-UP'
? `JAW ${s.gape.toFixed(0)}° · MOUTH OPEN`
: ACT[v] && opening > 0.05
? `${ASSEMBLY_LABEL[v]} · ${Math.round(opening * 100)}% APART`
: `DEPTH ${(DEPTH0 - M_PER * f.pos.y * 4).toFixed(1)} M · STATION`,
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
labelSet: labels,
};
};
return {SCRIPT, DURATION, stateAt, telemetry, camAt, flightAt};
}
/** Labels in two columns at the viewport's edges, from a set of anchors. */
export function makeLabels(st, fish) {
const p = new THREE.Vector3();
return ({set, o}) => {
if (o < 0.02) return [];
const pts = [];
for (const [key, name, sub] of set) {
const A = fish.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
const GUTTER_X = 1262;
export function makeCursor(ui, SCRIPT) {
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[BUTTON[e.act]]}));
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};
};
}
+7
View File
@@ -0,0 +1,7 @@
// THERAPHOS TH-8, the 10-second demo for the article (2026-11-06), green: the approved film's run-in and landing jump,
// the glass abdomen opening on its coils, the explode, a few steps and the jump at the camera. 11.3 s of the tour
// played at 1.13x (timeline.json: duration = scene seconds, film = film seconds).
import {runTarantulaGreen} from '../tarantula-shared/sim_green.js';
import TL from './timeline.json';
runTarantulaGreen(TL, 'tarantula-demo');
+1
View File
@@ -0,0 +1 @@
{"duration": 11.3, "film": 10.0, "script": [{"t": 2.7, "act": "abdomen"}, {"t": 5.2, "act": "exploded"}, {"t": 7.0, "act": "assemble"}, {"t": 7.8, "act": "hero"}, {"t": 9.6, "act": "jump"}]}
+6
View File
@@ -0,0 +1,6 @@
// THERAPHOS TH-8 on the green page, made 2026-11-06: the approved tarantula film (tarantula-film) with its movement,
// cameras, timing and sound untouched, re-shot in green. Code: ../tarantula-shared/sim_green.js and ../green.
import {runTarantulaGreen} from '../tarantula-shared/sim_green.js';
import TL from './timeline.json';
runTarantulaGreen(TL);
+13
View File
@@ -0,0 +1,13 @@
{
"duration": 24.8,
"script": [
{"t": 3.2, "act": "eyes"},
{"t": 5.8, "act": "leg"},
{"t": 8.4, "act": "abdomen"},
{"t": 11.0, "act": "head"},
{"t": 13.6, "act": "exploded"},
{"t": 16.9, "act": "assemble"},
{"t": 18.4, "act": "hero"},
{"t": 21.4, "act": "jump"}
]
}
+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};
};
}
+7
View File
@@ -0,0 +1,7 @@
// VESPION VX-9, the 10-second demo for the article (2026-11-06), green: a dive in from above, the wing pulled out and
// turned over, the explode in slow motion, a climb straight out of the top of the frame. Tour: ../wasp-shared/tour_10.js.
import {runWaspGreen} from '../wasp-shared/sim_green.js';
import {make10Tour} from '../wasp-shared/tour_10.js';
import TL from './timeline.json';
runWaspGreen(TL, 'wasp-demo', {tour: make10Tour});
+1
View File
@@ -0,0 +1 @@
{"duration": 10.0, "script": [{"t": 1.5, "act": "wing"}, {"t": 3.8, "act": "exploded"}, {"t": 6.6, "act": "assemble"}, {"t": 7.8, "act": "hero"}]}
+7
View File
@@ -0,0 +1,7 @@
// VESPION VX-9 on the green page, made 2026-11-06: the approved wasp film (wasp-film) with its movement, cameras,
// timing and sound untouched, re-shot in green on the model-launch page. Code: ../wasp-shared/sim_green.js and
// ../green (console.js, look.js).
import {runWaspGreen} from '../wasp-shared/sim_green.js';
import TL from './timeline.json';
runWaspGreen(TL);
+13
View File
@@ -0,0 +1,13 @@
{
"duration": 24.0,
"script": [
{"t": 3.0, "act": "optics"},
{"t": 5.7, "act": "wing"},
{"t": 8.5, "act": "leg"},
{"t": 11.0, "act": "thorax"},
{"t": 13.6, "act": "abdomen"},
{"t": 16.1, "act": "exploded"},
{"t": 19.3, "act": "assemble"},
{"t": 20.5, "act": "hero"}
]
}
File diff suppressed because it is too large Load Diff
+359
View File
@@ -0,0 +1,359 @@
// The Mellis HB-7 console, laid out at 1600 x 900 after the Cessna console and the reference app recordings: the
// orange HB-7 badge and title with the sim status cells, the wing beat with its live stroke chart, power, the six leg
// servos, flight telemetry with an attitude ball, the views, the display toggles, the subsystem registry, the flight
// log with the operator's actions on its timeline, the flight-mode word in the viewport, the labels with leaders into
// the bee and the operator's pointer. Panels are light paper over the near-white studio; the bee's orange is the one
// accent. update(s) redraws every live part from the frame's state; the film and a live page share it.
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', 'front', 'side', 'wing', 'legs'];
export const VIEW_LABEL = {hero: 'HERO', front: 'FRONT', side: 'SIDE', wing: 'WING', legs: 'LEGS'};
export const DISPLAY = ['labels', 'xray', 'exploded', 'blur', 'orbit'];
export const DISPLAY_LABEL = {labels: 'LABELS', xray: 'X-RAY', exploded: 'EXPLODED', blur: 'MOTION BLUR', orbit: 'ORBIT'};
// 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 = [
['OPTIC HEAD', '2 × 18 MM LENS · AMBER IR'],
['NECK BEARING', '10-SEGMENT COLLAR'],
['THORAX DRIVE', '3 GEARS · 11 ACTUATORS'],
['WING ROOTS', '4 HINGES · 7.5 HZ CRANK'],
['LEG SERVOS', '6 LEGS × 3 JOINTS'],
['ABDOMEN BANDS', '5 SEGMENTS · GLASS STING'],
];
const LEGS = ['L1', 'L2', 'L3', 'R1', 'R2', 'R3'];
// 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 lift bar, 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:24px;top:24px" width="44" height="40" viewBox="0 0 44 40"><g fill="none" stroke="#fff" stroke-width="2.2"><path d="M22 3l9 5.2v10.4l-9 5.2-9-5.2V8.2z"/><path d="M13 14C7 6 1 9 2 14s7 5 11 2M31 14c6-8 12-5 11 0s-7 5-11 2"/><path d="M18 26l-3 10M26 26l3 10M22 24v12"/></g></svg>`);
add(`<div class="mo" style="position:absolute;left:80px;top:34px;color:#fff;font-size:16px;font-weight:600;letter-spacing:3px">VX-9</div>`);
add(`<div class="sm" style="position:absolute;left:182px;top:20px;letter-spacing:2.4px">ROBOTIC WASP · MICRO AIR VEHICLE</div>`);
add(`<div style="position:absolute;left:181px;top:35px;font-size:33px;font-weight:700;letter-spacing:-.6px;line-height:1">Vespion VX-9 <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">FLAPPING-WING DRONE / FIELD SIMULATOR</div>`);
add(`<div class="sm" style="position:absolute;left:700px;top:22px">LIFT 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:852px;top:57px;font-size:7.6px">HOVER</div>`);
add(`<div class="sm" style="position:absolute;left:1010px;top:57px;font-size:7.6px">MAX</div>`);
const cells = [
['SIM ID', 'HB7-0412'],
['RUNTIME', ''],
['STATUS', ''],
['OPERATOR', 'LAB 3 · R.K.'],
];
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 wing beat
panel(L.x, 108, L.w, 226, 'WING BEAT', '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">STROKE FREQUENCY</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">AMPLITUDE</div>`);
const chart = add(`<svg style="position:absolute;left:38px;top:198px" width="262" height="96"></svg>`);
hr(38, 302, 262);
add(`<div class="sm" style="position:absolute;left:38px;top:312px">PLAYBACK</div>`);
const pb = add(`<div class="v" style="position:absolute;left:104px;top:310px"></div>`);
const shutter = add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:312px"></div>`);
// ------------------------------------------------------------ 02 power
panel(L.x, 346, L.w, 148, 'POWER', '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">BATTERY</div>`);
const battCells = [];
for (let i = 0; i < 10; i++) battCells.push(add(`<div style="position:absolute;left:${150 + i * 15}px;top:383px;width:11px;height:20px;border-radius:2px;background:${C.track}"></div>`));
hr(38, 428, 262);
const pw = [['DRAW', 444], ['CELL', 444], ['MOTOR', 444]].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
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 = 566 + i * 27;
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:178px;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 flight
panel(R.x, 108, R.w, 196, 'FLIGHT', '04');
const ball = add(`<svg style="position:absolute;left:1300px;top:142px" width="96" height="96"></svg>`);
const fl = [['ALT AGL', 0], ['V/S', 1], ['PITCH', 2], ['ROLL', 3]].map(([k], i) => {
const y = 142 + i * 24;
add(`<div class="sm" style="position:absolute;left:1412px;top:${y + 2}px">${k}</div>`);
return add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:${y}px"></div>`);
});
hr(1300, 252, 262);
add(`<div class="sm" style="position:absolute;left:1300px;top:264px">HOLD</div>`);
const hold = add(`<div class="v" style="position:absolute;left:1350px;top:262px"></div>`);
add(`<div class="sm" style="position:absolute;left:1440px;top:264px">AIRSPEED</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, 'FLIGHT 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">TAKE-OFF</div>`);
add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:791px">LAND</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 VX-9 · 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">FLIGHT 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; 6 LEGS · 4 WINGS · 2 OPTICS</div>`);
add(`<div class="sm" style="position:absolute;right:28px;top:878px;letter-spacing:2.2px">VESPION ROBOTICS · INTERCEPT 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(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}`;
// wing beat: the frequency, the amplitude, the stroke of the near forewing (orange) and hindwing (grey) over the
// last 1.2 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.amp)}°`;
{
const W = 262;
const H = 96;
const Y = (a) => H / 2 - (a / 40) * (H / 2 - 8);
let g = `<line x1="0" x2="${W}" y1="${H / 2}" y2="${H / 2}" stroke="${C.faint}" stroke-width="1"/>`;
for (const a of [-32, 32]) g += `<line x1="0" x2="${W}" y1="${Y(a)}" y2="${Y(a)}" stroke="${C.line}" stroke-width="1" stroke-dasharray="2 3"/><text x="${W - 2}" y="${Y(a) - 3}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono">${a > 0 ? '+' : ''}${a}°</text>`;
const path = (k) => s.stroke.map((p, i) => `${i ? 'L' : 'M'}${((i / (s.stroke.length - 1)) * (W - 10)).toFixed(1)} ${Y(p[k]).toFixed(1)}`).join('');
g += `<path d="${path(1)}" fill="none" stroke="${C.mute}" stroke-width="1" opacity=".7"/><path d="${path(0)}" fill="none" stroke="${C.or}" stroke-width="1.6"/>`;
const last = s.stroke[s.stroke.length - 1];
g += `<line x1="${W - 10}" x2="${W - 10}" y1="4" y2="${H - 4}" stroke="${C.ink}" stroke-width=".8" stroke-dasharray="2 2"/><circle cx="${W - 10}" cy="${Y(last[0]).toFixed(1)}" r="3.4" fill="${C.or}"/>`;
g += `<text x="0" y="${H - 1}" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">−1.2 S</text><text x="${W - 14}" y="${H - 1}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">NOW</text>`;
chart.innerHTML = g;
}
pb.textContent = `${s.playback.toFixed(1)}×`;
shutter.textContent = s.blur > 0.5 ? 'SHUTTER 1/60' : 'HI-SPEED 1/2000';
// power
batt.innerHTML = `${Math.round(s.battery * 100)}<span style="font-size:13px;color:${C.mute}">%</span>`;
const bc = Math.round(s.battery * 10);
battCells.forEach((c, i) => (c.style.background = i < bc ? (i < 2 ? C.or : C.green) : C.track));
pw[0].textContent = `${s.power.toFixed(1)} W`;
pw[1].textContent = `${s.volt.toFixed(2)} V`;
pw[2].textContent = `${s.motorT.toFixed(0)} °C`;
// leg servos
chipStyle(legState, s.legsFree ? 'warn' : 'ok', s.legsFree ? 'DETACHED' : 'HOLDING');
servo.forEach((b, i) => {
const v = s.servos[i];
b.f.style.width = `${(v * 178).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';
});
// flight: the attitude ball (the horizon tilts with roll and slides with pitch) and the numbers
{
const r = 44;
const off = s.pitch * 2.2;
ball.innerHTML = `<defs><clipPath id="bc"><circle cx="48" cy="48" r="${r}"/></clipPath></defs><circle cx="48" cy="48" r="${r}" fill="#fbf8f3" stroke="${C.faint}"/><g clip-path="url(#bc)"><g transform="rotate(${(-s.roll).toFixed(2)} 48 48) translate(0 ${off.toFixed(2)})"><rect x="-20" y="48" width="136" height="70" fill="${C.track}"/><line x1="-20" x2="116" y1="48" y2="48" stroke="${C.ink}" stroke-width="1"/>${[-20, -10, 10, 20].map((p) => `<line x1="${48 - (Math.abs(p) > 10 ? 12 : 7)}" x2="${48 + (Math.abs(p) > 10 ? 12 : 7)}" y1="${48 - p * 2.2}" y2="${48 - p * 2.2}" stroke="${C.mute}" stroke-width=".8"/>`).join('')}</g></g><path d="M26 48h14l4 5 4-5h22" fill="none" stroke="${C.or}" stroke-width="2"/><circle cx="48" cy="48" r="2" fill="${C.or}"/>`;
fl[0].textContent = s.airborne ? `${s.alt.toFixed(1)} MM` : '—';
fl[1].textContent = s.airborne ? `${s.vs >= 0 ? '+' : '−'}${Math.abs(s.vs).toFixed(1)} MM/S` : '—';
fl[2].textContent = `${s.pitch >= 0 ? '+' : '−'}${Math.abs(s.pitch).toFixed(2)}°`;
fl[3].textContent = `${s.roll >= 0 ? '+' : '−'}${Math.abs(s.roll).toFixed(2)}°`;
hold.textContent = s.airborne ? 'POSITION' : 'OFF';
air.textContent = `${s.airspeed.toFixed(2)} M/S`;
}
// 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,
};
}
+139
View File
@@ -0,0 +1,139 @@
// The construction drawing around the bee: 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 bee, 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} = {}) {
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],
];
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 eye and one round the tail, offset from the main centre
arc(new V3(1.2, 0.14, 0.1), 0.62, new V3(0.55, 0.05, 0.85), 0, Math.PI * 2, {dashed: true, width: 0.9, opacity: 0.4, dash: 0.03});
arc(new V3(-1.15, -0.25, 0), 0.75, new V3(-0.9, -0.3, 0.3), 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(0.9, 0.55, 0.2), new V3(1.9, 1.6, 0.4)],
[new V3(-0.6, -0.4, 0.3), new V3(-1.9, -1.1, 0.9)],
[new V3(0.2, 0.5, -0.3), new V3(0.6, 1.9, -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);
},
};
}
+304
View File
@@ -0,0 +1,304 @@
// The robotic bee's kitbash shop: the materials (gloss white shell, orange accent, graphite and black mechanism,
// steel, the lens, the clear abdomen and the wing membrane) 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 wasp: the orange light inside the waist rings, the abdomen gaps and the sting, a touch hotter than led
glow: std({color: '#000000', emissive: '#ff6a1c', emissiveIntensity: 1.9}),
// the sting: clear glass tinted toward amber, the glow core shows through it
// a faint amber tint in the glass itself
sting: phys({color: '#fff0e2', roughness: 0.04, metalness: 0, transmission: 1, thickness: 0.035, ior: 1.3, attenuationColor: '#ffb27a', attenuationDistance: 1.4, specularIntensity: 1, clearcoat: 1, clearcoatRoughness: 0.02, envMapIntensity: 1.8}),
// the sting's rim: a fresnel edge in warm amber over the glass, strongest where the surface turns from the eye
stingRim: new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
uniforms: {uColor: {value: new THREE.Color('#7c5236')}, uK: {value: 0.85}},
vertexShader: 'varying vec3 vN; varying vec3 vV; void main(){ vec4 mv = modelViewMatrix * vec4(position, 1.0); vN = normalize(normalMatrix * normal); vV = normalize(-mv.xyz); gl_Position = projectionMatrix * mv; }',
fragmentShader: 'uniform vec3 uColor; uniform float uK; varying vec3 vN; varying vec3 vV; void main(){ float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.0); gl_FragColor = vec4(uColor, f * uK); }',
}),
stingCore: std({color: '#000000', emissive: '#ff7424', emissiveIntensity: 2.0}),
};
}
// ------------------------------------------------------------ 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 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;
}
+76
View File
@@ -0,0 +1,76 @@
"""Score for the VESPION VX-9 wasp film (entry wasp-film), the bee's second-cut score with one more cue (the sting
sliding out in the abdomen act). The bee's notes: Score for the MELLIS HB-7 simulator film, second cut (entry robobee-sim2): the same bed as the other bee films (D minor,
96 bpm, e-piano, bass, soft drums and a pad on the same changes) at one level the whole way, a quiet click on every
button press, and for every act short quiet accents on its own moves: thread ticks as the lens unscrews and screws
back, a swish as the wing pulls out and turns over and a snap as it seats, servo ticks down the leg, a lift of air as
the thorax and the abdomen open and a click as they close, a whoosh into the explode and three clicks as the bee seats
again, and a rising air as it banks away. No drones.
python run_sfx.py sims/wasp-shared/score.py
Every cue comes from the script in robobee-sim2/timeline.json, with the offsets inside each act taken from tour_v2.js
(ACT, the explode out 0.2-1.8 s and home 0-1.0 s, the departure 1.0 s after HERO).
"""
import os
from sfx.score_kit import airy, bed, chords, hz # noqa: E402
from sfx.synth import blip, click, envelope, pad # noqa: E402
TIMELINE = os.environ.get("TL", "../wasp-film/timeline.json")
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "wasp-score.wav"))
TARGET_LUFS = -14.0
SEED = 29
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "Bbmaj7:Bb2 D3 F3 A3/Bb1", "Gm9:G2 Bb2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3/A1")
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
def score(mix, tl):
dur = tl["duration"]
left, right, low, drums = bed(dur, 96, 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 / 96
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)
# the fly-in: one air that follows the bank
mix.put(0.0, airy(2.4, 700, 1800, 0.6), 0.02, pan=-0.3)
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 == "optics":
for i, dt in enumerate((0.4, 0.62, 0.84, 1.06)):
mix.put(t + dt, click(3200 - 200 * i, 0.018), 0.035, pan=0.2)
for i, dt in enumerate((2.2, 2.36, 2.52)):
mix.put(t + dt, click(2600 + 200 * i, 0.018), 0.03, pan=0.2)
elif act == "wing":
mix.put(t + 0.45, airy(0.8, 600, 2200, 0.6), 0.025, pan=-0.3)
mix.put(t + 0.9, airy(1.4, 900, 1500, 0.5), 0.016, pan=-0.2)
mix.put(t + 2.68, click(1800, 0.03), 0.06, pan=-0.2)
elif act == "leg":
for i, dt in enumerate((0.38, 0.6, 0.82, 1.04)):
mix.put(t + dt, blip(hz("D6") * 2 ** (i / 6), 0.18, 0.06), 0.02, pan=0.1)
mix.put(t + 2.55, click(2000, 0.03), 0.05)
elif act in ("thorax", "abdomen"):
mix.put(t + 0.3, airy(1.0, 500, 1600, 0.6), 0.024)
mix.put(t + (2.6 if act == "thorax" else 2.45), click(2100, 0.03), 0.055)
if act == "abdomen":
# the sting slides out of its collar and back
mix.put(t + 1.05, blip(hz("A5"), 0.22, 0.07), 0.018, pan=-0.2)
mix.put(t + 1.5, click(2900, 0.02), 0.035, pan=-0.2)
mix.put(t + 2.15, click(2500, 0.02), 0.03, pan=-0.2)
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 + 0.9, airy(0.6, 400, 1300, 0.6), 0.016)
elif act == "hero":
mix.put(t + 1.0, airy(2.0, 500, 2400, 0.7), 0.03, pan=0.4)
+122
View File
@@ -0,0 +1,122 @@
"""Score for the MELLIS HB-7 18-second film (entry wasp-demo, tour_10.js): the bee films' bed in D minor (Dm9, Bbmaj7,
Gm9, A7sus at 96 bpm: e-piano, bass, soft drums and a pad) at one level the whole way, a quiet click on every button
press, and short quiet accents on each act's own moves: a falling air for the dive in from the left, thread ticks as
the lens unscrews and screws back, a swish as the wing leaves its hinge and another as it turns over and a snap as it
seats, a lift of air and a few gear ticks as the thorax and the abdomen open and a click as they close, a whoosh into
the explode with a long falling air and one low note under the 0.4x speed ramp and slow glass ticks as the parts drift
apart, three clicks as the bee seats again, and a rising air that swells as the bee darts at the lens and passes to
its right. No drones.
python run_sfx.py sims/wasp-shared/score_demo.py
Every cue comes from wasp-demo/timeline.json. The offsets inside each act are tour_10.js's, in SCENE seconds, and go
through the same speed-ramp warp (RAMP, anchored on EXPLODED) back to film time.
"""
import bisect
import os
from sfx.score_kit import airy, bed, chords, hz # noqa: E402
from sfx.synth import blip, click, envelope, pad # noqa: E402
TIMELINE = os.environ.get("TL", "../wasp-demo/timeline.json")
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "wasp-demo-score.wav"))
TARGET_LUFS = -14.0
SEED = 53
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "Bbmaj7:Bb2 D3 F3 A3/Bb1", "Gm9:G2 Bb2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3/A1")
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
# tour_10.js: the ramp in film seconds after the EXPLODED click, and the dart's start after HERO (scene seconds)
RAMP_A, RAMP_B, RAMP_LOW = (0.35, 0.55), (1.9, 2.1), 0.4
DEP = 0.75
def _smoother(x):
u = min(1.0, max(0.0, x))
return u * u * u * (u * (u * 6 - 15) + 10)
def make_warp(t_ramp, dur):
"""film time -> scene time and back, the same integral as tour_10.js makeWarp"""
dt = 1 / 480
n = int((dur + 2) / dt)
ts = [i * dt for i in range(n + 1)]
tau = [0.0]
for i in range(1, n + 1):
mid = ts[i] - dt / 2
bump = _smoother((mid - t_ramp - RAMP_A[0]) / (RAMP_A[1] - RAMP_A[0])) * (1 - _smoother((mid - t_ramp - RAMP_B[0]) / (RAMP_B[1] - RAMP_B[0])))
tau.append(tau[-1] + (1 - (1 - RAMP_LOW) * bump) * dt)
def interp(x, xs, ys):
if x <= xs[0]:
return ys[0]
if x >= xs[-1]:
return ys[-1]
j = bisect.bisect_right(xs, x) - 1
k = (x - xs[j]) / (xs[j + 1] - xs[j])
return ys[j] + (ys[j + 1] - ys[j]) * k
return (lambda x: interp(x, ts, tau)), (lambda y: interp(y, tau, ts))
def score(mix, tl):
dur = tl["duration"]
t_exp = next((e["t"] for e in tl["script"] if e["act"] == "exploded"), 999.0)
tau_at, film_at = make_warp(t_exp, dur)
left, right, low, drums = bed(dur, 96, 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 / 96
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.4, 1), (dur, 0)]), detune=0.8, tremolo=0.18, xfade=0.5)
mix.put_stereo(0, pl, pr, 0.07)
# the dive in from high on the left
mix.put(0.0, airy(1.6, 2200, 700, 0.6), 0.024, pan=-0.35)
for e in tl["script"]:
t, act = e["t"], e["act"]
k0 = tau_at(t)
def at(dt, t0=k0):
"""an offset in scene seconds after the click, in film time"""
return film_at(t0 + dt)
mix.put(t, click(2400, 0.025), 0.055, pan=0.45)
if act == "optics":
for i, dt in enumerate((0.3, 0.48, 0.66, 0.84)):
mix.put(at(dt), click(3200 - 200 * i, 0.018), 0.035, pan=0.2)
for i, dt in enumerate((1.58, 1.71, 1.84)):
mix.put(at(dt), click(2600 + 200 * i, 0.018), 0.03, pan=0.2)
elif act == "wing":
mix.put(at(0.2), airy(0.6, 600, 2200, 0.6), 0.025, pan=-0.3)
mix.put(at(0.5), airy(0.95, 900, 1500, 0.5), 0.016, pan=-0.2)
mix.put(at(1.92), click(1800, 0.03), 0.06, pan=-0.2)
elif act in ("thorax", "abdomen"):
mix.put(at(0.25), airy(0.8, 500, 1600, 0.6), 0.024)
for i in range(4):
mix.put(at(0.55 + 0.11 * i), click(3300 + 140 * i, 0.012), 0.02, pan=0.1 - 0.1 * i)
mix.put(at(1.9 if act == "thorax" else 1.95), click(2100, 0.03), 0.055)
elif act == "exploded":
mix.put(at(0.2), airy(1.0, 500, 2600, 0.7), 0.032, pan=-0.15)
mix.put(at(0.25), blip(hz("D6"), 0.3, 0.1), 0.024)
# the ramp: a long falling air under the slowed parts, one low note as time stretches, slow glass ticks
mix.put(t + RAMP_A[0], airy(RAMP_B[1] - RAMP_A[0] + 0.3, 1800, 450, 0.5), 0.022, pan=-0.1)
mix.put(t + RAMP_A[1], blip(hz("D4"), 1.1, 0.5), 0.015)
for i in range(6):
mix.put(t + RAMP_A[1] + 0.22 * i, click(3600 - 150 * i, 0.012), 0.018, pan=0.4 - 0.16 * i)
elif act == "assemble":
mix.put(t, airy(0.8, 2200, 600, 0.5), 0.02, pan=-0.15)
for i, dt in enumerate((0.45, 0.6, 0.75)):
mix.put(at(dt), click(2000 + 300 * i, 0.03), 0.05, pan=0.3 - 0.3 * i)
mix.put(at(0.7), airy(0.5, 400, 1300, 0.6), 0.016)
elif act == "hero":
mix.put(at(0.1), airy(0.7, 900, 1600, 0.5), 0.012, pan=-0.1)
# the dart: a rising air that swells to the pass by the lens and swings right with it
d0 = at(DEP)
n = max(0.4, dur - d0)
mix.put(d0, airy(n, 400, 3000, 0.7), 0.032, pan=0.15)
mix.put(d0 + n * 0.7, airy(n * 0.3, 2600, 1200, 0.6), 0.03, pan=0.6)
+121
View File
@@ -0,0 +1,121 @@
// VESPION VX-9, the approved wasp film re-shot on the green page (entry wasp-film). Everything that moves comes
// from this folder's tour_v2.js unchanged (the wasp, its flight, every assembly, every camera, the timing); what is new
// is only the look: green for orange on the wasp, white paper with mint haze, and the green page from ../green instead
// of the old console. The subject shifts by green/look.js SHIFT so it sits in the green page's 3D window.
import {runSim} from '../kit/runtime.js';
import {createConsole} from '../green/console.js';
import {makeCursor, makeLabels, ORANGE_TO, PAPER_GREEN, retint, SHIFT} from '../green/look.js';
import {buildBee} from './bee.js';
import {PAL} from './parts.js';
import {createStage, PAPER} from './stage.js';
import {FLOOR_Y} from './tour.js';
import {makeTour2, REACH} from './tour_v2.js';
const D2R = Math.PI / 180;
Object.assign(PAL, {orange: ORANGE_TO});
Object.assign(PAPER, PAPER_GREEN);
const PAGE = {
name: 'Vespion',
code: 'VX-9',
title: 'Robotic Wasp, Taken Apart',
date: '2026-11-6',
nav: [['overview', 'Overview'], ['optics', 'Optics'], ['wing', 'Wings'], ['leg', 'Legs'], ['thorax', 'Thorax'], ['abdomen', 'Abdomen'], ['exploded', 'Teardown'], ['hero', 'Release']],
pills: [['optics', 'Optics'], ['wing', 'Wings'], ['leg', 'Legs'], ['thorax', 'Thorax'], ['abdomen', 'Abdomen'], ['exploded', 'Teardown'], ['hero', 'Release']],
sub: {
overview: ['Wingspan 2 × 180 mm', '6 legs · 2 camera eyes'],
optics: ['Iris: 10 blades', 'Glass Ø 40 mm'],
wing: ['Frosted film, 0.1 mm', 'Hinge: quick release'],
leg: ['2 servos per leg', 'Foot: twin hooks'],
thorax: ['3 spur gears', 'Flight CPU + IMU'],
abdomen: ['5 telescoping bands', 'Glass stinger'],
exploded: ['Every part apart', 'Turntable 330°'],
hero: ['Wings to 7.5 Hz', 'Banking out'],
},
};
// tour_v2's capital labels in the page's voice
const TEXT = {
'OUTER GLASS': ['Front glass', 'Ø 40 mm, AR coated'],
'INNER ELEMENT': ['Inner element', 'Ø 15 mm'],
IRIS: ['Iris', '10 blades, opens 3×'],
'LENS BARREL': ['Lens barrel', 'threaded, 4 rings'],
'WING MEMBRANE': ['Wing film', '0.1 mm, frosted'],
'WING HINGE': ['Wing hinge', 'quick release'],
'HINDWING HINGE': ['Hindwing hinge', 'phase +40°'],
'HIP SERVO': ['Hip servo', 'yaw + lift'],
'KNEE SERVO': ['Knee servo', '0.4 N·m'],
'FOOT CLAW': ['Foot claw', 'twin hooks'],
'SADDLE PLATE': ['Saddle plate', 'polymer shell'],
'DRIVE GEAR STACK': ['Drive gears', '3 spur gears'],
'ACTUATOR RING': ['Actuator ring', '11 pistons'],
'CONTROL BOARDS': ['Flight boards', 'CPU + IMU'],
'WAIST STALK': ['Waist stalk', '5 lit beads'],
'SHELL BAND': ['Shell band', 'telescoping'],
'BAND 4': ['Band 4', '5 riveted segments'],
STINGER: ['Stinger', 'glass, extends 30 mm'],
'OPTIC HEAD': ['Optic head', '2 lenses'],
'NECK BEARING': ['Neck bearing', '10 segments'],
'DRIVE GEARS': ['Drive gears', 'spinning free'],
'ABDOMEN BANDS': ['Abdomen bands', '5 segments'],
};
const STATUS = {DIVING: 'Diving in', 'SLOW-MO': 'Slow motion', 'CLIMB-OUT': 'Climbing out', BANKING: 'Banking in', HOVER: 'Hovering', TEARDOWN: 'Teardown', REASSEMBLY: 'Reassembly', DEPARTING: 'Departing', 'OPTICS OPEN': 'Optics open', 'WING OFF': 'Wing off', 'LEG L2 OPEN': 'Leg open', 'THORAX OPEN': 'Thorax open', 'ABDOMEN OPEN': 'Abdomen open'};
export function makeWaspGreen(TL, {tour = makeTour2} = {}) {
const T = tour(TL);
return async ({canvas, capture}) => {
const app = document.getElementById('app');
const st = createStage({canvas, floorY: FLOOR_Y});
const bee = buildBee();
st.addBee(bee);
retint(bee.root);
bee.root.rotation.order = 'YXZ';
const ui = createConsole(app, PAGE);
const cursorAt = makeCursor(ui, T.SCRIPT);
const labels = makeLabels(st, bee.anchors, TEXT);
const fit = () => {
const k = Math.min(innerWidth / 1600, innerHeight / 900);
app.style.transform = `scale(${k})`;
};
const resize = () => {
fit();
st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));
};
resize();
window.WASP = {st, bee, T};
return {
resize,
render(t) {
const s = T.stateAt(t);
bee.pose({explode: s.explode, flap: s.flap, flapAmp: s.amp, display: s.display, t: s.spinT, spinT: s.spinT, blur: 1, reach: REACH, sub: s.sub, eye: s.eye, wingOut: s.wingOut, wingFlip: s.wingFlip, legK: s.legK, stingK: s.stingK});
retint(bee.root);
const f = s.flight;
bee.root.position.copy(f.pos);
bee.root.rotation.set(f.roll * D2R, f.yaw * D2R, f.pitch * D2R);
const c = s.cam;
st.frame({...c, az: c.az * D2R, el: c.el * D2R, sx: c.sx + SHIFT[0], sy: c.sy + SHIFT[1]}, {guides: s.guides});
const tel = T.telemetry(t, s);
const v = s.view;
const opening = Math.max(s.open?.[v] ?? 0, v === 'wing' ? s.wingOut : 0);
ui.update({
time: t,
dur: TL.duration,
status: STATUS[tel.status] ?? tel.status,
freq: tel.freq,
stroke: tel.stroke.map((p) => p[0]),
lift: tel.lift,
battery: tel.battery,
servos: tel.servos,
apart: Math.round(Math.max(opening, s.explode) * 100),
view: v === 'intro' ? 'overview' : v,
callouts: labels(tel.labelSet),
cursor: cursorAt(t),
});
return {};
},
};
};
}
export const runWaspGreen = (TL, title = 'wasp-film', opts = {}) =>
runSim({duration: TL.duration, fps: 60, theme: 'light', hud: {enabled: false, title, subtitle: ''}, director: {enabled: false}, watermark: ''}, makeWaspGreen(TL, opts));
+344
View File
@@ -0,0 +1,344 @@
// The robotic bee's stage: a near-white product studio. A warm paper backdrop with no horizon, a soft shadow pooled
// on the floor under the bee (the bee's silhouette seen from below, blurred wide, plus a tighter pass for what hangs
// close to 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;
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}) {
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: -3.4, right: 3.4, top: 3.4, bottom: -3.4, near: 1, far: 16});
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 = 4.2;
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();
// floor: 'full' (a wide pass and a tight one), 'one' (the wide pass only), 'half' / 'quarter' (that, every 2nd / 4th
// frame)
let floorMode = 'full';
let floorTick = 0;
const floorShadow = (c) => {
if ((floorMode === 'half' && floorTick++ % 2) || (floorMode === 'quarter' && floorTick++ % 4)) return;
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;
const passes = floorMode === 'full' ? [
[soft, 1.0, 1.0, 3.2, 4],
[near, 0.0, 1.5, 1.2, 2],
] : [[soft, 1.0, 1.0, 3.2, 3]];
backU.uNear.value = floorMode === 'full' ? 0.55 : 0;
for (const [rt, base, far, px, passes2] of passes) {
silU.uBase.value = base;
silU.uFar.value = far;
renderer.setRenderTarget(rt[0]);
renderer.clear();
renderer.render(scene, shCam);
blur(rt, px, passes2);
}
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 bee 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();
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
const frame = (cam, ops = {}) => {
const {tx, ty, tz, az, el, d} = cam;
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, 8);
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, floor, self, blur}) => {
if (blur !== undefined) key.shadow.blurSamples = blur;
if (floor !== undefined) floorMode = floor;
if (self !== undefined) key.castShadow = self;
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};
}
+363
View File
@@ -0,0 +1,363 @@
// The HB-7 simulator tour: everything the console film needs from one script (the entry's timeline.json, {duration,
// script: [{t, view | display, cam?}]}) as pure functions of film time t. The display toggles and their eased weights,
// the motion they drive (the motor winding down before the explode, the reassembly, the wings spinning up, the
// high-speed camera slowing playback to 0.2× when MOTION BLUR goes off), the cameras for the five views, the telemetry
// the console shows (all read off the same motion, so the numbers agree with the picture), the labels and the
// operator's pointer. The film (sim.js) and a later live page share it, the way cessna-shared/live.js reuses film.js.
import * as THREE from 'three';
import {DISPLAY, VIEWPORT} from './console.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;
export const FLAP_HZ = 7.5;
export const AMP = 32;
export const REACH = 0.6;
// bee units to millimetres (the body is 3 units, a 240 mm drone) and the floor under it
const MM = 80;
export const FLOOR_Y = -1.85;
// ------------------------------------------------------------ cameras (u = seconds since the view came on)
// [az, el, d, tx, ty, tz, sx, sy]; the viewport sits a little above the canvas centre, hence sy
export const VIEW_FN = {
'hero:intro': (u) => {
// from frame 0: an orbit round the front quarter and a push-in, the whole bee big the whole way
const k = ss(-0.6, 3.6, u);
return [lerp(82, 30, k), lerp(4, 11, k), lerp(9.4, 6.8, k), 0.1, -0.24, 0.25, -30, -14];
},
hero: (u) => [32 + 2.2 * u, 10, 7.6, -0.1, -0.28, 0.3, -40, -14],
'hero:end': (u) => [24 + 2.6 * u, 8, 7.3, -0.05, -0.26, 0.28, -30, -14],
front: (u) => [86 + 2 * u, 12, 7.8, 0.35, -0.28, 0.0, 0, -14],
side: (u) => [3 + 2 * u, 7, 8.8, -0.2, -0.3, 0.0, 0, -14],
// the near forewing from ahead and above: it spans the viewport, its face shows and its stroke sweeps up and down
wing: (u) => [70 - 1.2 * u, 36, 6.6, 0.05, 0.22, 1.0, 0, -14],
legs: (u) => [40 + 2 * u, 5, 6.8, 0.3, -0.62, 0.3, 0, -14],
};
const EASE = {labels: 0.5, xray: 0.8, exploded: 1.8, blur: 0.6, orbit: 1.4};
const button = (key) => key.split(':')[0];
/** Everything from one tour. */
export function makeTour(TL) {
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
const DURATION = TL.duration;
const EVENTS = SCRIPT.filter((e) => e.t > 0).map((e) => e.t);
const displayAt = (t) => {
const out = Object.fromEntries(DISPLAY.map((k) => [k, 0]));
for (const e of SCRIPT) if (e.display && e.t <= t) out[e.display] = out[e.display] ? 0 : 1;
return out;
};
const lastFlip = (key, t) => SCRIPT.filter((e) => e.display === key && e.t <= t).pop()?.t ?? -99;
const eased = (key, t) => {
const on = displayAt(t)[key];
const k = ss(lastFlip(key, t), lastFlip(key, t) + EASE[key], t);
return on ? k : 1 - k;
};
// the motor and the teardown: EXPLODED on winds the beat down over 0.7 s, then the parts travel out over 1.8 s;
// off brings them home over 1.8 s, then the beat spins back up over 0.7 s
const motion = (t) => {
const on = displayAt(t).exploded;
const t0 = lastFlip('exploded', t);
if (on) return {explode: ss(t0 + 0.5, t0 + 2.3, t), amp: AMP * (1 - ss(t0, t0 + 0.7, t))};
if (t0 < -90) return {explode: 0, amp: AMP};
return {explode: 1 - ss(t0, t0 + 1.8, t), amp: AMP * ss(t0 + 1.7, t0 + 2.4, t)};
};
// playback: 1× with the motion blur on, 0.2× (a high-speed capture) with it off; the bee's own clock integrates it,
// and so does the energy the wings draw
const rate = (t) => 1 - 0.8 * (1 - eased('blur', t));
const DT = 1 / 240;
const SIM = [0];
const FLY = [0];
for (let i = 1; i * DT <= DURATION + 1; i++) {
const t = (i - 0.5) * DT;
SIM.push(SIM[i - 1] + rate(t) * DT);
FLY.push(FLY[i - 1] + (motion(t).amp / AMP) * rate(t) * 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);
};
// before the film starts the bee was already flying at 1×
const simT = (t) => (t < 0 ? t : look(SIM, t));
const flyT = (t) => (t < 0 ? 0 : look(FLY, t));
// cameras: each view blends from the one before over 1.6 s; the explode pulls the camera back so the parts stay in
// the viewport; the orbit's turn rate ramps in
const VIEWS = SCRIPT.filter((e) => e.view).map((e) => ({t: e.t, key: e.cam ? `${e.view}:${e.cam}` : e.view}));
// the orbit: on, it ramps into a steady 16°/s; off, it keeps the turn made so far and coasts to a stop
const orbitTurn = (t) => {
const f = lastFlip('orbit', t);
if (f < -90) return 0;
const R = EASE.orbit;
const turned = (x) => 16 * (x < R ? (x * x) / (2 * R) : x - R / 2);
if (displayAt(t).orbit) return turned(t - f);
const on = SCRIPT.filter((e) => e.display === 'orbit' && e.t < f).pop();
if (!on) return 0;
const c = Math.min(t - f, R);
return turned(f - on.t) + 16 * c * (1 - c / (2 * R));
};
const viewIdx = (t) => {
let i = 0;
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= t) i++;
return i;
};
const blendCam = (a, b, k) => {
const o = b.map((v, i) => lerp(a[i], v, k));
const dAz = ((b[0] - a[0] + 540) % 360) - 180;
o[0] = a[0] + dAz * k;
const swing = Math.min(1, Math.abs(dAz) / 90);
// every move dollies out a little on the way, so between two close views the bee never passes cut by the panels
o[2] += Math.max(0, Math.max(a[2], b[2]) + 0.5 * swing + 1.4 - o[2]) * Math.sin(Math.PI * k);
return o;
};
const camAt = (t) => {
const i = viewIdx(t);
const V = VIEWS[i];
let o = VIEW_FN[V.key](t - V.t);
if (i > 0) {
const k = ss(V.t, V.t + 1.6, t);
if (k < 1) o = blendCam(VIEW_FN[VIEWS[i - 1].key](t - VIEWS[i - 1].t), o, k);
}
const ex = motion(t).explode;
o = [...o];
o[2] *= 1 + 0.62 * ex;
o[4] += 0.15 * ex;
o[1] += 6 * ex;
// the orbit's turn; once it is off, the next view blends it away
let az = orbitTurn(t);
if (!displayAt(t).orbit && V.t > lastFlip('orbit', t)) az *= 1 - ss(V.t, V.t + 1.6, t);
o[0] += az;
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]};
};
const viewAt = (t) => {
const V = VIEWS[viewIdx(t)];
return [V.t, button(V.key)];
};
// labels wait 0.9 s into a view before they come in; on a view change the old ones fade out over 0.3 s
const labelGate = (t) => {
const i = viewIdx(t);
const V = VIEWS[i];
const g = ss(V.t + 0.9, V.t + 1.5, t);
const prev = i > 0 ? ss(VIEWS[i - 1].t + 0.9, VIEWS[i - 1].t + 1.5, V.t) * (1 - ss(V.t, V.t + 0.3, t)) : 0;
return Math.min(1, g + prev);
};
/** The bee's state at film time t: pose parameters, hover, x-ray, guides, camera. */
const stateAt = (t) => {
const m = motion(t);
const T = simT(t);
const calm = 1 - Math.min(1, m.explode * 2.5);
return {
t,
simT: T,
explode: m.explode,
amp: m.amp,
flap: Math.PI * 2 * FLAP_HZ * T,
display: 1 - m.amp / AMP,
blur: eased('blur', t),
rate: rate(t),
xray: eased('xray', t),
hover: {y: 0.05 * Math.sin(T * 2.6) * calm, pitch: 0.025 * Math.sin(T * 1.9 + 0.6) * calm, roll: 0.03 * Math.sin(T * 1.3 + 1.1) * calm, calm},
guides: 0.45 + 0.55 * Math.max(Math.min(1, m.explode * 2.5), eased('xray', t)),
cam: camAt(t),
view: viewAt(t)[1],
displays: displayAt(t),
labels: eased('labels', t) * labelGate(t),
};
};
/** What the console shows at t, read off the same motion as the picture. */
const telemetry = (t, s) => {
const T = s.simT;
const D = s.displays;
// the stroke angle of the near forewing and hindwing over the last 1.2 s of film time
const stroke = [];
for (let i = 0; i <= 90; i++) {
const tt = t - 1.2 + (i / 90) * 1.2;
const a = motion(tt).amp;
const ph = Math.PI * 2 * FLAP_HZ * simT(tt);
stroke.push([a * Math.sin(ph), a * Math.sin(ph + 0.7)]);
}
const beat = ss(0.5, 6, s.amp);
const fly = flyT(t);
const power = 4.2 + 31 * Math.pow(s.amp / AMP, 1.5) * (1 + 0.04 * Math.sin(s.flap)) + 1.1 * s.hover.calm;
const ex = s.explode > 0.04;
// leg loads follow the hover: the legs take more as the bee decelerates at the bottom of each bob
const acc = -Math.sin(T * 2.6);
const servos = [0.44, 0.58, 0.49, 0.4, 0.53, 0.46].map((b, i) => (ex ? 0 : Math.max(0, Math.min(1, b * (1 + 0.32 * acc * (i % 3 === 1 ? 1.2 : 1)) + 0.03 * Math.sin(T * 7 + i)))));
const reassembling = !D.exploded && s.explode > 0.04;
const [status, statusKind] = D.exploded ? ['TEARDOWN', 'warn'] : reassembling ? ['REASSEMBLY', 'warn'] : s.blur < 0.5 ? ['HI-SPEED', 'warn'] : ['HOVER', 'ok'];
const modeSub = D.exploded
? `EXPLODED VIEW · ${Math.round(s.explode * 100)}% · 128 PARTS`
: reassembling
? 'PARTS SEATING · MOTOR ARMED'
: s.blur < 0.5
? 'CAPTURE 2000 FPS · 0.2× PLAYBACK'
: `STATION KEEPING · ${((s.hover.y - FLOOR_Y) * MM).toFixed(0)} MM AGL`;
const last = SCRIPT.filter((e) => e.t > 0 && e.t <= t).pop();
const say = (e) => (e.view ? `VIEW → ${button(e.view).toUpperCase()}` : `${e.display === 'blur' ? 'MOTION BLUR' : e.display === 'xray' ? 'X-RAY' : e.display.toUpperCase()} ${displayAt(e.t + 0.001)[e.display] ? 'ON' : 'OFF'}`);
const sub = (i) => {
if (ex && i !== 3) return ['warn', 'DETACHED'];
if (i === 0) return ['ok', 'TRACKING'];
if (i === 1) return ['ok', 'LOCKED'];
if (i === 2) return s.xray > 0.5 ? ['warn', 'EXPOSED'] : s.amp > 1 ? ['ok', 'RUNNING'] : ['idle', 'STOPPED'];
if (i === 3) return ex ? ['warn', 'DETACHED'] : s.blur < 0.5 ? ['warn', 'HI-SPEED'] : s.amp > 1 ? ['ok', `${FLAP_HZ} HZ`] : ['idle', 'PARKED'];
if (i === 4) return ['ok', 'HOLDING'];
return s.xray > 0.5 ? ['warn', 'EXPOSED'] : ['ok', 'SEALED'];
};
const focus = s.view === 'wing' ? 3 : s.view === 'legs' ? 4 : s.view === 'front' ? 0 : s.xray > 0.5 ? 2 : -1;
return {
time: t,
dur: DURATION,
lift: Math.max(0, (s.amp / AMP) * (0.68 + 0.02 * Math.sin(s.flap))),
status,
statusKind,
freq: FLAP_HZ * beat,
amp: s.amp,
stroke,
playback: s.rate,
blur: s.blur,
battery: 0.842 - 0.0024 * fly,
power,
volt: 3.92 - 0.006 * power,
motorT: 34 + 7 * Math.min(1, fly / 20) + 0.08 * power,
servos,
legsFree: ex,
airborne: !ex,
alt: (s.hover.y - FLOOR_Y) * MM,
vs: MM * 0.05 * 2.6 * Math.cos(T * 2.6) * s.hover.calm * s.rate,
pitch: (s.hover.pitch * 180) / Math.PI,
roll: (s.hover.roll * 180) / Math.PI,
airspeed: Math.abs(MM * 0.05 * 2.6 * Math.cos(T * 2.6) * s.hover.calm * s.rate) / 1000 + 0.004 * s.hover.calm,
view: s.view,
display: D,
subs: [0, 1, 2, 3, 4, 5].map(sub),
focus,
events: EVENTS,
next: `${EVENTS.length} OPERATOR ACTIONS`,
log: last ? `OPERATOR · ${say(last)}` : 'AUTO-HOVER · STATION KEEPING',
mode: status,
modeSub,
};
};
return {SCRIPT, DURATION, EVENTS, displayAt, eased, motion, simT, camAt, viewAt, stateAt, telemetry};
}
// ------------------------------------------------------------ labels
const V3 = THREE.Vector3;
const GENERAL = [
['lens', 'OPTIC LENS', '18 MM · AMBER IR PUPIL'],
['antenna', 'ANTENNA', 'AIRFLOW + SCENT SENSOR'],
['collar', 'NECK BEARING', '10-SEGMENT COLLAR'],
['hinge', 'WING HINGE', '7.5 HZ CRANK · ±32°'],
['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'],
['core', 'CONTROL BOARDS', 'FLIGHT CPU · IMU'],
['pad', 'SHOULDER PAD', 'POLYMER SHELL'],
['knee2', 'LEG SERVO', 'KNEE · 0.4 N·M'],
['capsule', 'ABDOMEN CAPSULE', 'GEAR TRAIN · SPRING'],
['sting', 'POLLEN PROBE', 'RETRACTABLE TIP'],
];
const LEGSET = [
['hip1', 'HIP SERVO', 'YAW + LIFT'],
['knee1', 'KNEE SERVO L1', '0.4 N·M'],
['knee2', 'KNEE SERVO L2', '0.4 N·M'],
['knee3', 'KNEE SERVO L3', '0.4 N·M'],
['foot', 'FOOT WHEEL', 'GRIP PAD'],
['pad', 'SHOULDER PAD', 'POLYMER SHELL'],
['core', 'CONTROL BOARDS', 'SERVO DRIVERS'],
];
const WINGSET = [
['hinge', 'WING HINGE', '7.5 HZ CRANK · ±32°'],
['wing', 'WING MEMBRANE', 'FROSTED FILM · 0.1 MM'],
['hinge2', 'HINDWING HINGE', 'PHASE +40°'],
['antenna', 'ANTENNA', 'AIRFLOW + SCENT SENSOR'],
['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'],
];
/** Labels for a view, in two columns at the viewport's edges, stacked by height so no two touch. */
export function makeLabels(st, bee) {
const p = new V3();
return (view, o) => {
if (o < 0.02) return [];
const set = view === 'legs' ? LEGSET : view === 'wing' ? WINGSET : GENERAL;
const pts = [];
for (const [key, name, sub] of set) {
const A = bee.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 Lc = pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]);
const Rc = pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]);
const out = [];
const stack = (col, x, w) => {
let y = VIEWPORT.y0 + 48;
// start low enough that the column ends above the flight-mode word
y = Math.max(y, Math.min(col.length ? col[0].at[1] - 10 : y, 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(Lc, VIEWPORT.x0 + 16, 168);
stack(Rc, VIEWPORT.x1 - 160, 150);
return out;
};
}
// ------------------------------------------------------------ the operator's pointer (after cessna-shared/film_v2.js)
// It reaches each button 0.1 s before the press, leaves 0.2 s after, travels in an eased bow, and between distant
// presses waits in the gutter left of the right-hand panels, never over the bee.
const GUTTER_X = 1262;
export function makeCursor(ui, SCRIPT) {
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[e.view ?? e.display]}));
const first = EV[0].spot;
const WP = [[0, GUTTER_X, first[1] + 60]];
let [px, py, pt] = [GUTTER_X, first[1] + 60, 0];
EV.forEach((e, n) => {
const [x, y] = e.spot;
const travel = Math.min(0.75, 0.32 + Math.hypot(x - px, y - py) / 900);
const arrive = e.t - 0.1;
if (arrive - travel - pt > 1.6) {
const rest = [GUTTER_X, Math.max(170, Math.min(720, y + 40))];
WP.push([pt + 0.75, ...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.2, x, y]);
[px, py, pt] = [x, y, e.t + 0.2];
const next = EV[n + 1];
if (!next || next.t - 0.1 - 0.75 - pt > 0.9) {
[px, py, pt] = [GUTTER_X, y + 12, pt + 0.6];
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};
};
}
+368
View File
@@ -0,0 +1,368 @@
// The Vespion VX-9 wasp's 10-second demo (entry wasp-demo), made 2026-11-06 for the article: the bee's 18-second
// film (robobee-shared/tour_18.js) carried onto the wasp (its tour_v2.js differences: the sting, the abdomen camera's
// target, the labels) and cut down to one assembly. What it runs:
// - the opening: the wasp dives in from high on the left, banking, and flares nose-up as it brakes;
// - one assembly, the WING: pulled out of its hinge and turned over in the air;
// - the explode in slow motion (0.4x while the parts leave), the camera passing low under them, a full 360 deg
// turntable and a push-in for the reassembly;
// - the exit: the wasp turns a little toward the lens, noses up and climbs straight out of the top of the frame.
// The speed ramp is a warp of film time t into scene time tau (tauAt), so everything stays a pure function of t.
import * as THREE from 'three';
import {FLOOR_Y} from './tour.js';
import {AMP, ASSEMBLY_LABEL, FLAP_HZ} from './tour_v2.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 bump = (a, b, c, d, t) => ss(a, b, t) * (1 - ss(c, d, t));
const D2R = Math.PI / 180;
const MM = 80;
const S = 1.15;
// each act's own clock in scene seconds after its click, a beat every 2.2 s
export const ACT_R = {
optics: {open: [0.25, 1.05], close: [1.55, 1.9], stop: false},
wing: {open: [0.2, 0.75], close: [1.6, 1.95], stop: true},
thorax: {open: [0.25, 1.0], close: [1.5, 1.9], stop: true},
abdomen: {open: [0.25, 1.0], close: [1.55, 1.95], stop: true},
};
// the pulled wing turns over once while it hangs out of its hinge
export const WING_FLIP = [0.45, 1.45];
// the ramp in film seconds after the EXPLODED click: down to 0.4x as the parts start to leave, held while they drift
// apart, back up as the turntable takes over
export const RAMP = {a: [0.35, 0.55], b: [1.9, 2.1], low: 0.4};
// the climb starts this long after HERO (scene seconds)
export const DEP = 0.75;
// the hero camera, low on the front-right so the climb reads against the paper above
const HERO_AZ = 32;
const HERO_EL = 4;
const HERO_D = 7.8;
export function makeWarp(tRamp, dur) {
const rate = (t) => 1 - (1 - RAMP.low) * bump(tRamp + RAMP.a[0], tRamp + RAMP.a[1], tRamp + RAMP.b[0], tRamp + RAMP.b[1], t);
const DT = 1 / 480;
const TAU = [0];
for (let i = 1; i * DT <= dur + 2; i++) TAU.push(TAU[i - 1] + rate((i - 0.5) * DT) * DT);
const tauAt = (t) => {
if (t <= 0) return t;
const u = Math.min(TAU.length - 2, t / DT);
const i = Math.floor(u);
return TAU[i] + (TAU[i + 1] - TAU[i]) * (u - i);
};
return {rate, tauAt};
}
export function make10Tour(TL) {
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
const DURATION = TL.duration;
const EVENTS = SCRIPT.map((e) => e.t);
const tfOf = (act) => (SCRIPT.find((e) => e.act === act) ?? {t: 999}).t;
const tfExp = tfOf('exploded');
const tfAsm = tfOf('assemble');
const {rate, tauAt} = makeWarp(tfExp, DURATION);
const AT = {};
for (const e of SCRIPT) (AT[e.act] ??= []).push(tauAt(e.t));
const at = (act) => AT[act] ?? [];
const T_EXP = at('exploded')[0] ?? 999;
const T_ASM = at('assemble')[0] ?? 999;
const T_END = at('hero')[0] ?? 999;
const T_FIRST = Math.min(...Object.keys(ACT_R).flatMap((a) => at(a)), 999);
const openOf = (act, x) => {
let v = 0;
for (const t0 of at(act)) {
const A2 = ACT_R[act];
v = Math.max(v, bump(t0 + A2.open[0], t0 + A2.open[1], t0 + A2.close[0], t0 + A2.close[1], x));
}
return v;
};
const explodeAt = (x) => ss(T_EXP + 0.2, T_EXP + 1.5, x) * (1 - ss(T_ASM, T_ASM + 0.8, x));
// the turntable: a full +360 deg from the explode to just after the bee is whole again
const TT = [T_EXP + 0.2, T_ASM + 1.2];
const turnAt = (x) => {
const [a, b] = TT;
if (x <= a) return 0;
const R = 0.5;
const span = b - a;
const v = 360 / (span - R);
const y0 = Math.min(x, b) - a;
if (y0 < R) return (v * y0 * y0) / (2 * R);
if (y0 < span - R) return v * (y0 - R / 2);
const y = y0 - (span - R);
return v * (span - 1.5 * R) + v * y - (v * y * y) / (2 * R);
};
// the wings park for the acts that need still wings and for the explode; when the next act parks them too they stay
// parked across the cut instead of spinning up for a moment between
const STOPS = [];
SCRIPT.forEach((e, n) => {
const A2 = ACT_R[e.act];
if (!A2?.stop) return;
const t0 = tauAt(e.t);
const nx = SCRIPT[n + 1];
const hold = nx && (ACT_R[nx.act]?.stop || nx.act === 'exploded') ? tauAt(nx.t) - t0 + 0.4 : A2.close[1];
STOPS.push([t0, t0 + 0.35, t0 + hold, t0 + hold + 0.45]);
});
STOPS.push([T_EXP, T_EXP + 0.4, T_ASM + 0.7, T_ASM + 1.2]);
const stopAt = (x) => Math.max(0, ...STOPS.map((w) => bump(w[0], w[1], w[2], w[3], x)));
const activity = (x) => Math.max(...Object.keys(ACT_R).map((a) => openOf(a, x)), explodeAt(x));
const DT = 1 / 240;
const SPIN = [0];
for (let i = 1; i * DT <= DURATION + 1; i++) SPIN.push(SPIN[i - 1] + (1 + 5 * activity((i - 0.5) * DT)) * DT);
const look = (A2, x) => {
const u = Math.max(0, Math.min(A2.length - 2, x / DT));
const i = Math.floor(u);
return A2[i] + (A2[i + 1] - A2[i]) * (u - i);
};
const spinAt = (x) => (x < 0 ? x : look(SPIN, x));
// the bee: dives in from high on the left banking, flares nose-up and hovers through the teardowns, turns on the
// explode turntable, turns a little toward the lens on HERO and climbs out of the top of the frame
const flightAt = (x) => {
const kIn = ss(-0.9, 1.6, x);
const ex = explodeAt(x);
const calm = 1 - Math.min(1, ex * 2.5);
const path = new THREE.Vector3(lerp(-0.8 * S, 0, kIn), lerp(1.0 * S, 0, kIn), lerp(0.45 * S, 0, kIn));
let yaw = lerp(-24, 0, kIn);
let roll = 28 * Math.sin(Math.PI * Math.min(1, kIn * 1.05)) - 7 * Math.sin(2 * Math.PI * kIn) * kIn + 1.7 * Math.sin(x * 1.3 + 1.1) * calm;
let pitch = -16 * (1 - kIn) + 10 * Math.sin(Math.PI * ss(0.55, 1.0, kIn)) + 1.4 * Math.sin(x * 1.9 + 0.6) * calm;
yaw += turnAt(x);
// HERO: the wasp turns a little toward the lens and lifts its nose, then climbs straight up out of the frame,
// pitching up into the climb with one roll
const kH = ss(T_END, T_END + 0.8, x);
yaw -= 22 * kH;
pitch += 8 * kH;
roll += 10 * Math.sin(Math.PI * kH);
if (x > T_END + DEP) {
const u = x - T_END - DEP;
const k = ss(0, 0.6, u);
pitch += 24 * k;
roll -= 12 * Math.sin(Math.PI * ss(0, 1.3, u));
path.y += 0.7 * u + 1.8 * u * u;
path.x += 0.3 * u * u;
}
const pos = path.clone().add(new THREE.Vector3(0, 0.05 * Math.sin(x * 2.6) * calm, 0));
return {pos, path, yaw, roll, pitch, calm};
};
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy]
// az from the right flank (0) toward the face (90); the hero side is about 20-40. The teardown targets and drift
// rates are the second cut's.
const macro = (act, u, depth = 0.12) => {
const A2 = ACT_R[act];
return 1 - depth * bump(A2.open[1] - 0.35, A2.open[1] + 0.1, A2.close[0] - 0.1, A2.close[1], u);
};
const push = (a, b, u, end = 1.9) => lerp(a, b, ss(0, end, u));
const EXP_SPAN_F = tfAsm - tfExp;
const CAM = {
// the dive: the camera comes down from above with the bee, pushing in
intro: (u) => {
const k = ss(0, 2.0, u);
return [lerp(46, 34, k), lerp(22, 10, k), lerp(7.9, 7.4, k), 0.0, -0.2, 0.25, -20, -14];
},
// the lens from the face side, so the barrel unscrews sideways across the frame
optics: (u) => [90 - 9 * u, 6, push(4.9, 4.3, u) * macro('optics', u, 0.07), 1.22, 0.12, 0.45, 0, -14],
// the wing from the hero side, rising with it as it leaves the hinge and turns over
wing: (u) => {
const k = ss(0, 1.9, u);
return [38 + 9 * k, lerp(12, 22, k), push(8.8, 7.8, u), -0.5, 0.95, 1.25, 0, -14];
},
// the thorax from high over the near flank
thorax: (u) => [6 + 10 * u, 34, push(6.9, 6.0, u) * macro('thorax', u), 0.0, 0.32, 0.05, 0, -14],
// the abdomen from behind the near flank as it telescopes out
abdomen: (u) => [-32 + 10 * u, 14, push(6.8, 5.9, u) * macro('abdomen', u, 0.08), -2.45, -0.95, 0.1, 0, -14],
// the explode, on FILM time (u = film seconds since the click): while the ramp holds the parts at 0.4x the camera
// keeps its own speed and swings round low under them looking up, then rises over the turntable and pushes in for
// the reassembly
exploded: (u) => {
const arc = ss(0.45, 2.0, u);
const rise = ss(1.9, 2.9, u);
const near = ss(EXP_SPAN_F - 0.3, EXP_SPAN_F + 0.9, u);
return [24 + 32 * arc - 14 * rise, lerp(10, -2, arc) + 20 * rise, lerp(11.4, 12.0, arc) - 3.6 * near, 0.0, lerp(-0.15, 0.05, arc) * (1 - rise) - 0.15 * rise, 0.0, -10, -14];
},
// HERO: low on the front-right, holding still while the wasp turns and climbs out
hero: (u) => {
const k = ss(0, 0.9, u);
return [lerp(42, HERO_AZ, k), lerp(18, HERO_EL, k), lerp(8.4, HERO_D, k), 0.0, -0.15, 0.25, -14, -14];
},
};
const VIEWS = [{t: -1, tf: -1, key: 'intro'}, ...SCRIPT.map((e) => ({t: tauAt(e.t), tf: e.t, key: e.act === 'assemble' ? 'exploded' : e.act}))];
const viewIdx = (x) => {
let i = 0;
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= x) i++;
return i;
};
// ASSEMBLE runs on the EXPLODED view's clock, so both read as one continuous shot (and HERO blends out of it)
const resolve = (i) => (VIEWS[i].key === 'exploded' && i > 0 && VIEWS[i - 1].key === 'exploded' ? VIEWS[i - 1] : VIEWS[i]);
const camFn = (V, x, t) => CAM[V.key](V.key === 'intro' ? x : V.key === 'exploded' ? t - V.tf : x - V.t);
const camAt = (x, t) => {
const i = viewIdx(x);
let o = camFn(resolve(i), x, t);
if (i > 0 && resolve(i) === VIEWS[i]) {
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.7, x);
if (k < 1) {
const a = camFn(resolve(i - 1), x, t);
const dAz = ((o[0] - a[0] + 540) % 360) - 180;
const b = o.map((v, j) => lerp(a[j], v, k));
b[0] = a[0] + dAz * k;
b[2] += 0.5 * Math.sin(Math.PI * k);
o = b;
}
}
const f = flightAt(x);
// the camera follows the wasp's path, and on the climb lets go sideways and follows the rise a third of the way
const kOut = ss(T_END + DEP - 0.2, T_END + DEP + 0.5, x);
const kIn = 1 - ss(0.2, 1.9, x);
const tr = (0.85 - 0.3 * kIn) * (1 - kOut);
const trY = (0.85 - 0.35 * kIn) * (1 - 0.65 * kOut);
return {az: o[0], el: o[1], d: o[2], tx: o[3] + f.path.x * tr, ty: o[4] + f.path.y * trY, tz: o[5] + f.path.z * tr, sx: o[6], sy: o[7]};
};
const actAt = (x) => VIEWS[viewIdx(x)].key;
const stateAt = (t) => {
const x = tauAt(t);
const ex = explodeAt(x);
const amp = AMP * (1 - stopAt(x));
const f = flightAt(x);
const open = Object.fromEntries(Object.keys(ACT_R).map((a) => [a, openOf(a, x)]));
let wingFlip = 0;
for (const t0 of at('wing')) wingFlip = Math.max(wingFlip, ss(t0 + WING_FLIP[0], t0 + WING_FLIP[1], x));
if (wingFlip >= 1) wingFlip = 0;
// the sting: out of its collar once the abdomen hangs open, back in before it closes
let stingK = 0;
for (const t0 of at('abdomen')) stingK = Math.max(stingK, ss(t0 + 0.75, t0 + 1.15, x) * (1 - ss(t0 + 1.4, t0 + 1.6, x)));
return {
t,
tau: x,
rate: rate(t),
spinT: spinAt(x),
explode: ex,
amp,
flap: Math.PI * 2 * FLAP_HZ * x,
display: 1 - amp / AMP,
blur: 1,
sub: {thorax: open.thorax, abdomen: open.abdomen},
eye: open.optics,
wingOut: open.wing,
wingFlip,
stingK,
legK: 0,
open,
flight: f,
cam: camAt(x, t),
view: actAt(x),
guides: 0.45 + 0.55 * Math.min(1, ex * 2.5 + activity(x)),
turn: turnAt(x),
};
};
// labels: on while the act's parts are moving apart and while they hang open, gone before they close
const LABELS = {
optics: [['eyeGlass', 'OUTER GLASS', 'Ø 40 MM · AR COATED'], ['eyeInner', 'INNER ELEMENT', 'Ø 15 MM'], ['iris', 'IRIS', '10 BLADES · OPENS 3×'], ['barrel', 'LENS BARREL', 'THREADED · 4 RINGS']],
wing: [['wing', 'WING MEMBRANE', 'FROSTED FILM · 0.1 MM'], ['hinge', 'WING HINGE', 'QUICK RELEASE'], ['hinge2', 'HINDWING HINGE', 'PHASE +40°']],
thorax: [['plate', 'SADDLE PLATE', 'POLYMER SHELL'], ['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'], ['act', 'ACTUATOR RING', '11 PISTONS'], ['core', 'CONTROL BOARDS', 'FLIGHT CPU · IMU']],
abdomen: [['waist', 'WAIST STALK', '5 BEADS · LIT RINGS'], ['s1', 'SHELL BAND', 'TELESCOPING'], ['capsule', 'BAND 4', 'RIVETED · 5 SEGMENTS'], ['sting', 'STINGER', 'GLASS · EXTENDS 30 MM']],
exploded: [['lens', 'OPTIC HEAD', '2 × LENS'], ['collar', 'NECK BEARING', '10 SEGMENTS'], ['gears', 'DRIVE GEARS', 'SPINNING FREE'], ['capsule', 'ABDOMEN BANDS', '5 SEGMENTS'], ['hinge', 'WING HINGE', 'QUICK RELEASE']],
};
const labelAt = (x, s) => {
const v = s.view;
if (ACT_R[v]) {
const t0 = at(v).filter((y) => y <= x).pop();
const A2 = ACT_R[v];
return {set: LABELS[v], o: bump(t0 + A2.open[0] + 0.1, t0 + A2.open[0] + 0.4, t0 + A2.close[0] - 0.25, t0 + A2.close[0], x)};
}
if (v === 'exploded') return {set: LABELS.exploded, o: bump(T_EXP + 0.4, T_EXP + 0.8, T_EXP + 1.6, T_EXP + 1.9, x)};
return {set: [], o: 0};
};
const telemetry = (t, s) => {
const x = s.tau;
const f = s.flight;
const stroke = [];
for (let i = 0; i <= 90; i++) {
const tt = x - 1.2 + (i / 90) * 1.2;
const a = AMP * (1 - stopAt(tt));
const ph = Math.PI * 2 * FLAP_HZ * tt;
stroke.push([a * Math.sin(ph), a * Math.sin(ph + 0.7)]);
}
const ex = s.explode > 0.04;
const acc = -Math.sin(x * 2.6);
const free = [0, 1, 2, 3, 4, 5].map(() => ex);
const servos = [0.44, 0.58, 0.49, 0.4, 0.53, 0.46].map((b, i) => (free[i] ? 0 : Math.max(0, Math.min(1, b * (1 + 0.32 * acc) + 0.12 * Math.abs(f.roll) / 30 + 0.03 * Math.sin(x * 7 + i)))));
const v = s.view;
const opening = ACT_R[v] ? s.open[v] : 0;
const NAME = {optics: 'OPTICS OPEN', wing: 'WING OFF', thorax: 'THORAX OPEN', abdomen: 'ABDOMEN OPEN'};
const dartU = x - T_END - DEP;
const darting = dartU > 0;
let status = 'HOVER';
let kind = 'ok';
if (x < T_FIRST) status = 'DIVING';
if (ACT_R[v] && opening > 0.05) [status, kind] = [NAME[v], 'warn'];
if (v === 'exploded') [status, kind] = s.rate < 0.9 ? ['SLOW-MO', 'warn'] : x < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['HOVER', 'ok'];
if (darting) status = 'CLIMB-OUT';
const ROW = {optics: 0, thorax: 2, wing: 3, leg: 4, abdomen: 5};
const sub = (i) => {
if (ex) return ['warn', 'DETACHED'];
if (ROW[v] === i && opening > 0.05) return ['warn', i === 3 ? 'DETACHED' : 'OPEN'];
if (i === 3) return s.amp > 1 ? ['ok', `${FLAP_HZ} HZ`] : ['idle', 'PARKED'];
if (i === 2) return s.amp > 1 ? ['ok', 'RUNNING'] : ['idle', 'STOPPED'];
return ['ok', ['TRACKING', 'LOCKED', '', '', 'HOLDING', 'SEALED'][i]];
};
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 · CLIMB-OUT' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
const sp = darting ? 0.4 + 1.2 * (1.2 + 3 * dartU) : f.pos.length() > 0.05 ? 0.4 + 0.2 * Math.abs(Math.sin(x)) : 0.004;
const labels = labelAt(x, s);
return {
time: t,
dur: DURATION,
lift: Math.max(0, (s.amp / AMP) * (0.68 + 0.02 * Math.sin(s.flap)) + 0.12 * Math.abs(f.roll) / 30),
status,
statusKind: kind,
freq: FLAP_HZ * ss(0.5, 6, s.amp),
amp: s.amp,
stroke,
playback: s.rate,
blur: 1,
battery: 0.842 - 0.0022 * t,
power: 4.2 + 31 * Math.pow(s.amp / AMP, 1.5) * (1 + 0.04 * Math.sin(s.flap)) + 3 * Math.abs(f.roll) / 30 + (darting ? 9 * ss(0, 0.5, dartU) : 0),
volt: 3.92 - 0.006 * 36,
motorT: 34 + 0.35 * t,
servos,
legsFree: ex,
legFreeEach: free,
airborne: true,
alt: (f.pos.y - FLOOR_Y) * MM,
vs: x < T_FIRST ? -MM * S * (ss(-0.9, 1.6, x + 0.05) - ss(-0.9, 1.6, x - 0.05)) * 10 : MM * 0.05 * 2.6 * Math.cos(x * 2.6) * f.calm,
pitch: f.pitch,
roll: f.roll,
airspeed: sp,
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
display: {labels: labels.o > 0.5, exploded: x >= T_EXP && x < T_ASM, blur: s.amp > 3, turntable: s.turn > 0.5 && x < TT[1]},
subs: [0, 1, 2, 3, 4, 5].map(sub),
focus: ROW[v] ?? (v === 'exploded' ? 1 : -1),
events: EVENTS,
next: `${EVENTS.length} OPERATOR ACTIONS`,
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · DIVING · BANK LEFT',
mode: status,
modeSub:
status === 'DIVING'
? `BANK ${f.roll.toFixed(0)}° · DIVING IN`
: status === 'SLOW-MO'
? `PLAYBACK ${s.rate.toFixed(2)}× · ${Math.round(s.explode * 100)}% APART`
: status === 'TEARDOWN' || status === 'REASSEMBLY'
? `TURNTABLE ${Math.round(s.turn)}° CW · ${Math.round(s.explode * 100)}% APART`
: status === 'CLIMB-OUT'
? `CLIMBING · ${sp.toFixed(1)} M/S`
: ACT_R[v]
? `${ASSEMBLY_LABEL[v]} · ${Math.round(opening * 100)}% APART`
: `STATION KEEPING · ${((f.pos.y - FLOOR_Y) * MM).toFixed(0)} MM AGL`,
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
labelSet: labels,
};
};
return {SCRIPT, DURATION, stateAt, telemetry, camAt, flightAt, tauAt};
}
+389
View File
@@ -0,0 +1,389 @@
// The VX-9 wasp's tour: the bee's (robobee-shared/tour_v2.js) 1:1, the stinger sliding out at the end of the abdomen act.
// The HB-7 simulator tour, second cut: the bee itself does something big every 2-3 s. It flies in and banks through a
// turn, then the operator opens one assembly after another, each with the camera pushed in on it: the lens unscrews
// along its axis and the iris opens, a wing pulls out of its hinge and turns over in the air, a leg comes apart
// segment by segment with its servos spinning, the thorax shells lift off over spinning gears, the abdomen telescopes
// apart; then the whole bee explodes on a 330° turntable with its parts spinning, snaps back together while it still
// turns, spins its wings up and banks away out of frame. Labels show only while parts move.
// Script: the entry's timeline.json, {duration, script: [{t, act}]}; act is an assembly (optics, wing, leg, thorax,
// abdomen), 'exploded', 'assemble' or 'hero' (the departure). Everything is a pure function of film time t.
import * as THREE from 'three';
import {VIEWPORT} from './console.js';
import {FLOOR_Y} from './tour.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;
const MM = 80;
export const FLAP_HZ = 7.5;
export const AMP = 32;
export const REACH = 0.62;
export const ASSEMBLIES = ['hero', 'optics', 'wing', 'leg', 'thorax', 'abdomen'];
export const ASSEMBLY_LABEL = {hero: 'HERO', optics: 'OPTICS', wing: 'WING', leg: 'LEG L2', thorax: 'THORAX', abdomen: 'ABDOMEN'};
export const DISPLAY2 = ['labels', 'exploded', 'blur', 'turntable'];
export const DISPLAY2_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', blur: 'MOTION BLUR', turntable: 'TURNTABLE'};
// the button each act presses
const BUTTON = {optics: 'optics', wing: 'wing', leg: 'leg', thorax: 'thorax', abdomen: 'abdomen', exploded: 'exploded', assemble: 'exploded', hero: 'hero'};
// each act's own clock (seconds after its click): when it opens, when it closes, whether the wings stop for it
const ACT = {
optics: {open: [0.35, 1.5], close: [2.2, 2.65], stop: false},
wing: {open: [0.45, 1.25], close: [2.35, 2.7], stop: true},
leg: {open: [0.35, 1.45], close: [2.15, 2.55], stop: false},
thorax: {open: [0.3, 1.4], close: [2.1, 2.6], stop: true},
abdomen: {open: [0.3, 1.3], close: [2.0, 2.45], stop: true},
};
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy], u = seconds on
export const CAM2 = {
intro: (u) => {
const k = ss(0, 3.0, u);
return [lerp(150, 34, k), lerp(15, 9, k), lerp(8.6, 7.3, k), 0.0, -0.25, 0.25, -30, -14];
},
optics: (u) => [88 - 8 * u, 6, lerp(4.9, 4.2, ss(0, 1.6, u)), 1.22, 0.12, 0.45, 0, -14],
wing: (u) => [40 + 6 * u, 18, lerp(8.6, 7.6, ss(0, 1.6, u)), -0.5, 0.95, 1.25, 0, -14],
leg: (u) => [14 + 9 * u, 6, lerp(6.6, 5.8, ss(0, 1.6, u)), 0.1, -0.8, 0.45, 0, -14],
thorax: (u) => [8 + 10 * u, 34, lerp(6.8, 6.0, ss(0, 1.6, u)), 0.0, 0.32, 0.05, 0, -14],
abdomen: (u) => [-30 + 9 * u, 14, lerp(6.6, 5.8, ss(0, 1.6, u)), -2.45, -0.95, 0.1, 0, -14],
exploded: (u) => [34 + 5 * u, 18, 11.6, 0.0, -0.15, 0.0, -20, -14],
hero: (u) => [18 + 14 * u, 9, 6.8, 0.0, -0.22, 0.25, -30, -14],
};
export function makeTour2(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 = {};
for (const e of SCRIPT) (AT[e.act] ??= []).push(e.t);
const at = (act) => AT[act] ?? [];
const T_EXP = at('exploded')[0] ?? 999;
const T_ASM = at('assemble')[0] ?? 999;
const T_END = at('hero')[0] ?? 999;
// an assembly's opening, 0..1, from its act's clock
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;
};
// the full explode: out 0.2-1.8 s after EXPLODED, home 0-1.0 s after it goes off (fast, it snaps)
const explodeAt = (t) => ss(T_EXP + 0.2, T_EXP + 1.8, t) * (1 - ss(T_ASM, T_ASM + 1.0, t));
// the turntable: 330° from the explode to just after the bee is whole again, steady in the middle
const TT = [T_EXP + 0.2, T_ASM + 1.5];
const turnAt = (t) => {
const [a, b] = TT;
if (t <= a) return 0;
const R = 0.6;
const span = b - a;
const v = 330 / (span - R);
const x = Math.min(t, b) - a;
// a trapezoid of speed: ramp up over R, steady, ramp down over R
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);
};
// the wings stop for the acts that need still wings and for the explode, and spin back up after
const stopAt = (t) => {
let v = 0;
for (const act of Object.keys(ACT)) {
if (!ACT[act].stop) continue;
for (const t0 of at(act)) v = Math.max(v, ss(t0, t0 + 0.45, t) * (1 - ss(t0 + ACT[act].close[1], t0 + ACT[act].close[1] + 0.5, t)));
}
return Math.max(v, ss(T_EXP, T_EXP + 0.45, t) * (1 - ss(T_ASM + 0.9, T_ASM + 1.5, t)));
};
// the busy clock the gears and loose parts turn on: they run five times faster while something is open
const activity = (t) => Math.max(...Object.keys(ACT).map((a) => openOf(a, t)), explodeAt(t));
const DT = 1 / 240;
const SPIN = [0];
for (let i = 1; i * DT <= DURATION + 1; i++) SPIN.push(SPIN[i - 1] + (1 + 5 * activity((i - 0.5) * DT)) * 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));
// the flight: in from behind-left banking through a turn, the hover, the turntable, the departure banking away
const flightAt = (t) => {
const kIn = ss(-0.3, 2.6, t);
const ex = explodeAt(t);
const calm = 1 - Math.min(1, ex * 2.5);
const pos = new THREE.Vector3(lerp(-2.6, 0, kIn), lerp(0.6, 0, kIn) + 0.05 * Math.sin(t * 2.6) * calm, lerp(-3.2, 0, kIn));
let yaw = lerp(-80, 0, kIn) + 14 * Math.sin(Math.PI * kIn);
let roll = 30 * Math.sin(Math.PI * Math.min(1, kIn * 1.05)) + 1.7 * Math.sin(t * 1.3 + 1.1) * calm;
let pitch = -6 * Math.sin(Math.PI * kIn) + 1.4 * Math.sin(t * 1.9 + 0.6) * calm;
yaw += turnAt(t);
if (t > T_END + 1.0) {
const u = t - T_END - 1.0;
const k = ss(0, 1.0, u);
yaw += 38 * k;
roll -= 30 * k;
pitch += 8 * k;
const h = new THREE.Vector3(Math.cos(yaw * D2R), 0, -Math.sin(yaw * D2R));
pos.addScaledVector(h, 1.6 * u * u).add(new THREE.Vector3(0, 0.45 * u * u, 0));
}
return {pos, yaw, roll, pitch, calm};
};
// the camera: each act's view, blended over 0.8 s with a short dolly out, tracking the bee as it flies
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) => CAM2[V.key](t - (V.key === 'intro' ? 0 : V.t));
const camAt = (t) => {
const i = viewIdx(t);
let o = camFn(VIEWS[i], t);
// the reassembly keeps the explode's camera running from where it was
if (VIEWS[i].key === 'exploded' && i > 0 && VIEWS[i - 1].key === 'exploded') o = camFn(VIEWS[i - 1], t);
else if (i > 0) {
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.85, t);
if (k < 1) {
const a = camFn(VIEWS[i - 1], t);
const dAz = ((o[0] - a[0] + 540) % 360) - 180;
const b = o.map((v, j) => lerp(a[j], v, k));
b[0] = a[0] + dAz * k;
b[2] += 0.7 * Math.sin(Math.PI * k);
o = b;
}
}
// the camera follows the bee in, and lets it go on the way out
const f = flightAt(t);
const track = 0.85 - 0.5 * ss(T_END + 1.0, T_END + 2.0, t);
return {az: o[0], el: o[1], d: o[2], tx: o[3] + f.pos.x * track, ty: o[4] + f.pos.y * track, tz: o[5] + f.pos.z * track, sx: o[6], sy: o[7]};
};
const actAt = (t) => {
const i = viewIdx(t);
return VIEWS[i].key;
};
const stateAt = (t) => {
const ex = explodeAt(t);
const amp = AMP * (1 - stopAt(t));
const f = flightAt(t);
const open = Object.fromEntries(Object.keys(ACT).map((a) => [a, openOf(a, t)]));
// the wing's own clock: out, one full turn over, back in fast
let wingOut = 0;
let wingFlip = 0;
for (const t0 of at('wing')) {
const A = ACT.wing;
wingOut = Math.max(wingOut, ss(t0 + A.open[0], t0 + A.open[1], t) * (1 - ss(t0 + A.close[0], t0 + A.close[1], t)));
wingFlip = Math.max(wingFlip, ss(t0 + 0.9, t0 + 2.3, t));
}
if (wingFlip >= 1) wingFlip = 0;
// the sting: out of its collar once the abdomen hangs open, back in before it closes
let stingK = 0;
for (const t0 of at('abdomen')) stingK = Math.max(stingK, ss(t0 + 1.05, t0 + 1.55, t) * (1 - ss(t0 + 1.9, t0 + 2.2, t)));
const view = actAt(t);
return {
t,
spinT: spinAt(t),
explode: ex,
amp,
flap: Math.PI * 2 * FLAP_HZ * t,
display: 1 - amp / AMP,
blur: 1,
sub: {thorax: open.thorax, abdomen: open.abdomen},
eye: open.optics,
wingOut,
wingFlip,
legK: open.leg,
stingK,
open,
flight: f,
cam: camAt(t),
view,
guides: 0.45 + 0.55 * Math.min(1, ex * 2.5 + activity(t)),
turn: turnAt(t),
};
};
// labels: on while the act's parts are moving apart and while they hang open, gone before they close
const LABELS = {
optics: [['eyeGlass', 'OUTER GLASS', 'Ø 40 MM · AR COATED'], ['eyeInner', 'INNER ELEMENT', 'Ø 15 MM'], ['iris', 'IRIS', '10 BLADES · OPENS 3×'], ['barrel', 'LENS BARREL', 'THREADED · 4 RINGS']],
wing: [['wing', 'WING MEMBRANE', 'FROSTED FILM · 0.1 MM'], ['hinge', 'WING HINGE', 'QUICK RELEASE'], ['hinge2', 'HINDWING HINGE', 'PHASE +40°']],
leg: [['hip2', 'HIP SERVO', 'YAW + LIFT'], ['knee2', 'KNEE SERVO', '0.4 N·M'], ['foot', 'FOOT CLAW', 'TWIN HOOKS']],
thorax: [['plate', 'SADDLE PLATE', 'POLYMER SHELL'], ['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'], ['act', 'ACTUATOR RING', '11 PISTONS'], ['core', 'CONTROL BOARDS', 'FLIGHT CPU · IMU']],
abdomen: [['waist', 'WAIST STALK', '5 BEADS · LIT RINGS'], ['s1', 'SHELL BAND', 'TELESCOPING'], ['capsule', 'BAND 4', 'RIVETED · 5 SEGMENTS'], ['sting', 'STINGER', 'GLASS · EXTENDS 30 MM']],
exploded: [['lens', 'OPTIC HEAD', '2 × LENS'], ['collar', 'NECK BEARING', '10 SEGMENTS'], ['gears', 'DRIVE GEARS', 'SPINNING FREE'], ['capsule', 'ABDOMEN BANDS', '5 SEGMENTS'], ['hinge', 'WING HINGE', 'QUICK RELEASE']],
};
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};
};
const telemetry = (t, s) => {
const f = s.flight;
const stroke = [];
for (let i = 0; i <= 90; i++) {
const tt = t - 1.2 + (i / 90) * 1.2;
const a = AMP * (1 - stopAt(tt));
const ph = Math.PI * 2 * FLAP_HZ * tt;
stroke.push([a * Math.sin(ph), a * Math.sin(ph + 0.7)]);
}
const ex = s.explode > 0.04;
const acc = -Math.sin(t * 2.6);
const free = [0, 1, 2, 3, 4, 5].map((i) => ex || (i === 1 && s.legK > 0.08));
const servos = [0.44, 0.58, 0.49, 0.4, 0.53, 0.46].map((b, i) => (free[i] ? 0 : Math.max(0, Math.min(1, b * (1 + 0.32 * acc) + 0.12 * Math.abs(f.roll) / 30 + 0.03 * Math.sin(t * 7 + i)))));
const v = s.view;
const opening = ACT[v] ? s.open[v] : 0;
const NAME = {optics: 'OPTICS OPEN', wing: 'WING OFF', leg: 'LEG L2 OPEN', thorax: 'THORAX OPEN', abdomen: 'ABDOMEN OPEN'};
let status = 'HOVER';
let kind = 'ok';
if (t < 2.6) status = 'BANKING';
if (ACT[v] && (opening > 0.05 || (v === 'wing' && s.wingOut > 0.05))) [status, kind] = [NAME[v], 'warn'];
if (v === 'exploded') [status, kind] = t < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['HOVER', 'ok'];
if (t > T_END + 1.0) status = 'DEPARTING';
const ROW = {optics: 0, thorax: 2, wing: 3, leg: 4, abdomen: 5};
const sub = (i) => {
if (ex) return ['warn', 'DETACHED'];
if (ROW[v] === i && (opening > 0.05 || (v === 'wing' && s.wingOut > 0.05))) return ['warn', i === 3 ? 'DETACHED' : 'OPEN'];
if (i === 3) return s.amp > 1 ? ['ok', `${FLAP_HZ} HZ`] : ['idle', 'PARKED'];
if (i === 2) return s.amp > 1 ? ['ok', 'RUNNING'] : ['idle', 'STOPPED'];
return ['ok', ['TRACKING', 'LOCKED', '', '', 'HOLDING', 'SEALED'][i]];
};
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 · RELEASE' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
const sp = f.pos.length() > 0.05 ? 0.4 + 0.2 * Math.abs(Math.sin(t)) : 0.004;
const labels = labelAt(t, s);
return {
time: t,
dur: DURATION,
lift: Math.max(0, (s.amp / AMP) * (0.68 + 0.02 * Math.sin(s.flap)) + 0.12 * Math.abs(f.roll) / 30),
status,
statusKind: kind,
freq: FLAP_HZ * ss(0.5, 6, s.amp),
amp: s.amp,
stroke,
playback: 1,
blur: 1,
battery: 0.842 - 0.0022 * t,
power: 4.2 + 31 * Math.pow(s.amp / AMP, 1.5) * (1 + 0.04 * Math.sin(s.flap)) + 3 * Math.abs(f.roll) / 30,
volt: 3.92 - 0.006 * 36,
motorT: 34 + 0.35 * t,
servos,
legsFree: ex,
legFreeEach: free,
airborne: true,
alt: (f.pos.y - FLOOR_Y) * MM,
vs: MM * 0.05 * 2.6 * Math.cos(t * 2.6) * f.calm,
pitch: f.pitch,
roll: f.roll,
airspeed: sp,
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
display: {labels: labels.o > 0.5, exploded: t >= T_EXP && t < T_ASM, blur: s.amp > 3, turntable: s.turn > 0 && t < TT[1]},
subs: [0, 1, 2, 3, 4, 5].map(sub),
focus: ROW[v] ?? (v === 'exploded' ? 1 : -1),
events: EVENTS,
next: `${EVENTS.length} OPERATOR ACTIONS`,
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · BANKING LEFT',
mode: status,
modeSub:
status === 'BANKING'
? `ROLL ${f.roll.toFixed(0)}° · INBOUND`
: status === 'TEARDOWN' || status === 'REASSEMBLY'
? `TURNTABLE ${Math.round(s.turn)}° · ${Math.round(s.explode * 100)}% APART`
: status === 'DEPARTING'
? `BANK ${f.roll.toFixed(0)}° · RELEASED`
: ACT[v]
? `${ASSEMBLY_LABEL[v]} · ${Math.round(Math.max(opening, s.wingOut) * 100)}% APART`
: `STATION KEEPING · ${((f.pos.y - FLOOR_Y) * MM).toFixed(0)} MM AGL`,
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
labelSet: labels,
};
};
return {SCRIPT, DURATION, stateAt, telemetry, camAt};
}
/** Labels in two columns at the viewport's edges, as the first cut, from a set of anchors. */
export function makeLabels2(st, bee) {
const p = new THREE.Vector3();
return ({set, o}) => {
if (o < 0.02) return [];
const pts = [];
for (const [key, name, sub] of set) {
const A = bee.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
const GUTTER_X = 1262;
export function makeCursor2(ui, SCRIPT) {
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[BUTTON[e.act]]}));
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};
};
}
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env node
// Sound check: waveform with every timeline beat drawn on top, plus loudness.
//
// node wave.mjs cutaway-out/effort.wav --timeline sfx/cues/effort_timeline.json
// node wave.mjs final.mp4 --timeline timeline.json measure what you will actually post
// without --timeline: waveform and loudness only, no beat lines
// → <input>_wave.png next to the input
//
// Every hit in the waveform should sit on (or a hair after) a beat line.
import {execFileSync, spawnSync} from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import {FFMPEG, FFPROBE} from './paths.mjs';
const argv = process.argv.slice(2);
const ti = argv.indexOf('--timeline');
const timelinePath = ti === -1 ? null : path.resolve(argv.splice(ti, 2)[1]);
if (!argv[0] || !fs.existsSync(argv[0])) {
console.error('usage: node wave.mjs <file.wav|file.mp4> [--timeline timeline.json]');
process.exit(1);
}
const input = path.resolve(argv[0]);
const TARGET_LUFS = -14;
const MAX_TRUE_PEAK = -1;
const W = 1800;
const H = 280;
const probed = Number(execFileSync(FFPROBE, ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', input]).toString());
const tl = timelinePath ? JSON.parse(fs.readFileSync(timelinePath, 'utf8')) : {duration: probed};
tl.duration ??= probed;
const beats = [];
const walk = (v, key) => {
if (key === 'fps' || key === 'duration') return;
if (typeof v === 'number') beats.push(v);
else if (Array.isArray(v)) v.forEach((x) => walk(x));
else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x]) => walk(x, k));
};
walk(tl);
const marks = [...new Set(beats)]
.map((t) => `drawbox=x=${Math.round((t / tl.duration) * W)}:y=0:w=2:h=ih:color=0xD97757@0.9:t=fill`)
.join(',');
const seconds = `drawgrid=w=${W / tl.duration}:h=${H}:color=white@0.12`;
const png = input.replace(/\.[^.]+$/, '') + '_wave.png';
execFileSync(FFMPEG, [
'-loglevel', 'error', '-y', '-i', input,
'-filter_complex',
`color=c=0x141413:s=${W}x${H}:d=1[bg];` +
`[0:a]aformat=channel_layouts=mono,showwavespic=s=${W}x${H}:scale=sqrt:colors=0x8A877F[w];` +
`[bg][w]overlay=format=auto,${seconds}${marks ? ',' + marks : ''}`,
'-frames:v', '1', png,
]);
const r = spawnSync(FFMPEG, ['-hide_banner', '-nostats', '-i', input, '-af', 'ebur128=peak=true', '-f', 'null', '-'], {
encoding: 'utf8',
});
const summary = r.stderr.slice(r.stderr.lastIndexOf('Summary'));
const lufs = Number(summary.match(/I:\s+(-?[\d.]+) LUFS/)?.[1]);
const peak = Number(summary.match(/Peak:\s+(-?[\d.]+) dBFS/)?.[1]);
console.log(`waveform: ${png} (${beats.length} beats in coral, grid = 1s)`);
console.log(`loudness: ${lufs} LUFS integrated (target ${TARGET_LUFS} ±1)`);
console.log(`true peak: ${peak} dBFS (keep ≤ ${MAX_TRUE_PEAK})`);
if (Math.abs(lufs - TARGET_LUFS) > 1) console.warn('WARN loudness off target: re-run the cue sheet, check TARGET_LUFS');
if (peak > MAX_TRUE_PEAK) console.warn('WARN true peak too hot: AAC encoding may clip, lower the master ceiling');