Skip to content

Photoreal Blender scenes from a one-paragraph brief, built by AI agents: image→3D props on fal, scripted layout, lighting, camera and grade.

Python

AnyScene endpoints, AnyShot, AnyKit, render farm and web UI

Apekshik Panigrahi4b1b10409b04
diff --git a/.gitignore b/.gitignore
index be64e22..21b11bb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,15 +20,45 @@ scenes/*/cache/
breakdown/*/
!breakdown/*.py
!breakdown/*.md
+# other heavy formats that should never be committed
+*.mov
+*.webm
+*.fbx
+*.obj
+*.usd
+*.usdz
+*.hdr
+*.blend@
+# small README images are the exception to *.png / *.jpg above
+!docs/media/
+!docs/media/*.jpg
+!docs/media/*.png
+!docs/media/*.gif
# Local state
generate/spend.jsonl
+**/spend.jsonl
logs/
+*.log
.gpu.queue/
.gpu.*_done
__pycache__/
node_modules/
.env*
+!.env.example
+pipeline/env.local.sh
+*.pem
+*.key
+.secrets*
+credentials*.json
+.venv/
# Blender writes this into the working directory
waveletNoiseTile.bin
+
+# Client output folders (responses, downloaded stills/videos, event logs)
+anyshot_out/
+builder_out/
+# Generation records (refs/**/*.json) hold local output paths; refs/ above already excludes them, this is explicit
+refs/**/*.json
+*.tsbuildinfo
diff --git a/README.md b/README.md
index 0baa4ae..19d4756 100644
--- a/README.md
+++ b/README.md
@@ -1,61 +1,111 @@
# AnyScene
-Photoreal Blender scenes from a one-paragraph brief, built by AI agents.
+Give it reference images of a place (or a one-paragraph brief) and it builds a dressed, lit Blender scene: a real room
+with every prop as its own model, practical lights, grime, haze, cinematic camera moves and graded renders.
-You describe a place. An agent following [`SKILL.md`](SKILL.md) then:
-1. generates concept images and a reference image for every prop;
-2. turns each prop into 3D with both Tripo H3.1 and Meshy 7.1 on [fal](https://fal.ai), and picks the better one;
-3. scripts the room, dresses it from big furniture down to small clutter, and checks every prop for collisions and floating;
-4. adds grime, decals, night lighting, haze, steam and rain;
-5. shoots cinematic and handheld walk-through shots, renders them in Cycles and grades them;
-6. cuts a behind-the-scenes video of how the scene was built.
+The work is done by an AI agent (Claude, in Claude Code) following [`SKILL.md`](SKILL.md). No prop is modelled by hand:
+each one is generated as an image, turned into 3D with two image-to-3D models on [fal](https://fal.ai), and the better
+result is picked by comparing same-light renders.
-No prop is modelled by hand. The two example scenes were each made in about a day of agent work, for about $150 of generation.
+![Five AnyScene scenes](docs/media/strip.jpg)
-| Scene | Props | Shots |
+## Five places, one process
+
+| | Scene | |
|---|---|---|
-| [`scenes/tokyo-electronics-repair`](scenes/tokyo-electronics-repair) — a 1 AM electronics repair counter, rain outside | 86 generated | 7 cinematic + 2 handheld |
-| [`scenes/tokyo-ramen-shop`](scenes/tokyo-ramen-shop) — a ramen counter at last orders, steam and rain | 74 generated | 6 cinematic + 2 handheld |
+| ![](docs/media/repair.jpg) | **Electronics repair shop**, Tokyo, 1 AM, rain outside | [`scenes/tokyo-electronics-repair`](scenes/tokyo-electronics-repair) · 86 generated props |
+| ![](docs/media/ramen.jpg) | **Ramen shop**, Tokyo, last orders, steam and rain | [`scenes/tokyo-ramen-shop`](scenes/tokyo-ramen-shop) · 74 generated props |
+| ![](docs/media/hk.jpg) | **Dai pai dong**, Hong Kong, an open-air street kitchen just after rain | [`scenes/hk-dai-pai-dong`](scenes/hk-dai-pai-dong) · 78 generated props |
+| ![](docs/media/mc.jpg) | **Mission control**, 1970s, a night shift during an orbital flight | [`scenes/mission-control-1970s`](scenes/mission-control-1970s) |
+| ![](docs/media/bakery.jpg) | **Maison Roussel**, a Paris bakery. Built by the hosted endpoint from [one reference image](docs/media/bakery_reference.jpg), with no human input, in under two hours | (endpoint run) |
+
+The first four were built by an agent working through `SKILL.md`, with a person checking its gates. The bakery was built
+end to end by the same process running unattended on a fal GPU worker.
+
+This repo is the process and the code. The finished scenes (.blend files, generated models, textures, renders) add up
+to tens of gigabytes and are not in git. Each scene folder keeps what's needed to rebuild it: its prop list
+(`assets.json`), model picks with reasons (`picks.json`), shots (`shots.json`), notes and build scripts.
+
+## Quick start
+
+You need:
+- [Blender](https://www.blender.org/) 5.0 or newer. Set `BLENDER` if it isn't on your PATH or in the default install location.
+- [Node](https://nodejs.org/) 20 or newer, then `npm install` in the repo root.
+- A [fal API key](https://fal.ai/dashboard/keys) in `FAL_KEY`. Generation is billed to your fal account: roughly $1.65
+ per prop (an image plus two 3D models), so about $150 for a 90-prop scene.
+- ffmpeg with an H.264 encoder (`FFMPEG`, default `ffmpeg`). The example scenes were built on Windows with an NVIDIA GPU
+ and use `h264_nvenc`; on other machines, swap in `libx264`.
+- [uv](https://docs.astral.sh/uv/) for the Python helper scripts.
+- [Claude Code](https://claude.com/claude-code).
+- A GPU with 12–16 GB of memory for Cycles.
+
+Then open the repo in Claude Code and ask for a scene:
-This repo holds the process and the code. The finished scenes (.blend files, generated models, renders) are large and are
-downloaded separately.
+> Use SKILL.md to build a new scene: a Lisbon tram depot at dawn, one tram half-stripped for repair.
-## Layout
+Or start from your own references: put a few images (and, optionally, a floor plan) in `refs/<scene>/` and say so:
-```
-SKILL.md the process, step by step, with every gotcha we hit; agents start here
-generate/ fal client: reference images and image→3D (Tripo H3.1, Meshy 7.1), with a spend log
-pipeline/ env.sh (finds Blender/ffmpeg), GPU queue, comparison renders, gallery page
-camera/ camera rig and shot renderer: moves, rack focus, handheld walk, lens FX (see camera/README.md)
-breakdown/ the behind-the-scenes video and the promo cut
-scenes/<name>/ one folder per scene: assets.json (props), picks.json (model choices), shots.json, NOTES.md, scripts/
-```
+> Use SKILL.md to build a scene from the reference images in refs/lisbon-tram-depot/. Treat them as the approved concept.
-Each scene keeps its own build scripts in `scripts/`. A scene's room shell and dressing are specific to that place, so a
-new scene starts from the closer example and an agent rewrites those parts.
+Check the agent's work at each gate: concept, prop picks, clay layout, lit stills, shot previews. Expect most of a day
+of agent time and 1–2 GPU-hours of final renders per scene.
-## Requirements
+## How the agent works
-- Blender 5.0+ (`BLENDER`, otherwise found on PATH or in the default install location)
-- ffmpeg with `h264_nvenc` (`FFMPEG`, default `ffmpeg`). The example scenes were built on Windows with an NVIDIA GPU;
- on other GPUs, swap `h264_nvenc` for `libx264` in the encode steps.
-- Node 20+
-- A fal API key in `FAL_KEY`
-- `uv` for the breakdown videos (`uv run --with pillow python breakdown/assemble.py <scene>`)
+[`SKILL.md`](SKILL.md) is the whole process, step by step, with every gotcha the example scenes hit:
-## Start a new scene
+1. brief → scene spec (room size, zones, hero spots, real light sources);
+2. concept images, or your references;
+3. a prop manifest, then a reference image for every prop;
+4. each prop through both Tripo H3.1 and Meshy 7.1, picked by looking at same-light renders;
+5. a scripted room shell, dressing from big furniture down to small clutter, with collision and floating checks;
+6. grime, de-branding, decals, practical lighting, haze, steam and rain;
+7. cinematic and long handheld walkthrough shots, rendered in Cycles and graded;
+8. optionally, a behind-the-scenes video.
-Point your agent at `SKILL.md` and give it a brief:
+Every step ends with a gate: a contact sheet the agent has to look at before moving on. Everything is a script, so the
+.blend is a build output that can be regenerated.
-> Use SKILL.md to build a new scene: a Lisbon tram depot at dawn, one tram half-stripped for repair.
+[`builder/CRAFT.md`](builder/CRAFT.md) is the short version of what made the good scenes good: render it and look, name
+the problem precisely, fix it in code, check the fix from a view that shows it, and get an independent critic.
+
+## Layout
+
+```
+SKILL.md the process; agents start here
+builder/CRAFT.md the review loop that separates good scenes from first drafts
+generate/ fal client: images and image→3D (Tripo H3.1, Meshy 7.1), with a local spend log
+pipeline/ Blender/ffmpeg discovery, a FIFO GPU queue, comparison renders, gallery pages, floating-prop check
+camera/ camera rig and shot renderer: moves, rack focus, handheld walk, lens effects (camera/README.md)
+breakdown/ behind-the-scenes videos, promo cuts and the launch supercut
+scenes/<name>/ one folder per scene: assets.json, picks.json, shots.json, NOTES.md, brief.md, scripts/
+farm/ a fal Serverless render farm for Cycles, and a client that renders a scene's shots on it
+blender_addon/ the fal Render Farm add-on for Blender
+builder/ the same process packaged as a fal Serverless app (the hosted endpoint)
+docs/ endpoint and API notes, README images
+```
+
+## Hosted endpoint (optional)
+
+If you'd rather not set up Blender, a GPU and the toolchain, the hosted endpoint runs the whole build on fal: send one
+to four reference images (and an optional prompt), and get back the scene package (`scene.blend` with every prop as
+its own object, a `scene.glb`, stills and panoramas; walkthroughs render on the farm). The bakery above was built this way, from a single image.
+
+<!-- TODO(apek): link the public endpoint page / model id here once it's listed. -->
-Then check its work at each step's gate: concept, prop picks, clay layout, lit stills, shot previews.
+The endpoint's code is in [`builder/`](builder) if you want to deploy your own copy to your fal account
+(`fal deploy builder/app.py::SceneBuilderApp --app-name anyscene-builder`). It needs `FAL_KEY` and `OPENROUTER_API_KEY` set
+as secrets on the app, and the `endpoint/` folder alongside it (the builder imports its planner and schema).
-## Credits
+## Render farm add-on
-The process follows the "create high quality blender scene with AI" video workflow: concept image, scripted room shell,
-image-to-3D props, scripted repair, dressing, shaders, lighting, handheld camera, grade.
+[`blender_addon/`](blender_addon) is a Blender add-on that renders the open scene on fal GPUs instead of your own:
+direct a scene in Blender, press **Render animation on fal**, and the frames come back into the scene's output path
+with the same names a local render would give them. See [`blender_addon/README.md`](blender_addon/README.md) for
+install and settings. The farm itself is [`farm/app.py`](farm/app.py); you can deploy your own and point the add-on's
+**Farm app** preference at it.
-## License
+## Licence
-Code: MIT, see [LICENSE](LICENSE). Generated assets are released separately under their own license.
+Code is MIT, see [LICENSE](LICENSE). Generated assets are not in this repo; where they're published, they come with
+their own licence.
diff --git a/SKILL.md b/SKILL.md
index 6a87c71..f190995 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -119,7 +119,7 @@ What the reference scenes found across ~150 props:
### 6. Prep
Turn every pick into `props/<id>.blend`:
-- **Front faces −Y.** Tripo's front faces +X, so rotate it −90°; Meshy's already faces −Y. Rotate the mesh data, not the object.
+- **Front faces −Y.** Tripo's front faces +X, so rotate it −90°; Meshy's already faces −Y. Rotate the mesh data, not the object. Tripo H3.1 with `orientation: align_image` also bakes a ±20–30° Z rotation into the glTF node (to match the reference photo's three-quarter view): clear that node rotation before the −90° turn, and frame by vertex bounds, not `bound_box`.
- **Real scale** from `h`/`dims`.
- **Bottom-centre origin.**
- **Decimate** heroes to about 150k tris.
@@ -151,8 +151,20 @@ Place furniture props, then heroes, then mid props, then clutter. Each pass drop
- floating more than 1 cm. Start the float ray *above* the support's top face, or a thin bench top reports its own thickness.
Clashing small props get spiral-searched to a clear spot. Validator reports are noisy, so read them: a plinth or pots on a burner can be legitimate.
-
-**Gate:** the validator shows 0 unexplained issues, plus a dressed clay sheet and a textured flat-lit sheet.
+- **Re-drop after every move.** Anything a clash resolver or a later pass moves sideways must be dropped onto the
+ surface under its new position. Skipping this left two stools hovering at table height in the dai pai dong.
+- **Run the grounding check** after the last dressing pass and again before final renders:
+ `blender -b scene.blend --python pipeline/grounding.py -- --prefix <scene prefix> --max-gap 2`, then with `--all`.
+ It casts rays down from each object's lowest vertices (feet, legs, base rings) and skips volumes. Checking from the
+ bounding box misses floaters whenever the box bottom isn't where the object touches down. Fix floaters in the
+ dressing scripts, not only in the saved file, so a rebuild stays grounded. Hanging items (signs, AC units, lamps,
+ posters) are skipped unless you pass `--all`; check that each one it lists really is meant to hang.
+
+**Gate:**
+- The validator and the grounding check show 0 unexplained issues: no prop more than 1 cm off its support.
+- A dressed clay sheet and a textured flat-lit sheet.
+- **A contact sheet of low-angle stills** (camera ~30 cm off the floor) along the main furniture: chairs, stools,
+ tables, bins. A floating chair is obvious from there and nearly invisible in a wide shot.
### 9. Script fixes, grime and de-branding
@@ -160,6 +172,23 @@ Place furniture props, then heroes, then mid props, then clutter. Each pass drop
- **Grime:** a shared node group with AO-driven dirt, edge wear and per-instance tint. Add decals (stains, flyers, stickers) generated on flat backgrounds, alpha-keyed and stuck on with raycasts.
- **De-branding without regenerating:** render ortho views and mark the brand rectangles. Raycast the rectangles to texels, fill each with the label's ground colour plus grain, and flatten the same texels in the normal map, or embossed text survives.
+### 9b. Build the scene as a rig of dials
+
+The scene must expose the ten dials in `docs/ENDPOINT.md` (density, tidiness, wear, wetness, time_of_day, weather,
+atmosphere, power, warmth, look) as real controls, so they can be changed after the build without rebuilding:
+- **wear:** one strength input on the shared grime group, plus decal counts and label fading, all driven by one value;
+- **wetness:** a wetness mask feeding roughness, puddle masks and drips;
+- **atmosphere:** the density of every haze, dust, smoke and steam volume, scaled together;
+- **power:** lights and emitters in named groups (practicals, screens, fires and flames, machines), each switched or
+ dimmed by one value;
+- **time_of_day, weather:** sky/world and sun setups plus weather objects (rain, mist) selected by name;
+- **warmth, look:** light colour temperatures and the grade preset;
+- **density, tidiness:** recorded as the values the dressing passes used; changing them reruns those passes.
+
+Write `dials.json` (each dial's value plus what it means in this scene) and `scripts/apply_dials.py`, which reads
+`dials.json` and sets every control. Apply the dials once at the end of the build, so the rig is what produced the
+finals.
+
### 10. Lighting (night)
1. Start with practicals: the light fixtures a real place would have (lamps, pendants, tubes, signage, screens, the fridge, the street spill).
@@ -188,7 +217,7 @@ Write `shots.json` for `camera/shoot.py`. Its README is the contract: moves, rac
1. **Block:** start with `--framing` (3 stamped stills per shot), then `--preview` (Eevee, stamped).
2. **Design:** mix 2–3 cinematic moves (push-ins, a dolly zoom, a 100–135 mm rack) with 1–2 long **handheld walkthroughs**: `"handheld": {"profile": "walk"}`, a 4–6 key `path` at walking pace. People respond most to the walkthroughs. Keep them as long, uncut takes.
-3. **Path check:** check the camera against the scene before rendering, keeping more than 0.45 m from every mesh on every frame.
+3. **Path check:** check the camera against the scene before rendering, keeping more than 0.45 m from every solid surface on every frame (walls, furniture, props: not dust motes, particles, haze volumes or decals, which a real camera moves through). Load the scene once and test every frame in one Blender session.
4. **Focus:**
- A focus target must never be one the camera passes through, or the distance collapses to 0 and the frame goes soft. Rack to something past it first.
- Focus `obj` uses the bounding-box centre. For deep objects, put a `pos` on the face you want sharp.
@@ -256,6 +285,7 @@ Time on one 16 GB GPU: a scene is roughly a day of agent work, and the final sho
- [ ] Every placed prop is in `picks.json` with a reason, and no real brands are visible in any shot.
- [ ] The validator is clean, or every remaining report is explained.
+- [ ] `pipeline/grounding.py` reports 0 unintended floaters on the file the finals are rendered from.
- [ ] Each hero spot has a final still, and every shot is rendered, graded and has the right duration.
- [ ] There's a reel and a compressed copy; an optional BTS video.
- [ ] `NOTES.md` is updated, and the spend is totalled.
diff --git a/anyshot/README.md b/anyshot/README.md
new file mode 100644
index 0000000..57e974f
--- /dev/null
+++ b/anyshot/README.md
@@ -0,0 +1,228 @@
+# AnyShot: an AI cinematographer for 3D scenes
+
+AnyShot turns a 3D scene and plain-language shot directions into finished stills and camera moves. It is not a
+render farm with a prompt box: a Claude agent works the set the way a DP would. It reads the scene, works out what
+is where, turns "slow push along the counter, rack focus to the register" into a real camera move with a lens, an
+ease and a focus pull, checks every frame of the move for clearance against walls and furniture, blocks each shot
+with quick previews and fixes what reads wrong from the new angle, then renders and grades the finals.
+
+- **`/scene2image`**: finished, graded stills, rendered with Cycles on the agent's own GPU.
+- **`/scene2video`**: camera moves as mp4s. The agent plans and checks the moves; the frames are rendered on a render
+ farm app (`farm/app.py`) across up to 100 GPUs at once, then graded and encoded.
+
+Direct it shot by shot (`shots`), or just brief it in words (`prompt`: "a 40-second piece: open wide, walk in like a
+visitor, then three close dolly reveals with rack focus") and the agent plans the shot list itself.
+
+The scene comes in one of two ways:
+- `scene_url`: a `.blend`, or a `.zip` holding a `.blend` and its textures, uploaded anywhere (fal storage, S3,
+ a signed link). The agent unpacks it, finds the main `.blend`, repairs texture paths, packs a self-contained copy
+ and works only on that copy. It keeps the scene's own look.
+- `build_id`: an [AnyScene](../README.md) build (`/ref2scene`) on the same fal account's storage. The agent also gets
+ the builder's notes and scouting cameras, so shots can be asked for by name.
+
+Optionally, `floor_plan_url` is an image of the set's plan, with or without a camera path drawn on it. The agent
+registers the plan to the scene and places cameras from it, following a drawn path as a walkthrough.
+
+Each order is retry-safe: an identical request (same scene, shots, settings) returns the finished result, attaches to
+the attempt still running, or resumes a dead one where it stopped, without re-rendering frames already on disk.
+
+## How it works
+
+```
+request ─▶ AnyShotApp (fal, 1 GPU) farm/app.py (fal, up to 100 GPUs)
+ ├ fetch the scene (or open the AnyScene build)
+ ├ Claude agent (builder/shots.py, builder/SHOTS.md)
+ │ read the set · plan cameras (camera/camrig.py)
+ │ clearance check every frame · block with Eevee previews
+ │ stills: Cycles finals on this GPU, ffmpeg grade
+ │ video: farm_render ────────────────────────────────▶ frame chunks, one Blender per request
+ │ grade + encode mp4 ◀───────────────────────── frames zip on fal storage
+ └ stills / videos / result.json ─▶ response
+```
+
+The code is shared with the AnyScene scene builder rather than copied. `anyshot/app.py` imports `builder/shots.py`
+(the `ShotsDirector` agent and its `farm_render` tool), `builder/scene_builder.py` (the agent harness: hooks, stage
+events, session resume) and `endpoint/planner.py`, and ships them with `local_python_modules`. The agent's workspace
+gets `camera/` (the camrig shot rig), `pipeline/` and `SHOTS.md` (its instructions) at deploy time. The scene
+builder's own `/scene2image` and `/scene2video` routes run the same code.
+
+## Deploy your own
+
+You need a fal account with Serverless access and an [OpenRouter](https://openrouter.ai) or Anthropic API key.
+
+1. **Secrets.** fal secrets are shared by every app on the account, so set each once:
+
+ ```bash
+ fal secrets set OPENROUTER_API_KEY=... # Claude through OpenRouter (or ANTHROPIC_API_KEY=... for the Anthropic API)
+ fal secrets set FAL_KEY=... # a fal key of this account: uploads, and the farm calls
+ fal secrets set FAL_SERVERLESS_KEY=... # optional: the key the farm is called with (defaults to FAL_KEY)
+ fal secrets set ANYSHOT_FARM_APP=<your-fal-username>/blender-farm
+ ```
+
+ With both OPENROUTER_API_KEY and ANTHROPIC_API_KEY set, OpenRouter is used. Optional: `FARM_WORKERS` (default
+ 100) caps how many farm requests run at once; keep it at or under the farm's `max_concurrency` and your
+ account's concurrency limit.
+
+2. **The render farm** (for `/scene2video`):
+
+ ```bash
+ fal deploy farm/app.py::BlenderFarm --app-name blender-farm --auth private
+ ```
+
+ Without `ANYSHOT_FARM_APP` (or if the farm is down), `/scene2video` still works: the agent renders the frames on
+ its own GPU in chunks, which is slower.
+
+ How the farm is set up, and why:
+ - **RTX 5090 workers** (`machine_type` in `farm/app.py`): $2.50/h against $4.00/h for an RTX PRO 6000, with about
+ 10% fewer cores. Switch to `GPU-RTXPRO6000` for sets that need more than 32 GB of VRAM.
+ - **Chunks of at least 24 frames** (`FARM_MIN_CHUNK`, a secret/env on the AnyShot app). Every chunk pays a worker
+ boot, the scene download and Blender setting up the set; at 5 frames a chunk that overhead was about 75% of the
+ bill.
+ - **Each worker downloads the scene to its own disk** from the bundle's CDN URL. Don't point workers at one shared
+ copy on `/data`: when 42 workers read the same 1.6 GB set at once, each waited about 30 minutes before its first
+ frame, against 18 seconds to download its own copy.
+ - **Shared OptiX kernel cache** on `/data/anyscene-farm/optix/<gpu>/` (a small file, read once at boot). OptiX
+ compiles its kernels on a worker's first Cycles render, about 2 minutes; each worker starts from the shared cache,
+ warms it in `setup()` and saves it back when it grows.
+ - **`keep_alive = 300`** so a burst of orders reuses booted workers.
+
+ Measured on a 1.6 GB set (458 objects, 8.6M triangles, 118 textures) at 1920x804 and 160 samples: 42 chunks of 8
+ frames on 42 RTX 5090s, all done in 3 minutes, about 102 s of Blender per chunk (17 s to the first frame, then
+ about 11 s a frame). A 20-second walkthrough at 1920x804 and 256 samples cost about $9 of farm time.
+
+3. **AnyShot:**
+
+ ```bash
+ fal deploy anyshot/app.py::AnyShotApp --app-name anyshot --auth private
+ ```
+
+ Deploy from the repository root: the app pulls in `builder/`, `endpoint/` and `camera/`. Requirements are listed
+ on the app class (`fal==1.84.0`, `claude-agent-sdk==0.2.176`, `anthropic`, `pydantic`, `pillow`, `fal-client`);
+ the deploying Python needs the same packages, e.g.
+ `uv run --python 3.13 --with fal==1.84.0 --with pydantic --with anthropic --with pillow --with fal-client --with claude-agent-sdk==0.2.176 fal deploy ...`.
+ The worker image installs Blender 5.0.1, ffmpeg and node. `request_timeout` is 7200 s (fal's cap): the agent
+ stops itself at 110 minutes to deliver what it has, and a retried request resumes the order.
+
+4. **Optional, AnyScene:** `/ref2scene` on the scene builder (`builder/app.py`) takes a `shots` order and hands the
+ finished build to AnyShot. Set `ANYSHOT_APP=<your-fal-username>/anyshot` so it calls your deployment.
+
+Storage: AnyShot keeps uploaded scenes and its retry index under `/data/anyshot/`, and reads AnyScene builds from
+`/data/anyscene/builder/`, on the account's persistent `/data` volume. Each order's working files (blocking
+previews, frames, the packed copy) live in `out/shots/<job_id>/` inside the scene's workspace.
+
+## API
+
+Both routes take the same body and return the same response.
+
+| field | type | |
+|---|---|---|
+| `scene_url` | string | A `.blend`, or a `.zip` with a `.blend` and its textures. Give this **or** `build_id`. |
+| `build_id` | string | An AnyScene build (`b_...`) on the same account. |
+| `prompt` | string | Direction for the whole order in your own words ("a 45 s trailer: open wide, walk in like a visitor, then slow dolly reveals with rack focus; moody"). On its own, the agent plans the shot list; with `shots`, it applies to all of them. Give `prompt`, `shots`, or both. |
+| `shots` | list | Optional. Each `{"name": ..., "description": ...}`; either or both. A name picks an existing camera (an AnyScene scouting camera, or a camera in the `.blend`) and names the output file. |
+| `floor_plan_url` | string | Optional plan image, optionally with a camera path or camera marks drawn on it. |
+| `settings` | object | Optional: `res` `[w, h]`, `samples`, `fps`, `seconds` (per video shot), `lens_mm`, `handheld` (`none` / `walk` / `subtle`), `look` (`clean` / `cinematic` / `gritty` / `vintage`). Missing ones are chosen per shot. |
+| `dials` | object | Optional changes to the set for this order only (`time_of_day`, `atmosphere`, `power`, `warmth`, `wetness`, ...). The source scene is never changed. |
+| `effort` | string | Claude effort: `low`, `medium` (default), `high`, `xhigh`, `max`. |
+| `fresh` | bool | Shoot again even if an identical order already finished. |
+
+Response: `job_id`, `scene_id`, `stills` (URLs), `videos` (URLs), `result` (per shot: camera, lens, move, settings
+and a note), `missing` (anything not delivered), `agent_cost_usd`, `minutes`.
+
+The agent streams its progress as `ANYSCENE_STAGE {json}` lines in the request's logs (`stage`, `message`, and a
+`preview_url` for blocking frames and finals). An order takes minutes for a couple of stills and longer for video
+(blocking, the farm, grading); use the queue, not a synchronous call.
+
+### curl
+
+```bash
+# 1. upload the scene (any URL works; this uses fal storage via the client below, or your own bucket)
+# 2. submit
+curl -s https://queue.fal.run/<your-fal-username>/anyshot/scene2video \
+ -H "Authorization: Key $FAL_KEY" -H "Content-Type: application/json" \
+ -d '{
+ "scene_url": "https://example.com/my_set.zip",
+ "shots": [
+ {"name": "counter_push", "description": "slow push along the counter at eye level, ending close on the register; rack focus from the jar in the foreground to the register"},
+ {"description": "walk in through the door and turn to reveal the back room, handheld walk, 24mm"}
+ ],
+ "settings": {"seconds": 6, "fps": 24, "res": [1920, 1080]}
+ }'
+# -> {"request_id": "...", "status_url": ".../requests/<id>/status", "response_url": ".../requests/<id>"}
+
+curl -s "https://queue.fal.run/<your-fal-username>/anyshot/requests/<id>/status?logs=1" -H "Authorization: Key $FAL_KEY"
+curl -s "https://queue.fal.run/<your-fal-username>/anyshot/requests/<id>" -H "Authorization: Key $FAL_KEY"
+```
+
+### Python
+
+```python
+import fal_client # FAL_KEY in the environment
+
+scene = fal_client.upload_file("my_set.zip")
+res = fal_client.subscribe(
+ "<your-fal-username>/anyshot/scene2image",
+ arguments={
+ "scene_url": scene,
+ "shots": [{"description": "wide establishing shot from the doorway, eye level, 24mm"},
+ {"description": "tight 85mm detail of the teapot on the counter, shallow focus"}],
+ "settings": {"res": [1920, 1080]},
+ },
+ with_logs=True,
+ on_queue_update=lambda u: [print(l["message"]) for l in getattr(u, "logs", None) or []],
+)
+print(res["stills"])
+```
+
+### Command line
+
+`anyshot/client.py` uploads local files, prints the agent's live log and downloads the results:
+
+```bash
+export FAL_KEY=... ANYSHOT_APP=<your-fal-username>/anyshot
+python anyshot/client.py image --scene my_set.blend --shot "wide from the doorway, 24mm" --shot "hero: tight on the teapot, f/1.8"
+python anyshot/client.py video --scene my_set.zip --floor-plan plan_with_path.png \
+ --shot "follow the drawn path at walking pace" --settings '{"seconds": 8}'
+python anyshot/client.py video --build-id b_1234567890 --shot hero_wide --shot "orbit the bar, 35mm"
+```
+
+`--shot` takes a camera name, words, or `name: words` for both. Results land in `--out` (default `anyshot_out/`):
+`response.json`, `events.jsonl`, and the stills and videos.
+
+## Shot grammar
+
+Describe shots the way you would to a camera crew. The agent maps the words onto the camrig moves
+(`camera/README.md`) and checks each against the set:
+
+| say | the agent does |
+|---|---|
+| push in, dolly in, pull out, track along X | a dolly move on 2+ keys; "slow" is about 0.2-0.4 m/s |
+| truck, crab, slide past X | sideways move |
+| crane up, jib, rise, pedestal down | vertical move, aim held or reframed |
+| pan, tilt, whip pan to X | same position, the aim moves |
+| orbit, arc, circle around X | an orbit on X's centre, with a radius and an angle range |
+| reveal X | starts on a foreground element or behind an occluder and moves until X comes into view and frames it |
+| rack focus / pull focus from A to B | a hold on A, then a focus pull to B, with a shallow f-stop so it reads |
+| walkthrough, follow the path, Steadicam | a smooth path at walking pace and eye height; `handheld: walk` adds an operator's step and sway |
+| dolly zoom, vertigo | the lens is solved per frame to hold the subject's size |
+| locked off, tripod | a static camera; `subtle` handheld for life |
+| wide / normal / tight, 24mm, 85mm | 18-24 mm / 35-50 mm / 85-135 mm, or the exact focal length |
+| low angle, eye level, top down, over the shoulder of X | camera height and aim |
+| "a 6 second push" | the shot's length (wins over `settings.seconds`) |
+
+Objects are found by name in the scene, so naming them helps ("the teapot", "the red stool"); the agent also looks
+at the set to find what you mean. A drawn path on a `floor_plan_url` becomes a walkthrough along it, and camera marks
+(an X, a camera icon, a cone of view) become camera positions.
+
+Every move is checked so the camera never passes within 0.45 m of a wall, furniture or a prop (dust, haze and glass
+the move is meant to pass don't count). A path through an obstacle goes around it, and the result says so.
+
+## Files
+
+- `anyshot/app.py`: the fal app (`AnyShotApp`): request handling, scene fetching, retry index.
+- `anyshot/client.py`: the CLI.
+- `builder/shots.py`: `ShotsDirector` (the agent), `farm_render`, scene fetching and the shared `shoot()` runner.
+- `builder/SHOTS.md`: the agent's instructions.
+- `builder/scene_builder.py`: the agent harness shared with the scene builder.
+- `camera/`: camrig (moves, focus, handheld) and `shoot.py` (previews, framing, finals).
+- `farm/app.py`: the render farm.
diff --git a/anyshot/app.py b/anyshot/app.py
new file mode 100644
index 0000000..48de861
--- /dev/null
+++ b/anyshot/app.py
@@ -0,0 +1,274 @@
+"""AnyShot as a fal Serverless app: an AI cinematographer for 3D scenes (see anyshot/README.md).
+
+ fal deploy anyshot/app.py::AnyShotApp --app-name anyshot --auth private
+ python anyshot/client.py video --scene ./set.zip --shot "slow push along the counter, ending on the register"
+
+POST /scene2image a scene + shots in words or by name -> finished, graded stills (rendered on this worker's GPU)
+POST /scene2video a scene + shots in words or by name -> camera moves as mp4s (frames rendered on the farm app)
+
+The scene is either `scene_url` (a .blend, or a .zip holding a .blend and its textures) or `build_id` (an AnyScene
+build on the same fal account's storage). A Claude agent (builder/shots.py, instructions in builder/SHOTS.md) reads
+the set, plans every camera (moves, lenses, focus pulls, a path drawn on an optional floor plan), checks clearance on
+every frame, blocks with quick previews, then renders finals. It streams ANYSCENE_STAGE lines that the fal queue relays
+to the caller as logs.
+
+Configuration is all environment (fal secrets): OPENROUTER_API_KEY or ANTHROPIC_API_KEY, FAL_KEY,
+FAL_SERVERLESS_KEY (the key the farm is called with; defaults to FAL_KEY) and ANYSHOT_FARM_APP (the farm app id).
+The agent, its tools and the camera rig are shared with the scene builder, not copied: this module imports them from
+builder/, endpoint/ and camera/, the way kit/app.py does.
+"""
+
+import json
+import os
+import sys
+from pathlib import PurePosixPath
+
+import fal
+from fal.container import ContainerImage
+from pydantic import BaseModel, Field
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_REPO = os.path.dirname(_HERE)
+sys.path.insert(0, os.path.join(_REPO, "builder"))
+sys.path.insert(0, os.path.join(_REPO, "endpoint"))
+import planner # noqa: E402,F401 (Claude client used by scene_builder; module level so fal bundles it)
+import schema # noqa: E402,F401
+import scene_builder # noqa: E402
+import shots # noqa: E402 (ShotsDirector, the farm_render tool, scene fetching)
+
+if os.name == "nt":
+ # Deploying from Windows: ContainerImage's context_dir default is a WindowsPath Linux can't unpickle.
+ _posix = PurePosixPath("/tmp")
+ ContainerImage.__dataclass_fields__["context_dir"].default = _posix
+ ContainerImage.context_dir = _posix
+ ContainerImage.__init__.__defaults__ = tuple(
+ _posix if isinstance(d, os.PathLike) else d for d in ContainerImage.__init__.__defaults__ or ()
+ )
+
+TOOLKIT = scene_builder.toolkit_files() # SHOTS.md, SKILL.md, camera/, pipeline/...: carried in the app
+BLENDER_GPU = open(os.path.join(_REPO, "builder", "blender_gpu.py"), encoding="utf-8").read()
+OPTIX_CACHE_LOCAL = "/var/tmp/OptixCache_root/optix7cache.db"
+OPTIX_CACHE_SHARED = "/data/anyscene/cache/optix7cache.db" # shared with the scene builder on the same account
+BUILDS_DIR = "/data/anyscene/builder" # AnyScene builds (build_id) on this account's storage
+SHOT_DIR = "/data/anyshot" # uploaded scenes (scenes/<scene_id>) and the retry index (_index)
+BLENDER_VERSION = "5.0.1"
+BLENDER_WRAPPER = '#!/bin/sh\nexec /usr/local/bin/blender.real --python /opt/anyscene/blender_gpu.py "$@"\n'
+WARMUP = """import bpy
+s = bpy.context.scene
+s.render.engine = "CYCLES"; s.cycles.samples = 4; s.render.resolution_x = s.render.resolution_y = 64
+m = bpy.data.materials.new("glass"); m.use_nodes = True; m.node_tree.nodes.new("ShaderNodeBsdfGlass")
+bpy.ops.mesh.primitive_uv_sphere_add(location=(0, 0, 0.5))
+bpy.context.object.data.materials.append(m)
+bpy.ops.render.render()
+print("WARMUP done")
+"""
+
+# identical to the scene builder's, so the image layers are shared
+DOCKERFILE = f"""
+FROM python:3.13-slim
+ENV NVIDIA_DRIVER_CAPABILITIES=all
+RUN apt-get update && apt-get install -y --no-install-recommends \\
+ curl ca-certificates xz-utils git procps fonts-dejavu-core libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 \\
+ libegl1 libxkbcommon0 libsm6 libice6 libx11-6 libglib2.0-0 ffmpeg nodejs ripgrep zip \\
+ && rm -rf /var/lib/apt/lists/*
+RUN curl -fsSL https://download.blender.org/release/Blender{BLENDER_VERSION[:3]}/blender-{BLENDER_VERSION}-linux-x64.tar.xz \\
+ | tar -xJ -C /opt \\
+ && ln -s /opt/blender-{BLENDER_VERSION}-linux-x64/blender /usr/local/bin/blender.real
+"""
+
+
+def save_optix_cache():
+ """Copy this worker's OptiX cache to /data if it has grown, so new workers skip the ~2 min kernel compile."""
+ import shutil
+ if os.path.exists(OPTIX_CACHE_LOCAL) and (not os.path.exists(OPTIX_CACHE_SHARED)
+ or os.path.getsize(OPTIX_CACHE_LOCAL) > os.path.getsize(OPTIX_CACHE_SHARED)):
+ os.makedirs(os.path.dirname(OPTIX_CACHE_SHARED), exist_ok=True)
+ tmp = f"{OPTIX_CACHE_SHARED}.{os.getpid()}.tmp"
+ shutil.copy(OPTIX_CACHE_LOCAL, tmp)
+ os.replace(tmp, OPTIX_CACHE_SHARED)
+
+
+class Shot(BaseModel):
+ name: str = Field("", description="A camera or move by name: one of an AnyScene build's scouting cameras "
+ "(its shots.json), a camera in the uploaded .blend, or a new name for the output.")
+ description: str = Field("", description="The shot in words, e.g. 'slow push along the pastry case, ending close "
+ "on the croissants, rack focus to the price card'. With a name, it adjusts "
+ "that camera.")
+
+
+class ShotRequest(BaseModel):
+ scene_url: str | None = Field(None, description="The scene: a .blend, or a .zip holding a .blend and its textures "
+ "(any public or signed URL). Give this or build_id.")
+ build_id: str | None = Field(None, description="Or an AnyScene build (b_...) on the same fal account's storage.")
+ prompt: str = Field("", description=(
+ "Direction for the whole order in your own words, like you'd brief a camera crew: 'a 45 second trailer: "
+ "open wide, walk in like a visitor, then three slow dolly reveals with rack focus; moody, let the caustics "
+ "move'. With no shots, the agent plans the shot list from this; with shots, it applies to all of them."))
+ shots: list[Shot] = Field(default_factory=list, description="The shots to make, by name or in words. Optional "
+ "when prompt describes them.")
+ floor_plan_url: str | None = Field(None, description="Optional plan of the set (image), optionally with a camera "
+ "path or camera marks drawn on it; the agent follows it.")
+ settings: dict = Field(default_factory=dict, description=(
+ "Optional: res [w, h], samples, fps, seconds (per video shot), lens_mm, handheld (none|walk|subtle), "
+ "look (clean|cinematic|gritty|vintage). Missing ones are chosen per shot."))
+ dials: dict[str, float | str] = Field(default_factory=dict, description=(
+ "Optional changes to the set for this order only (time_of_day, atmosphere, power, warmth, wetness, ...); "
+ "the source scene is never changed."))
+ effort: str = Field("medium", description="Claude effort for the agent: low, medium, high, xhigh, max.")
+ fresh: bool = Field(False, description="Shoot again even if an identical request already has a result.")
+
+
+class ShotResponse(BaseModel):
+ job_id: str
+ scene_id: str = Field(description="The build_id, or the id of the uploaded scene's workspace (s_...).")
+ stills: list[str]
+ videos: list[str]
+ result: dict = Field(description="Per shot: the camera, lens, move and settings used, and a note.")
+ missing: list[str]
+ agent_cost_usd: float | None
+ minutes: float
+
+
+def _stage(stage, status, message):
+ print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": stage, "status": status, "message": message}), flush=True)
+
+
+class AnyShotApp(fal.App):
+ machine_type = ["GPU-RTX5090", "GPU-RTXPRO6000"]
+ image = ContainerImage.from_dockerfile_str(DOCKERFILE)
+ requirements = ["pydantic", "anthropic", "pillow", "fal==1.84.0", "fal-client", "claude-agent-sdk==0.2.176"]
+ local_python_modules = ["shots", "scene_builder", "planner", "schema"]
+ min_concurrency = 0
+ max_concurrency = 10
+ request_timeout = 7200 # fal's cap; the agent stops at 110 min to deliver, and a retried request resumes
+ startup_timeout = 1200
+
+ def setup(self):
+ import shutil
+ import subprocess
+ import time
+ os.makedirs("/opt/anyscene", exist_ok=True)
+ with open(shots.BLENDER_GPU_PATH, "w") as f:
+ f.write(BLENDER_GPU)
+ with open("/usr/local/bin/blender", "w") as f:
+ f.write(BLENDER_WRAPPER)
+ os.chmod("/usr/local/bin/blender", 0o755)
+ if os.path.exists(OPTIX_CACHE_SHARED):
+ os.makedirs(os.path.dirname(OPTIX_CACHE_LOCAL), exist_ok=True)
+ shutil.copy(OPTIX_CACHE_SHARED, OPTIX_CACHE_LOCAL)
+ t = time.time()
+ r = subprocess.run(["blender", "-b", "--factory-startup", "--python-expr", WARMUP], capture_output=True, text=True,
+ timeout=900)
+ print(f"setup: OptiX warm-up {'ok' if 'WARMUP done' in r.stdout else 'FAILED'} in {time.time() - t:.0f} s", flush=True)
+ save_optix_cache()
+
+ @fal.endpoint("/scene2image")
+ async def scene2image(self, req: ShotRequest) -> ShotResponse:
+ """Finished, graded stills of a 3D scene: cameras named or described in words."""
+ return await self._order(req, "images")
+
+ @fal.endpoint("/scene2video")
+ async def scene2video(self, req: ShotRequest) -> ShotResponse:
+ """Camera moves through a 3D scene, planned and clearance-checked by the agent, rendered on the farm."""
+ return await self._order(req, "video")
+
+ async def _order(self, req: ShotRequest, mode: str) -> ShotResponse:
+ import asyncio
+ import hashlib
+ import time
+ import uuid
+
+ t0 = time.time()
+ if bool(req.scene_url) == bool(req.build_id):
+ raise ValueError("give exactly one of scene_url or build_id")
+ if not req.shots and not req.prompt.strip():
+ raise ValueError("give shots, a prompt, or both")
+ if req.build_id and not req.build_id.replace("_", "").isalnum():
+ raise ValueError("bad build_id")
+
+ # Retry-safe, as builder/app.py's _build: fal's queue re-runs a request that times out or loses its worker.
+ # Each identical order maps to one job; a repeat returns the finished result, attaches to a live attempt, or
+ # resumes a dead one in the same job folder (frames already on disk are not rendered again).
+ order = {"mode": mode, "scene_url": req.scene_url, "build_id": req.build_id, "floor_plan": req.floor_plan_url,
+ "prompt": req.prompt, "shots": [s.model_dump() for s in req.shots], "settings": req.settings, "dials": req.dials,
+ "effort": req.effort}
+ fp = hashlib.sha256(json.dumps(order, sort_keys=True).encode()).hexdigest()[:20]
+ index = os.path.join(SHOT_DIR, "_index", fp + ".json")
+ os.makedirs(os.path.dirname(index), exist_ok=True)
+ resume, rec = False, None
+ if not req.fresh and os.path.exists(index):
+ told = False
+ while True:
+ rec = json.load(open(index))
+ if rec.get("response"):
+ _stage("done", "done", f"identical request: returning finished job {rec['job_id']}")
+ return ShotResponse(**rec["response"])
+ alive = os.path.join(rec["work"], "out", "shots", rec["job_id"], ".alive")
+ if not os.path.exists(alive) or time.time() - os.path.getmtime(alive) > 90:
+ break # its attempt died: resume it below
+ if not told:
+ _stage("received", "running", f"identical request: attached to job {rec['job_id']}, still running")
+ told = True
+ await asyncio.sleep(20)
+ resume = True
+ else:
+ if req.build_id:
+ work, scene_id = os.path.join(BUILDS_DIR, req.build_id), req.build_id
+ else:
+ scene_id = "s_" + hashlib.sha256(req.scene_url.encode()).hexdigest()[:12]
+ work = os.path.join(SHOT_DIR, "scenes", scene_id)
+ rec = {"job_id": "j_" + uuid.uuid4().hex[:8], "work": work, "scene_id": scene_id, "fingerprint": fp,
+ "started": time.time()}
+ json.dump(rec, open(index, "w"))
+ job_dir = os.path.join(rec["work"], "out", "shots", rec["job_id"])
+ os.makedirs(job_dir, exist_ok=True)
+
+ async def keep_alive(): # proves this attempt is alive to any retry of the same request
+ while True:
+ open(os.path.join(job_dir, ".alive"), "w").close()
+ await asyncio.sleep(20)
+ alive_task = asyncio.create_task(keep_alive())
+ try:
+ return await self._order_in(req, mode, rec, index, job_dir, resume, t0)
+ finally:
+ alive_task.cancel()
+
+ async def _order_in(self, req, mode, rec, index, job_dir, resume, t0) -> ShotResponse:
+ import asyncio
+ import time
+
+ from fal.toolkit import File
+
+ upload = lambda p: File.from_path(p).url
+ work, job_id = rec["work"], rec["job_id"]
+ if req.build_id:
+ if not os.path.isdir(work):
+ raise ValueError(f"build {req.build_id} is not on this account's storage")
+ scene = shots.build_scene_name(work)
+ source = {"kind": "build", "build_id": req.build_id}
+ else:
+ scene = "scene"
+ _stage("received", "running", "fetching the scene")
+ await asyncio.to_thread(shots.fetch_scene, work, req.scene_url)
+ for d in (f"scenes/{scene}", "out"):
+ os.makedirs(os.path.join(work, d), exist_ok=True)
+ source = {"kind": "upload", "scene_url": req.scene_url, "files": "input/scene/"}
+ shots.write_toolkit(work, TOOLKIT) # the current tools and SHOTS.md; never the scene's own files
+ request = {"mode": mode, "source": source, "prompt": req.prompt, "shots": [s.model_dump() for s in req.shots],
+ "settings": req.settings, "dials": req.dials, "floor_plan_url": req.floor_plan_url, "floor_plan": None}
+ if req.floor_plan_url:
+ if not os.path.exists(os.path.join(job_dir, "floor_plan.png")):
+ await asyncio.to_thread(shots.fetch_floor_plan, req.floor_plan_url, job_dir)
+ request["floor_plan"] = os.path.relpath(os.path.join(job_dir, "floor_plan.png"), work).replace(os.sep, "/")
+
+ d, out = await shots.shoot(work, scene, job_id, request, upload, effort=req.effort, resume=resume)
+ res = ShotResponse(**out, scene_id=rec["scene_id"], minutes=round((time.time() - t0) / 60, 1))
+ save_optix_cache()
+ d.emit("packaged", "done", f"{len(res.stills)} stills, {len(res.videos)} videos after {res.minutes:.0f} min",
+ stills=res.stills, videos=res.videos)
+ if not res.missing: # a repeat of this order now gets this result; an incomplete one is resumed instead
+ rec = json.load(open(index))
+ rec.update(response=res.model_dump(), finished=time.time())
+ json.dump(rec, open(index, "w"))
+ await asyncio.sleep(2) # let the last stage lines reach the queue logs before COMPLETED
+ return res
diff --git a/anyshot/client.py b/anyshot/client.py
new file mode 100644
index 0000000..c239bef
--- /dev/null
+++ b/anyshot/client.py
@@ -0,0 +1,100 @@
+"""AnyShot command-line client: send a scene and shot directions, follow the agent's live log, save the results.
+
+ pip install fal-client # or: uv run --with fal-client python anyshot/client.py ...
+ export FAL_KEY=... # a key of the account the app is deployed under
+ export ANYSHOT_APP=<your-fal-username>/anyshot
+
+ python anyshot/client.py image --scene ./set.blend --shot "wide establishing shot from the doorway, 24mm"
+ python anyshot/client.py video --scene ./set.zip --shot "slow push along the counter, ending on the register" \
+ --settings '{"seconds": 6, "res": [1920, 1080]}' --floor-plan ./plan_with_path.png
+ python anyshot/client.py video --build-id b_1234567890 --shot hero_wide --shot "orbit the bar, 35mm"
+
+--scene and --floor-plan take a local file (uploaded to fal storage first) or a URL. Every stage event is written to
+<out>/events.jsonl; the response goes to <out>/response.json and the stills/videos next to it.
+"""
+
+import argparse
+import json
+import os
+import sys
+import time
+import urllib.request
+
+STAGE = "ANYSCENE_STAGE " # the agent's stage events in the queue logs (shared with the scene builder)
+
+
+def main():
+ p = argparse.ArgumentParser(description="AnyShot: shots of a 3D scene, planned by an AI cinematographer.")
+ p.add_argument("mode", choices=["image", "video"], help="image: /scene2image (stills). video: /scene2video.")
+ src = p.add_mutually_exclusive_group(required=True)
+ src.add_argument("--scene", help="a .blend, or a .zip holding a .blend and its textures (path or URL)")
+ src.add_argument("--build-id", help="an AnyScene build (b_...) on the app's account")
+ p.add_argument("--prompt", default="", help="direction for the whole order in words; enough on its own")
+ p.add_argument("--shot", action="append", default=[],
+ help="a camera name, or a shot in words (repeatable); 'name: words' gives both")
+ p.add_argument("--floor-plan", help="optional plan image, optionally with a camera path drawn on it (path or URL)")
+ p.add_argument("--settings", default="{}", help='JSON, e.g. {"seconds": 6, "fps": 24, "res": [1920, 1080]}')
+ p.add_argument("--dials", default="{}", help='JSON, e.g. {"time_of_day": "night", "atmosphere": 0.6}')
+ p.add_argument("--effort", default="medium")
+ p.add_argument("--fresh", action="store_true", help="shoot again even if an identical order already finished")
+ p.add_argument("--app", default=os.environ.get("ANYSHOT_APP"), help="fal app id (default: $ANYSHOT_APP)")
+ p.add_argument("--out", default="anyshot_out")
+ a = p.parse_args()
+ if not a.shot and not a.prompt:
+ p.error("give --prompt, --shot, or both")
+ if not a.app:
+ p.error("set ANYSHOT_APP=<owner>/<app> or pass --app")
+ if not os.environ.get("FAL_KEY"):
+ p.error("set FAL_KEY to a key of the account the app is deployed under")
+ sys.stdout.reconfigure(encoding="utf-8")
+ import fal_client
+
+ up = lambda s: s if s is None or s.startswith(("http://", "https://")) else fal_client.upload_file(s)
+ shots = []
+ for s in a.shot:
+ name, sep, words = s.partition(":")
+ if sep and name.strip().replace("_", "").isalnum():
+ shots.append({"name": name.strip(), "description": words.strip()})
+ elif " " in s.strip():
+ shots.append({"description": s.strip()})
+ else:
+ shots.append({"name": s.strip()})
+ payload = {"prompt": a.prompt, "shots": shots, "settings": json.loads(a.settings), "dials": json.loads(a.dials), "effort": a.effort,
+ "fresh": a.fresh, "floor_plan_url": up(a.floor_plan)}
+ if a.scene:
+ payload["scene_url"] = up(a.scene)
+ else:
+ payload["build_id"] = a.build_id
+
+ os.makedirs(a.out, exist_ok=True)
+ events = open(os.path.join(a.out, "events.jsonl"), "a", encoding="utf-8")
+ t0, seen = time.time(), set()
+
+ def on_update(update):
+ for log in getattr(update, "logs", None) or []:
+ msg = log.get("message", "")
+ if msg in seen or STAGE not in msg:
+ continue
+ seen.add(msg)
+ ev = json.loads(msg.split(STAGE, 1)[1])
+ if ev.get("stage") == "heartbeat":
+ continue
+ events.write(json.dumps(ev) + "\n")
+ events.flush()
+ line = f"[{(time.time() - t0) / 60:5.1f}m] {ev['stage']:<10} {ev.get('message', '')[:160]}"
+ if ev.get("preview_url"):
+ line += f"\n{'':19}image: {ev['preview_url']}"
+ print(line, flush=True)
+
+ route = "scene2image" if a.mode == "image" else "scene2video"
+ res = fal_client.subscribe(f"{a.app}/{route}", arguments=payload, with_logs=True, on_queue_update=on_update,
+ on_enqueue=lambda rid: print(f"request {rid}", flush=True), client_timeout=3 * 3600)
+ with open(os.path.join(a.out, "response.json"), "w", encoding="utf-8") as f:
+ json.dump(res, f, indent=1)
+ for url in res.get("stills", []) + res.get("videos", []):
+ urllib.request.urlretrieve(url, os.path.join(a.out, url.rsplit("/", 1)[-1]))
+ print(json.dumps({k: v for k, v in res.items() if k != "result"}, indent=1))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/blender_addon/README.md b/blender_addon/README.md
new file mode 100644
index 0000000..3b251ac
--- /dev/null
+++ b/blender_addon/README.md
@@ -0,0 +1,152 @@
+# fal Render Farm (Blender add-on)
+
+Render the open scene on the AnyScene render farm (fal Serverless, RTX PRO 6000 GPUs) instead of your local GPU.
+Direct a downloaded scene in your own Blender (cameras, lights, edits), then press **Render animation on fal**. Frames
+come back into the scene's own output path with the same names a local render would give them.
+
+```
+blender_addon/
+ fal_render_farm/ the add-on (an extension folder: blender_manifest.toml + bl_info, works either way)
+ __init__.py panel, operators, preferences, status bar, UI timer
+ job.py planning (main thread) and the job runner (background thread)
+ fal_api.py fal queue API + fal storage upload over plain urllib
+ pack_copy.py runs in a separate Blender on a temp copy: make local, pack_all, refuse on externals
+ farm_gpu.py shipped in every bundle, run with --python on the farm: OptiX/CUDA + GPU on every scene
+ fal_render_farm-1.0.0.zip installable build
+ tests/ make_test_scene.py, test_farm.py (headless end-to-end test against the real farm)
+```
+
+## Install
+
+Blender 4.2 or newer (built and tested on 5.0.1).
+
+1. **Edit > Preferences > Get Extensions**, then the drop-down at the top right > **Install from Disk...**, and pick
+ `blender_addon/fal_render_farm-1.0.0.zip`. Dragging the zip onto the Blender window also works.
+2. Enable **fal Render Farm** if it isn't enabled already.
+
+For development, symlink or copy `blender_addon/fal_render_farm/` into an extensions repo (or a legacy
+`scripts/addons/` folder) instead.
+
+## Set the key
+
+Open the add-on's preferences (Preferences > Add-ons > fal Render Farm):
+
+- **fal key**: the key of the account that owns the farm app (the Serverless key the farm is deployed under,
+ `FAL_SERVERLESS_KEY` in this repo, not a generation-only `FAL_KEY`). It's a password field, stored in Blender's user preferences (`userpref.blend`), and the
+ add-on never prints or logs it. Press **Check key** to make sure fal accepts it.
+- **Farm app**: empty by default; set it to your own deployment of `farm/app.py`, e.g.
+ `<your-fal-username>/blender-farm-2` (see "Farm change" below). The add-on refuses to render until it's set. A farm
+ deployed from the older build as `blender-farm` returns **PNG frames only**; `blender-farm-2` is the same farm with
+ one backward-compatible addition (an `outputs` field), so it also returns EXR, multilayer EXR, JPEG, TIFF and so on.
+ The panel warns when the output format isn't PNG and the app is a `.../blender-farm`.
+- **Frames per chunk** (24) and **Concurrent chunks** (20): one chunk is one farm request on one GPU.
+- **Chunk timeout**, **Encode MP4 when done**, and the **ffmpeg** path (empty means use the one on PATH).
+
+Remember to save preferences (or keep auto-save on).
+
+## Render
+
+**Properties > Render > fal Render Farm**:
+
+- **Render animation on fal** renders the scene's frame range (and frame step).
+- **Render this frame on fal** renders the current frame and saves it to the output path as frame N. If an Image
+ Editor is open, the frame is shown there when it arrives.
+- **Cancel** cancels in-flight chunks on fal. Frames that already arrived stay on disk.
+- **Retry failed chunks** re-submits failed chunks against the bundle that's already uploaded.
+
+What happens when you press render:
+
+1. The open file, unsaved edits included, is written to a temp folder with `save_as_mainfile(copy=True)`. Your
+ working file isn't modified or re-saved, and it doesn't get marked dirty.
+2. A separate background Blender opens that copy, makes linked data local, runs `pack_all` and saves `scene.blend`.
+ If something still points outside the file (unpackable images or movies, Alembic/USD caches, libraries), the
+ render stops and the panel lists those paths.
+3. `scene.blend` and `farm_gpu.py` are zipped, the `bundle_id` is set to the first 16 hex characters of the zip's
+ sha256, and the zip is uploaded to fal storage. An unchanged bundle is uploaded only once per session.
+4. Frames that already exist at their output path are **skipped** (that's how resume works). The remaining frames
+ are cut into chunks. Each chunk goes to the queue API as
+ `{bundle}/scene.blend -S <scene> --python {bundle}/farm_gpu.py -o {out}/frames/<filename pattern> -s A -e B -j STEP -a`,
+ and at most *Concurrent chunks* are in flight at once.
+5. Each finished chunk's zip is downloaded and its files are written to the paths that `scene.render.frame_path()`
+ gives locally. That covers `#` padding, relative `//` paths and the file extension setting.
+
+The scene renders with its own settings: engine, samples, resolution and percentage, file format and colour depth,
+view layers, compositor, color management and camera. The only thing the farm changes is the device: `farm_gpu.py`
+selects OptiX (or CUDA) and sets `cycles.device = 'GPU'`, the same way `builder/blender_gpu.py` does for the builder.
+
+Progress appears in the panel (phase, chunks queued/rendering/done/failed, frames, elapsed time, GPU-seconds and their
+cost) and in the status bar. Everything runs on a background thread, and a timer redraws the UI every 0.5 s, so
+Blender stays responsive. Each failed chunk shows its error. A chunk is retried once automatically before it's marked
+failed.
+
+When an animation finishes with PNG/JPEG/TIFF/... frames and ffmpeg is available, the add-on writes an H.264 MP4
+(`<name>_<first>-<last>.mp4`, CRF 16) next to the frames. EXR frames are skipped, because they're linear and belong
+in your grade.
+
+## What the estimate means
+
+The estimate scales a measured reference to your scene. Mission control rendered at **5 to 7 s per frame at
+1920x804 and 48 spp** on an RTX PRO 6000. That figure is multiplied by `(your pixels / 1920x804) x (your samples / 48)`,
+using Cycles samples or EEVEE render samples. Each chunk also adds about 20 s of overhead (Blender start, scene load,
+returning the frames). GPU time is priced at **$4.00 per GPU-hour**. Wall time assumes chunks run *Concurrent chunks*
+at a time, plus about 90 s of cold start if the app has scaled to zero.
+
+Treat the estimate as an order-of-magnitude figure, not a quote. Scene complexity, volumes, adaptive sampling,
+denoising, light paths and EEVEE versus Cycles can each move the real number by 2x or more. Once a job is running,
+the panel shows the real GPU-seconds the farm reports (render time plus bundle fetch per chunk). That figure leaves
+out cold starts and idle keep-alive, which fal also bills.
+
+## Troubleshooting
+
+- **"Set your fal key"** or **HTTP 401/403**: the key is missing, or it belongs to an account that can't see the farm
+ app. Use the farm owner's Serverless key and press **Check key**.
+- **"the file references data that can't be packed"**: these are the listed images/movies/caches. Fix their paths or
+ make them local. Fluid and other disk simulation caches aren't shipped (you get a warning, not an error), so bake
+ them into the mesh or render those shots locally.
+- **"output path is relative (//) but this file has never been saved"**: save the file once, or set an absolute
+ output path.
+- **"Output is a video format"**: the farm renders frame sequences in chunks. Pick PNG/EXR/... and turn on *Encode
+ MP4*.
+- **A chunk fails with "the farm returned no OPEN_EXR files"**: you're on a `blender-farm` deployment, which only returns
+ PNG. Deploy and switch to `<your-fal-username>/blender-farm-2`.
+- **Chunks sit in "queued"**: the farm is busy or scaling up (it allows at most 20 workers, shared with other jobs on
+ the same app). They start once workers free up.
+- **A chunk timed out**: lower *Frames per chunk*, or raise *Chunk timeout* (the farm's hard cap is 3600 s per request).
+- **Frames look different from a local render**: the farm runs Blender **5.0.1** on Linux. Scenes that depend on
+ add-ons (custom nodes, drivers that call add-on Python, Python-scripted drivers in general) only render correctly if
+ the farm has them, and it has no add-ons. Disk caches and file-output nodes with absolute paths aren't shipped
+ either.
+- **Nothing comes back for a stereo/multiview scene**: per-view files (`_L`/`_R`) are written next to the frames,
+ but resume doesn't know about them yet.
+- The **System Console** (Window > Toggle System Console) shows one `fal render farm:` line per step and per chunk.
+
+## Tests
+
+```
+"C:/Program Files/Blender Foundation/Blender 5.0/blender.exe" -b --factory-startup --python-exit-code 1 \
+ --python blender_addon/tests/test_farm.py -- <workdir> --app <your-fal-username>/blender-farm-2 [--chunk 12] [--ffmpeg <path>]
+
+BLENDER_USER_RESOURCES=<empty temp dir> "C:/Program Files/Blender Foundation/Blender 5.0/blender.exe" -b \
+ --factory-startup --python-exit-code 1 --python blender_addon/tests/test_zip_install.py -- blender_addon/fal_render_farm-1.0.0.zip
+```
+
+Rebuild the zip with `blender --factory-startup --command extension build --source-dir blender_addon/fal_render_farm --output-dir blender_addon`.
+
+The test builds a 48-frame 640x360 Cycles scene with an external texture and enables the add-on from its folder. It
+reads `FAL_SERVERLESS_KEY` from the Windows user environment, for that process only, then draws the panel and polls
+the operators. It renders the animation through the operator and checks every frame name. It also confirms the
+working .blend is untouched, tests resume (it deletes 2 frames and re-renders), compares frame 1 against a local GPU
+render (PSNR), and renders one EXR frame. It ends with a `TEST-SUMMARY` JSON line.
+
+## Farm change (blender-farm-2)
+
+`farm/app.py` gained one optional request field, `outputs` (glob patterns relative to `{out}`). It defaults to
+`["**/*.png"]`, which is exactly the old behaviour, so existing clients (`farm/farm.py`, `builder/shots.py`) are
+unaffected. The add-on always sends `["frames/**/*"]`, and an older `blender-farm` deployment ignores the unknown field.
+The changed app is deployed as `blender-farm-2` on your own account:
+
+```
+fal deploy farm/app.py::BlenderFarm --app-name blender-farm-2 --auth private
+```
+
+An existing `blender-farm` deployment doesn't need to be redeployed.
diff --git a/blender_addon/fal_render_farm-1.0.0.zip b/blender_addon/fal_render_farm-1.0.0.zip
new file mode 100644
index 0000000..bd0fa4b
Binary files /dev/null and b/blender_addon/fal_render_farm-1.0.0.zip differ
diff --git a/blender_addon/fal_render_farm/__init__.py b/blender_addon/fal_render_farm/__init__.py
new file mode 100644
index 0000000..bb72ed2
--- /dev/null
+++ b/blender_addon/fal_render_farm/__init__.py
@@ -0,0 +1,357 @@
+"""fal Render Farm: render the open scene on a fal Serverless Blender farm (farm/app.py, deployed on your own fal account) instead of the local GPU.
+
+Properties > Render > fal Render Farm. The open file is copied (never re-saved), packed in a separate Blender, zipped
+with a GPU script, uploaded to fal storage and rendered in chunks on up to N GPUs. Frames come back into the scene's
+own output path with the names a local render would give them. Talks to fal over plain HTTPS (urllib) only.
+"""
+
+bl_info = {
+ "name": "fal Render Farm",
+ "author": "AnyScene contributors",
+ "version": (1, 0, 0),
+ "blender": (4, 2, 0),
+ "location": "Properties > Render > fal Render Farm",
+ "description": "Render the open scene on a fal Serverless GPU render farm",
+ "category": "Render",
+}
+
+import os
+import time
+
+import bpy
+from bpy.props import BoolProperty, IntProperty, StringProperty
+
+from . import fal_api, job as farm_job
+
+PKG = __package__
+
+
+def prefs():
+ return bpy.context.preferences.addons[PKG].preferences
+
+
+class FALRF_Preferences(bpy.types.AddonPreferences):
+ bl_idname = PKG
+
+ fal_key: StringProperty(
+ name="fal key", subtype="PASSWORD", default="",
+ description="fal API key of the account that owns the farm app (key_id:key_secret). Stored in Blender's "
+ "preferences; never printed or logged")
+ app_id: StringProperty(
+ name="Farm app", default="",
+ description="fal app id of your render farm, <your-fal-username>/blender-farm-2 (farm/app.py deployed on your "
+ "account). An app deployed as blender-farm (the older build) returns PNG frames only; "
+ "blender-farm-2 also returns EXR, JPEG, TIFF and other image formats")
+ chunk_size: IntProperty(name="Frames per chunk", default=24, min=1, max=1000,
+ description="Frames rendered by one farm request (one GPU)")
+ concurrency: IntProperty(name="Concurrent chunks", default=100, min=1, max=200,
+ description="Requests in flight at once (the farm caps at its own max workers)")
+ timeout_s: IntProperty(name="Chunk timeout (s)", default=3000, min=60, max=3500,
+ description="The farm kills Blender after this long on one chunk")
+ encode_mp4: BoolProperty(name="Encode MP4 when done", default=True,
+ description="After an animation finishes, encode the frames to an H.264 MP4 next to "
+ "them if ffmpeg is found (PNG/JPEG/TIFF/... frames only)")
+ ffmpeg_path: StringProperty(name="ffmpeg", subtype="FILE_PATH", default="",
+ description="Path to ffmpeg; empty = look it up on PATH")
+
+ def draw(self, context):
+ col = self.layout.column()
+ col.prop(self, "fal_key")
+ col.prop(self, "app_id")
+ row = col.row()
+ row.prop(self, "chunk_size")
+ row.prop(self, "concurrency")
+ col.prop(self, "timeout_s")
+ row = col.row()
+ row.prop(self, "encode_mp4")
+ row.prop(self, "ffmpeg_path", text="")
+ col.operator(FALRF_OT_check_key.bl_idname, icon="KEY_HLT")
+
+
+# -- operators --------------------------------------------------------------------------------------------------
+
+def _busy():
+ j = farm_job.CURRENT
+ return j is not None and j.running
+
+
+class FALRF_OT_render(bpy.types.Operator):
+ """Render on the fal render farm instead of the local GPU"""
+
+ bl_idname = "fal_render_farm.render"
+ bl_label = "Render on fal"
+ bl_options = {"REGISTER"}
+
+ mode: bpy.props.EnumProperty(items=[("ANIMATION", "Animation", "The scene's frame range"),
+ ("FRAME", "Frame", "The current frame")], default="ANIMATION")
+
+ @classmethod
+ def poll(cls, context):
+ if _busy():
+ cls.poll_message_set("A farm render is already running")
+ return False
+ if context.scene is None:
+ return False
+ return True
+
+ @classmethod
+ def description(cls, context, props):
+ if props.mode == "FRAME":
+ return "Render the current frame on the fal render farm; it is saved to the output path"
+ return "Render the scene's frame range on the fal render farm, into the output path"
+
+ def execute(self, context):
+ try:
+ p = farm_job.plan(context, self.mode, prefs())
+ farm_job.save_copy(p)
+ except farm_job.PlanError as e:
+ self.report({"ERROR"}, str(e))
+ return {"CANCELLED"}
+ farm_job.CURRENT = farm_job.Job(p).start()
+ _start_ui_timer()
+ self.report({"INFO"}, f"fal render farm: {len(p.frames)} frame(s) of '{p.scene_name}' on {p.app}")
+ return {"FINISHED"}
+
+
+class FALRF_OT_cancel(bpy.types.Operator):
+ """Cancel the running farm render (in-flight chunks are cancelled on fal; finished frames stay on disk)"""
+
+ bl_idname = "fal_render_farm.cancel"
+ bl_label = "Cancel"
+
+ @classmethod
+ def poll(cls, context):
+ return _busy()
+
+ def execute(self, context):
+ farm_job.CURRENT.cancel()
+ return {"FINISHED"}
+
+
+class FALRF_OT_retry(bpy.types.Operator):
+ """Re-submit the chunks that failed, reusing the uploaded bundle"""
+
+ bl_idname = "fal_render_farm.retry"
+ bl_label = "Retry failed chunks"
+
+ @classmethod
+ def poll(cls, context):
+ j = farm_job.CURRENT
+ return j is not None and not j.running and j.bundle_url and any(
+ c.status in ("failed", "cancelled") for c in j.chunks)
+
+ def execute(self, context):
+ if farm_job.CURRENT.retry_failed():
+ _start_ui_timer()
+ return {"FINISHED"}
+
+
+class FALRF_OT_check_key(bpy.types.Operator):
+ """Check that fal accepts the key (a status read on the farm app; nothing is rendered)"""
+
+ bl_idname = "fal_render_farm.check_key"
+ bl_label = "Check key"
+
+ def execute(self, context):
+ pr = prefs()
+ if not pr.fal_key.strip():
+ self.report({"ERROR"}, "No key set")
+ return {"CANCELLED"}
+ if not pr.app_id.strip().strip("/"):
+ self.report({"ERROR"}, farm_job.NO_APP_MSG)
+ return {"CANCELLED"}
+ ok, msg = fal_api.check_key(pr.fal_key.strip(), pr.app_id)
+ self.report({"INFO"} if ok else {"ERROR"}, msg)
+ return {"FINISHED"} if ok else {"CANCELLED"}
+
+
+class FALRF_OT_open_output(bpy.types.Operator):
+ """Open the folder the frames are written to"""
+
+ bl_idname = "fal_render_farm.open_output"
+ bl_label = "Open output folder"
+
+ def execute(self, context):
+ path = bpy.path.abspath(context.scene.render.frame_path(frame=context.scene.frame_start))
+ folder = os.path.dirname(os.path.abspath(path))
+ os.makedirs(folder, exist_ok=True)
+ bpy.ops.wm.path_open(filepath=folder)
+ return {"FINISHED"}
+
+
+# -- panel ------------------------------------------------------------------------------------------------------
+
+def _progress_text(s):
+ c = s["counts"]
+ done = c.get("done", 0)
+ parts = [f"{done}/{s['n_chunks']} chunks", f"{s['frames_done']}/{s['frames_total']} frames",
+ farm_job.fmt_s(s["elapsed"])]
+ if s["gpu_s"]:
+ parts.append(f"{s['gpu_s']:.0f} GPU-s (~${s['gpu_s'] / 3600 * farm_job.GPU_RATE_PER_HOUR:.2f})")
+ return " · ".join(parts)
+
+
+class FALRF_PT_panel(bpy.types.Panel):
+ bl_label = "fal Render Farm"
+ bl_space_type = "PROPERTIES"
+ bl_region_type = "WINDOW"
+ bl_context = "render"
+
+ def draw_header(self, context):
+ self.layout.label(icon="WORLD")
+
+ def draw(self, context):
+ layout = self.layout
+ scene = context.scene
+ pr = prefs()
+
+ frames = farm_job.frame_list(scene, "ANIMATION")
+ est = farm_job.estimate(scene, len(frames), pr.chunk_size, pr.concurrency)
+ samples, unit = farm_job.samples_of(scene)
+ r = scene.render
+ w = int(r.resolution_x * r.resolution_percentage / 100)
+ h = int(r.resolution_y * r.resolution_percentage / 100)
+
+ box = layout.box()
+ col = box.column(align=True)
+ col.label(text=f"Frames {scene.frame_start}-{scene.frame_end}"
+ + (f" step {scene.frame_step}" if scene.frame_step > 1 else "")
+ + f": {len(frames)} · {est['chunks']} chunks of {pr.chunk_size}", icon="RENDER_ANIMATION")
+ col.label(text=f"{w}x{h}" + (f" · {samples} {unit}" if samples else "")
+ + f" · {r.engine.replace('BLENDER_', '').title()} · {r.image_settings.file_format}")
+ lo, hi = est["cost"], est["wall"]
+ col.label(text=f"Estimate: ${lo[0]:.2f}-{lo[1]:.2f} · {farm_job.fmt_s(est['gpu_s'][0])}-"
+ f"{farm_job.fmt_s(est['gpu_s'][1])} of GPU time", icon="INFO")
+ col.label(text=f" ~{farm_job.fmt_s(hi[0])}-{farm_job.fmt_s(hi[1])} wall at {pr.concurrency} GPUs, "
+ f"+ ~{farm_job.fmt_s(est['cold_start'])} cold start")
+ col.label(text=f" {est['sec_per_frame'][0]:.1f}-{est['sec_per_frame'][1]:.1f} s/frame, "
+ f"${farm_job.GPU_RATE_PER_HOUR:.2f}/GPU-h (RTX PRO 6000); an estimate")
+
+ if not pr.fal_key.strip():
+ layout.label(text="Set your fal key in the add-on preferences", icon="ERROR")
+ if not pr.app_id.strip().strip("/"):
+ layout.label(text="Set the farm app (<your-fal-username>/blender-farm-2) below", icon="ERROR")
+ if r.image_settings.file_format != "PNG" and pr.app_id.strip().strip("/").endswith("/blender-farm"):
+ layout.label(text=f"{pr.app_id} returns PNG only; use a blender-farm-2 deployment for "
+ f"{r.image_settings.file_format}", icon="ERROR")
+ if r.image_settings.file_format == "FFMPEG":
+ layout.label(text="Video output: pick an image format (MP4 is encoded after)", icon="ERROR")
+
+ row = layout.row(align=True)
+ row.scale_y = 1.4
+ row.operator(FALRF_OT_render.bl_idname, text="Render animation on fal", icon="RENDER_ANIMATION").mode = "ANIMATION"
+ row = layout.row(align=True)
+ row.operator(FALRF_OT_render.bl_idname, text="Render this frame on fal", icon="RENDER_STILL").mode = "FRAME"
+ row.operator(FALRF_OT_cancel.bl_idname, text="Cancel", icon="CANCEL")
+
+ sub = layout.column(align=True)
+ sub.prop(pr, "app_id")
+ row = sub.row(align=True)
+ row.prop(pr, "chunk_size", text="Chunk")
+ row.prop(pr, "concurrency", text="GPUs")
+ sub.prop(pr, "encode_mp4")
+ layout.label(text="Output: " + (r.filepath or "(blend file folder)"), icon="FILE_FOLDER")
+
+ j = farm_job.CURRENT
+ if j is None:
+ return
+ s = j.snapshot()
+ box = layout.box()
+ icon = {"done": "CHECKMARK", "failed": "ERROR", "cancelled": "CANCEL"}.get(s["phase"], "SORTTIME")
+ box.label(text=f"{s['phase'].title()} · {s['app']}", icon=icon)
+ if s["n_chunks"]:
+ box.progress(factor=s["frames_done"] / max(1, s["frames_total"]), text=_progress_text(s))
+ c = s["counts"]
+ box.label(text=f"queued {c.get('queued', 0) + c.get('pending', 0)} · rendering {c.get('rendering', 0)} "
+ f"· downloading {c.get('downloading', 0)} · done {c.get('done', 0)} "
+ f"· failed {c.get('failed', 0)}" + (f" · {s['skipped']} frames already on disk"
+ if s["skipped"] else ""))
+ if s["message"]:
+ box.label(text=s["message"][:160])
+ for label, err in s["failed"][:8]:
+ box.label(text=f"chunk {label}: {err[:140]}", icon="ERROR")
+ if s["mp4"]:
+ box.label(text=f"MP4: {s['mp4']}", icon="FILE_MOVIE")
+ row = box.row()
+ row.operator(FALRF_OT_retry.bl_idname, icon="FILE_REFRESH")
+ row.operator(FALRF_OT_open_output.bl_idname, icon="FILE_FOLDER")
+
+
+def draw_status(self, context):
+ j = farm_job.CURRENT
+ if j is None or (not j.running and j.finished_seen and time.time() - (j.t_end or 0) > 30):
+ return
+ s = j.snapshot()
+ text = f"fal farm: {s['phase']}"
+ if s["n_chunks"]:
+ text += " · " + _progress_text(s)
+ self.layout.separator()
+ self.layout.label(text=text, icon="WORLD")
+
+
+# -- UI timer: redraws while a job runs, then reacts once to its end --------------------------------------------
+
+def _redraw():
+ wm = bpy.context.window_manager
+ if wm is None:
+ return
+ for win in wm.windows:
+ for area in win.screen.areas:
+ if area.type in ("PROPERTIES", "STATUSBAR"):
+ area.tag_redraw()
+
+
+def _tick():
+ j = farm_job.CURRENT
+ if j is None:
+ return None
+ try:
+ _redraw()
+ except Exception: # noqa: BLE001 - never let a redraw problem kill the timer
+ pass
+ if j.running:
+ return 0.5
+ if not j.finished_seen:
+ j.finished_seen = True
+ if j.p.mode == "FRAME" and j.phase == "done":
+ _show_frame(j)
+ return None
+
+
+def _show_frame(j):
+ path = j.p.targets[j.p.frames[0]]
+ if not os.path.exists(path):
+ return
+ img = bpy.data.images.load(path, check_existing=True)
+ img.reload()
+ for win in bpy.context.window_manager.windows:
+ for area in win.screen.areas:
+ if area.type == "IMAGE_EDITOR":
+ area.spaces.active.image = img
+ area.tag_redraw()
+ return
+
+
+def _start_ui_timer():
+ if not bpy.app.timers.is_registered(_tick):
+ bpy.app.timers.register(_tick, first_interval=0.5, persistent=True)
+
+
+classes = (FALRF_Preferences, FALRF_OT_render, FALRF_OT_cancel, FALRF_OT_retry, FALRF_OT_check_key,
+ FALRF_OT_open_output, FALRF_PT_panel)
+
+
+def register():
+ for c in classes:
+ bpy.utils.register_class(c)
+ bpy.types.STATUSBAR_HT_header.append(draw_status)
+
+
+def unregister():
+ if farm_job.CURRENT is not None and farm_job.CURRENT.running:
+ farm_job.CURRENT.cancel()
+ if bpy.app.timers.is_registered(_tick):
+ bpy.app.timers.unregister(_tick)
+ bpy.types.STATUSBAR_HT_header.remove(draw_status)
+ for c in reversed(classes):
+ bpy.utils.unregister_class(c)
diff --git a/blender_addon/fal_render_farm/blender_manifest.toml b/blender_addon/fal_render_farm/blender_manifest.toml
new file mode 100644
index 0000000..6bbcfbe
--- /dev/null
+++ b/blender_addon/fal_render_farm/blender_manifest.toml
@@ -0,0 +1,20 @@
+schema_version = "1.0.0"
+
+id = "fal_render_farm"
+version = "1.0.0"
+name = "fal Render Farm"
+tagline = "Render the open scene on a fal Serverless GPU render farm"
+maintainer = "AnyScene contributors"
+type = "add-on"
+
+blender_version_min = "4.2.0"
+
+license = ["SPDX:GPL-3.0-or-later"]
+tags = ["Render"]
+
+[permissions]
+network = "Upload the scene to fal storage and render it on fal Serverless"
+files = "Save a packed temp copy and write frames to the output path"
+
+[build]
+paths_exclude_pattern = ["__pycache__/", "*.pyc", "/.git/"]
diff --git a/blender_addon/fal_render_farm/fal_api.py b/blender_addon/fal_render_farm/fal_api.py
new file mode 100644
index 0000000..55f94ed
--- /dev/null
+++ b/blender_addon/fal_render_farm/fal_api.py
@@ -0,0 +1,159 @@
+"""fal over plain HTTPS (urllib only, nothing Blender doesn't ship): the queue API and CDN storage uploads.
+
+Queue: POST https://queue.fal.run/<app> -> {request_id, status_url, response_url, cancel_url}
+ GET status_url -> {status: IN_QUEUE | IN_PROGRESS | COMPLETED, queue_position?}
+ GET response_url -> the app's result (or an HTTP error with the app's exception)
+ PUT cancel_url
+Storage: the same CDN v3 flow fal_client uses: a short-lived upload token from rest.fal.ai, then a single POST
+ (small files) or a multipart upload (big ones) to the token's base URL. Returns a public access URL.
+
+The key is only ever put in an Authorization header; it never appears in an error message or a log line.
+"""
+
+import json
+import os
+import time
+import urllib.error
+import urllib.request
+
+QUEUE_URL = "https://queue.fal.run"
+REST_URL = "https://rest.fal.ai"
+USER_AGENT = "fal-render-farm-blender/1.0"
+MULTIPART_THRESHOLD = 90 * 1024 * 1024
+PART_SIZE = 10 * 1024 * 1024
+TRANSIENT = {408, 409, 425, 429, 500, 502, 503, 504}
+
+
+class FalError(RuntimeError):
+ def __init__(self, msg, status=None):
+ super().__init__(msg)
+ self.status = status
+
+
+def _scrub(text, key):
+ text = text or ""
+ if key:
+ text = text.replace(key, "[key]")
+ return text
+
+
+def _request(method, url, *, key=None, auth=None, body=None, headers=None, timeout=60, retries=3, raw=False):
+ """One HTTP call with retries on transient failures. `auth` is a full Authorization header value."""
+ hdrs = {"User-Agent": USER_AGENT, "Accept": "application/json"}
+ if key:
+ hdrs["Authorization"] = f"Key {key}"
+ if auth:
+ hdrs["Authorization"] = auth
+ if isinstance(body, (dict, list)):
+ body = json.dumps(body).encode()
+ hdrs["Content-Type"] = "application/json"
+ hdrs.update(headers or {})
+ last = None
+ for attempt in range(retries):
+ req = urllib.request.Request(url, data=body, method=method, headers=hdrs)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ data = r.read()
+ if raw:
+ return data, dict(r.headers)
+ return json.loads(data) if data else {}
+ except urllib.error.HTTPError as e:
+ detail = _scrub(e.read().decode("utf-8", "replace"), key)
+ last = FalError(f"HTTP {e.code} from {method} {url.split('?')[0]}: {detail[:2000]}", e.code)
+ if e.code not in TRANSIENT:
+ raise last from None
+ except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
+ last = FalError(f"{method} {url.split('?')[0]} failed: {_scrub(str(e), key)}")
+ time.sleep(1.5 * (attempt + 1))
+ raise last
+
+
+# -- storage ----------------------------------------------------------------------------------------------------
+
+def _cdn_token(key):
+ data = _request("POST", f"{REST_URL}/storage/auth/token?storage_type=fal-cdn-v3", key=key, body={})
+ return f"{data['token_type']} {data['token']}", data["base_url"]
+
+
+def upload_file(key, path, content_type="application/zip", expires_s=7 * 86400, progress=None):
+ """Upload a local file to fal storage and return its public URL. progress(bytes_sent, total) is optional."""
+ size = os.path.getsize(path)
+ name = os.path.basename(path)
+ auth, base = _cdn_token(key)
+ lifecycle = json.dumps({"expiration_duration_seconds": int(expires_s)})
+ if size <= MULTIPART_THRESHOLD:
+ with open(path, "rb") as f:
+ data = f.read()
+ res = _request("POST", f"{base}/files/upload", auth=auth, body=data, timeout=600, headers={
+ "Content-Type": content_type, "X-Fal-File-Name": name, "X-Fal-Object-Lifecycle": lifecycle})
+ if progress:
+ progress(size, size)
+ return res["access_url"]
+
+ res = _request("POST", f"{base}/files/upload/multipart", auth=auth, headers={
+ "Content-Type": content_type, "X-Fal-File-Name": name, "X-Fal-Object-Lifecycle": lifecycle})
+ access, upload_id = res["access_url"], res["uploadId"]
+ parts, sent = [], 0
+ with open(path, "rb") as f:
+ n = 1
+ while chunk := f.read(PART_SIZE):
+ _, hdrs = _request("PUT", f"{access}/multipart/{upload_id}/{n}", auth=auth, body=chunk, timeout=600,
+ raw=True, headers={"Content-Type": content_type, "Accept-Encoding": "identity"})
+ etag = {k.lower(): v for k, v in hdrs.items()}.get("etag")
+ parts.append({"partNumber": n, "etag": etag})
+ sent += len(chunk)
+ if progress:
+ progress(sent, size)
+ n += 1
+ _request("POST", f"{access}/multipart/{upload_id}/complete", auth=auth, body={"parts": parts})
+ return access
+
+
+def download(url, dest, timeout=600):
+ """Stream a URL to a file (written to dest.part, then renamed)."""
+ tmp = dest + ".part"
+ for attempt in range(3):
+ try:
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
+ with urllib.request.urlopen(req, timeout=timeout) as r, open(tmp, "wb") as f:
+ while chunk := r.read(4 << 20):
+ f.write(chunk)
+ os.replace(tmp, dest)
+ return dest
+ except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
+ err = e
+ time.sleep(2 * (attempt + 1))
+ raise FalError(f"download failed: {err}")
+
+
+# -- queue ------------------------------------------------------------------------------------------------------
+
+def submit(key, app, payload):
+ return _request("POST", f"{QUEUE_URL}/{app.strip('/')}", key=key, body=payload)
+
+
+def status(key, handle):
+ return _request("GET", handle["status_url"], key=key)
+
+
+def result(key, handle):
+ return _request("GET", handle["response_url"], key=key, timeout=120)
+
+
+def cancel(key, handle):
+ try:
+ _request("PUT", handle["cancel_url"], key=key, retries=1, timeout=15)
+ except FalError:
+ pass # already finished, or never started: nothing to cancel
+
+
+def check_key(key, app):
+ """Cheap auth probe: a status read of a request id that doesn't exist. 401/403 means a bad key."""
+ try:
+ _request("GET", f"{QUEUE_URL}/{app.strip('/')}/requests/00000000-0000-0000-0000-000000000000/status",
+ key=key, retries=1, timeout=15)
+ except FalError as e:
+ if e.status in (401, 403):
+ return False, "fal rejected the key (HTTP %s)" % e.status
+ return True, "key accepted"
+ return True, "key accepted"
diff --git a/blender_addon/fal_render_farm/farm_gpu.py b/blender_addon/fal_render_farm/farm_gpu.py
new file mode 100644
index 0000000..07c9418
--- /dev/null
+++ b/blender_addon/fal_render_farm/farm_gpu.py
@@ -0,0 +1,36 @@
+"""Shipped in every bundle and run with --python before the render: headless Blender on the farm would otherwise
+render Cycles on the CPU. Picks OptiX (else CUDA), enables only those devices, and puts every scene on the GPU now,
+on file load and at render start. Nothing else about the scene is touched. (Same idea as builder/blender_gpu.py.)"""
+
+import bpy
+from bpy.app.handlers import persistent
+
+
+def _devices():
+ try:
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ except (KeyError, AttributeError):
+ return "no cycles"
+ for kind in ("OPTIX", "CUDA"):
+ try:
+ prefs.compute_device_type = kind
+ prefs.get_devices()
+ except TypeError:
+ continue
+ if any(d.type == kind for d in prefs.devices):
+ for d in prefs.devices:
+ d.use = d.type == kind
+ return kind
+ return "none"
+
+
+@persistent
+def _gpu_scenes(*_):
+ for sc in bpy.data.scenes:
+ sc.cycles.device = "GPU"
+
+
+print("fal-farm: compute device", _devices())
+_gpu_scenes()
+bpy.app.handlers.load_post.append(_gpu_scenes)
+bpy.app.handlers.render_init.append(_gpu_scenes)
diff --git a/blender_addon/fal_render_farm/job.py b/blender_addon/fal_render_farm/job.py
new file mode 100644
index 0000000..b9ae39b
--- /dev/null
+++ b/blender_addon/fal_render_farm/job.py
@@ -0,0 +1,496 @@
+"""A farm render job: everything that touches bpy happens in plan() on the main thread; Job.run() is pure Python on a
+background thread (pack in a separate Blender, zip, upload, fan chunks out to the queue, download frames), so the UI
+never blocks. The UI reads Job.snapshot() from a timer."""
+
+import concurrent.futures as cf
+import hashlib
+import math
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import traceback
+import zipfile
+from collections import deque
+from dataclasses import dataclass, field
+
+from . import fal_api
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+GPU_RATE_PER_HOUR = 4.00 # RTX PRO 6000 on fal
+REF_PIXELS = 1920 * 804
+REF_SAMPLES = 48
+REF_SEC_PER_FRAME = (5.0, 7.0) # measured on mission control at 1920x804 / 48 spp
+CHUNK_OVERHEAD_S = 20.0 # Blender start + scene load + zip/upload of the frames, per request
+COLD_START_S = 90.0 # first workers when the app has scaled to zero
+VIDEO_SAFE = {"PNG", "JPEG", "TIFF", "TARGA", "TARGA_RAW", "BMP", "WEBP"}
+NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0 # CREATE_NO_WINDOW: no console flashing up per subprocess
+
+_uploads = {} # bundle sha256 -> fal storage URL, so a retry or re-render of an unchanged file skips the upload
+CURRENT = None # the job the panel shows
+
+
+class PlanError(Exception):
+ pass
+
+
+NO_APP_MSG = ("Set the farm app in Preferences > Add-ons > fal Render Farm: the fal app id of your render farm, "
+ "<your-fal-username>/blender-farm-2 (deploy farm/app.py on your own fal account)")
+
+
+# -- estimate ---------------------------------------------------------------------------------------------------
+
+def samples_of(scene):
+ eng = scene.render.engine
+ if eng == "CYCLES":
+ return scene.cycles.samples, "spp"
+ if eng.startswith("BLENDER_EEVEE"):
+ return scene.eevee.taa_render_samples, "samples"
+ return None, ""
+
+
+def frame_list(scene, mode):
+ if mode == "FRAME":
+ return [scene.frame_current]
+ return list(range(scene.frame_start, scene.frame_end + 1, max(1, scene.frame_step)))
+
+
+def estimate(scene, n_frames, chunk, concurrency):
+ """Rough cost/time from the reference rate, scaled by pixels x samples. An estimate, not a quote."""
+ r = scene.render
+ pixels = r.resolution_x * r.resolution_y * (r.resolution_percentage / 100.0) ** 2
+ samples, _ = samples_of(scene)
+ scale = pixels / REF_PIXELS * ((samples or REF_SAMPLES * 0.05) / REF_SAMPLES)
+ spf = [max(0.3, s * scale) for s in REF_SEC_PER_FRAME]
+ n_chunks = max(1, math.ceil(n_frames / max(1, chunk))) if n_frames else 0
+ gpu_s = [n_frames * s + n_chunks * CHUNK_OVERHEAD_S for s in spf]
+ waves = math.ceil(n_chunks / max(1, min(concurrency, n_chunks or 1))) if n_chunks else 0
+ per = min(chunk, n_frames)
+ wall = [waves * (per * s + CHUNK_OVERHEAD_S) for s in spf]
+ return {
+ "sec_per_frame": spf, "chunks": n_chunks, "gpu_s": gpu_s, "cost": [g / 3600 * GPU_RATE_PER_HOUR for g in gpu_s],
+ "wall": wall, "cold_start": COLD_START_S, "pixels": int(pixels), "samples": samples,
+ }
+
+
+def fmt_s(s):
+ s = int(round(s))
+ if s < 60:
+ return f"{s}s"
+ if s < 3600:
+ return f"{s // 60}m{s % 60:02d}s"
+ return f"{s // 3600}h{(s % 3600) // 60:02d}m"
+
+
+# -- plan (main thread) -----------------------------------------------------------------------------------------
+
+@dataclass
+class Plan:
+ mode: str
+ scene_name: str
+ frames: list
+ step: int
+ targets: dict # frame -> absolute local path, exactly as a local render names it
+ farm_pattern: str # the filename part of render.filepath, with its # padding
+ file_format: str
+ fps: float
+ key: str
+ app: str
+ chunk_size: int
+ concurrency: int
+ timeout_s: int
+ encode_mp4: bool
+ ffmpeg: str
+ blender_bin: str
+ workdir: str = ""
+ copy_path: str = ""
+ skipped: list = field(default_factory=list)
+
+
+def plan(context, mode, prefs):
+ import bpy
+
+ scene = context.scene
+ r = scene.render
+ if not prefs.fal_key.strip():
+ raise PlanError("Set your fal key in Preferences > Add-ons > fal Render Farm")
+ if not prefs.app_id.strip().strip("/"):
+ raise PlanError(NO_APP_MSG)
+ if r.image_settings.file_format == "FFMPEG" or getattr(r.image_settings, "media_type", "") == "VIDEO":
+ raise PlanError("Output is a video format; the farm renders frame sequences in chunks. Pick an image format "
+ "(PNG, EXR...) and enable 'Encode MP4' in the add-on preferences instead")
+ if scene.camera is None:
+ raise PlanError("The scene has no active camera")
+ if r.filepath.startswith("//") and not bpy.data.filepath:
+ raise PlanError("The output path is relative (//) but this file has never been saved; save it first "
+ "or set an absolute output path")
+ frames = frame_list(scene, mode)
+ if not frames:
+ raise PlanError("The frame range is empty")
+ targets = {f: os.path.abspath(bpy.path.abspath(r.frame_path(frame=f))) for f in frames}
+ pattern = re.split(r"[\\/]", r.filepath)[-1]
+ if pattern in ("", ".", ".."):
+ pattern = ""
+ ffmpeg = prefs.ffmpeg_path.strip() or shutil.which("ffmpeg") or ""
+ return Plan(
+ mode=mode, scene_name=scene.name, frames=frames, step=max(1, scene.frame_step) if mode == "ANIMATION" else 1,
+ targets=targets, farm_pattern=pattern, file_format=r.image_settings.file_format,
+ fps=r.fps / (r.fps_base or 1.0), key=prefs.fal_key.strip(), app=prefs.app_id.strip().strip("/"),
+ chunk_size=max(1, prefs.chunk_size), concurrency=max(1, prefs.concurrency), timeout_s=prefs.timeout_s,
+ encode_mp4=prefs.encode_mp4 and mode == "ANIMATION", ffmpeg=ffmpeg, blender_bin=bpy.app.binary_path,
+ )
+
+
+def save_copy(p):
+ """Write the open file, unsaved edits included, to a temp dir. copy=True leaves the user's file, its path and its
+ dirty state alone; relative_remap keeps // paths pointing at the same files from the new location."""
+ import bpy
+
+ p.workdir = tempfile.mkdtemp(prefix="fal_farm_")
+ p.copy_path = os.path.join(p.workdir, "copy.blend")
+ bpy.ops.wm.save_as_mainfile(filepath=p.copy_path, copy=True, relative_remap=True, compress=False,
+ check_existing=False)
+ if not os.path.exists(p.copy_path):
+ raise PlanError("Could not save a temporary copy of the file")
+
+
+# -- job (background thread) ------------------------------------------------------------------------------------
+
+@dataclass
+class Chunk:
+ frames: list
+ step: int
+ status: str = "pending" # pending queued rendering downloading done failed cancelled
+ error: str = ""
+ attempts: int = 0
+ render_s: float = 0.0
+ gpu_s: float = 0.0
+ device: str = ""
+ handle: dict = None
+
+ @property
+ def label(self):
+ a, b = self.frames[0], self.frames[-1]
+ return f"{a}" if a == b else f"{a}-{b}"
+
+
+class Job:
+ def __init__(self, p: Plan):
+ self.p = p
+ self.lock = threading.Lock()
+ self.cancel_ev = threading.Event()
+ self.phase = "starting" # packing uploading rendering encoding done failed cancelled
+ self.message = ""
+ self.log = deque(maxlen=200)
+ self.chunks = []
+ self.bundle_url = self.bundle_id = None
+ self.t0 = time.time()
+ self.t_end = None
+ self.mp4 = None
+ self.thread = None
+ self.finished_seen = False # set by the UI once it has reacted to the end of the job
+
+ # ---- public ----
+ def start(self):
+ self.thread = threading.Thread(target=self._run, name="fal-render-farm", daemon=True)
+ self.thread.start()
+ return self
+
+ def cancel(self):
+ self.cancel_ev.set()
+ self._say("cancelling...")
+ with self.lock:
+ handles = [c.handle for c in self.chunks if c.handle and c.status in ("queued", "rendering")]
+ for h in handles:
+ threading.Thread(target=fal_api.cancel, args=(self.p.key, h), daemon=True).start()
+
+ def retry_failed(self):
+ if self.running:
+ return False
+ with self.lock:
+ failed = [c for c in self.chunks if c.status in ("failed", "cancelled")]
+ for c in failed:
+ c.status, c.error, c.attempts, c.handle = "pending", "", 0, None
+ if not failed:
+ return False
+ self.cancel_ev.clear()
+ self.t0, self.t_end, self.phase = time.time(), None, "starting"
+ self.finished_seen = False
+ self.thread = threading.Thread(target=self._run, name="fal-render-farm", daemon=True)
+ self.thread.start()
+ return True
+
+ @property
+ def running(self):
+ return self.thread is not None and self.thread.is_alive()
+
+ def wait(self, timeout=None):
+ if self.thread:
+ self.thread.join(timeout)
+ return not self.running
+
+ def snapshot(self):
+ with self.lock:
+ counts = {}
+ for c in self.chunks:
+ counts[c.status] = counts.get(c.status, 0) + 1
+ frames_done = sum(len(c.frames) for c in self.chunks if c.status == "done")
+ return {
+ "phase": self.phase, "message": self.message, "counts": counts, "n_chunks": len(self.chunks),
+ "frames_done": frames_done + len(self.p.skipped), "frames_total": len(self.p.frames),
+ "skipped": len(self.p.skipped), "elapsed": (self.t_end or time.time()) - self.t0,
+ "gpu_s": sum(c.gpu_s for c in self.chunks), "render_s": sum(c.render_s for c in self.chunks),
+ "failed": [(c.label, c.error) for c in self.chunks if c.status == "failed"],
+ "mp4": self.mp4, "mode": self.p.mode, "app": self.p.app,
+ }
+
+ # ---- internals ----
+ def _say(self, msg):
+ with self.lock:
+ self.message = msg
+ self.log.append(f"[{time.strftime('%H:%M:%S')}] {msg}")
+ print("fal render farm:", msg)
+
+ def _set_phase(self, phase, msg=None):
+ with self.lock:
+ self.phase = phase
+ if msg:
+ self._say(msg)
+
+ def _run(self):
+ try:
+ if not self.chunks:
+ missing = [f for f in self.p.frames if not os.path.exists(self.p.targets[f])]
+ self.p.skipped = [f for f in self.p.frames if f not in set(missing)]
+ if self.p.skipped:
+ self._say(f"{len(self.p.skipped)} frames already on disk, skipped")
+ self.chunks = self._split(missing)
+ if not self.chunks:
+ self._finish()
+ return
+ if not self.bundle_url:
+ self._bundle()
+ self._render()
+ self._finish()
+ except Exception as e: # noqa: BLE001 - any failure lands in the panel, not a stack trace on stderr only
+ if self.cancel_ev.is_set():
+ self._set_phase("cancelled", "cancelled")
+ else:
+ self._set_phase("failed", f"failed: {fal_api._scrub(str(e), self.p.key)}")
+ self.log.append(fal_api._scrub(traceback.format_exc(), self.p.key))
+ self.t_end = time.time()
+ finally:
+ if self.p.workdir and not self.running_chunks():
+ shutil.rmtree(self.p.workdir, ignore_errors=True)
+
+ def running_chunks(self):
+ return any(c.status in ("queued", "rendering", "downloading") for c in self.chunks)
+
+ def _split(self, missing):
+ """Contiguous runs (in steps of frame_step) of missing frames, cut into chunks of at most chunk_size."""
+ step, out, run = self.p.step, [], []
+ for f in missing:
+ if run and (f != run[-1] + step or len(run) >= self.p.chunk_size):
+ out.append(Chunk(run, step))
+ run = []
+ run.append(f)
+ if run:
+ out.append(Chunk(run, step))
+ return out
+
+ def _bundle(self):
+ p = self.p
+ self._set_phase("packing", "packing a copy of the file (textures, fonts, linked data)...")
+ packed = os.path.join(p.workdir, "scene.blend")
+ proc = subprocess.run(
+ [p.blender_bin, "-b", "--factory-startup", p.copy_path, "--python", os.path.join(HERE, "pack_copy.py"),
+ "--", packed],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", creationflags=NO_WINDOW)
+ out = proc.stdout + proc.stderr
+ for line in out.splitlines():
+ if line.startswith(("PACK-WARNING:", "PACK-INFO:")):
+ self.log.append(line)
+ problems = [l[len("PACK-PROBLEM:"):].strip() for l in out.splitlines() if l.startswith("PACK-PROBLEM:")]
+ if problems:
+ raise RuntimeError("the file references data that can't be packed: " + "; ".join(problems[:6]))
+ if proc.returncode != 0 or not os.path.exists(packed):
+ raise RuntimeError(f"packing failed (Blender exited {proc.returncode}): {out[-800:]}")
+ os.remove(p.copy_path)
+ if self.cancel_ev.is_set():
+ raise RuntimeError("cancelled")
+
+ zpath = os.path.join(p.workdir, "bundle.zip")
+ with zipfile.ZipFile(zpath, "w", zipfile.ZIP_STORED) as z: # the .blend is saved compressed already
+ z.write(packed, "scene.blend")
+ z.write(os.path.join(HERE, "farm_gpu.py"), "farm_gpu.py")
+ os.remove(packed)
+ sha = hashlib.sha256()
+ with open(zpath, "rb") as f:
+ while b := f.read(8 << 20):
+ sha.update(b)
+ digest = sha.hexdigest()
+ self.bundle_id = digest[:16]
+ size = os.path.getsize(zpath)
+ if digest in _uploads:
+ self.bundle_url = _uploads[digest]
+ self._say(f"bundle {self.bundle_id} ({size / 1e6:.1f} MB) already uploaded")
+ else:
+ self._set_phase("uploading", f"uploading bundle {self.bundle_id} ({size / 1e6:.1f} MB)...")
+
+ def prog(sent, total):
+ with self.lock:
+ self.message = f"uploading bundle {self.bundle_id}: {sent / 1e6:.0f}/{total / 1e6:.0f} MB"
+
+ self.bundle_url = fal_api.upload_file(p.key, zpath, progress=prog)
+ _uploads[digest] = self.bundle_url
+ self._say(f"bundle {self.bundle_id} uploaded")
+ os.remove(zpath)
+
+ def _args(self, c):
+ p = self.p
+ return ["{bundle}/scene.blend", "-S", p.scene_name, "--python", "{bundle}/farm_gpu.py",
+ "-o", "{out}/frames/" + p.farm_pattern,
+ "-s", str(c.frames[0]), "-e", str(c.frames[-1]), "-j", str(c.step), "-a"]
+
+ def _render(self):
+ pending = [c for c in self.chunks if c.status == "pending"]
+ n = len(pending)
+ self._set_phase("rendering", f"rendering {sum(len(c.frames) for c in pending)} frames in {n} chunks "
+ f"on {self.p.app} ({min(n, self.p.concurrency)} at a time)")
+ with cf.ThreadPoolExecutor(max_workers=min(n, self.p.concurrency), thread_name_prefix="fal-chunk") as pool:
+ list(pool.map(self._chunk, pending))
+
+ def _chunk(self, c):
+ p = self.p
+ while not self.cancel_ev.is_set():
+ c.attempts += 1
+ try:
+ self._chunk_once(c)
+ return
+ except Exception as e: # noqa: BLE001
+ err = fal_api._scrub(str(e), p.key)
+ if "with 0 frames" in err and p.file_format != "PNG":
+ err = (f"the farm returned no {p.file_format} files. {p.app} may only return PNGs; "
+ f"set the farm app to your blender-farm-2 deployment. Blender said: {err[-600:]}")
+ if c.handle and c.status in ("queued", "rendering"):
+ fal_api.cancel(p.key, c.handle) # e.g. a status poll gave up: don't leave a twin rendering
+ with self.lock:
+ c.error, c.handle = err, None
+ if self.cancel_ev.is_set():
+ break
+ if c.attempts >= 2:
+ with self.lock:
+ c.status = "failed"
+ self._say(f"chunk {c.label} failed: {err[:300]}")
+ return
+ self._say(f"chunk {c.label} attempt {c.attempts} failed, retrying: {err[:200]}")
+ time.sleep(3)
+ with self.lock:
+ c.status = "cancelled"
+
+ def _chunk_once(self, c):
+ p = self.p
+ payload = {"bundle_url": self.bundle_url, "bundle_id": self.bundle_id, "blender_args": self._args(c),
+ "timeout_s": int(p.timeout_s), "outputs": ["frames/**/*"]}
+ with self.lock:
+ c.status = "queued"
+ handle = fal_api.submit(p.key, p.app, payload)
+ with self.lock:
+ c.handle = handle
+ delay = 1.0
+ while True:
+ if self.cancel_ev.is_set():
+ fal_api.cancel(p.key, handle)
+ raise RuntimeError("cancelled")
+ st = fal_api.status(p.key, handle).get("status")
+ if st == "IN_PROGRESS":
+ with self.lock:
+ c.status = "rendering"
+ elif st == "COMPLETED":
+ break
+ time.sleep(delay)
+ delay = min(delay * 1.5, 4.0)
+ res = fal_api.result(p.key, handle)
+ if "frames_url" not in res:
+ raise RuntimeError(f"unexpected farm response: {str(res)[:500]}")
+ with self.lock:
+ c.status = "downloading"
+ zpath = os.path.join(tempfile.gettempdir(), f"fal_farm_{self.bundle_id}_{c.frames[0]}_{c.frames[-1]}.zip")
+ fal_api.download(res["frames_url"], zpath)
+ try:
+ self._extract(zpath, c)
+ finally:
+ os.remove(zpath)
+ with self.lock:
+ c.status, c.error, c.handle = "done", "", None
+ c.render_s = float(res.get("render_seconds", 0))
+ c.gpu_s = c.render_s + float(res.get("bundle_seconds", 0))
+ c.device = res.get("device", "")
+ self._say(f"chunk {c.label}: {res.get('frame_count')} frames, render {c.render_s:.0f}s on "
+ f"{c.device.split(',')[0]}")
+
+ def _extract(self, zpath, c):
+ p = self.p
+ by_name = {os.path.basename(p.targets[f]): p.targets[f] for f in c.frames}
+ by_lower = {k.lower(): v for k, v in by_name.items()}
+ fallback_dir = os.path.dirname(p.targets[c.frames[0]])
+ with zipfile.ZipFile(zpath) as z:
+ for info in z.infolist():
+ if info.is_dir():
+ continue
+ name = info.filename.rsplit("/", 1)[-1]
+ dest = by_name.get(name) or by_lower.get(name.lower()) or os.path.join(fallback_dir, name)
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
+ with z.open(info) as src, open(dest + ".part", "wb") as dst:
+ shutil.copyfileobj(src, dst, 4 << 20)
+ os.replace(dest + ".part", dest)
+ missing = [f for f in c.frames if not os.path.exists(p.targets[f])]
+ if missing:
+ got = ", ".join(n.rsplit("/", 1)[-1] for n in zipfile.ZipFile(zpath).namelist()[:4])
+ raise RuntimeError(f"farm output is missing frames {missing[:8]} (got {got})")
+
+ def _finish(self):
+ if self.cancel_ev.is_set():
+ self._set_phase("cancelled", "cancelled")
+ elif any(c.status == "failed" for c in self.chunks):
+ n = sum(c.status == "failed" for c in self.chunks)
+ self._set_phase("failed", f"{n} chunk(s) failed; fix and press Retry failed chunks")
+ else:
+ if self.p.encode_mp4:
+ self._encode()
+ self._set_phase("done", f"done: {len(self.p.frames)} frames in "
+ f"{os.path.dirname(self.p.targets[self.p.frames[0]])}")
+ self.t_end = time.time()
+
+ def _encode(self):
+ p = self.p
+ if not p.ffmpeg:
+ self._say("ffmpeg not found; skipping the MP4 (set its path in the add-on preferences)")
+ return
+ if p.file_format not in VIDEO_SAFE:
+ self._say(f"skipping the MP4: {p.file_format} frames are linear/HDR, encode them in your grade instead")
+ return
+ self._set_phase("encoding", "encoding MP4...")
+ first, last = p.frames[0], p.frames[-1]
+ stem = os.path.splitext(os.path.basename(p.targets[first]))[0]
+ stem = re.sub(r"\d+$", "", stem).rstrip("_.- ") or "render"
+ out = os.path.join(os.path.dirname(p.targets[first]), f"{stem}_{first:04d}-{last:04d}.mp4")
+ listing = os.path.join(tempfile.gettempdir(), f"fal_farm_concat_{os.getpid()}.txt")
+ with open(listing, "w", encoding="utf-8") as f:
+ for fr in p.frames:
+ f.write("file '%s'\nduration %.6f\n" % (p.targets[fr].replace("\\", "/").replace("'", r"'\''"), 1 / p.fps))
+ f.write("file '%s'\n" % p.targets[last].replace("\\", "/").replace("'", r"'\''"))
+ cmd = [p.ffmpeg, "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", listing,
+ "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-r", f"{p.fps:g}", "-c:v", "libx264", "-pix_fmt", "yuv420p",
+ "-crf", "16", "-preset", "slow", out]
+ proc = subprocess.run(cmd, capture_output=True, text=True, errors="replace", creationflags=NO_WINDOW)
+ os.remove(listing)
+ if proc.returncode == 0:
+ self.mp4 = out
+ self._say(f"MP4: {out}")
+ else:
+ self._say(f"ffmpeg failed: {proc.stderr[-400:]}")
diff --git a/blender_addon/fal_render_farm/pack_copy.py b/blender_addon/fal_render_farm/pack_copy.py
new file mode 100644
index 0000000..633803d
--- /dev/null
+++ b/blender_addon/fal_render_farm/pack_copy.py
@@ -0,0 +1,54 @@
+"""Run by the add-on in a separate background Blender, on a temporary copy of the user's file (never the file itself):
+
+ blender -b --factory-startup <copy.blend> --python pack_copy.py -- <out.blend>
+
+Makes linked library data local, packs images/fonts/sounds/volumes, and refuses (exit 2) if anything the render
+needs still points outside the file, listing each path on a "PACK-PROBLEM:" line.
+"""
+
+import os
+import sys
+
+import bpy
+
+out = sys.argv[sys.argv.index("--") + 1]
+
+if bpy.data.libraries:
+ print("PACK-INFO: making linked data local:", ", ".join(l.filepath for l in bpy.data.libraries))
+ try:
+ bpy.ops.object.make_local(type="ALL")
+ except RuntimeError as e:
+ print("PACK-INFO: make_local:", e)
+
+try:
+ bpy.ops.file.pack_all()
+except RuntimeError as e: # missing files: reported below as problems
+ print("PACK-INFO: pack_all:", str(e).strip())
+
+problems, warnings = [], []
+for img in bpy.data.images:
+ if img.users and img.source in {"FILE", "SEQUENCE", "TILED", "MOVIE"} and not img.packed_file and img.filepath:
+ problems.append(f"image not packed ({img.source.lower()}): {img.name} -> {img.filepath}")
+for v in bpy.data.volumes:
+ if v.users and not v.packed_file and v.filepath:
+ problems.append(f"volume not packed: {v.name} -> {v.filepath}")
+for c in bpy.data.cache_files:
+ if c.users:
+ problems.append(f"cache file (Alembic/USD) can't be packed: {c.name} -> {c.filepath}")
+for lib in bpy.data.libraries:
+ problems.append(f"library still linked: {lib.filepath}")
+for ob in bpy.data.objects:
+ for m in ob.modifiers:
+ if m.type == "FLUID" and m.fluid_type == "DOMAIN":
+ warnings.append(f"fluid domain {ob.name}: its disk cache is not shipped "
+ f"({bpy.path.abspath(m.domain_settings.cache_directory)})")
+
+for w in warnings:
+ print("PACK-WARNING:", w)
+for p in problems:
+ print("PACK-PROBLEM:", p)
+if problems:
+ sys.exit(2)
+
+bpy.ops.wm.save_as_mainfile(filepath=os.path.abspath(out), copy=True, compress=True)
+print("PACK-OK:", os.path.getsize(out))
diff --git a/blender_addon/tests/make_test_scene.py b/blender_addon/tests/make_test_scene.py
new file mode 100644
index 0000000..cb97ea8
--- /dev/null
+++ b/blender_addon/tests/make_test_scene.py
@@ -0,0 +1,115 @@
+"""Build the add-on's test scene: a few animated objects, an external image texture (to exercise packing), a sun and
+an area light, a moving camera, 48 frames at 640x360, Cycles at 32 spp with a fixed seed and no denoiser.
+
+ blender -b --factory-startup --python make_test_scene.py -- <dir>
+
+Writes <dir>/test_scene.blend and <dir>/tex/checker.png; output path is //renders/test_#### (relative on purpose).
+"""
+
+import math
+import os
+import sys
+
+import bpy
+
+out_dir = os.path.abspath(sys.argv[sys.argv.index("--") + 1])
+os.makedirs(os.path.join(out_dir, "tex"), exist_ok=True)
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+scene = bpy.context.scene
+scene.name = "FarmTest"
+
+# external texture, saved next to the .blend and referenced relatively -> must be packed for the farm
+tex_path = os.path.join(out_dir, "tex", "checker.png")
+img = bpy.data.images.new("checker", 256, 256)
+px = []
+for y in range(256):
+ for x in range(256):
+ c = 0.9 if ((x // 32) + (y // 32)) % 2 else 0.1
+ px += [c, 0.35 + 0.5 * (x / 255), 1.0 - c * 0.6, 1.0]
+img.pixels = px
+img.filepath_raw = tex_path
+img.file_format = "PNG"
+img.save()
+
+
+def material(name, color=None, image=None):
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ bsdf = m.node_tree.nodes["Principled BSDF"]
+ if image:
+ t = m.node_tree.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(tex_path)
+ m.node_tree.links.new(t.outputs["Color"], bsdf.inputs["Base Color"])
+ else:
+ bsdf.inputs["Base Color"].default_value = (*color, 1)
+ bsdf.inputs["Roughness"].default_value = 0.35
+ return m
+
+
+bpy.data.images.remove(img) # the material loads it back from disk, as a normal external image
+
+bpy.ops.mesh.primitive_plane_add(size=20)
+bpy.context.object.data.materials.append(material("floor", image=True))
+
+bpy.ops.mesh.primitive_cube_add(size=1.5, location=(-2, 0, 0.75))
+cube = bpy.context.object
+cube.data.materials.append(material("red", (0.8, 0.1, 0.08)))
+bpy.ops.mesh.primitive_uv_sphere_add(radius=0.9, location=(0.5, 1.5, 0.9))
+sphere = bpy.context.object
+bpy.ops.object.shade_smooth()
+sphere.data.materials.append(material("blue", (0.1, 0.3, 0.9)))
+bpy.ops.mesh.primitive_monkey_add(size=1.4, location=(2.2, -0.8, 1.0))
+monkey = bpy.context.object
+bpy.ops.object.shade_smooth()
+monkey.data.materials.append(material("gold", (0.9, 0.65, 0.2)))
+
+for f, z_rot, sz in ((1, 0, 0.9), (48, 2 * math.pi, 2.6)):
+ scene.frame_set(f)
+ cube.rotation_euler.z = z_rot
+ cube.keyframe_insert("rotation_euler", index=2)
+ sphere.location.z = sz
+ sphere.keyframe_insert("location", index=2)
+ monkey.rotation_euler.z = -z_rot / 2
+ monkey.keyframe_insert("rotation_euler", index=2)
+
+bpy.ops.object.light_add(type="SUN", rotation=(math.radians(50), 0, math.radians(30)))
+bpy.context.object.data.energy = 3
+bpy.ops.object.light_add(type="AREA", location=(-3, -4, 4))
+bpy.context.object.data.energy = 400
+bpy.context.object.data.size = 3
+
+bpy.ops.object.camera_add(location=(0, -9, 4))
+cam = bpy.context.object
+scene.camera = cam
+for f, x in ((1, -2.0), (48, 2.0)):
+ cam.location.x = x
+ cam.keyframe_insert("location", index=0, frame=f)
+con = cam.constraints.new("TRACK_TO")
+bpy.ops.object.empty_add(location=(0, 0, 0.8))
+con.target = bpy.context.object
+
+world = bpy.data.worlds.new("World")
+world.use_nodes = True
+world.node_tree.nodes["Background"].inputs[0].default_value = (0.05, 0.07, 0.1, 1)
+world.node_tree.nodes["Background"].inputs[1].default_value = 1.0
+scene.world = world
+
+r = scene.render
+r.engine = "CYCLES"
+scene.cycles.samples = 32
+scene.cycles.use_adaptive_sampling = False
+scene.cycles.use_denoising = False
+scene.cycles.seed = 0
+r.resolution_x, r.resolution_y, r.resolution_percentage = 640, 360, 100
+r.fps = 24
+scene.frame_start, scene.frame_end = 1, 48
+r.image_settings.file_format = "PNG"
+r.image_settings.color_mode = "RGBA"
+r.filepath = "//renders/test_####"
+scene.frame_set(1)
+
+bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_dir, "test_scene.blend"), relative_remap=True)
+bpy.ops.file.make_paths_relative() # the texture becomes //tex/checker.png, like a real project
+bpy.ops.wm.save_mainfile()
+print("TEST-SCENE:", os.path.join(out_dir, "test_scene.blend"))
diff --git a/blender_addon/tests/test_farm.py b/blender_addon/tests/test_farm.py
new file mode 100644
index 0000000..4131624
--- /dev/null
+++ b/blender_addon/tests/test_farm.py
@@ -0,0 +1,266 @@
+"""End-to-end test of the fal Render Farm add-on, headless, against the real farm.
+
+ blender -b --factory-startup --python-exit-code 1 --python test_farm.py -- <workdir> --app <your-fal-username>/blender-farm-2 [--chunk 12]
+
+1. builds the test scene (make_test_scene.py) in <workdir>/scene/
+2. enables the add-on from blender_addon/fal_render_farm (the folder, as an add-on module)
+3. sets the fal key from FAL_SERVERLESS_KEY (Windows user env / registry) in this process only; never printed
+4. registers the UI: calls every operator's poll() and draws the panel + status bar into a recording layout
+5. renders the 48-frame animation through the add-on's operator, waits, and checks every frame file by name
+6. checks the user's .blend was not modified, then resume: deletes 2 frames and re-renders (only those go out)
+7. renders frame 1 locally on this GPU and compares it with the farm's frame 1 (PSNR)
+8. "Render this frame" with OPEN_EXR output (needs the farm's `outputs` support)
+Prints a TEST-SUMMARY json line at the end; exits 1 on any failure.
+"""
+
+import argparse
+import hashlib
+import json
+import math
+import os
+import runpy
+import shutil
+import subprocess
+import sys
+import time
+
+import bpy
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ADDON_PARENT = os.path.dirname(HERE) # blender_addon/
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+ap = argparse.ArgumentParser()
+ap.add_argument("workdir")
+ap.add_argument("--app", default=os.environ.get("ANYSHOT_FARM_APP"),
+ help="fal app id of your farm, <your-fal-username>/blender-farm-2 (default: $ANYSHOT_FARM_APP)")
+ap.add_argument("--chunk", type=int, default=12)
+ap.add_argument("--concurrency", type=int, default=20)
+ap.add_argument("--ffmpeg", default="", help="ffmpeg path for the MP4 step (else PATH)")
+args = ap.parse_args(argv)
+if not args.app:
+ ap.error("pass --app <your-fal-username>/blender-farm-2 or set ANYSHOT_FARM_APP")
+work = os.path.abspath(args.workdir)
+summary = {"app": args.app, "chunk": args.chunk, "checks": {}}
+failures = []
+
+
+def check(name, ok, detail=""):
+ summary["checks"][name] = {"ok": bool(ok), "detail": detail}
+ print(("PASS " if ok else "FAIL ") + name + (f": {detail}" if detail else ""), flush=True)
+ if not ok:
+ failures.append(name)
+
+
+def user_env(name):
+ if os.environ.get(name):
+ return os.environ[name]
+ out = subprocess.run(["reg", "query", r"HKCU\Environment", "/v", name], capture_output=True, text=True).stdout
+ parts = out.split()
+ return parts[parts.index(name) + 2] if name in parts else None
+
+
+def sha(path):
+ return hashlib.sha256(open(path, "rb").read()).hexdigest()
+
+
+def wait(job, label):
+ t0, last = time.time(), ""
+ while not job.wait(timeout=5):
+ s = job.snapshot()
+ line = f" [{label} {time.time() - t0:5.0f}s] {s['phase']}: {s['message'][:110]} | {s['counts']}"
+ if line != last:
+ print(line, flush=True)
+ last = line
+ return job.snapshot()
+
+
+# 1. scene -------------------------------------------------------------------------------------------------------
+scene_dir = os.path.join(work, "scene")
+shutil.rmtree(scene_dir, ignore_errors=True)
+subprocess.run([bpy.app.binary_path, "-b", "--factory-startup", "--python", os.path.join(HERE, "make_test_scene.py"),
+ "--", scene_dir], check=True, capture_output=True)
+blend = os.path.join(scene_dir, "test_scene.blend")
+check("test scene built", os.path.exists(blend), blend)
+
+# 2. add-on from its folder --------------------------------------------------------------------------------------
+import addon_utils # noqa: E402
+
+sys.path.insert(0, ADDON_PARENT)
+mod = addon_utils.enable("fal_render_farm", default_set=True, handle_error=None) # --factory-startup: prefs are never saved
+check("add-on enabled from folder", mod is not None and "fal_render_farm" in bpy.context.preferences.addons,
+ getattr(mod, "__file__", ""))
+import fal_render_farm as addon # noqa: E402
+from fal_render_farm import job as farm_job # noqa: E402
+
+# 3. key ---------------------------------------------------------------------------------------------------------
+prefs = bpy.context.preferences.addons["fal_render_farm"].preferences
+key = user_env("FAL_SERVERLESS_KEY")
+check("FAL_SERVERLESS_KEY found", bool(key))
+prefs.fal_key = key
+prefs.app_id = args.app
+prefs.chunk_size = args.chunk
+prefs.concurrency = args.concurrency
+prefs.encode_mp4 = True
+prefs.ffmpeg_path = args.ffmpeg
+
+bpy.ops.wm.open_mainfile(filepath=blend)
+before = sha(blend)
+dirty_before = bpy.data.is_dirty # background Blender reports a freshly opened file as dirty; compare, don't assume
+scene = bpy.context.scene
+
+
+# 4. UI: polls + panel/status draw into a recording layout -------------------------------------------------------
+class Rec:
+ """Stands in for UILayout: accepts any call/attribute and records labels, ops and props."""
+
+ def __init__(self, log):
+ self._log = log
+
+ def __getattr__(self, name):
+ def fn(*a, **k):
+ if name in ("label", "operator", "prop", "progress"):
+ self._log.append((name, k.get("text") or (a[1] if name == "prop" and len(a) > 1 else (a[0] if a else ""))))
+ return Rec(self._log)
+ return fn
+
+ def __setattr__(self, name, value):
+ object.__setattr__(self, name, value)
+
+
+def draw_panel():
+ log = []
+ fake = type("P", (), {})()
+ fake.layout = Rec(log)
+ addon.FALRF_PT_panel.draw(fake, bpy.context)
+ addon.FALRF_PT_panel.draw_header(fake, bpy.context)
+ addon.draw_status(fake, bpy.context)
+ return log
+
+
+try:
+ ui = draw_panel()
+ labels = [t for k, t in ui if k == "label"]
+ check("panel draws (idle)", any("Estimate" in str(t) for t in labels), " | ".join(map(str, labels[:5])))
+ summary["panel_idle"] = [str(t) for t in labels]
+except Exception as e: # noqa: BLE001
+ check("panel draws (idle)", False, repr(e))
+
+ctx = bpy.context
+polls = {
+ "render": addon.FALRF_OT_render.poll(ctx), "cancel(idle)": addon.FALRF_OT_cancel.poll(ctx),
+ "retry(idle)": bool(addon.FALRF_OT_retry.poll(ctx)), "check_key": True,
+}
+check("operator polls (idle)", polls["render"] and not polls["cancel(idle)"] and not polls["retry(idle)"], str(polls))
+check("fal accepts the key", fal_ok := addon.fal_api.check_key(key, args.app)[0])
+
+# 5. animation on the farm ---------------------------------------------------------------------------------------
+frames = list(range(scene.frame_start, scene.frame_end + 1))
+targets = {f: os.path.abspath(bpy.path.abspath(scene.render.frame_path(frame=f))) for f in frames}
+shutil.rmtree(os.path.dirname(targets[1]), ignore_errors=True)
+est = farm_job.estimate(scene, len(frames), args.chunk, args.concurrency)
+summary["estimate"] = {"cost_usd": [round(c, 3) for c in est["cost"]], "gpu_s": [round(g) for g in est["gpu_s"]],
+ "wall_s": [round(w) for w in est["wall"]], "sec_per_frame": est["sec_per_frame"]}
+
+t0 = time.time()
+res = bpy.ops.fal_render_farm.render(mode="ANIMATION")
+check("render operator started", res == {"FINISHED"} and farm_job.CURRENT is not None, str(res))
+job = farm_job.CURRENT
+check("operator polls (running)", not addon.FALRF_OT_render.poll(ctx) and addon.FALRF_OT_cancel.poll(ctx))
+time.sleep(1)
+try:
+ ui = draw_panel()
+ check("panel draws (running)", any("Starting" in str(t) or "Packing" in str(t) or "Uploading" in str(t)
+ or "Rendering" in str(t) for k, t in ui if k == "label"))
+except Exception as e: # noqa: BLE001
+ check("panel draws (running)", False, repr(e))
+s = wait(job, "anim")
+wall = time.time() - t0
+missing = [f for f in frames if not os.path.exists(targets[f])]
+check("animation job done", s["phase"] == "done", s["message"])
+check("all 48 frames on disk with local names", not missing,
+ f"{len(frames) - len(missing)}/48 e.g. {os.path.basename(targets[1])} .. {os.path.basename(targets[48])}"
+ + (f", missing {missing[:6]}" if missing else ""))
+extra = sorted(set(os.listdir(os.path.dirname(targets[1]))) - {os.path.basename(t) for t in targets.values()})
+check("no stray files in the output dir", all(e.endswith(".mp4") for e in extra), str(extra[:5]))
+summary["anim"] = {"wall_s": round(wall, 1), "chunks": s["n_chunks"], "gpu_s": round(s["gpu_s"], 1),
+ "render_s": round(s["render_s"], 1), "cost_usd": round(s["gpu_s"] / 3600 * 4.0, 4),
+ "devices": sorted({c.device for c in job.chunks}), "mp4": s["mp4"],
+ "per_chunk_render_s": [c.render_s for c in job.chunks], "log": list(job.log)[-12:]}
+if args.ffmpeg or shutil.which("ffmpeg"):
+ check("MP4 encoded", bool(s["mp4"]) and os.path.getsize(s["mp4"]) > 10000, str(s["mp4"]))
+check("user's .blend untouched (bytes and dirty flag)", sha(blend) == before and bpy.data.is_dirty == dirty_before,
+ f"sha {sha(blend)[:12]} vs {before[:12]}, dirty {bpy.data.is_dirty} vs {dirty_before}")
+ui = draw_panel()
+check("panel draws (done)", any("Done" in str(t) for k, t in ui if k == "label"))
+check("operator polls (done)", addon.FALRF_OT_render.poll(ctx) and not addon.FALRF_OT_cancel.poll(ctx))
+
+# 6. resume --------------------------------------------------------------------------------------------------------
+for f in (5, 30):
+ os.remove(targets[f])
+t0 = time.time()
+bpy.ops.fal_render_farm.render(mode="ANIMATION")
+s2 = wait(farm_job.CURRENT, "resume")
+check("resume re-renders only the missing frames",
+ s2["phase"] == "done" and s2["skipped"] == 46 and s2["n_chunks"] == 2 and all(os.path.exists(targets[f]) for f in frames),
+ f"skipped {s2['skipped']}, chunks {s2['n_chunks']}, {time.time() - t0:.0f}s")
+summary["resume"] = {"wall_s": round(time.time() - t0, 1), "chunks": s2["n_chunks"], "skipped": s2["skipped"],
+ "log": list(farm_job.CURRENT.log)[-4:]}
+
+# 7. parity: local GPU render of frame 1 vs the farm's ------------------------------------------------------------
+runpy.run_path(os.path.join(ADDON_PARENT, "fal_render_farm", "farm_gpu.py")) # same device setup as the farm
+local = os.path.join(work, "local_0001.png")
+saved_fp = scene.render.filepath
+scene.frame_set(1)
+scene.render.filepath = local
+t0 = time.time()
+bpy.ops.render.render(write_still=True)
+local_s = time.time() - t0
+scene.render.filepath = saved_fp
+
+
+def pixels(path):
+ import numpy as np
+
+ img = bpy.data.images.load(path, check_existing=False)
+ a = np.empty(img.size[0] * img.size[1] * 4, dtype=np.float32)
+ img.pixels.foreach_get(a)
+ size = tuple(img.size)
+ bpy.data.images.remove(img)
+ return a.reshape(-1, 4), size
+
+
+import numpy as np # noqa: E402
+
+a, sa = pixels(local)
+b, sb = pixels(targets[1])
+mse = float(np.mean((a[:, :3] - b[:, :3]) ** 2))
+psnr = 99.0 if mse == 0 else 10 * math.log10(1.0 / mse)
+maxdiff = float(np.max(np.abs(a - b)))
+check("local vs farm frame 1: same size", sa == sb, f"{sa} vs {sb}")
+check("local vs farm frame 1: PSNR >= 30 dB", psnr >= 30, f"PSNR {psnr:.2f} dB, max abs diff {maxdiff:.3f}")
+summary["parity"] = {"psnr_db": round(psnr, 2), "max_abs_diff": round(maxdiff, 4), "local_render_s": round(local_s, 1),
+ "local": local, "farm": targets[1], "local_device": bpy.context.preferences.addons["cycles"].preferences.compute_device_type}
+
+# 8. single frame, EXR -------------------------------------------------------------------------------------------
+scene.render.image_settings.file_format = "OPEN_EXR"
+scene.render.filepath = "//renders/exr/still_###"
+scene.frame_set(17)
+exr = os.path.abspath(bpy.path.abspath(scene.render.frame_path(frame=17)))
+shutil.rmtree(os.path.dirname(exr), ignore_errors=True)
+t0 = time.time()
+bpy.ops.fal_render_farm.render(mode="FRAME")
+s3 = wait(farm_job.CURRENT, "exr")
+ok = s3["phase"] == "done" and os.path.exists(exr)
+check("render this frame (OPEN_EXR) lands as " + os.path.basename(exr), ok, s3["message"])
+if ok:
+ with open(exr, "rb") as f:
+ check("EXR file is a real OpenEXR", f.read(4) == b"\x76\x2f\x31\x01")
+summary["exr_frame"] = {"wall_s": round(time.time() - t0, 1), "path": exr, "gpu_s": round(s3["gpu_s"], 1)}
+
+# unregister cleanly
+addon_utils.disable("fal_render_farm", default_set=True)
+check("add-on unregisters", "fal_render_farm" not in bpy.context.preferences.addons)
+
+summary["failures"] = failures
+print("TEST-SUMMARY " + json.dumps(summary), flush=True)
+sys.exit(1 if failures else 0)
diff --git a/blender_addon/tests/test_zip_install.py b/blender_addon/tests/test_zip_install.py
new file mode 100644
index 0000000..9bb1d8b
--- /dev/null
+++ b/blender_addon/tests/test_zip_install.py
@@ -0,0 +1,27 @@
+"""Install the built extension zip the way a user would, into a throwaway user profile, and check it registers.
+
+ BLENDER_USER_RESOURCES=<empty temp dir> blender -b --factory-startup --python-exit-code 1 \
+ --python test_zip_install.py -- blender_addon/fal_render_farm-1.0.0.zip
+"""
+
+import os
+import sys
+
+import bpy
+
+zip_path = os.path.abspath(sys.argv[sys.argv.index("--") + 1])
+ext_dir = bpy.utils.user_resource("EXTENSIONS")
+assert os.environ.get("BLENDER_USER_RESOURCES") and os.path.normcase(os.path.abspath(ext_dir)).startswith(os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_RESOURCES"]))), \
+ f"refusing to install into the real profile ({ext_dir})"
+print("ZIP-TEST extensions dir:", ext_dir)
+
+res = bpy.ops.extensions.package_install_files(repo="user_default", filepath=zip_path, enable_on_install=True)
+print("ZIP-TEST install:", res)
+name = "bl_ext.user_default.fal_render_farm"
+assert name in bpy.context.preferences.addons, list(bpy.context.preferences.addons.keys())
+prefs = bpy.context.preferences.addons[name].preferences
+assert prefs.app_id == "" and prefs.chunk_size == 24 and prefs.concurrency == 100, "defaults"
+assert hasattr(bpy.types, "FALRF_PT_panel"), "panel not registered"
+assert bpy.ops.fal_render_farm.render.poll(), "render op poll"
+assert not bpy.ops.fal_render_farm.cancel.poll(), "cancel op poll"
+print("ZIP-TEST OK: installed and enabled as", name, "with defaults", prefs.app_id, prefs.chunk_size, prefs.concurrency)
diff --git a/breakdown/anyshot_supercut.py b/breakdown/anyshot_supercut.py
new file mode 100644
index 0000000..3d01d09
--- /dev/null
+++ b/breakdown/anyshot_supercut.py
@@ -0,0 +1,222 @@
+"""AnyShot supercut: four AnyScene sets shot by AnyShot (scene to video), for the launch post.
+
+Every shot here was planned and rendered by the AnyShot endpoint from words. The caustics chamber was directed shot by
+shot; riad, apothecary and submarine got one text brief each and the agent picked the shots. Each set runs establishing
+wide -> first-person walk -> close dolly reveals, the same grammar as the brief.
+
+ python breakdown/anyshot_supercut.py -> breakdown/supercut/anyshot_supercut.mp4 (1920x1080, 24 fps)
+"""
+
+import glob
+import os
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+if "FFMPEG" not in os.environ:
+ capcut = sorted(glob.glob(os.path.expandvars(r"%LOCALAPPDATA%/CapCut/Apps/*/ffmpeg.exe")))
+ os.environ["FFMPEG"] = capcut[-1] if capcut else "ffmpeg"
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from assemble import BG, DIM, FPS, H, INK, LETTERBOX, W, duration, ff, font # noqa: E402
+from PIL import Image, ImageDraw, ImageFilter # noqa: E402
+
+RUNS = Path(os.environ.get("ANYSCENE_RUNS", ROOT.parent / "anyscene-runs"))
+OUT = ROOT / "breakdown/supercut"
+XF = 0.5 # crossfade, seconds
+CARD = 2.4 # name card length, including both crossfades
+SEG_ENC = ["-an", "-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "16", "-b:v", "0", "-pix_fmt", "yuv420p"]
+BRASS = (226, 178, 92)
+
+
+def shot(folder, name):
+ """An AnyShot output by shot name (the files carry a fal upload prefix)."""
+ hits = sorted((RUNS / folder).glob(f"*{name}.mp4"))
+ if not hits:
+ raise FileNotFoundError(f"{folder}/*{name}.mp4")
+ return hits[0]
+
+
+C1, C2 = RUNS / "videos/caustic_shots", RUNS / "videos/caustic_shots2"
+SCENES = [
+ dict(key="chamber", kicker="Directed shot by shot", title="The caustics chamber", accent=BRASS, clips=[
+ (C2 / "establishing_wide.mp4", 0.5, 5.0), (C2 / "walk_pov.mp4", 1.0, 9.0),
+ (C2 / "reveal_from_sculpture.mp4", 0.5, 6.0), (C1 / "rack_desk_chair.mp4", 0.5, 6.5),
+ (C1 / "zoom_out_reveal.mp4", 0.5, 7.5)]),
+ dict(key="riad", kicker="One text brief", title="A Marrakech riad", accent=(214, 170, 112), clips=[
+ (shot("shot_riad", "est_wide"), 0.5, 5.0), (shot("shot_riad", "walk_in"), 1.0, 9.0),
+ (shot("shot_riad", "reveal_tea_court"), 0.3, 6.0), (shot("shot_riad", "reveal_lemon_salon"), 0.3, 6.0),
+ (shot("shot_riad", "reveal_fountain"), 0.3, 6.2)]),
+ dict(key="apothecary", kicker="One text brief", title="A Victorian apothecary", accent=(200, 140, 80), clips=[
+ (shot("shot_apothecary", "establish_wide"), 0.5, 5.0), (shot("shot_apothecary", "walk_in"), 1.0, 9.0),
+ (shot("shot_apothecary", "globes_reveal"), 0.0, 5.0), (shot("shot_apothecary", "register_reveal"), 0.0, 5.0),
+ (shot("shot_apothecary", "bottle_wall_reveal"), 0.0, 5.0)]),
+ dict(key="submarine", kicker="One text brief", title="A submarine control room", accent=(226, 96, 80), clips=[
+ (shot("shot_submarine", "establish_wide"), 0.5, 5.0), (shot("shot_submarine", "walk_in"), 1.0, 9.0),
+ (shot("shot_submarine", "reveal_chart"), 0.0, 5.25), (shot("shot_submarine", "reveal_planes"), 0.0, 5.25),
+ (shot("shot_submarine", "reveal_depth"), 0.0, 5.25)]),
+]
+
+
+def text_centered(d, y, txt, fnt, fill):
+ d.text(((W - d.textlength(txt, font=fnt)) / 2, y), txt, font=fnt, fill=fill)
+
+
+def still_video(img, secs, out):
+ png = out.with_suffix(".png")
+ img.save(png)
+ ff("-loop", "1", "-t", f"{secs:.3f}", "-i", png, "-vf", f"fps={FPS},format=yuv420p", *SEG_ENC, out)
+ return secs
+
+
+def blurred_frame(src, at, dim=0.38):
+ png = OUT / f"_bg_{Path(src).stem}_{at:.1f}.png"
+ ff("-ss", f"{at:.2f}", "-i", src, "-frames:v", "1", "-vf", f"scale={W}:-2", png)
+ fr = Image.open(png).convert("RGB")
+ canvas = Image.new("RGB", (W, H), BG)
+ canvas.paste(fr.filter(ImageFilter.GaussianBlur(16)).point(lambda v: int(v * dim)), (0, (H - fr.height) // 2))
+ return canvas
+
+
+def name_card(i, s, out):
+ src, ss, t = s["clips"][0]
+ canvas = blurred_frame(src, ss + t * 0.5)
+ d = ImageDraw.Draw(canvas)
+ y = (H - 30 - 80) // 2
+ text_centered(d, y, f"{i + 1:02d} / {len(SCENES):02d} {s['kicker'].upper()}", font("bahnschrift.ttf", 30), s["accent"])
+ text_centered(d, y + 30, s["title"], font("segoeuib.ttf", 80), INK)
+ return still_video(canvas, CARD, out)
+
+
+def fit(img, bw, bh):
+ """Centre-crop img to bw:bh and resize."""
+ r = bw / bh
+ w, h = img.size
+ if w / h > r:
+ nw = int(h * r)
+ img = img.crop(((w - nw) // 2, 0, (w - nw) // 2 + nw, h))
+ else:
+ nh = int(w / r)
+ img = img.crop((0, (h - nh) // 2, w, (h - nh) // 2 + nh))
+ return img.resize((bw, bh), Image.LANCZOS)
+
+
+def tile_frames(sc, idx, w, h, secs):
+ """secs of one of the scene's clips from its start point, cropped to a mosaic tile, as PIL frames at FPS."""
+ src, ss, _ = sc["clips"][idx]
+ d = OUT / f"_as_tile_{sc['key']}_{idx}"
+ if not d.exists() or len(list(d.glob("*.png"))) < int(secs * FPS):
+ d.mkdir(exist_ok=True)
+ ff("-ss", ss, "-t", secs, "-i", src, "-vf", f"fps={FPS}", d / "%04d.png")
+ return [fit(Image.open(f).convert("RGB"), w, h) for f in sorted(d.glob("*.png"))[: int(secs * FPS)]]
+
+
+def cold_open(out, secs=11.0):
+ """The overview before the details: the four sets' establishing frames as a 2x2 mosaic ("ANY SCENE IN"), tiles
+ fading in one by one, then each tile wipes left to right to its first-person walkthrough, already playing
+ ("DIRECTED SHOTS OUT"); all four keep walking until the cut. Text stays above the mosaic, never over the footage."""
+ gap, top, bottom, side = 14, 96, 40, 40
+ tw, th = (W - 2 * side - gap) // 2, (H - top - bottom - gap) // 2
+ tiles = [(sc, side + (i % 2) * (tw + gap), top + (i // 2) * (th + gap), tw, th) for i, sc in enumerate(SCENES)]
+ wipe0, wipe_step, wipe_len = 2.6, 0.25, 0.8
+ stills = [tile_frames(sc, 0, tw, th, 1.0 / FPS)[0] for sc, *_ in tiles] # the establishing wide's first frame
+ walks = [tile_frames(sc, 1, tw, th, secs - wipe0 + 0.2) for sc, *_ in tiles]
+ head = font("bahnschrift.ttf", 40)
+ n = int(round(secs * FPS))
+ frames = OUT / "_as_open_frames"
+ frames.mkdir(exist_ok=True)
+ ease = lambda a: (lambda a: a * a * (3 - 2 * a))(min(max(a, 0.0), 1.0))
+ mix = lambda c0, c1, a: tuple(int(c0[j] + (c1[j] - c0[j]) * a) for j in range(3))
+ for f in range(n):
+ t = f / FPS
+ fr = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(fr)
+ a_in = ease((t - 0.1) / 0.5) * (1 - ease((t - wipe0) / 0.5))
+ a_out = ease((t - wipe0 - 0.3) / 0.6)
+ if a_in > 0:
+ text_centered(d, 30, "ANY SCENE IN", head, mix(BG, BRASS, a_in))
+ if a_out > 0:
+ text_centered(d, 30, "DIRECTED SHOTS OUT", head, mix(BG, BRASS, a_out))
+ for i, ((sc, x, y, w, h), still, walk) in enumerate(zip(tiles, stills, walks)):
+ a = ease((t - 0.25 - i * 0.3) / 0.55)
+ if a <= 0:
+ continue
+ tile = Image.blend(Image.new("RGB", still.size, BG), still, a)
+ p = ease((t - wipe0 - i * wipe_step) / wipe_len)
+ if p > 0: # the walkthrough, already playing, slides in from the left over the establishing frame
+ st = walk[min(len(walk) - 1, max(0, int((t - wipe0 - i * wipe_step) * FPS)))]
+ cut = int(w * p)
+ tile.paste(st.crop((0, 0, cut, h)), (0, 0))
+ if 0 < cut < w:
+ ImageDraw.Draw(tile).line((cut, 0, cut, h), fill=BRASS, width=3)
+ fr.paste(tile, (x, y))
+ band = Image.new("RGB", (w, 44), (0, 0, 0))
+ fr.paste(Image.blend(fr.crop((x, y + h - 44, x + w, y + h)), band, 0.55 * a), (x, y + h - 44))
+ d.text((x + 16, y + h - 37), sc["title"].upper(), font=font("bahnschrift.ttf", 26), fill=mix(BG, INK, a))
+ fr.save(frames / f"{f:04d}.png", compress_level=1)
+ ff("-framerate", str(FPS), "-i", frames / "%04d.png", "-vf", "format=yuv420p", *SEG_ENC, out)
+ return n / FPS
+
+
+def title_card(out, secs=3.0):
+ canvas = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(canvas)
+ y = (H - 128 - 36) // 2
+ text_centered(d, y, "AnyShot", font("segoeuib.ttf", 96), INK)
+ text_centered(d, y + 128, "SCENE TO VIDEO", font("bahnschrift.ttf", 36), BRASS)
+ return still_video(canvas, secs, out)
+
+
+def end_card(out, secs=4.5):
+ canvas = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(canvas)
+ lines = [(font("segoeuib.ttf", 96), INK, "AnyShot", 128),
+ (font("bahnschrift.ttf", 36), BRASS, "OPEN SOURCE · github.com/apekshik/anyscene", 92),
+ (font("segoeuisl.ttf", 30), DIM, "AnyScene builds the set. AnyShot shoots it.", 0)]
+ y = (H - sum(g for *_, g in lines) - 30) // 2
+ for fnt, col, txt, g in lines:
+ text_centered(d, y, txt, fnt, col)
+ y += g
+ return still_video(canvas, secs, out)
+
+
+def clip(src, ss, t, out):
+ ff("-ss", f"{ss:.3f}", "-t", f"{t:.3f}", "-i", src, "-vf", f"{LETTERBOX},fps={FPS},setsar=1,format=yuv420p",
+ *SEG_ENC, out)
+ return duration(out)
+
+
+def xfade_join(parts, final):
+ inputs, chain = [], []
+ for p, _ in parts:
+ inputs += ["-i", p]
+ prev, offset = "[0:v]", parts[0][1]
+ for i in range(1, len(parts)):
+ lbl = f"[x{i}]"
+ chain.append(f"{prev}[{i}:v]xfade=transition=fade:duration={XF}:offset={offset - XF:.3f}{lbl}")
+ offset += parts[i][1] - XF
+ prev = lbl
+ chain.append(f"{prev}fade=t=in:st=0:d=0.5,fade=t=out:st={offset - 0.8:.3f}:d=0.8[vout]")
+ ff(*inputs, "-filter_complex", ";".join(chain), "-map", "[vout]", "-c:v", "h264_nvenc", "-preset", "p7", "-tune", "hq",
+ "-multipass", "fullres", "-rc", "vbr", "-b:v", "24M", "-maxrate", "36M", "-bufsize", "48M", "-pix_fmt", "yuv420p",
+ "-r", str(FPS), "-movflags", "+faststart", final)
+ return offset
+
+
+def main():
+ OUT.mkdir(parents=True, exist_ok=True)
+ parts = [(OUT / "_as_open.mp4", cold_open(OUT / "_as_open.mp4"))]
+ for i, s in enumerate(SCENES):
+ card = OUT / f"_as_card_{s['key']}.mp4"
+ parts.append((card, name_card(i, s, card)))
+ for j, (src, ss, t) in enumerate(s["clips"]):
+ seg = OUT / f"_as_{s['key']}_{j}.mp4"
+ parts.append((seg, clip(src, ss, t, seg)))
+ parts.append((OUT / "_as_end.mp4", end_card(OUT / "_as_end.mp4")))
+ final = OUT / "anyshot_supercut.mp4"
+ total = xfade_join(parts, final)
+ print(f"{final} {total:.1f} s, {len(parts)} parts")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/breakdown/builder_reel.py b/breakdown/builder_reel.py
new file mode 100644
index 0000000..3be469e
--- /dev/null
+++ b/breakdown/builder_reel.py
@@ -0,0 +1,232 @@
+"""Posting videos for one scene-builder run, made from the run's own event log.
+
+ uv run --with pillow python -I breakdown/builder_reel.py <run dir> --reference ref.png [--clips a.mp4 b.mp4]
+ [--name "Maison Roussel"] [--out DIR]
+
+<run dir> is a builder/client.py output folder: events.jsonl (every stage event, with the image of each one) and,
+once the build has finished, build.json (stills, previews). Writes two videos:
+ hero.mp4 the tweet: reference, wipe to the finished render, the walkthrough clips, end card
+ breakdown.mp4 the thread reply: how it got there, chapter by chapter (plan, prop references, 3D comparisons, every
+ test render it looked at, each critic round with its scores, finals, scouting previews, walkthrough)
+Images come from the fal URLs in the log (cached under <out>/img). Encoded with NVENC (the CapCut ffmpeg here has no
+libx264 or drawtext, so every caption is drawn with PIL).
+"""
+
+import argparse
+import hashlib
+import json
+import re
+import sys
+import textwrap
+import urllib.request
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from assemble import BG, DIM, FPS, H, INK, W, ff, font # noqa: E402
+from PIL import Image, ImageDraw # noqa: E402
+
+ACCENT = (226, 178, 92) # warm brass, the AnyScene stamp colour on dark
+ENC = ["-c:v", "h264_nvenc", "-preset", "p6", "-cq", "19", "-pix_fmt", "yuv420p", "-r", str(FPS)]
+SCORE_KEYS = ["layout", "props", "screens_signage", "materials", "lighting", "atmosphere", "plausibility", "composition"]
+SCORE_LABELS = ["Layout", "Props", "Screens/signs", "Materials", "Lighting", "Atmosphere", "Plausibility", "Composition"]
+
+
+def clock(s):
+ s = int(s)
+ return f"{s // 3600}:{s % 3600 // 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60}:{s % 60:02d}"
+
+
+def fetch(url, cache):
+ cache.mkdir(parents=True, exist_ok=True)
+ path = cache / (hashlib.md5(url.encode()).hexdigest()[:12] + Path(url).suffix)
+ if not path.exists():
+ urllib.request.urlretrieve(url, path)
+ return path
+
+
+def fit(img, box_w, box_h):
+ img = img.convert("RGB")
+ s = min(box_w / img.width, box_h / img.height)
+ return img.resize((max(1, int(img.width * s)), max(1, int(img.height * s))), Image.LANCZOS)
+
+
+def card(out, image=None, chapter="", sub="", when=None, scores=None, big=None):
+ """One 1920x1080 frame: the image fitted in the middle, a chapter line on top, the agent's note under it."""
+ c = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(c)
+ top, bottom = 190, 60
+ if image is not None:
+ im = fit(Image.open(image), W - 120, H - top - bottom - (0 if not scores else 0))
+ if scores:
+ im = fit(Image.open(image), W - 120 - 520, H - top - bottom)
+ x = 60 if scores else (W - im.width) // 2
+ c.paste(im, (x, top + (H - top - bottom - im.height) // 2))
+ if chapter:
+ d.text((60, 46), chapter.upper(), font=font("bahnschrift.ttf", 44), fill=ACCENT)
+ if when is not None:
+ d.text((W - 60, 52), f"T+{clock(when)}", font=font("consola.ttf", 34), fill=DIM, anchor="ra")
+ if sub:
+ lines = textwrap.wrap(sub, 120)[:3]
+ for i, ln in enumerate(lines):
+ d.text((60, 100 + i * 28), ln, font=font("segoeui.ttf", 23), fill=INK)
+ if scores:
+ x0, y0 = W - 60 - 460, top + 20
+ d.text((x0, y0), "CRITIC SCORES", font=font("bahnschrift.ttf", 30), fill=DIM)
+ for i, (k, lab) in enumerate(zip(SCORE_KEYS, SCORE_LABELS)):
+ v = scores.get(k, 0)
+ y = y0 + 60 + i * 64
+ d.text((x0, y), lab, font=font("segoeui.ttf", 26), fill=INK)
+ d.text((x0 + 460, y), str(v), font=font("consolab.ttf", 30), fill=ACCENT if v >= 6 else (214, 96, 80), anchor="ra")
+ d.rectangle((x0, y + 38, x0 + 460, y + 46), fill=(40, 38, 35))
+ d.rectangle((x0, y + 38, x0 + int(460 * v / 10), y + 46), fill=ACCENT if v >= 6 else (214, 96, 80))
+ d.line((x0 + int(460 * 0.6), y + 34, x0 + int(460 * 0.6), y + 50), fill=DIM, width=2)
+ if big:
+ f = font("bahnschrift.ttf", 84)
+ for i, ln in enumerate(big):
+ d.text((W // 2, H // 2 - 70 * (len(big) - 1) // 2 + i * 90 - 40), ln, font=f if i == 0 else font("segoeui.ttf", 40),
+ fill=INK if i == 0 else DIM, anchor="mm")
+ c.save(out)
+ return out
+
+
+def slideshow(cards, out):
+ """cards: [(png, seconds)] -> mp4 (hard cuts; the cards already carry their own titles)."""
+ lst = out.with_suffix(".txt")
+ with open(lst, "w", encoding="utf-8") as f:
+ for png, s in cards:
+ f.write(f"file '{Path(png).as_posix()}'\nduration {s:.3f}\n")
+ f.write(f"file '{Path(cards[-1][0]).as_posix()}'\n")
+ ff("-f", "concat", "-safe", "0", "-i", lst, "-vf", f"fps={FPS},format=yuv420p", *ENC, "-an", out)
+ return out
+
+
+def clip_with_caption(src, cap_png, out, seconds=None):
+ """A walkthrough clip letterboxed to 1920x1080 with a caption band drawn on top."""
+ trim = ["-t", str(seconds)] if seconds else []
+ ff("-i", src, "-i", cap_png, *trim, "-filter_complex",
+ f"[0]scale={W}:-2:flags=lanczos,pad={W}:{H}:0:(oh-ih)/2:color=black,fps={FPS}[v];[v][1]overlay=0:0",
+ *ENC, "-an", out)
+ return out
+
+
+def caption_band(out, chapter, sub=""):
+ c = Image.new("RGBA", (W, H), (0, 0, 0, 0))
+ d = ImageDraw.Draw(c)
+ d.rectangle((0, 0, W, 130), fill=(14, 13, 12, 200))
+ d.text((60, 30), chapter.upper(), font=font("bahnschrift.ttf", 44), fill=ACCENT)
+ if sub:
+ d.text((60, 86), sub, font=font("segoeui.ttf", 24), fill=INK)
+ c.save(out)
+ return out
+
+
+def concat(parts, out):
+ lst = out.with_suffix(".txt")
+ lst.write_text("".join(f"file '{Path(p).as_posix()}'\n" for p in parts), encoding="utf-8")
+ ff("-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", out)
+ return out
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("run")
+ p.add_argument("--reference", required=True)
+ p.add_argument("--clips", nargs="*", default=[])
+ p.add_argument("--name", default="")
+ p.add_argument("--out")
+ a = p.parse_args()
+ run = Path(a.run)
+ out = Path(a.out or run / "reel")
+ tmp = out / "cards"
+ tmp.mkdir(parents=True, exist_ok=True)
+ cache = out / "img"
+
+ events = [json.loads(l) for l in open(run / "events.jsonl", encoding="utf-8")]
+ build = json.loads((run / "build.json").read_text(encoding="utf-8")) if (run / "build.json").exists() else {}
+ seen, imgs = set(), []
+ for e in events:
+ u = e.get("preview_url")
+ if u and u not in seen:
+ seen.add(u)
+ imgs.append(e)
+ first_critic = next((e["t"] for e in imgs if e["stage"] == "critique"), 1e9)
+ end_t = max(e["t"] for e in events)
+ stills = build.get("stills", [])
+ previews = build.get("previews", [])
+ n = 0
+
+ def nxt():
+ nonlocal n
+ n += 1
+ return tmp / f"{n:03d}.png"
+
+ # ------------------------------------------------------------------ breakdown
+ cards = [(card(nxt(), big=[a.name or "One image in", "a 3D set out, built by an agent, nobody steering"]), 2.2),
+ (card(nxt(), a.reference, "Input", "One reference image. No prompt, no floor plan, no human in the loop."), 2.6)]
+ plan = next((e for e in imgs if e["stage"] == "plan"), None)
+ if plan:
+ cards.append((card(nxt(), fetch(plan["preview_url"], cache), "01 Plan", plan["message"], plan["t"]), 3.2))
+ sheets = [e for e in imgs if e["t"] < first_critic and re.search(r"ref_sheet|refsheet|imgsheet|sheet\.png", e.get("message", ""))]
+ for e in sheets[:2]:
+ cards.append((card(nxt(), fetch(e["preview_url"], cache), "02 Prop references",
+ "Every prop gets a product-shot reference first, checked for real brands.", e["t"]), 2.0))
+ compares = [e for e in imgs if e["t"] < first_critic and re.search(r"compar|pick|tripo|meshy", e.get("message", ""), re.I)]
+ for e in compares[:6]:
+ cards.append((card(nxt(), fetch(e["preview_url"], cache), "03 3D models",
+ "Tripo and Meshy both build every prop; the agent compares them under the same light and picks.",
+ e["t"]), 0.9))
+ shown = {plan["preview_url"]} if plan else set()
+ tests, paths = [], set()
+ for e in imgs: # each file once (the agent re-opens the same render), and never the plan again
+ key = e.get("message", "")
+ if (e["t"] < first_critic and e not in sheets and e not in compares and e["preview_url"] not in shown
+ and "floor_plan" not in key and key not in paths
+ and e["stage"] in ("log", "layout", "props", "dressing", "lighting", "screens", "materials")):
+ paths.add(key)
+ tests.append(e)
+ step = max(1, len(tests) // 28)
+ for e in tests[::step]:
+ cards.append((card(nxt(), fetch(e["preview_url"], cache), "04 Building it",
+ "Every test render the agent looked at, in order. It writes a script to fix whatever it sees.",
+ e["t"]), 0.45))
+ rounds = [e for e in events if e["stage"] == "critique" and e.get("critique")]
+ for e in rounds:
+ c = e["critique"]
+ img = e.get("preview_url")
+ fix = (c.get("fixes") or [""])[0]
+ cards.append((card(nxt(), fetch(img, cache) if img else None, f"05 Critic, round {c['round']}",
+ ("PASS. " if c.get("passed") else "Not yet. Top fix: ") + fix, e["t"], scores=c["scores"]), 1.6))
+ for i, u in enumerate(stills):
+ cards.append((card(nxt(), fetch(u, cache), "06 Finals", f"Graded still {i + 1} of {len(stills)}", end_t), 1.8))
+ for pv in previews[:16]:
+ cards.append((card(nxt(), fetch(pv["url"], cache), "07 Scouting previews",
+ pv["name"].replace("_", " "), end_t), 0.8))
+ parts = [slideshow(cards, out / "breakdown_a.mp4")]
+ for k, clip in enumerate(a.clips):
+ cap = caption_band(tmp / f"clipcap_{k}.png", "08 Walkthrough",
+ "Shot by the shots agent on the finished set, rendered on the render farm.")
+ parts.append(clip_with_caption(clip, cap, out / f"breakdown_clip_{k}.mp4"))
+ total = clock(end_t)
+ parts.append(slideshow([(card(nxt(), big=[f"{total} start to finish", "AnyScene"]), 2.5)], out / "breakdown_end.mp4"))
+ concat(parts, out / "breakdown.mp4")
+
+ # ------------------------------------------------------------------ hero
+ hero_still = stills[0] if stills else (rounds[-1].get("preview_url") if rounds else None)
+ if hero_still:
+ ref = card(tmp / "hero_ref.png", a.reference, "Reference", "")
+ fin = card(tmp / "hero_final.png", fetch(hero_still, cache), "AnyScene · 3D set", "")
+ ff("-loop", "1", "-t", "2.6", "-i", ref, "-loop", "1", "-t", "3.4", "-i", fin, "-filter_complex",
+ f"[0]fps={FPS},format=yuv420p[a];[1]fps={FPS},format=yuv420p[b];[a][b]xfade=transition=wiperight:duration=0.8:offset=1.8",
+ *ENC, "-an", out / "hero_a.mp4")
+ hparts = [out / "hero_a.mp4"]
+ for k, clip in enumerate(a.clips):
+ cap = caption_band(tmp / f"herocap_{k}.png", "Walkthrough", "")
+ hparts.append(clip_with_caption(clip, cap, out / f"hero_clip_{k}.mp4"))
+ hparts.append(slideshow([(card(tmp / "hero_end.png", big=["Reference in. 3D set out.", f"{total}, fully automated · AnyScene"]), 2.4)],
+ out / "hero_end.mp4"))
+ concat(hparts, out / "hero.mp4")
+ print("wrote", out / "breakdown.mp4", "and", out / "hero.mp4", f"({len(cards)} breakdown cards)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/breakdown/kit_motion.py b/breakdown/kit_motion.py
new file mode 100644
index 0000000..36d49d7
--- /dev/null
+++ b/breakdown/kit_motion.py
@@ -0,0 +1,301 @@
+"""Motion renders of an AnyKit kit for the kit supercut: a lineup dolly and per-item turntables, in the same studio as
+kit/tools/present.py (neutral grey ground, soft key/fill/rim, AgX, scale bar, ground labels).
+
+ blender -b --factory-startup --python builder/blender_gpu.py --python breakdown/kit_motion.py -- \
+ --pkg <unzipped package>/out --out <dir> [--only dolly|turn] [--secs 9] [--turn-secs 4]
+ [--samples 96] [--turn-samples 48] [--frames a,b,c] [--ids a,b]
+
+Reads <pkg>/kit.json and <pkg>/items/<id>/<id>.glb (normalised: metres, bottom-centre origin, facing -Y).
+Writes <out>/dolly/####.png (1920x1080) and <out>/turn/<id>/####.png (960x540: the item sits in the central square,
+so a tile can crop it narrower). --frames renders only those frame numbers (1-based), to check a look first.
+Does not reset factory settings (that would drop the GPU device chosen by blender_gpu.py).
+"""
+
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+opt = lambda k, d: type(d)(argv[argv.index(k) + 1]) if k in argv else d
+PKG = os.path.abspath(opt("--pkg", "out"))
+OUT = os.path.abspath(opt("--out", "motion"))
+ONLY = opt("--only", "")
+SECS = opt("--secs", 9.0)
+TSECS = opt("--turn-secs", 4.0)
+SAMPLES = opt("--samples", 96)
+TSAMPLES = opt("--turn-samples", 48)
+FRAMES = [int(s) for s in opt("--frames", "").split(",") if s]
+IDS = [s for s in opt("--ids", "").split(",") if s]
+FPS = 24
+
+kit = json.load(open(os.path.join(PKG, "kit.json"), encoding="utf-8"))
+items = [it for it in kit["items"] if not IDS or it["id"] in IDS]
+
+
+def setup():
+ for o in list(bpy.data.objects):
+ bpy.data.objects.remove(o, do_unlink=True)
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ sc.cycles.device = "GPU"
+ sc.cycles.use_denoising = True
+ sc.cycles.denoiser = "OPTIX"
+ sc.cycles.use_adaptive_sampling = True
+ sc.render.use_persistent_data = True
+ sc.render.fps = FPS
+ sc.render.image_settings.file_format = "PNG"
+ sc.render.image_settings.color_mode = "RGB"
+ sc.render.image_settings.compression = 30
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "AgX - Medium High Contrast"
+ w = bpy.data.worlds.new("w")
+ sc.world = w
+ w.use_nodes = True
+ w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.36, 0.37, 0.38, 1)
+ w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.35
+ bpy.ops.mesh.primitive_plane_add(size=1)
+ g = bpy.context.object
+ g.name = "ground"
+ g.scale = (2000, 2000, 1) # far enough that its edge never shows
+ gm = bpy.data.materials.new("ground")
+ gm.use_nodes = True
+ p = gm.node_tree.nodes["Principled BSDF"]
+ p.inputs["Base Color"].default_value = (0.42, 0.42, 0.42, 1)
+ p.inputs["Roughness"].default_value = 0.85
+ g.data.materials.append(gm)
+ return sc
+
+
+def light(name, loc, target, energy, size):
+ d = bpy.data.lights.new(name, "AREA")
+ d.energy, d.size = energy, size
+ o = bpy.data.objects.new(name, d)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = loc
+ o.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
+ return o
+
+
+def studio(centre, radius):
+ c, s = Vector(centre), max(radius, 0.2)
+ light("key", c + Vector((1.6, -2.2, 2.4)) * s, c, 220 * s * s, 1.6 * s)
+ light("fill", c + Vector((-2.6, -1.4, 1.2)) * s, c, 60 * s * s, 2.5 * s)
+ light("rim", c + Vector((-0.8, 2.6, 2.2)) * s, c, 140 * s * s, 1.4 * s)
+
+
+def load(item):
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=os.path.join(PKG, "items", item["id"], f"{item['id']}.glb"))
+ new = [o for o in bpy.data.objects if o not in before]
+ root = bpy.data.objects.new(item["id"], None)
+ bpy.context.scene.collection.objects.link(root)
+ for o in new:
+ if o.parent is None:
+ o.parent = root
+ bpy.context.view_layer.update()
+ return root, [o for o in new if o.type == "MESH"]
+
+
+def bounds(objs):
+ pts = [o.matrix_world @ Vector(c) for o in objs for c in o.bound_box]
+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
+ return lo, hi
+
+
+def camera(lens):
+ d = bpy.data.cameras.new("cam")
+ d.lens = lens
+ o = bpy.data.objects.new("cam", d)
+ bpy.context.scene.collection.objects.link(o)
+ bpy.context.scene.camera = o
+ return o
+
+
+def place(cam, centre, az, el, dist):
+ a, e = math.radians(az), math.radians(el)
+ cam.location = Vector(centre) + Vector((math.sin(a) * math.cos(e), -math.cos(a) * math.cos(e), math.sin(e))) * dist
+ cam.rotation_euler = (Vector(centre) - cam.location).to_track_quat("-Z", "Y").to_euler()
+
+
+def mat(name, rgb):
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ p = m.node_tree.nodes["Principled BSDF"]
+ p.inputs["Base Color"].default_value = (*rgb, 1)
+ p.inputs["Roughness"].default_value = 0.6
+ return m
+
+
+def text(body, loc, size, m):
+ c = bpy.data.curves.new("t", "FONT")
+ c.body, c.size, c.align_x = body, size, "CENTER"
+ o = bpy.data.objects.new("label_" + body[:20], c)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = loc
+ o.rotation_euler = (math.pi / 2, 0, 0)
+ o.data.materials.append(m)
+ return o
+
+
+def render_frames(sc, folder, n, per_frame):
+ """Render frames 1..n (or just FRAMES) into folder/####.png, calling per_frame(t in 0..1) first."""
+ os.makedirs(folder, exist_ok=True)
+ for f in FRAMES or range(1, n + 1):
+ if f > n:
+ continue
+ path = os.path.join(folder, f"{f:04d}.png")
+ if os.path.exists(path) and not FRAMES:
+ continue # resumable
+ per_frame((f - 1) / max(n - 1, 1))
+ sc.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+
+
+def smoothstep(a):
+ a = min(max(a, 0.0), 1.0)
+ return a * a * (3 - 2 * a)
+
+
+def dolly():
+ """The lineup laid out exactly like present.py, then a slow lateral move along it. The framed width follows the
+ tallest item near the camera (smoothed), so a 13 cm sign is not lost next to a 1.4 m peel."""
+ sc = setup()
+ sc.cycles.samples = SAMPLES
+ loaded = [(it, *load(it)) for it in items]
+ heights = [bounds(m)[1].z for _, _, m in loaded]
+ gap = max(0.06, 0.12 * max(heights))
+ x, depth = 0.0, 0.0
+ for it, root, meshes in loaded:
+ lo, hi = bounds(meshes)
+ root.location.x = x + (hi.x - lo.x) / 2 - (lo.x + hi.x) / 2
+ x += hi.x - lo.x + gap
+ depth = max(depth, hi.y - lo.y)
+ bpy.context.view_layer.update()
+ allm = [o for _, _, m in loaded for o in m]
+ lo, hi = bounds(allm)
+ total = hi.x - lo.x
+ nice = min((0.05, 0.1, 0.2, 0.25, 0.5, 1.0, 2.0, 5.0), key=lambda v: abs(v - total / 5))
+ step = nice / 10 if nice <= 0.25 else 0.1
+ dark, light_m, ink = mat("bar_dark", (0.03, 0.03, 0.03)), mat("bar_light", (0.85, 0.85, 0.85)), mat("ink", (0.04, 0.04, 0.04))
+ by = lo.y - max(0.06, depth * 0.35)
+ th = max(0.004, nice / 40)
+ for i in range(round(nice / step)):
+ bpy.ops.mesh.primitive_cube_add(size=1, location=(lo.x + step * (i + 0.5), by, 0.001))
+ b = bpy.context.object
+ b.scale = (step, th * 2, 0.002)
+ b.data.materials.append(dark if i % 2 == 0 else light_m)
+ text(f"{nice * 100:.0f} cm" if nice < 1 else f"{nice:g} m", (lo.x + nice / 2, by - th, th * 1.5), th * 4, ink)
+ lsize = max(0.01, min(0.04, gap * 0.22))
+ spans = []
+ for it, root, meshes in loaded:
+ l2, h2 = bounds(meshes)
+ text(it.get("label", it["id"])[:28], ((l2.x + h2.x) / 2, l2.y - lsize * 1.5, 0.003), lsize, ink)
+ spans.append((l2.x, h2.x, h2.z))
+ bpy.context.view_layer.update()
+ studio(Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, hi.z * 0.42)), max(total, hi.z) * 0.6)
+
+ sc.render.resolution_x, sc.render.resolution_y = 1920, 1080
+ cam = camera(50)
+ fov = cam.data.angle # horizontal for a landscape frame
+ aspect = 16 / 9
+ base = max(total / 4.5, 0.45) # narrowest framed width: about a fifth of the row
+ n = int(round(SECS * FPS))
+ def need(cx):
+ """Framed width at cx: wide enough that every item in the central 90% of that same frame fits in height
+ (a fixed point: widening can bring a taller item into view, so iterate; it only grows)."""
+ w = base
+ for _ in range(20):
+ hmax = max([z for a, b, z in spans if b > cx - 0.45 * w and a < cx + 0.45 * w] or [0.05])
+ w2 = max(base, hmax * 1.6 * aspect)
+ if w2 <= w + 1e-6:
+ break
+ w = w2
+ return w
+
+ # ends: first item's left edge / last item's right edge about 9% in from the frame edge (fixed points again)
+ xa, xb = lo.x + 0.41 * base, hi.x - 0.41 * base
+ for _ in range(20):
+ xa, xb = lo.x + 0.41 * need(xa), hi.x - 0.41 * need(xb)
+ if xb < xa:
+ xa = xb = (lo.x + hi.x) / 2
+ xs, raw = [], []
+ for i in range(n):
+ u = i / max(n - 1, 1)
+ cx = xa + (xb - xa) * (0.5 * u + 0.5 * smoothstep(u)) # near-constant speed, soft start and stop
+ xs.append(cx)
+ raw.append(need(cx))
+ # dilate (never frame tighter than an item needs) then a wide gaussian, so the zoom is a gentle push/pull
+ rad = int(FPS * 0.8)
+ dil = [max(raw[max(0, i - rad):i + rad + 1]) for i in range(n)]
+ sig = FPS * 1.0
+ ws = []
+ for i in range(n):
+ acc = wsum = 0.0
+ for j in range(n):
+ k = math.exp(-((i - j) / sig) ** 2 / 2)
+ acc += dil[j] * k
+ wsum += k
+ ws.append(max(acc / wsum, raw[i]))
+
+ def pose(t):
+ i = min(int(round(t * (n - 1))), n - 1)
+ w = ws[i]
+ vh = w / aspect
+ dist = (w / 2) / math.tan(fov / 2) # w is the width seen at the row, so ws and the path ends agree
+ centre = Vector((xs[i], (lo.y + hi.y) / 2 - 0.1 * depth, vh * 0.26))
+ place(cam, centre, 0, 13, dist)
+
+ render_frames(sc, os.path.join(OUT, "dolly"), n, pose)
+
+
+def turntables():
+ sc = setup()
+ sc.cycles.samples = TSAMPLES
+ sc.render.resolution_x, sc.render.resolution_y = 960, 540
+ cam = camera(60)
+ n = int(round(TSECS * FPS))
+ loaded = [(it, *load(it)) for it in items]
+ for it, root, meshes in loaded:
+ root.hide_render = True
+ for o in meshes:
+ o.hide_render = True
+ for it, root, meshes in loaded:
+ for o in meshes:
+ o.hide_render = False
+ root.rotation_euler = (0, 0, 0)
+ bpy.context.view_layer.update()
+ lo, hi = bounds(meshes)
+ rxy = max(math.hypot(p.x - root.location.x, p.y - root.location.y)
+ for o in meshes for p in (o.matrix_world @ Vector(c) for c in o.bound_box))
+ h = hi.z - lo.z
+ centre = Vector((root.location.x, root.location.y, lo.z + h / 2))
+ radius = math.hypot(rxy, h / 2)
+ for o in [o for o in bpy.data.objects if o.type == "LIGHT"]:
+ bpy.data.objects.remove(o, do_unlink=True)
+ studio(centre, radius * 1.4)
+ vfov = 2 * math.atan(math.tan(cam.data.angle / 2) * 9 / 16)
+ # fit the spin's bounding cylinder in the frame height: half height + the depth swing seen from 18 degrees
+ e = math.radians(20)
+ half = (h / 2) * math.cos(e) + rxy * math.sin(e)
+ fit_r = max(half, rxy) # rxy: keep the width inside the central 540x540 square too
+ dist = fit_r / math.tan(vfov / 2) * 1.05 + rxy * 0.3
+ place(cam, centre, -30, 20, dist)
+
+ def spin(t, root=root):
+ root.rotation_euler = (0, 0, math.radians(360 * t * (n - 1) / n))
+
+ render_frames(sc, os.path.join(OUT, "turn", it["id"]), n, spin)
+ for o in meshes:
+ o.hide_render = True
+ root.rotation_euler = (0, 0, 0)
+
+
+if ONLY in ("", "dolly"):
+ dolly()
+if ONLY in ("", "turn"):
+ turntables()
diff --git a/breakdown/kit_supercut.py b/breakdown/kit_supercut.py
new file mode 100644
index 0000000..a49e283
--- /dev/null
+++ b/breakdown/kit_supercut.py
@@ -0,0 +1,329 @@
+"""AnyKit supercut: five AI-built prop kits in one ~110 s cut, crossfaded, 1920x1080 @ 24 fps.
+
+ uv run --python 3.13 --with pillow python -I breakdown/kit_supercut.py [--check]
+
+Order: open (the five style references -> each wipes to its kit's lineup dolly) -> for each kit a name card, its lineup
+dolly, then a grid of six of its turntables (KITS[...]["grid"]) -> end card.
+
+Footage is rendered by breakdown/kit_motion.py into ANYSCENE_RUNS/anykit/motion/run<n>/ (dolly/####.png and
+turn/<id>/####.png); item order comes from the kit's kit.json next to it (motion/pkg<n>/out/kit.json).
+ ANYSCENE_RUNS folder holding the endpoint runs (default ../anyscene-runs)
+ FFMPEG an ffmpeg with h264_nvenc (default: CapCut's bundled ffmpeg if found, else ffmpeg)
+Cards and captions are drawn with Pillow because that ffmpeg has no drawtext.
+
+Writes breakdown/kit_supercut/anykit_supercut.mp4 (full quality), plus parts.json and, with --check, a contact sheet
+and a black/frozen-frame report.
+"""
+
+import glob
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+if "FFMPEG" not in os.environ:
+ capcut = sorted(glob.glob(os.path.expandvars(r"%LOCALAPPDATA%/CapCut/Apps/*/ffmpeg.exe")))
+ os.environ["FFMPEG"] = capcut[-1] if capcut else "ffmpeg"
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from assemble import BG, DIM, FF, FPS, H, INK, W, duration, ff, font # noqa: E402
+from PIL import Image, ImageDraw, ImageFilter # noqa: E402
+
+RUNS = Path(os.environ.get("ANYSCENE_RUNS", ROOT.parent / "anyscene-runs"))
+MOTION = RUNS / "anykit/motion"
+OUT = ROOT / "breakdown/kit_supercut"
+XF = 0.6 # crossfade, seconds
+CARD = 2.6 # name card length, including both crossfades
+GRID = 8.0 # the turntable grid: two full 360s of every item in it (the 4 s turntables loop seamlessly)
+SEG_ENC = ["-an", "-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "14", "-b:v", "0", "-pix_fmt", "yuv420p"]
+BRASS = (226, 178, 92)
+
+KITS = [ # grid: the six items in the kit's turntable grid, in tile order
+ dict(n=1, key="orbital", title="Orbital Analysis Desk", place="1970s mission control", accent=(132, 212, 150),
+ ref=ROOT / "refs/mission-control-1970s/concept_wide_0.png",
+ grid=["line_printer", "crt_monitor", "desk_lamp", "desk_phone", "cigarette_pack", "ashtray"]),
+ dict(n=2, key="roussel", title="Maison Roussel Counter", place="Paris bakery", accent=BRASS,
+ ref=RUNS / "refs/bakery_0.png",
+ grid=["cash_register", "baguette_basket", "brass_scale", "flour_sack", "croissant_tray", "fruit_tart"]),
+ dict(n=3, key="ramen", title="Hoshimaru Ramen-ya", place="Tokyo ramen counter", accent=(232, 150, 92),
+ ref=ROOT.parent / "blender-scene/refs/ramen/concept_wide_sunburst_0.png",
+ grid=["bar_stool", "red_lantern", "stock_pot", "gas_burner", "condiment_caddy", "ramen_bowl"]),
+ dict(n=4, key="daipaidong", title="Dai Pai Dong Street Kitchen", place="Hong Kong", accent=(228, 98, 86),
+ ref=ROOT / "refs/hk-dai-pai-dong/concept_wide_0.png",
+ grid=["gas_cylinder", "plastic_stool", "plastic_crate", "enamel_teapot", "wok", "soy_bottle"]),
+ dict(n=5, key="repair", title="Sorano Night Repair Bench", place="Tokyo", accent=(122, 200, 168),
+ ref=ROOT.parent / "blender-scene/refs/repair/concept_wide_sunburst_0.png",
+ grid=["oscilloscope", "radio_cassette", "vcr_open", "soldering_station", "tool_cup", "solder_spool"]),
+]
+for k in KITS: # a kit may name itself: anykit/motion/run<n>/title.txt overrides the default title
+ t = MOTION / f"run{k['n']}/title.txt"
+ if t.exists():
+ k["title"] = t.read_text(encoding="utf-8").strip()
+
+
+def dolly_files(k):
+ return sorted((MOTION / f"run{k['n']}/dolly").glob("*.png"))
+
+
+def item_ids(k):
+ kit = json.loads((MOTION / f"pkg{k['n']}/out/kit.json").read_text(encoding="utf-8"))
+ return [it["id"] for it in kit["items"] if (MOTION / f"run{k['n']}/turn/{it['id']}").exists()]
+
+
+def text_centered(d, y, txt, fnt, fill):
+ d.text(((W - d.textlength(txt, font=fnt)) / 2, y), txt, font=fnt, fill=fill)
+
+
+def still_video(img, secs, out):
+ png = out.with_suffix(".png")
+ img.save(png)
+ ff("-loop", "1", "-t", f"{secs:.3f}", "-i", png, "-vf", f"fps={FPS},format=yuv420p", *SEG_ENC, out)
+ return secs
+
+
+def name_card(k, out):
+ """Number and kit name only, over the kit's own lineup, blurred and darkened."""
+ files = dolly_files(k)
+ fr = Image.open(files[len(files) // 2]).convert("RGB").resize((W, H), Image.LANCZOS)
+ canvas = fr.filter(ImageFilter.GaussianBlur(18)).point(lambda v: int(v * 0.22))
+ d = ImageDraw.Draw(canvas)
+ num = font("bahnschrift.ttf", 30)
+ big = font("segoeuib.ttf", 80)
+ y = (H - 30 - 30 - 80) // 2
+ text_centered(d, y, f"{k['n']:02d} / {len(KITS):02d}", num, k["accent"])
+ text_centered(d, y + 60, k["title"], big, INK)
+ return still_video(canvas, CARD, out)
+
+
+def dolly_clip(k, out):
+ d = MOTION / f"run{k['n']}/dolly"
+ ff("-framerate", FPS, "-i", d / "%04d.png", "-vf", f"scale={W}:{H},setsar=1,format=yuv420p", *SEG_ENC, out)
+ return duration(out)
+
+
+def fit(img, bw, bh):
+ """Centre-crop img to bw:bh and resize."""
+ r = bw / bh
+ w, h = img.size
+ if w / h > r:
+ nw = int(h * r)
+ img = img.crop(((w - nw) // 2, 0, (w - nw) // 2 + nw, h))
+ else:
+ nh = int(w / r)
+ img = img.crop((0, (h - nh) // 2, w, (h - nh) // 2 + nh))
+ return img.resize((bw, bh), Image.LANCZOS)
+
+
+def grid_clip(k, ids, out):
+ """Turntables spinning together: up to 6 as 3 over 2 (tiles cropped to the central square-ish part, where
+ kit_motion keeps the item), 4 as 2 over 2 at full 16:9. Rendered frame by frame and piped to ffmpeg."""
+ gap, vpad = 10, 56
+ if len(ids) > 4:
+ cols = 3
+ tw = (W - 2 * 40 - gap * (cols - 1)) // cols
+ th = (H - 2 * vpad - gap) // 2
+ else:
+ cols = 2
+ th = (H - 2 * vpad - gap) // 2
+ tw = th * 16 // 9
+ rows = [ids[i:i + cols] for i in range(0, len(ids), cols)]
+ slots = []
+ for r, row in enumerate(rows):
+ x0 = (W - (len(row) * tw + (len(row) - 1) * gap)) // 2
+ y0 = (H - (len(rows) * th + (len(rows) - 1) * gap)) // 2
+ for c, iid in enumerate(row):
+ slots.append((iid, x0 + c * (tw + gap), y0 + r * (th + gap)))
+ seqs = {iid: sorted((MOTION / f"run{k['n']}/turn/{iid}").glob("*.png")) for iid in ids}
+ n = int(round(GRID * FPS))
+ frames = OUT / f"_grid_{k['key']}_{len(ids)}_{ids[0]}"
+ frames.mkdir(exist_ok=True)
+ for f in range(n):
+ png = frames / f"{f:04d}.png"
+ if png.exists():
+ continue
+ fr = Image.new("RGB", (W, H), BG)
+ for iid, x, y in slots:
+ seq = seqs[iid]
+ fr.paste(fit(Image.open(seq[f % len(seq)]).convert("RGB"), tw, th), (x, y))
+ fr.save(png, compress_level=1)
+ ff("-framerate", FPS, "-i", frames / "%04d.png", "-vf", "format=yuv420p", *SEG_ENC, out)
+ return n / FPS
+
+
+def open_frames(k, w, h, secs):
+ """The kit's lineup dolly for its mosaic tile, as a list of PIL frames at FPS. A dolly shorter than secs is
+ retimed (nearest frame, slightly slower) to span it, so the tile never freezes on its last frame."""
+ files = dolly_files(k)
+ n = int(secs * FPS)
+ if len(files) < n:
+ files = [files[min(len(files) - 1, int(i * len(files) / n))] for i in range(n)]
+ cache = {}
+ return [cache.setdefault(f, fit(Image.open(f).convert("RGB"), w, h)) for f in files[:n]]
+
+
+def cold_open(out, secs=12.4):
+ """"ANY REFERENCE IN": the five style references as a mosaic (3 over 2, each captioned with its kit), tiles fading
+ in one by one. Then each tile wipes left to right to its kit's lineup dolly, already playing, and the header turns
+ to "PROP KITS OUT". Text stays above and below the mosaic, never over the images."""
+ gap, top, bottom, side, band = 14, 96, 40, 40, 46
+ row_h = (H - top - bottom - gap - 2 * band) // 2
+ rows = [KITS[:3], KITS[3:]]
+ tiles = [] # (kit, x, y, w, h)
+ for r, row in enumerate(rows):
+ w = (W - 2 * side - gap * (len(row) - 1)) // len(row)
+ for c, k in enumerate(row):
+ tiles.append((k, side + c * (w + gap), top + r * (row_h + band + gap), w, row_h))
+ refs = [fit(Image.open(k["ref"]).convert("RGB"), w, h) for k, _, _, w, h in tiles]
+ wipe0, wipe_step, wipe_len = 2.7, 0.22, 0.75
+ play = secs - wipe0 + 0.2
+ sets = [open_frames(k, w, h, play) for k, _, _, w, h in tiles]
+ head = font("bahnschrift.ttf", 40)
+ n = int(round(secs * FPS))
+ frames = OUT / "_open_frames"
+ frames.mkdir(exist_ok=True)
+
+ def ease(a):
+ a = min(max(a, 0.0), 1.0)
+ return a * a * (3 - 2 * a)
+
+ def mix(c0, c1, a):
+ return tuple(int(c0[j] + (c1[j] - c0[j]) * a) for j in range(3))
+
+ for f in range(n):
+ t = f / FPS
+ fr = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(fr)
+ a_in = ease((t - 0.1) / 0.5) * (1 - ease((t - wipe0) / 0.5))
+ a_out = ease((t - wipe0 - 0.3) / 0.6)
+ if a_in > 0:
+ text_centered(d, 30, "ANY REFERENCE IN", head, mix(BG, BRASS, a_in))
+ if a_out > 0:
+ text_centered(d, 30, "PROP KITS OUT", head, mix(BG, BRASS, a_out))
+ for i, ((k, x, y, w, h), ref, clipf) in enumerate(zip(tiles, refs, sets)):
+ a = ease((t - 0.25 - i * 0.3) / 0.55)
+ if a <= 0:
+ continue
+ tile = Image.blend(Image.new("RGB", ref.size, BG), ref, a)
+ p = ease((t - wipe0 - i * wipe_step) / wipe_len)
+ if p > 0: # the kit's lineup, already moving, slides in from the left over the reference
+ st = clipf[min(len(clipf) - 1, max(0, int((t - wipe0 - i * wipe_step) * FPS)))]
+ cut = int(w * p)
+ tile.paste(st.crop((0, 0, cut, h)), (0, 0))
+ if 0 < cut < w:
+ ImageDraw.Draw(tile).line((cut, 0, cut, h), fill=BRASS, width=3)
+ fr.paste(tile, (x, y))
+ # caption below its own tile, never over the image
+ txt, size = f"{k['n']:02d} {k['title']}".upper(), 26
+ while size > 16 and d.textlength(txt, font=font("bahnschrift.ttf", size)) > w - 8:
+ size -= 1
+ d.text((x + 2, y + h + 10 + (26 - size) // 2), txt, font=font("bahnschrift.ttf", size),
+ fill=mix(BG, INK, a))
+ fr.save(frames / f"{f:04d}.png", compress_level=1)
+ ff("-framerate", str(FPS), "-i", frames / "%04d.png", "-vf", "format=yuv420p", *SEG_ENC, out)
+ return n / FPS
+
+
+def end_card(out, secs=4.0):
+ canvas = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(canvas)
+ text_centered(d, (H - 120) // 2, "AnyKit", font("segoeuib.ttf", 110), INK)
+ return still_video(canvas, secs, out)
+
+
+def xfade_join(parts, final):
+ inputs, chain = [], []
+ for p, _ in parts:
+ inputs += ["-i", p]
+ prev, offset = "[0:v]", parts[0][1]
+ for i in range(1, len(parts)):
+ lbl = f"[x{i}]"
+ chain.append(f"{prev}[{i}:v]xfade=transition=fade:duration={XF}:offset={offset - XF:.3f}{lbl}")
+ offset += parts[i][1] - XF
+ prev = lbl
+ chain.append(f"{prev}fade=t=in:st=0:d=0.5,fade=t=out:st={offset - 0.8:.3f}:d=0.8[vout]")
+ ff(*inputs, "-filter_complex", ";".join(chain), "-map", "[vout]", "-c:v", "h264_nvenc", "-preset", "p7", "-tune", "hq",
+ "-multipass", "fullres", "-rc", "vbr", "-b:v", "30M", "-maxrate", "45M", "-bufsize", "60M", "-pix_fmt", "yuv420p",
+ "-r", str(FPS), "-movflags", "+faststart", final)
+
+
+def check(final, parts):
+ """Contact sheet (frames from every part) + per-part black / frozen report."""
+ starts, t = [], 0.0
+ for i, (p, d) in enumerate(parts):
+ starts.append((p.stem, t, d))
+ t += d - (XF if i < len(parts) - 1 else 0)
+ thumbs = []
+ for name, st, d in starts:
+ for frac in (0.25, 0.75) if d > 6 else (0.5,):
+ png = OUT / f"_cs_{name}_{frac}.png"
+ ff("-ss", f"{st + d * frac:.2f}", "-i", final, "-frames:v", "1", "-vf", "scale=480:-2", png)
+ thumbs.append((f"{name} @ {st + d * frac:.1f}s", Image.open(png).convert("RGB")))
+ cols = 5
+ rows = (len(thumbs) + cols - 1) // cols
+ sheet = Image.new("RGB", (cols * 480, rows * 300), (0, 0, 0))
+ d = ImageDraw.Draw(sheet)
+ for i, (lab, im) in enumerate(thumbs):
+ x, y = (i % cols) * 480, (i // cols) * 300
+ sheet.paste(im, (x, y))
+ d.text((x + 8, y + 274), lab, font=font("consola.ttf", 18), fill=(230, 230, 230))
+ sheet.save(OUT / "contact_sheet.jpg", quality=88)
+
+ raw = subprocess.run([FF, "-v", "error", "-i", str(final), "-vf", "fps=4,scale=64:36,format=gray", "-f", "rawvideo", "-"],
+ capture_output=True, check=True).stdout
+ n = len(raw) // (64 * 36)
+ means, diffs = [], []
+ for i in range(n):
+ fr = raw[i * 2304:(i + 1) * 2304]
+ means.append(sum(fr) / 2304)
+ if i:
+ prev = raw[(i - 1) * 2304:i * 2304]
+ diffs.append(sum(abs(a - b) for a, b in zip(fr, prev)) / 2304)
+ report = []
+ for name, st, d in starts:
+ a, b = int(st * 4), min(int((st + d) * 4), n)
+ seg_m = means[a:b]
+ seg_d = diffs[a:max(b - 1, a)]
+ still_run, run = 0, 0
+ for v in seg_d:
+ run = run + 1 if v < 0.15 else 0
+ still_run = max(still_run, run)
+ report.append(dict(part=name, start=round(st, 2), secs=round(d, 2), min_luma=round(min(seg_m), 1),
+ mean_luma=round(sum(seg_m) / len(seg_m), 1), longest_static_s=round(still_run / 4, 2)))
+ (OUT / "check.json").write_text(json.dumps(report, indent=1))
+ for r in report:
+ print(r)
+
+
+def main():
+ OUT.mkdir(parents=True, exist_ok=True)
+ for k in KITS:
+ if not dolly_files(k) or not item_ids(k):
+ raise SystemExit(f"missing motion for kit {k['n']}: {MOTION / ('run%d' % k['n'])}")
+ parts = []
+ p = OUT / "00_open.mp4"
+ parts.append((p, cold_open(p)))
+ for k in KITS:
+ i = k["n"]
+ p = OUT / f"{i}0_{k['key']}_card.mp4"
+ parts.append((p, name_card(k, p)))
+ p = OUT / f"{i}1_{k['key']}_dolly.mp4"
+ parts.append((p, dolly_clip(k, p)))
+ ids = item_ids(k)
+ g = [iid for iid in k.get("grid", []) if iid in ids] or ids[:6]
+ p = OUT / f"{i}2_{k['key']}_turn.mp4"
+ parts.append((p, grid_clip(k, g, p)))
+ p = OUT / "90_end.mp4"
+ parts.append((p, end_card(p)))
+
+ final = OUT / "anykit_supercut.mp4"
+ xfade_join(parts, final)
+ (OUT / "parts.json").write_text(json.dumps([[p.name, round(d, 2)] for p, d in parts], indent=1))
+ print(f"wrote {final} ({duration(final):.1f} s, {final.stat().st_size / 1e6:.1f} MB)")
+ if "--check" in sys.argv:
+ check(final, parts)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/breakdown/supercut.py b/breakdown/supercut.py
new file mode 100644
index 0000000..f294fa8
--- /dev/null
+++ b/breakdown/supercut.py
@@ -0,0 +1,357 @@
+"""Launch supercut: all five AnyScene scenes in one ~75 s cut, crossfaded, 1920x1080 @ 24 fps.
+
+ uv run --python 3.13 --with pillow python -I breakdown/supercut.py [--check]
+
+Order: cold open (the five references) -> for each scene a name card, then one long uncut walkthrough -> end card.
+The bakery section opens on the reference -> render wipe from its endpoint hero cut ("one image in").
+
+Footage lives outside this repo (renders are not committed). Point the script at it with:
+ ANYSCENE_TOKYO folder holding the Tokyo scenes' renders (default ../blender-scene/scenes)
+ ANYSCENE_RUNS folder holding the endpoint runs (default ../anyscene-runs)
+ ANYSCENE_APP the endpoint's fal app id, shown on the slack end card
+ FFMPEG an ffmpeg with h264_nvenc (default: CapCut's bundled ffmpeg if found, else ffmpeg)
+Cards and captions are drawn with Pillow because that ffmpeg has no drawtext.
+
+Writes breakdown/supercut/anyscene_supercut_twitter.mp4 (the open-source repo) and _slack.mp4 (the endpoint),
+identical but for the end card, full quality,
+plus parts.json (segment lengths) and, with --check, a contact sheet and a black/frozen-frame report.
+"""
+
+import glob
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+if "FFMPEG" not in os.environ:
+ capcut = sorted(glob.glob(os.path.expandvars(r"%LOCALAPPDATA%/CapCut/Apps/*/ffmpeg.exe")))
+ os.environ["FFMPEG"] = capcut[-1] if capcut else "ffmpeg"
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from assemble import BG, DIM, FF, FPS, H, INK, LETTERBOX, W, duration, ff, font # noqa: E402
+from PIL import Image, ImageDraw, ImageFilter # noqa: E402
+
+TOKYO = Path(os.environ.get("ANYSCENE_TOKYO", ROOT.parent / "blender-scene/scenes"))
+RUNS = Path(os.environ.get("ANYSCENE_RUNS", ROOT.parent / "anyscene-runs"))
+OUT = ROOT / "breakdown/supercut"
+XF = 0.6 # crossfade, seconds
+CARD = 2.6 # name card length, including both crossfades
+SEG_ENC = ["-an", "-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "16", "-b:v", "0", "-pix_fmt", "yuv420p"]
+BRASS = (226, 178, 92)
+
+
+def mc_clips():
+ """The hand-built mission control (Apek's pick over the endpoint build): its long uncut handheld walk down the rows."""
+ return [(ROOT / "scenes/mission-control-1970s/out/graded/walk_rows.mp4", 0.0, 16.5)]
+
+
+BAKERY_CLOSEUPS = ["croissant_macro", "tarts_low", "chalkboard", "window_letters", "overhead_vitrine"]
+
+
+def push_in(img, secs, out):
+ """A scouting preview as a slow push-in (Ken Burns), 1920x804 at 24 fps. Upscaled first so zoompan moves smoothly."""
+ if not out.exists():
+ n = int(round(secs * FPS))
+ ff("-loop", "1", "-i", img, "-vf",
+ f"scale=3840:-2:flags=lanczos,zoompan=z='1+0.07*on/{n}':d={n}:x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)'"
+ f":s=1920x804:fps={FPS}", "-frames:v", n, *SEG_ENC, out)
+ return out
+
+
+def bakery_clips():
+ """The walkthrough, the pastry push, then the scouting previews' close-ups as slow push-ins."""
+ # the walk only while it is in the shop: from 4 s it turns toward the bakehouse
+ clips = [(RUNS / "bakery_walk_2/walkthrough.mp4", 0.0, 4.0), (RUNS / "bakery_walk_2/pastry_push.mp4", 0.0, 10.0)]
+ pv = RUNS / "fal_bakery_1/pkg/out/previews"
+ OUT.mkdir(parents=True, exist_ok=True)
+ for name in BAKERY_CLOSEUPS:
+ src = pv / f"pv_{name}.png"
+ if src.exists():
+ clips.append((push_in(src, 2.6, OUT / f"_pv_{name}.mp4"), 0.0, 2.6))
+ return clips
+
+
+SCENES = [
+ dict(key="bakery", kicker="Paris · present day", title="Maison Roussel, a bakery",
+ line="One reference image in. No human input. Under two hours, start to finish.", accent=BRASS,
+ ref=RUNS / "refs/bakery_0.png",
+ clips=bakery_clips(), tile_clip=1),
+ dict(key="mc", kicker="Launch centre · 1970s", title="Mission control",
+ line="03:40 on a long shift. Green phosphor, cigarette haze, a floodlit pad outside.", accent=(132, 212, 150),
+ ref=ROOT / "refs/mission-control-1970s/concept_wide_0.png",
+ clips=mc_clips()),
+ dict(key="repair", kicker="Tokyo · present day", title="Electronics repair shop",
+ line="1 AM, rain on the glass. 86 generated props, none modelled by hand.", accent=(122, 200, 168),
+ ref=TOKYO.parent / "refs/repair/concept_wide_sunburst_0.png",
+ clips=[(TOKYO / "repair/out/shots/h2_shop_walkaround_graded.mp4", 0.4, 12.0)]),
+ dict(key="ramen", kicker="Tokyo · present day", title="Ramen shop",
+ line="Last orders. Through the noren to a counter of steam and clutter.", accent=(232, 150, 92),
+ ref=TOKYO.parent / "refs/ramen/concept_wide_sunburst_0.png",
+ clips=[(TOKYO / "ramen/out/shots/h1_door_to_counter/h1_door_to_counter_graded.mp4", 0.0, 11.0)],
+ tile_ss=5.0, tile_slow=1.65),
+ dict(key="hk", kicker="Hong Kong · present day", title="Dai pai dong",
+ line="An open-air street kitchen at 1:30 AM, just after the rain.", accent=(228, 98, 86),
+ ref=ROOT / "refs/hk-dai-pai-dong/concept_wide_0.png",
+ clips=[(ROOT / "scenes/hk-dai-pai-dong/out/shots/h1_walk_in_to_wok_graded.mp4", 7.5, 12.5)]),
+]
+
+
+def text_centered(d, y, txt, fnt, fill):
+ d.text(((W - d.textlength(txt, font=fnt)) / 2, y), txt, font=fnt, fill=fill)
+
+
+def blurred_frame(src, at, dim=0.38):
+ """One frame of src, letterboxed onto the card background, blurred and darkened."""
+ png = OUT / f"_bg_{Path(src).stem}_{at:.1f}.png"
+ ff("-ss", f"{at:.2f}", "-i", src, "-frames:v", "1", "-vf", f"scale={W}:-2", png)
+ fr = Image.open(png).convert("RGB")
+ canvas = Image.new("RGB", (W, H), BG)
+ canvas.paste(fr.filter(ImageFilter.GaussianBlur(16)).point(lambda v: int(v * dim)), (0, (H - fr.height) // 2))
+ return canvas
+
+
+def still_video(img, secs, out):
+ png = out.with_suffix(".png")
+ img.save(png)
+ ff("-loop", "1", "-t", f"{secs:.3f}", "-i", png, "-vf", f"fps={FPS},format=yuv420p", *SEG_ENC, out)
+ return secs
+
+
+def name_card(i, s, out):
+ src, ss, t = s["clips"][s.get("card_bg", 0)]
+ canvas = blurred_frame(src, ss + t * 0.5)
+ d = ImageDraw.Draw(canvas)
+ k = font("bahnschrift.ttf", 30)
+ num = f"{i + 1:02d} / 05"
+ lines = [(k, s["accent"], f"{num} {s['kicker'].upper()}"), (font("segoeuib.ttf", 80), INK, s["title"])]
+ gaps = [30, 0]
+ y = (H - 30 - 80) // 2
+ for (fnt, col, txt), g in zip(lines, gaps):
+ text_centered(d, y, txt, fnt, col)
+ y += g
+ return still_video(canvas, CARD, out)
+
+
+def clip(src, ss, t, out, hold=0.0):
+ """One stretch of footage, letterboxed to 1920x1080; hold freezes its first frame for that many extra seconds."""
+ vf = f"{LETTERBOX},fps={FPS},setsar=1,format=yuv420p"
+ if hold:
+ vf = f"tpad=start_duration={hold}:start_mode=clone,{vf}"
+ ff("-ss", f"{ss:.3f}", "-t", f"{t:.3f}", "-i", src, "-vf", vf, *SEG_ENC, out)
+ return duration(out)
+
+
+def fit(img, bw, bh):
+ """Centre-crop img to bw:bh and resize."""
+ r = bw / bh
+ w, h = img.size
+ if w / h > r:
+ nw = int(h * r)
+ img = img.crop(((w - nw) // 2, 0, (w - nw) // 2 + nw, h))
+ else:
+ nh = int(w / r)
+ img = img.crop((0, (h - nh) // 2, w, (h - nh) // 2 + nh))
+ return img.resize((bw, bh), Image.LANCZOS)
+
+
+def set_frames(sc, w, h, secs):
+ """The scene's own footage for its mosaic tile: secs of its first clip from the start, cropped to the tile
+ (letterbox bars removed), as a list of PIL frames at FPS."""
+ src, ss, t = sc["clips"][sc.get("tile_clip", 0)]
+ ss = sc.get("tile_ss", ss) # where in the clip the tile's few seconds start, if not at the clip start
+ d = OUT / f"_tile_{sc['key']}"
+ if not d.exists() or len(list(d.glob("*.png"))) < int(secs * FPS):
+ d.mkdir(exist_ok=True)
+ slow = sc.get("tile_slow", 1.0) # stretch a short good stretch to fill the mosaic (slow motion)
+ ff("-ss", ss, "-t", secs / slow, "-i", src, "-vf", f"setpts={slow}*PTS,fps={FPS}", d / "%04d.png")
+ files = sorted(d.glob("*.png"))[: int(secs * FPS)]
+ first = Image.open(files[0]).convert("RGB")
+ bbox = first.point(lambda v: 255 if v > 12 else 0).convert("L").getbbox() or (0, 0, *first.size)
+ return [fit(Image.open(f).convert("RGB").crop(bbox), w, h) for f in files]
+
+
+def cold_open(out, secs=12.4):
+ """"ANY REFERENCE IN": the five references as a mosaic (3 over 2, each captioned with its place), tiles fading in
+ one by one. Then each tile wipes left to right to its finished set, already playing, and the header turns to
+ "BLENDER SETS OUT"; all five keep playing for 8 s after the last wipe lands.
+ Text stays above and below the mosaic, never over it. Rendered frame by frame and piped to ffmpeg."""
+ gap, top, bottom, side = 14, 96, 84, 40
+ row_h = (H - top - bottom - gap) // 2
+ rows = [SCENES[:3], SCENES[3:]]
+ tiles = [] # (scene, x, y, w, h)
+ for r, row in enumerate(rows):
+ w = (W - 2 * side - gap * (len(row) - 1)) // len(row)
+ for c, sc in enumerate(row):
+ tiles.append((sc, side + c * (w + gap), top + r * (row_h + gap), w, row_h))
+ refs = [fit(Image.open(sc["ref"]).convert("RGB"), w, h) for sc, _, _, w, h in tiles]
+ wipe0, wipe_step, wipe_len = 2.7, 0.22, 0.75 # tile i wipes from wipe0 + i * wipe_step, over wipe_len
+ play = secs - wipe0 + 0.2
+ sets = [set_frames(sc, w, h, play) for sc, _, _, w, h in tiles]
+ head = font("bahnschrift.ttf", 40)
+ small = font("segoeuisl.ttf", 30)
+ n = int(round(secs * FPS))
+ frames = OUT / "_open_frames"
+ frames.mkdir(exist_ok=True)
+
+ def ease(a):
+ a = min(max(a, 0.0), 1.0)
+ return a * a * (3 - 2 * a)
+
+ def mix(c0, c1, a):
+ return tuple(int(c0[j] + (c1[j] - c0[j]) * a) for j in range(3))
+
+ def centred(d, y, txt, fnt, fill):
+ d.text(((W - d.textlength(txt, font=fnt)) / 2, y), txt, font=fnt, fill=fill)
+
+ for f in range(n):
+ t = f / FPS
+ fr = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(fr)
+ # header: ANY REFERENCE IN -> BLENDER SETS OUT, crossfading as the wipes start
+ a_in = ease((t - 0.1) / 0.5) * (1 - ease((t - wipe0) / 0.5))
+ a_out = ease((t - wipe0 - 0.3) / 0.6)
+ if a_in > 0:
+ centred(d, 30, "ANY REFERENCE IN", head, mix(BG, BRASS, a_in))
+ if a_out > 0:
+ centred(d, 30, "BLENDER SETS OUT", head, mix(BG, BRASS, a_out))
+ for i, ((sc, x, y, w, h), ref, clipf) in enumerate(zip(tiles, refs, sets)):
+ a = ease((t - 0.25 - i * 0.3) / 0.55)
+ if a <= 0:
+ continue
+ tile = Image.blend(Image.new("RGB", ref.size, BG), ref, a)
+ p = ease((t - wipe0 - i * wipe_step) / wipe_len)
+ if p > 0: # the finished set, already playing, slides in from the left over the reference
+ st = clipf[min(len(clipf) - 1, max(0, int((t - wipe0 - i * wipe_step) * FPS)))]
+ cut = int(w * p)
+ tile.paste(st.crop((0, 0, cut, h)), (0, 0))
+ if 0 < cut < w:
+ ImageDraw.Draw(tile).line((cut, 0, cut, h), fill=BRASS, width=3)
+ fr.paste(tile, (x, y))
+ band = Image.new("RGB", (w, 44), (0, 0, 0))
+ fr.paste(Image.blend(fr.crop((x, y + h - 44, x + w, y + h)), band, 0.55 * a), (x, y + h - 44))
+ txt, size = f"{sc['title']} · {sc['kicker']}".upper(), 26
+ while size > 16 and d.textlength(txt, font=font("bahnschrift.ttf", size)) > w - 32:
+ size -= 1 # keep the caption inside its own tile
+ d.text((x + 16, y + h - 37 + (26 - size) // 2), txt, font=font("bahnschrift.ttf", size), fill=mix(BG, INK, a))
+ fr.save(frames / f"{f:04d}.png", compress_level=1)
+ ff("-framerate", str(FPS), "-i", frames / "%04d.png", "-vf", "format=yuv420p", *SEG_ENC, out)
+ return n / FPS
+
+
+# The slack end card names the endpoint: ANYSCENE_APP=<your-fal-username>/anyscene (the app the builder runs as).
+ENDPOINT = (os.environ.get("ANYSCENE_APP", "").strip().strip("/") or "<your-fal-username>/anyscene") + "/ref2scene"
+END_CARDS = { # the only difference between the versions
+ "twitter": [(font("segoeuib.ttf", 96), INK, "AnyScene", 128),
+ (font("bahnschrift.ttf", 36), BRASS, "OPEN SOURCE · github.com/apekshik/anyscene", 92),
+ (font("segoeuisl.ttf", 30), DIM, "Build your own worlds with Claude Code, Blender and fal.", 0)],
+ "slack": [(font("segoeuib.ttf", 96), INK, "AnyScene", 128),
+ (font("bahnschrift.ttf", 36), BRASS, ENDPOINT, 92),
+ (font("segoeuisl.ttf", 30), DIM, "Reference images in, a production-ready 3D set out. Fully automated.", 0)],
+}
+
+
+def end_card(out, version, secs=5.0):
+ canvas = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(canvas)
+ lines = END_CARDS[version]
+ y = (H - sum(g for *_, g in lines) - 30) // 2
+ for fnt, col, txt, g in lines:
+ text_centered(d, y, txt, fnt, col)
+ y += g
+ return still_video(canvas, secs, out)
+
+
+def xfade_join(parts, final):
+ inputs, chain = [], []
+ for p, _ in parts:
+ inputs += ["-i", p]
+ prev, offset = "[0:v]", parts[0][1]
+ for i in range(1, len(parts)):
+ lbl = f"[x{i}]"
+ chain.append(f"{prev}[{i}:v]xfade=transition=fade:duration={XF}:offset={offset - XF:.3f}{lbl}")
+ offset += parts[i][1] - XF
+ prev = lbl
+ chain.append(f"{prev}fade=t=in:st=0:d=0.5,fade=t=out:st={offset - 0.8:.3f}:d=0.8[vout]")
+ ff(*inputs, "-filter_complex", ";".join(chain), "-map", "[vout]", "-c:v", "h264_nvenc", "-preset", "p7", "-tune", "hq",
+ "-multipass", "fullres", "-rc", "vbr", "-b:v", "24M", "-maxrate", "36M", "-bufsize", "48M", "-pix_fmt", "yuv420p",
+ "-r", str(FPS), "-movflags", "+faststart", final)
+
+
+def check(final, parts):
+ """Contact sheet (one frame from the middle of every part) + per-second black / frozen report."""
+ starts, t = [], 0.0
+ for i, (p, d) in enumerate(parts):
+ starts.append((p.stem, t, d))
+ t += d - (XF if i < len(parts) - 1 else 0)
+ thumbs = []
+ for name, st, d in starts:
+ for frac in (0.25, 0.75) if d > 6 else (0.5,):
+ png = OUT / f"_cs_{name}_{frac}.png"
+ ff("-ss", f"{st + d * frac:.2f}", "-i", final, "-frames:v", "1", "-vf", "scale=480:-2", png)
+ thumbs.append((f"{name} @ {st + d * frac:.1f}s", Image.open(png).convert("RGB")))
+ cols = 4
+ rows = (len(thumbs) + cols - 1) // cols
+ sheet = Image.new("RGB", (cols * 480, rows * 300), (0, 0, 0))
+ d = ImageDraw.Draw(sheet)
+ for i, (lab, im) in enumerate(thumbs):
+ x, y = (i % cols) * 480, (i // cols) * 300
+ sheet.paste(im, (x, y))
+ d.text((x + 8, y + 274), lab, font=font("consola.ttf", 18), fill=(230, 230, 230))
+ sheet.save(OUT / "contact_sheet.jpg", quality=88)
+
+ # 4 fps greyscale 64x36 samples: mean luma (black) and frame-to-frame change (frozen)
+ raw = subprocess.run([FF, "-v", "error", "-i", str(final), "-vf", "fps=4,scale=64:36,format=gray", "-f", "rawvideo", "-"],
+ capture_output=True, check=True).stdout
+ n = len(raw) // (64 * 36)
+ means, diffs = [], []
+ for i in range(n):
+ fr = raw[i * 2304:(i + 1) * 2304]
+ means.append(sum(fr) / 2304)
+ if i:
+ prev = raw[(i - 1) * 2304:i * 2304]
+ diffs.append(sum(abs(a - b) for a, b in zip(fr, prev)) / 2304)
+ report = []
+ for name, st, d in starts:
+ a, b = int(st * 4), min(int((st + d) * 4), n)
+ seg_m = means[a:b]
+ seg_d = diffs[a:max(b - 1, a)]
+ still_run, run = 0, 0
+ for v in seg_d:
+ run = run + 1 if v < 0.15 else 0
+ still_run = max(still_run, run)
+ report.append(dict(part=name, start=round(st, 2), secs=round(d, 2), min_luma=round(min(seg_m), 1),
+ mean_luma=round(sum(seg_m) / len(seg_m), 1), longest_static_s=round(still_run / 4, 2)))
+ (OUT / "check.json").write_text(json.dumps(report, indent=1))
+ for r in report:
+ print(r)
+
+
+def main():
+ OUT.mkdir(parents=True, exist_ok=True)
+ parts = []
+ p = OUT / "00_open.mp4"
+ parts.append((p, cold_open(p)))
+ for i, s in enumerate(SCENES):
+ p = OUT / f"{i + 1}0_{s['key']}_card.mp4"
+ parts.append((p, name_card(i, s, p)))
+ for j, (src, ss, t) in enumerate(s["clips"]):
+ if not Path(src).exists():
+ raise SystemExit(f"missing footage: {src}")
+ p = OUT / f"{i + 1}{j + 1}_{s['key']}_clip.mp4"
+ parts.append((p, clip(src, ss, t, p, s.get("hold", 0.0) if j == 0 else 0.0)))
+ body = list(parts)
+ for version in END_CARDS:
+ p = OUT / f"90_end_{version}.mp4"
+ parts = body + [(p, end_card(p, version))]
+ final = OUT / f"anyscene_supercut_{version}.mp4"
+ xfade_join(parts, final)
+ print(f"wrote {final} ({duration(final):.1f} s, {final.stat().st_size / 1e6:.1f} MB)")
+ (OUT / "parts.json").write_text(json.dumps([[p.name, round(d, 2)] for p, d in parts], indent=1))
+ if "--check" in sys.argv:
+ check(final, parts)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/builder/CRAFT.md b/builder/CRAFT.md
new file mode 100644
index 0000000..1ce00e1
--- /dev/null
+++ b/builder/CRAFT.md
@@ -0,0 +1,58 @@
+# How the good scenes got good
+
+Four scenes (a Tokyo repair shop, a ramen shop, a Hong Kong dai pai dong, a 1970s mission control) were built by
+agents with `SKILL.md`. What separated the good results from the first drafts was never a model or a setting. It was
+this loop, run many times:
+
+1. **Render it and look.** After every change, render the views that matter (small and fast while working) and open the
+ images. Look for what's wrong the way a production designer would.
+2. **Name the problem precisely.** "The CRT faces are flat grey", not "the screens look off".
+3. **Write the fix as code in the scene's scripts**, specific to this scene, so a rebuild keeps it. Every scene grew its
+ own `screens.py`, `fixes.py`, `dress.py`, `lights.py`, `validate.py`, written because the agent saw something wrong.
+4. **Check the fix from a view that shows it.** A wide shot hides a floating chair; a camera 30 cm off the floor shows
+ it at once.
+5. **Get an outside opinion.** The agent that built a scene stops seeing its flaws. An independent critic, comparing
+ it with the reference, catches what you've stopped seeing.
+
+## What the reference scenes had to fix by hand (expect the same)
+
+**Props**
+- Generate every prop with both 3D models and pick by looking at same-light renders, including clay. The best model
+ differs per prop (small printed items vs big hard-surface heroes).
+- Generators bake glass opaque, fake screens into the texture, invent depth for boxy things, and put real brands on
+ labels. Expect to fix all four on most scenes.
+- Scale every prop to its real-world size; set the origin bottom-centre; face it the way it will be placed.
+
+**Screens, signs, labels**
+- Screens are a hero detail. Make them emissive with real content in one invented world (one fictional organisation,
+ consistent across every screen, sign and label), at the screen's real aspect ratio. Never tile an image containing
+ text; never stretch one image across a wall of differently sized panels.
+- A CRT is curved: a flat patch on a domed tube leaves a hole. Fit the screen geometry to the tube.
+- Signage text should be exact. Use real text objects or images made for that one sign.
+
+**Placement**
+- Drop everything onto its support with raycasts from the object's lowest vertices, starting below anything overhead.
+ Re-drop after anything moves. Check for floaters, intersections and props resting on the wrong thing.
+- Density sells realism more than size. Real places are small and full.
+
+**Materials**
+- Nothing should stay untextured or flat grey. Scripted architecture needs real materials (paint, laminate, tile,
+ acoustic panels, wood) and wear: AO-driven dirt, edge wear, per-instance tint so copies don't read as copies.
+- Glass needs real transmission; mask it so that opaque parts of the same prop (labels, contents) stay opaque.
+
+**Light**
+- Light the way the real place would be lit: the practicals first (fixtures, screens, signs, windows), fills last and
+ weak. Fills that are too strong flatten the mood instantly.
+- Emissive detail (indicator lamps, button glows) should glow without becoming hundreds of light sources: turn off
+ emission sampling on dense emissive meshes. Too many weak lights make noise and denoiser blotches.
+- Re-check exposure after each new practical.
+
+**Atmosphere and finish**
+- Haze is cheap and worth it. Overlapping volumes are what get expensive.
+- Grade in post (lifted blacks, a colour split, a vignette, grain). The raw render is never the deliverable.
+- Windows need something behind them at the right scale and distance.
+
+**Process**
+- Never trust that a script that ran did the right thing. Every important claim gets an image.
+- Keep `NOTES.md`: one line per thing that cost you time.
+- Generation is slow and parallel: start it early, in bulk, and build the room, the screens and the lights while it runs.
diff --git a/builder/PROMPT.md b/builder/PROMPT.md
new file mode 100644
index 0000000..2496cfa
--- /dev/null
+++ b/builder/PROMPT.md
@@ -0,0 +1,103 @@
+# AnyScene scene builder (endpoint mode)
+
+You are running inside the AnyScene endpoint. A customer gave you reference image(s) and is paying for a scene that
+matches them at film quality. Nobody will help you: you are the whole art department, set dresser, gaffer, DP and
+colourist, and you work the way `SKILL.md` describes. Read `SKILL.md` and `CRAFT.md` first: `CRAFT.md` is what
+earlier scenes learned about getting from a first draft to a good result. You write this scene's scripts yourself.
+
+## The job
+
+- Inputs are in `input/`: `reference_*.png`, `brief.md` (the customer's prompt, may be empty) and, if the customer
+ gave one, `floor_plan.png`: their layout. When there is a floor plan, it decides the room's shape, size and where
+ things go; the references decide what things look like. Where they disagree, the floor plan wins on layout.
+- Your scene folder is `scenes/{scene}/`. Assets go where `SKILL.md` says (`refs/{scene}/`, `assets/gen/...`).
+- The reference is the guide for WHAT is in the scene and WHERE: the space and its layout, every notable object and
+ its placement, the screens and signage, the materials, the period and the level of detail and fidelity. Match those
+ closely. Anything it can't show (the reverse angle, the rest of the room), invent in the same world.
+- Light, atmosphere, grade and cameras are yours to make cinematic. Don't copy the reference's lighting: design it.
+ Use what Blender is good at when the scene calls for it (volumetric haze and light shafts, practicals that pool
+ light, rim light, smoke, depth, contrast, a considered grade), and leave it out when it doesn't. The place should
+ still feel like itself (a night control room stays a night control room unless a dial says otherwise).
+- Look at your own renders constantly (Read the PNG). A script that ran proves nothing. When you see something wrong,
+ write the code that fixes it, in this scene's scripts, so a rebuild keeps the fix.
+
+## Endpoint deliverables (put them in `out/`, relative to the workspace root)
+
+1. `out/plan.json` + `out/floor_plan.png` early (within the first ~15 minutes): room, zones, every object with
+ position/size, lights, hero cameras. Report it with stage `plan`.
+2. `out/scene.blend`: the final scene, packed (`bpy.ops.file.pack_all()`), rebuildable from `scenes/{scene}/scripts/`.
+3. `out/stills/`: the finished stills (3840×1608, 2.39:1, at least 256 spp with the denoiser, graded): 3+ hero shots of the set, your own angles. One of
+ them may echo the reference's view, but nothing needs to match it. These are what the critic judges.
+4. `out/previews/`: at the end, scout the finished set the way a DP would, covering it rather than hitting a count:
+ - every zone of the place gets at least one wide and one closer shot (a counter, a back room, a window bay, an
+ aisle each count as a zone), including at least two views of parts the reference never showed;
+ - every hero material and surface gets a close detail where its texture and wear read (brass, glass, tile, wood,
+ screens, food, fabric: whatever this place is made of);
+ - vary lens (wide 18-24 mm, normal 35-50 mm, long 85-135 mm with shallow focus) and height (eye, seated, low,
+ overhead where it makes sense).
+ That is usually 10-16 previews for a small room and 20-30 for a big or multi-room space; never fewer than 8.
+ Render them at final quality: 2560×1072, at least 128 spp with the denoiser, graded like the finals. Customers
+ judge materials and pick shots from these, so they must hold up full screen. Each one is a camera
+ in `out/shots.json`, its file is named after that camera (`out/previews/<camera name>.png`), and its `note` says
+ what it shows (zone, material, lens). Report each with stage `previews`. The customer picks from these which shots
+ become stills or walkthroughs later.
+5. `out/shots.json`: every camera above (camrig format, `camera/README.md`), named, with a short `note` each. For two
+ or three of them, also write a camera move (a push-in, a dolly, a slow handheld walk) that a walkthrough could use;
+ don't render the animation.
+6. `out/panoramas/` and `out/scene.glb`: run `endpoint/refine_blender.py` (`pano` and `glb` commands) on the final
+ blend at the end, at `--res 4096 --samples 128` (4K equirect: the 360 view is seen full screen).
+7. `out/dials.json`: the value of every dial you built to, and where it came from (below).
+8. `scenes/{scene}/NOTES.md`: what you hit, one line each.
+
+Walkthrough animations are NOT part of this job: a separate step renders them on a render farm from `shots.json`.
+
+## Dials
+
+The dials are settings you build to, not features to build. `input/dials.json` holds the ones the customer set (the
+ten are listed in `docs/ENDPOINT.md`: density, tidiness, wear, wetness, atmosphere, power: 0-1; warmth: -1 cold to
+1 warm; time_of_day, weather, look: named presets).
+- A dial the customer set is an instruction: build exactly that, even when the reference says otherwise (a night
+ reference with `time_of_day: day` is built as day).
+- A dial left out: pick the ONE value the reference shows, and build that.
+- Build one version of the scene. Don't generate alternatives for other values (other times of day, other weather,
+ other looks), and don't build switchable presets or an `apply_dials.py`. This overrides `SKILL.md` step 9b, which
+ is for a different workflow.
+- Write `out/dials.json`: for each of the ten dials, `{"value": ..., "source": "customer" | "reference"}`, plus one
+ short line on what it meant for this scene.
+
+## Speed
+
+There is no time limit: you are done when the critic passes. But the customer is waiting, so don't waste time:
+- **Generate in bulk and in the background.** The fal account has no rate limit: submit every reference image at once,
+ then every Tripo AND Meshy job at once (`node generate/fal.mjs ...` per job, launched in parallel in the
+ background, e.g. with `xargs -P 48`). About 10–20% fail transiently: retry those. Meshy takes up to ~10 min,
+ Tripo ~3–5. While they run, build the shell, the layout with stand-in boxes, the screens and the lights.
+- Pass `--face-limit` to Tripo jobs (`node generate/fal.mjs 3d ... --face-limit 150000` for hero props, 60000 for
+ small ones): unlimited, Tripo returns ~2M triangles per prop, slow to import, compare and decimate.
+- Process props as their meshes land (compare, pick, prep) rather than waiting for all of them; poll with short
+ checks, never long sleeps.
+- Keep Cycles test renders small (960 px wide, 16–32 spp) until the finals. One Blender GPU job at a time
+ (`pipeline/gpu_run.sh`). Never let a Bash call run longer than ~9 minutes; background long jobs and check on them.
+
+## Quality gate: the critic
+
+`critique` sends the reference and your stills to an independent critic that has never seen your work. It judges
+whether the set is a good production base in the reference's world (not a copy of the reference) and returns scores
+and up to five fixes that matter. Call it on your first decent stills, fix what it lists, re-render, call it again.
+You are done when it passes, or after its 8th round (the most a build gets): then finish the remaining deliverables
+and deliver. Don't argue with it; fix things. But don't chase polish it didn't ask for either: the customer's artists
+will refine the set.
+
+## Reporting
+
+The customer watches a live log. Every image you open with Read is shown to them automatically, so they see what
+you see. Call `report(stage, message, image)` at every milestone, with your best current render: `plan`, `props` (references/meshes landing, picks), `layout`, `dressing`, `screens`,
+`materials`, `lighting`, `atmosphere`, `cameras`, `critique`, `finals`, `done`. Messages are one plain sentence about
+what you just did or decided, e.g. "Picked Meshy for 31 of 44 props; Tripo for the consoles, whose knobs are real
+geometry."
+
+## Rules
+
+- Never print or log keys. They are in the environment (`FAL_KEY`).
+- No real brands anywhere: invent a fictional organisation and use it on every screen, sign and label.
+- Work only inside this workspace.
diff --git a/builder/SHOTS.md b/builder/SHOTS.md
new file mode 100644
index 0000000..8be4d45
--- /dev/null
+++ b/builder/SHOTS.md
@@ -0,0 +1,119 @@
+# AnyShot (scene to images / scene to video)
+
+You are the DP and colourist on a set that is already built. Your job is shots of it: stills, or camera moves
+(dollies, push-ins, reveals, orbits, rack focus, walkthroughs) that stay clear of the set and read as filmed.
+Read `{job}/request.json` and `camera/README.md` first.
+
+## Where the set comes from
+
+`{job}/request.json` has `source.kind`:
+
+- **`build`**: an AnyScene build; this workspace is the build's own. `out/scene.blend` is the finished set (if the
+ build is still running or was cut off, there is no `out/scene.blend` yet: use the newest working file,
+ `scenes/{scene}/scene.blend`, and don't modify it). `scenes/{scene}/scripts/` are the scripts that built it,
+ `scenes/{scene}/NOTES.md` is what the builder learned (read it), and `out/shots.json` holds its cameras (the scouting
+ previews are in `out/previews/`).
+- **`upload`**: a scene the customer uploaded, unpacked as it came in `input/scene/` (a single `.blend`, or the
+ contents of their zip: a `.blend` plus its textures, maybe more). There is no builder, no NOTES.md from one and no
+ shots.json. Before anything else:
+ 1. Find the `.blend` to shoot. If there are several, take the main one: the one with the most mesh objects or the
+ one the others link to, not a `.blend1` backup, an asset library or a single prop.
+ 2. Open it once and survey it: scenes, the active camera and any other cameras, lights, world, render engine, units,
+ the set's bounds and its floor height, and the big objects (`camera/shoot.py --list ""` prints names with
+ bounds). Note linked libraries and missing files.
+ 3. Repair texture and library paths: `bpy.ops.file.find_missing_files(directory=<input/scene>)` and
+ `bpy.ops.file.make_paths_relative()`, then check that nothing is still missing (`bpy.data.images` with no data,
+ pink materials in a quick render). Make linked libraries local if they are in the upload.
+ 4. Save a packed, self-contained copy as `{job}/scene.blend` (`bpy.ops.file.pack_all()`, then save as) and work only
+ on that copy from now on, for stills and video alike. Never modify anything in `input/scene/`.
+ 5. Write what you learned (what the set is, where its main areas are, scale, floor height, sightlines, problem
+ spots, the render settings it looks right with) to `scenes/{scene}/NOTES.md`, so the next order on this upload
+ starts from it. If it already exists, read it and add to it.
+ Keep the scene's own look: its lights, world, materials and engine settings. If it renders with Eevee and looks
+ right that way, keep Eevee unless the order asks otherwise; if it has no lights at all, add a simple, motivated
+ key and fill and say so in the result.
+
+## The job
+
+`{job}/request.json` is the customer's order:
+- `mode`: `images` (finished stills) or `video` (animated shots).
+- `prompt`: the customer's direction in their own words, for the whole order (pace, mood, length, what to show,
+ what to avoid). If `shots` is empty, plan the shot list from it yourself: pick the shots a good DP would make for
+ that brief (a typical arc is establishing wide, a walk, then close dolly reveals), name each, and list them with
+ why in `result.json`. If `shots` is given, the prompt applies to every shot; where they conflict, the shot wins.
+- `shots`: each one is a name from `out/shots.json` (use that camera or move as the start; builds only), a
+ description in words ("slow push along the pastry case, ending close on the croissants"), or both. Turn each into
+ a camera (images) or a camera move (video) in camrig format, written to `{job}/shots.json`. Name each shot by its
+ `name`, or a short `[a-z0-9_]` name of your own for a description; the customer gets files by those names.
+- `settings`: resolution, samples, fps, seconds per shot, lens, handheld (`none` | `walk` | `subtle`), `look`.
+ Anything missing: choose well for the shot.
+- `dials`: optional changes to the set for this order only (time_of_day, atmosphere, power, warmth, wetness, ...).
+ Apply them to a copy (`{job}/scene.blend`), never to `out/scene.blend` or `input/scene/`. With no dials, a build is
+ rendered from `out/scene.blend` as it is.
+- `floor_plan`: if set, `{job}/floor_plan.png` is a plan of the set (see below).
+
+### Shot language
+
+Read the descriptions the way a crew would. Map them onto camrig moves:
+- push in / dolly in / pull out / track along: `push_in` or `dolly`, 2+ keys; "slow" means about 0.2-0.4 m/s.
+- truck / crab / slide: `truck` (sideways). Crane / jib / pedestal / rise: `crane`, `pedestal`.
+- pan / tilt / whip: `pan`, `tilt` (same position, aim moves).
+- orbit / arc / circle around X: `orbit` with `center_obj`.
+- reveal: start on a foreground element or behind an occluder (a wall edge, a shelf, a doorway) and move so the
+ subject comes into view; end on the subject, framed.
+- rack focus / pull focus from A to B: `focus.mode: rack` with a hold, then the pull; use a shallow `fstop` (1.4-2.8)
+ so it reads.
+- walkthrough / follow the path / Steadicam: `path` with 4-6 keys at walking pace (0.4-0.6 m/s) and eye height
+ (1.5-1.7 m) unless told otherwise, with `handheld: {"profile": "walk"}` when it should feel carried.
+- vertigo / dolly zoom: `dolly_zoom`. Locked off / tripod: `static`.
+- lens words: wide = 18-24 mm, normal = 35-50 mm, tight / telephoto = 85-135 mm. "Low angle", "eye level", "top
+ down", "over the shoulder of X" set the camera height and aim.
+- A length in the description ("a 6 second push") wins over `settings.seconds`.
+
+## Floor plan
+
+When `{job}/floor_plan.png` exists, it is the customer's plan of the set, drawn, photographed or exported, maybe with
+a camera path drawn on it (a line or arrows, often in a bright colour), camera marks (an X, a dot, a camera icon, a
+cone of view) or labels. Use it to place the cameras:
+1. Register it to the scene: render an orthographic top view of the set (floor up to about 2 m, walls visible) and
+ match the plan's walls, doors and big furniture to it to get the plan's scale, rotation and offset. Check the
+ registration by drawing the set's walls over the plan; write the transform into `{job}/floor_plan.json`.
+2. A drawn path becomes a `path` move: sample the line into 4-8 key positions in world space, in drawing order
+ (arrowheads give the direction; otherwise start at the end nearer a door or the plan's label). Aim along the path
+ unless the order says what to look at. Eye height and pace as for a walkthrough unless told otherwise.
+3. Camera marks become camera positions; a cone or arrow gives the aim. Labels name what is where.
+4. Follow the plan's intent, not its exact pixels: a path drawn through a table goes around it, a mark inside a wall
+ moves out to clearance. Say in the result where you deviated and why.
+Report the registered plan overlay with stage `blocking`.
+
+## How
+
+1. Block every shot first: quick Eevee or low-sample Cycles frames (start, middle and end frame for a move). Look at
+ them. Check framing, focus, that the camera never passes within 0.45 m of a solid surface, and that nothing reads wrong
+ from the new angle (floating props, missing backs, holes, untextured faces). Fix the camera, or fix the set in
+ the copy, and look again. Report each blocked shot with stage `blocking` and its image.
+ Clearance is about walls, furniture and props only: leave out dust motes, particles, haze and volume boxes,
+ light shafts, decals, glass panes the move is meant to pass, and anything smaller than ~5 cm. A real camera
+ moves through dust. Check every shot in ONE Blender session (load the set once, build the BVH once, test every
+ frame of every move), not one Blender launch per attempt: the set file can be close to 1 GB.
+2. Finals:
+ - `images`: render each at full quality on this machine's GPU, grade it (ffmpeg, as `SKILL.md` step 14) and save
+ `{job}/stills/<shot>.png`. Report each with stage `finals`.
+ - `video`: first save a packed copy of the set to `{job}/scene.blend` (`bpy.ops.file.pack_all()`, every
+ texture inside; for an upload it already exists): the farm receives only that file. Then call `farm_render`
+ with the shot names. It renders every frame on a render farm (up to 100 GPUs) and puts them in
+ `{job}/frames/<shot>/frames/####.png`. Check a few frames, then grade and encode `{job}/video/<shot>.mp4` (h264,
+ the requested fps). Check the duration and frame count of every file. Report each with stage `finals` and a
+ frame from it. If `farm_render` fails (no farm configured, no farm access, farm down), render the frames on this
+ machine instead: `camera/shoot.py` with `--only <shot> --frames a-b --no-encode` in chunks short enough to stay
+ under ~9 minutes per call, into the same `{job}/frames/` layout.
+3. Write `{job}/result.json`: per shot, the camera and settings used, plus a one-line note (and, with a floor plan,
+ how the shot follows it).
+
+Work fast: the customer is waiting. Keep previews small. One Blender GPU job at a time on this machine
+(`pipeline/gpu_run.sh`). Never let one Bash call run longer than ~9 minutes; background long jobs and check on them.
+
+## Rules
+
+- Don't rebuild or restyle the set. These are shots of the scene the customer approved.
+- No real brands. Never print keys.
diff --git a/builder/app.py b/builder/app.py
new file mode 100644
index 0000000..8fd2578
--- /dev/null
+++ b/builder/app.py
@@ -0,0 +1,522 @@
+"""AnyScene scene builder as a fal Serverless app: one request = one Claude agent building the whole scene on a GPU worker.
+
+ fal deploy builder/app.py::SceneBuilderApp --app-name anyscene-builder --auth private
+ python builder/client.py <reference image path or url> [...] [--prompt "..."]
+
+POST /build reference images (+ prompt) -> stills, scene.blend, scene.glb, panoramas, package, critic rounds.
+The agent (scene_builder.py) streams ANYSCENE_STAGE lines that the fal queue relays to the caller as logs: every tool
+call, every report with its image, every critique. There is no time budget: it ends when the critic passes (or stalls).
+"""
+
+import json
+import os
+import sys
+from pathlib import PurePosixPath
+
+import fal
+from fal.container import ContainerImage
+from pydantic import BaseModel, Field
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, _HERE)
+sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "endpoint"))
+import planner # noqa: E402 (the critic's Claude client; bundled by value)
+import scene_builder # noqa: E402
+import shots # noqa: E402
+import gallery # noqa: E402 (the shared builds gallery: /builds, /build_events)
+import schema # noqa: E402,F401
+
+if os.name == "nt":
+ # Deploying from Windows: ContainerImage's context_dir default is a WindowsPath Linux can't unpickle.
+ _posix = PurePosixPath("/tmp")
+ ContainerImage.__dataclass_fields__["context_dir"].default = _posix
+ ContainerImage.context_dir = _posix
+ ContainerImage.__init__.__defaults__ = tuple(
+ _posix if isinstance(d, os.PathLike) else d for d in ContainerImage.__init__.__defaults__ or ()
+ )
+
+TOOLKIT = scene_builder.toolkit_files() # SKILL.md, CRAFT.md, prompt, shared tools: carried in the app
+BLENDER_GPU = open(os.path.join(_HERE, "blender_gpu.py"), encoding="utf-8").read()
+# `blender` on the worker: every launch loads blender_gpu.py first, so Cycles is on the GPU however it is called
+# OptiX compiles its kernels on a worker's first Cycles render (~2 min on a 5090) into a local sqlite cache. Keep that
+# cache on /data so new workers start with it, and warm it in setup() so no build waits for it.
+OPTIX_CACHE_LOCAL = "/var/tmp/OptixCache_root/optix7cache.db"
+OPTIX_CACHE_SHARED = "/data/anyscene/cache/optix7cache.db"
+WARMUP = """import bpy
+s = bpy.context.scene
+s.render.engine = "CYCLES"; s.cycles.samples = 4; s.render.resolution_x = s.render.resolution_y = 64
+for name, kind in (("glass", "BSDF_GLASS"), ("emit", "EMISSION")):
+ m = bpy.data.materials.new(name); m.use_nodes = True
+ m.node_tree.nodes.new("ShaderNodeEmission" if kind == "EMISSION" else "ShaderNodeBsdfGlass")
+bpy.ops.mesh.primitive_cube_add(size=4)
+haze = bpy.data.materials.new("haze"); haze.use_nodes = True
+out = haze.node_tree.nodes["Material Output"]
+vol = haze.node_tree.nodes.new("ShaderNodeVolumePrincipled")
+haze.node_tree.links.new(vol.outputs[0], out.inputs["Volume"])
+bpy.context.object.data.materials.append(haze)
+bpy.ops.mesh.primitive_uv_sphere_add(location=(0, 0, 0.5))
+bpy.context.object.data.materials.append(bpy.data.materials["glass"])
+bpy.ops.render.render()
+print("WARMUP done")
+"""
+
+
+def save_optix_cache():
+ """Copy this worker's OptiX cache to /data if it has grown (atomic replace; concurrent workers just race)."""
+ import shutil
+ if os.path.exists(OPTIX_CACHE_LOCAL) and (not os.path.exists(OPTIX_CACHE_SHARED)
+ or os.path.getsize(OPTIX_CACHE_LOCAL) > os.path.getsize(OPTIX_CACHE_SHARED)):
+ os.makedirs(os.path.dirname(OPTIX_CACHE_SHARED), exist_ok=True)
+ tmp = f"{OPTIX_CACHE_SHARED}.{os.getpid()}.tmp"
+ shutil.copy(OPTIX_CACHE_LOCAL, tmp)
+ os.replace(tmp, OPTIX_CACHE_SHARED)
+
+
+BLENDER_WRAPPER = '#!/bin/sh\nexec /usr/local/bin/blender.real --python /opt/anyscene/blender_gpu.py "$@"\n'
+BUILDS_DIR = "/data/anyscene/builder"
+# /ref2scene's optional `shots` go to the AnyShot app (anyshot/app.py) named by ANYSHOT_APP, a fal secret on your own
+# account (e.g. <your-fal-username>/anyshot). No default: an unset name says so instead of calling someone else's app.
+ANYSHOT_APP_ENV = "ANYSHOT_APP"
+SHOTS_WAIT_S = 7200 - 300 # wait for AnyShot until 5 min before this request's cap, then return its request_id
+BLENDER_VERSION = "5.0.1"
+
+DOCKERFILE = f"""
+FROM python:3.13-slim
+ENV NVIDIA_DRIVER_CAPABILITIES=all
+RUN apt-get update && apt-get install -y --no-install-recommends \\
+ curl ca-certificates xz-utils git procps fonts-dejavu-core libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 \\
+ libegl1 libxkbcommon0 libsm6 libice6 libx11-6 libglib2.0-0 ffmpeg nodejs ripgrep zip \\
+ && rm -rf /var/lib/apt/lists/*
+RUN curl -fsSL https://download.blender.org/release/Blender{BLENDER_VERSION[:3]}/blender-{BLENDER_VERSION}-linux-x64.tar.xz \\
+ | tar -xJ -C /opt \\
+ && ln -s /opt/blender-{BLENDER_VERSION}-linux-x64/blender /usr/local/bin/blender.real
+"""
+
+
+class Shot(BaseModel):
+ name: str = Field("", description="A camera or move from the build's shots.json (its scouting previews), or a new name.")
+ description: str = Field("", description="The shot in words, e.g. 'slow push along the pastry case, ending close on "
+ "the croissants'. With a name, it adjusts that camera.")
+
+
+class BuildShots(BaseModel):
+ """/ref2scene's optional shots order: once the build passes, the AnyShot app shoots it."""
+ mode: str = Field("images", description="images: finished stills. video: camera moves, rendered on the farm.")
+ shots: list[Shot] = Field(description="The shots to make: scouting camera names or descriptions in words.")
+ settings: dict = Field(default_factory=dict, description="As /scene2video's settings (res, fps, seconds, ...).")
+ dials: dict[str, float | str] = Field(default_factory=dict, description="Changes for these shots only.")
+
+
+class BuildRequest(BaseModel):
+ reference_image_urls: list[str] = Field(description="1-4 reference images: the look to build.")
+ prompt: str = Field("", description="Anything the images can't show.")
+ floor_plan_url: str | None = Field(None, description="Optional floor plan: a sketch, photo or drawing of the layout.")
+ fresh: bool = Field(False, description="Build again from scratch even if an identical request already has a build.")
+ effort: str = Field("medium", description="Claude effort for the builder: low, medium, high, xhigh, max.")
+ scene: str = Field("scene", description="Folder name for the scene inside the build.")
+ dials: dict[str, float | str] = Field(default_factory=dict, description=(
+ "Scene dials (docs/ENDPOINT.md); any left out are read from the reference. density, tidiness, wear, wetness, "
+ "atmosphere, power: 0-1. warmth: -1 (cold) to 1 (warm). time_of_day: dawn|day|dusk|night. "
+ "weather: clear|overcast|rain|fog|snow. look: clean|cinematic|gritty|vintage."))
+ shots: BuildShots | None = Field(None, description=(
+ "Optional: shots of the finished set. When the build passes its critic, the AnyShot app (ANYSHOT_APP) shoots "
+ "them and the stills/videos come back in shot_stills / shot_videos."))
+
+
+class BuildResponse(BaseModel):
+ build_id: str
+ stills: list[str]
+ scene_blend_url: str | None
+ scene_glb_url: str | None
+ panorama_urls: list[str]
+ previews: list[dict] = Field(default_factory=list, description="The scouting previews: name (a camera in shots.json, usable in /shots), url.")
+ package_url: str | None
+ critiques: list[dict]
+ dials: dict = Field(default_factory=dict, description="Every dial as built, with what it controls (out/dials.json).")
+ missing: list[str]
+ agent_cost_usd: float | None
+ minutes: float
+ shot_stills: list[str] = Field(default_factory=list, description="With `shots`: the stills AnyShot made.")
+ shot_videos: list[str] = Field(default_factory=list, description="With `shots`: the videos AnyShot made.")
+ shots_job: dict | None = Field(None, description=(
+ "With `shots`: the AnyShot request (app, route, request_id, status, job_id, missing, error). If it was still "
+ "running when this request had to return, fetch its result from the fal queue with request_id."))
+
+
+class ShotsRequest(BaseModel):
+ build_id: str = Field(description="A finished build from /build.")
+ mode: str = Field("images", description="images: finished stills. video: animated shots, rendered on the farm.")
+ shots: list[Shot] = Field(description="The shots to make.")
+ settings: dict = Field(default_factory=dict, description=(
+ "Optional: res [w, h], samples, fps, seconds (per video shot), lens_mm, handheld (none|walk|subtle), "
+ "look (clean|cinematic|gritty|vintage). Missing ones are chosen per shot."))
+ dials: dict[str, float | str] = Field(default_factory=dict, description=(
+ "Optional changes to the set for this order only (time_of_day, atmosphere, power, warmth, wetness, ...); "
+ "the build itself is never changed."))
+ effort: str = Field("medium", description="Claude effort for the shots agent.")
+
+
+class SceneShotsRequest(BaseModel):
+ """/scene2image and /scene2video: a ShotsRequest whose route sets the mode."""
+ build_id: str = Field(description="A finished build from /ref2scene.")
+ shots: list[Shot] = Field(description="The shots to make.")
+ settings: dict = Field(default_factory=dict, description=(
+ "Optional: res [w, h], samples, fps, seconds (per video shot), lens_mm, handheld (none|walk|subtle), "
+ "look (clean|cinematic|gritty|vintage). Missing ones are chosen per shot."))
+ dials: dict[str, float | str] = Field(default_factory=dict, description=(
+ "Optional changes to the set for this order only; the build itself is never changed."))
+ effort: str = Field("medium", description="Claude effort for the shots agent.")
+
+
+class ShotsResponse(BaseModel):
+ job_id: str
+ stills: list[str]
+ videos: list[str]
+ result: dict
+ missing: list[str]
+ agent_cost_usd: float | None
+ minutes: float
+
+
+class GalleryRequest(BaseModel):
+ limit: int = Field(200, description="Most builds to list, newest first.")
+
+
+class BuildEventsRequest(BaseModel):
+ build_id: str = Field(description="A build id (b_...) from /builds.")
+ after: int = Field(0, description="Byte offset into the build's event stream: 0, then the previous call's `next`.")
+ heartbeats: bool = Field(False, description="Include every heartbeat (default: only the newest in each page).")
+
+
+class SceneBuilderApp(fal.App):
+ machine_type = ["GPU-RTX5090", "GPU-RTXPRO6000"]
+ image = ContainerImage.from_dockerfile_str(DOCKERFILE)
+ requirements = ["pydantic", "anthropic", "pillow", "fal==1.84.0", "fal-client", "claude-agent-sdk==0.2.176"]
+ local_python_modules = ["scene_builder", "shots", "planner", "schema", "gallery"]
+ min_concurrency = 0
+ max_concurrency = 10
+ request_timeout = 7200 # fal's cap; longer builds resume in a second request
+ startup_timeout = 1200
+
+ def setup(self):
+ os.makedirs("/opt/anyscene", exist_ok=True)
+ with open("/opt/anyscene/blender_gpu.py", "w") as f:
+ f.write(BLENDER_GPU)
+ with open("/usr/local/bin/blender", "w") as f:
+ f.write(BLENDER_WRAPPER)
+ os.chmod("/usr/local/bin/blender", 0o755)
+ import shutil
+ import subprocess
+ import time
+ if os.path.exists(OPTIX_CACHE_SHARED):
+ os.makedirs(os.path.dirname(OPTIX_CACHE_LOCAL), exist_ok=True)
+ shutil.copy(OPTIX_CACHE_SHARED, OPTIX_CACHE_LOCAL)
+ t = time.time()
+ r = subprocess.run(["blender", "-b", "--factory-startup", "--python-expr", WARMUP], capture_output=True, text=True,
+ timeout=900)
+ print(f"setup: OptiX warm-up {'ok' if 'WARMUP done' in r.stdout else 'FAILED'} in {time.time() - t:.0f} s", flush=True)
+ save_optix_cache()
+
+ # Public routes follow fal's <owner>/<app>/<route> naming (target: fal-ai/anyscene/ref2scene, /scene2image,
+ # /scene2video); /build and /shots stay as aliases for existing clients.
+ @fal.endpoint("/ref2scene")
+ async def ref2scene(self, req: BuildRequest) -> BuildResponse:
+ """Reference images (+ optional floor plan, prompt, dials, shots) -> a production-ready 3D set."""
+ return await self._build_and_shoot(req)
+
+ @fal.endpoint("/build")
+ async def build(self, req: BuildRequest) -> BuildResponse:
+ return await self._build_and_shoot(req)
+
+ async def _build_and_shoot(self, req: BuildRequest) -> BuildResponse:
+ import time
+ t0 = time.time()
+ res = await self._build(req) # the build's fingerprint leaves out `shots`: one build serves any shots order
+ if req.shots and req.shots.shots:
+ await self._anyshot(req, res, t0)
+ return res
+
+ async def _anyshot(self, req: BuildRequest, res: BuildResponse, t0: float):
+ """Hand a passed build to the AnyShot app and wait for it while this request has time left. AnyShot is
+ retry-safe on its side, so a retry of this request attaches to the same shots job instead of a second one."""
+ import asyncio
+ import time
+
+ import fal_client
+
+ app = os.environ.get(ANYSHOT_APP_ENV, "").strip().strip("/")
+ route = "scene2video" if req.shots.mode == "video" else "scene2image"
+ res.shots_job = {"app": app, "route": route, "status": "skipped"}
+ if not app:
+ res.shots_job["error"] = (f"no AnyShot app configured: set the fal secret {ANYSHOT_APP_ENV}="
+ "<your-fal-username>/anyshot and redeploy")
+ return
+ last = res.critiques[-1] if res.critiques else {}
+ if not (last.get("passed") and res.scene_blend_url):
+ res.shots_job["error"] = "the build did not pass its critic (or has no scene.blend): no shots"
+ return
+ say = lambda status, msg, **kw: print(scene_builder.PREFIX + json.dumps(
+ {"t": round(time.time() - t0, 1), "stage": "shots", "status": status, "message": msg, **kw}), flush=True)
+ try:
+ client = fal_client.AsyncClient(key=os.environ.get("FAL_SERVERLESS_KEY") or os.environ.get("FAL_KEY"))
+ handle = await client.submit(f"{app}/{route}", arguments={
+ "build_id": res.build_id, "shots": [s.model_dump() for s in req.shots.shots],
+ "settings": req.shots.settings, "dials": req.shots.dials, "effort": req.effort})
+ res.shots_job.update(request_id=handle.request_id, status="running")
+ say("running", f"AnyShot {route}: {len(req.shots.shots)} shot(s) on {res.build_id}",
+ request_id=handle.request_id)
+ deadline = t0 + SHOTS_WAIT_S
+ seen = set()
+ while time.time() < deadline:
+ st = await handle.status(with_logs=True)
+ for log in getattr(st, "logs", None) or []: # relay AnyShot's stage lines into this build's log
+ msg = log.get("message", "")
+ if scene_builder.PREFIX in msg and msg not in seen:
+ seen.add(msg)
+ print(msg, flush=True)
+ if isinstance(st, fal_client.Completed):
+ out = await handle.get()
+ res.shot_stills, res.shot_videos = out.get("stills", []), out.get("videos", [])
+ res.shots_job.update(status="done", job_id=out.get("job_id"), missing=out.get("missing", []))
+ say("done", f"AnyShot: {len(res.shot_stills)} stills, {len(res.shot_videos)} videos")
+ return
+ await asyncio.sleep(15)
+ say("running", f"AnyShot is still running; fetch request {handle.request_id} from {app} when it finishes")
+ except Exception as e: # the build itself is delivered either way
+ res.shots_job.update(status="failed", error=f"{type(e).__name__}: {str(e)[:300]}")
+ say("running", f"AnyShot call failed: {res.shots_job['error']}")
+
+ @fal.endpoint("/scene2image")
+ async def scene2image(self, req: SceneShotsRequest) -> ShotsResponse:
+ """Finished stills of a built scene: picked scouting previews or shots described in words."""
+ return await self._shots(ShotsRequest(**req.model_dump(), mode="images"))
+
+ @fal.endpoint("/scene2video")
+ async def scene2video(self, req: SceneShotsRequest) -> ShotsResponse:
+ """Camera moves through a built scene, rendered on the render farm."""
+ return await self._shots(ShotsRequest(**req.model_dump(), mode="video"))
+
+ async def _build(self, req: BuildRequest) -> BuildResponse:
+ import time
+ import urllib.request
+ import uuid
+ import zipfile
+
+ from fal.toolkit import File
+
+ import asyncio
+ import hashlib
+
+ t0 = time.time()
+ # Retry-safe: fal's queue re-runs a request that times out or loses its worker. Each identical request maps
+ # to one build; a repeat returns the finished result, waits for a live attempt, or resumes a dead one in the
+ # same workspace, where nothing already generated is paid for again (generate/fal.mjs skips and resumes).
+ fp = hashlib.sha256(json.dumps({"refs": req.reference_image_urls, "prompt": req.prompt, "dials": req.dials,
+ "floor_plan": req.floor_plan_url, "scene": req.scene, "effort": req.effort},
+ sort_keys=True).encode()).hexdigest()[:20]
+ index = os.path.join(BUILDS_DIR, "_index", fp + ".json")
+ os.makedirs(os.path.dirname(index), exist_ok=True)
+ resume = False
+ if not req.fresh and os.path.exists(index):
+ told = False
+ while True:
+ rec = json.load(open(index))
+ if rec.get("response"):
+ print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": "done", "status": "done", "message":
+ f"identical request: returning finished build {rec['build_id']}"}), flush=True)
+ return BuildResponse(**rec["response"])
+ alive = os.path.join(BUILDS_DIR, rec["build_id"], "out", ".alive")
+ if not os.path.exists(alive) or time.time() - os.path.getmtime(alive) > 90:
+ break # its attempt died: resume it below
+ if not told:
+ print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": "received", "status": "running", "message":
+ f"identical request: attached to build {rec['build_id']}, still running"}), flush=True)
+ told = True
+ await asyncio.sleep(20)
+ build_id, resume = rec["build_id"], True
+ else:
+ build_id = "b_" + uuid.uuid4().hex[:10]
+ json.dump({"build_id": build_id, "fingerprint": fp, "started": time.time()}, open(index, "w"))
+ work = os.path.join(BUILDS_DIR, build_id)
+ os.makedirs(os.path.join(work, "out"), exist_ok=True)
+
+ async def keep_alive(): # proves this attempt is alive to any retry of the same request
+ while True:
+ open(os.path.join(work, "out", ".alive"), "w").close()
+ await asyncio.sleep(20)
+ alive_task = asyncio.create_task(keep_alive())
+ try:
+ return await self._build_in(req, build_id, work, index, resume, t0)
+ finally:
+ alive_task.cancel()
+
+ async def _build_in(self, req, build_id, work, index, resume, t0) -> BuildResponse:
+ import time
+ import urllib.request
+ import zipfile
+
+ from fal.toolkit import File
+
+ os.makedirs(os.path.join(work, "input"), exist_ok=True)
+ upload = lambda p: File.from_path(p).url
+ refs = []
+ if resume: # the workspace is there: refresh the shared tools, keep the scene's own scripts and assets
+ for rel, text in TOOLKIT.items():
+ path = os.path.join(work, rel)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
+ f.write(text)
+ for i, url in enumerate([] if resume else req.reference_image_urls[:4]):
+ path = os.path.join(work, "input", f"src_{i + 1}")
+ urllib.request.urlretrieve(url, path)
+ refs.append(path)
+ # references as PNG whatever came in
+ from PIL import Image
+ pngs = []
+ for i, p in enumerate(refs):
+ out = os.path.join(work, f"ref_{i + 1}.png")
+ Image.open(p).convert("RGB").save(out)
+ pngs.append(out)
+ if not resume:
+ scene_builder.make_workspace(work, pngs, req.prompt, req.scene, TOOLKIT, req.dials)
+ if req.floor_plan_url and not resume: # the agent reads it as input/floor_plan.png
+ fp = os.path.join(work, "input", "floor_plan_src")
+ urllib.request.urlretrieve(req.floor_plan_url, fp)
+ Image.open(fp).convert("RGB").save(os.path.join(work, "input", "floor_plan.png"))
+ refs = sorted(os.path.join(work, "input", f) for f in os.listdir(os.path.join(work, "input"))
+ if f.startswith("reference_"))
+
+ b = scene_builder.SceneBuilder(work, refs, req.scene, uploader=upload, effort=req.effort)
+ if resume:
+ b.ASK = ("This build was cut off (its request was retried) and is resuming in the same workspace. Read "
+ "out/builder.log, out/events.jsonl and scenes/*/NOTES.md to see how far it got. Everything already "
+ "generated is on disk, and generate/fal.mjs skips finished outputs and picks up jobs that were in "
+ "flight, so re-running your batch scripts costs nothing for done items. Don't start over: continue "
+ "from the current state to the deliverables.")
+ b.emit("received", "running", f"{'resuming' if resume else 'build'} {build_id}: {len(refs)} reference image(s)",
+ reference_urls=req.reference_image_urls, prompt=req.prompt, dials=req.dials, effort=req.effort,
+ floor_plan_url=req.floor_plan_url)
+ result = None
+ try:
+ result = await b.run(scene_builder.agent_env())
+ except Exception as e: # deliver whatever exists rather than a bare 500
+ import traceback
+ print(traceback.format_exc(), flush=True)
+ b.emit("error", "failed", f"build stopped: {type(e).__name__}: {str(e)[:300]}")
+
+ out = os.path.join(work, "out")
+ stills = [upload(os.path.join(out, "stills", f)) for f in sorted(os.listdir(os.path.join(out, "stills")))
+ if f.lower().endswith((".png", ".jpg"))]
+ url_if = lambda p: upload(p) if os.path.exists(p) else None
+ pano_dir = os.path.join(out, "panoramas")
+ panos = [upload(os.path.join(pano_dir, f)) for f in sorted(os.listdir(pano_dir))] if os.path.isdir(pano_dir) else []
+ prev_dir = os.path.join(out, "previews")
+ previews = [{"name": os.path.splitext(f)[0], "url": upload(os.path.join(prev_dir, f))}
+ for f in sorted(os.listdir(prev_dir)) if f.lower().endswith((".png", ".jpg"))] if os.path.isdir(prev_dir) else []
+ pkg = os.path.join(work, f"{build_id}.zip")
+ with zipfile.ZipFile(pkg, "w", zipfile.ZIP_DEFLATED) as z:
+ for root, dirs, names in os.walk(out):
+ # shot jobs (frames, their own copies of the set) and ungraded raw renders are not the deliverable
+ dirs[:] = [d for d in dirs if d not in ("shots", "raw")]
+ for n in names:
+ z.write(os.path.join(root, n), os.path.relpath(os.path.join(root, n), work))
+ scripts = os.path.join(work, "scenes", req.scene)
+ for root, _, names in os.walk(scripts):
+ for n in names:
+ if n.endswith((".py", ".json", ".md", ".sh")):
+ z.write(os.path.join(root, n), os.path.relpath(os.path.join(root, n), work))
+ res = BuildResponse(
+ build_id=build_id, stills=stills, scene_blend_url=url_if(os.path.join(out, "scene.blend")),
+ scene_glb_url=url_if(os.path.join(out, "scene.glb")), panorama_urls=panos, previews=previews, package_url=upload(pkg),
+ critiques=[{k: c[k] for k in ("round", "scores", "passed", "summary", "fixes")} for c in b.critiques],
+ dials=json.load(open(os.path.join(out, "dials.json"))) if os.path.exists(os.path.join(out, "dials.json")) else {},
+ missing=b.missing(), agent_cost_usd=getattr(result, "total_cost_usd", None),
+ minutes=round((time.time() - t0) / 60, 1))
+ save_optix_cache()
+ b.emit("packaged", "done", f"package ready after {res.minutes:.0f} min", package_url=res.package_url)
+ rec = json.load(open(index)) # a repeat of this request now gets this result instead of a new build
+ rec.update(response=res.model_dump(), finished=time.time())
+ json.dump(rec, open(index, "w"))
+ await __import__("asyncio").sleep(2) # let the last stage lines reach the queue logs before COMPLETED
+ return res
+
+ @fal.endpoint("/shots")
+ async def shots(self, req: ShotsRequest) -> ShotsResponse:
+ return await self._shots(req)
+
+ async def _shots(self, req: ShotsRequest) -> ShotsResponse:
+ """Scene to images / scene to video: an agent shoots a finished build (see builder/SHOTS.md)."""
+ import time
+ import uuid
+
+ from fal.toolkit import File
+
+ t0 = time.time()
+ if not req.build_id.replace("_", "").isalnum():
+ raise ValueError("bad build_id")
+ work = os.path.join(BUILDS_DIR, req.build_id)
+ try:
+ scene = shots.build_scene_name(work)
+ except ValueError as e:
+ raise ValueError(f"build {req.build_id}: {e}")
+ # older builds carry older tools: refresh the toolkit (never the scene's own scripts or outputs)
+ shots.write_toolkit(work, TOOLKIT)
+ job_id = "j_" + uuid.uuid4().hex[:8]
+ upload = lambda p: File.from_path(p).url
+ # the same agent and tools as the AnyShot app (anyshot/app.py), on the build's own workspace
+ request = {**req.model_dump(), "source": {"kind": "build", "build_id": req.build_id}}
+ d, out = await shots.shoot(work, scene, job_id, request, upload, effort=req.effort)
+ res = ShotsResponse(**out, minutes=round((time.time() - t0) / 60, 1))
+ save_optix_cache()
+ d.emit("packaged", "done", f"{len(res.stills)} stills, {len(res.videos)} videos after {res.minutes:.0f} min",
+ stills=res.stills, videos=res.videos)
+ await __import__("asyncio").sleep(2)
+ return res
+
+ # The shared builds gallery: every build anyone ran, read from storage (the fal queue only shows a request to the
+ # key that submitted it). Light and read-only; see builder/gallery.py.
+ @fal.endpoint("/builds")
+ async def builds(self, req: GalleryRequest) -> dict:
+ """Every build on this app's storage, newest first: status, inputs, critic, cover and preview URLs."""
+ import asyncio
+ return await asyncio.to_thread(gallery.list_builds, BUILDS_DIR, "scene", max(1, min(req.limit, 1000)))
+
+ @fal.endpoint("/build_events")
+ async def build_events(self, req: BuildEventsRequest) -> dict:
+ """One build's stage events from byte offset `after` (poll with `next` to follow a running build), its summary,
+ and on the first page of a finished build its response."""
+ import asyncio
+
+ from fal.toolkit import File
+ return await asyncio.to_thread(gallery.build_events, BUILDS_DIR, req.build_id, req.after, "scene",
+ req.heartbeats, 8 << 20, lambda p: File.from_path(p).url)
+
+ @fal.endpoint("/smoke")
+ async def smoke(self, req: BuildRequest) -> dict:
+ """Container check: tools present, the agent starts, can run Bash/Blender/node and see an image."""
+ import subprocess
+ vers = {c[0]: subprocess.run(c, capture_output=True, text=True).stdout.splitlines()[:1]
+ for c in (["blender", "--version"], ["node", "--version"], ["ffmpeg", "-version"], ["nvidia-smi", "-L"])}
+ from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, ResultMessage, TextBlock
+ work = "/tmp/smoke"
+ os.makedirs(work, exist_ok=True)
+ said, cost = [], None
+ opts = ClaudeAgentOptions(model=scene_builder.MODEL, effort="low", permission_mode="bypassPermissions", cwd=work,
+ setting_sources=[], settings='{"fastMode": true}', env=scene_builder.agent_env())
+ async with ClaudeSDKClient(opts) as c:
+ await c.query("Run `blender -b --python-expr \"import bpy; print('BPY', bpy.app.version_string)\"` and "
+ "`node -e \"console.log(typeof fetch)\"`, then reply with both outputs in one line.")
+ async for m in c.receive_response():
+ if isinstance(m, AssistantMessage):
+ said += [b.text for b in m.content if isinstance(b, TextBlock)]
+ elif isinstance(m, ResultMessage):
+ cost = m.total_cost_usd
+ # the critic runs in this process (not the agent's): check it imports and answers here too
+ from PIL import Image
+ Image.new("RGB", (256, 128), (40, 60, 50)).save(f"{work}/plate.png")
+ try:
+ crit = scene_builder.run_critic([f"{work}/plate.png"], [f"{work}/plate.png"])
+ critic = {"ok": True, "scores": crit["scores"]}
+ except Exception as e:
+ critic = {"ok": False, "error": f"{type(e).__name__}: {e}"[:300]}
+ return {"versions": vers, "agent": said[-1] if said else None, "cost": cost, "critic": critic}
diff --git a/builder/blender_gpu.py b/builder/blender_gpu.py
new file mode 100644
index 0000000..13d33dd
--- /dev/null
+++ b/builder/blender_gpu.py
@@ -0,0 +1,35 @@
+"""Every Blender the builder starts renders Cycles on the GPU, even with --factory-startup and no gpu_prefs script.
+On the fal worker `blender` is a wrapper that runs this first (`blender.real --python blender_gpu.py "$@"`): headless
+Blender otherwise renders on the CPU, which an agent forgot once and lost most of a build to."""
+
+import bpy
+from bpy.app.handlers import persistent
+
+
+def _devices():
+ try:
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ except (KeyError, AttributeError):
+ return
+ for kind in ("OPTIX", "CUDA"):
+ try:
+ prefs.compute_device_type = kind
+ prefs.get_devices()
+ except TypeError:
+ continue
+ if any(d.type == kind for d in prefs.devices):
+ for d in prefs.devices:
+ d.use = d.type == kind
+ return
+
+
+@persistent
+def _gpu_scenes(*_):
+ for sc in bpy.data.scenes:
+ sc.cycles.device = "GPU"
+
+
+_devices()
+_gpu_scenes()
+bpy.app.handlers.load_post.append(_gpu_scenes)
+bpy.app.handlers.render_init.append(_gpu_scenes)
diff --git a/builder/client.py b/builder/client.py
new file mode 100644
index 0000000..42bb423
--- /dev/null
+++ b/builder/client.py
@@ -0,0 +1,91 @@
+"""Call the scene builder and print its live log.
+
+ uv run --python 3.13 --with fal-client python builder/client.py build <image path or url> [...] [--prompt "..."]
+ uv run --python 3.13 --with fal-client python builder/client.py smoke
+
+Local images are uploaded to fal storage first. Every stage event goes to --events (JSON lines, for UI replay); the
+response and the stills are saved to --out. Uses FAL_SERVERLESS_KEY (the account the app is deployed under).
+"""
+
+import argparse
+import json
+import os
+import sys
+import time
+import urllib.request
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "endpoint"))
+from client import user_env # noqa: E402
+
+# /ref2scene, /scene2image, /scene2video (/build, /shots kept as aliases); ANYSCENE_APP=<owner>/<app> for your own
+APP = os.environ.get("ANYSCENE_APP")
+PREFIX = "ANYSCENE_STAGE "
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("cmd", choices=["build", "smoke", "shots"])
+ p.add_argument("refs", nargs="*")
+ p.add_argument("--prompt", default="")
+ p.add_argument("--effort", default="medium")
+ p.add_argument("--out", default="builder_out")
+ p.add_argument("--events")
+ p.add_argument("--app", default=APP, help="fal app id (default: $ANYSCENE_APP)")
+ p.add_argument("--build-id", help="shots: the finished build to shoot")
+ p.add_argument("--mode", default="images", choices=["images", "video"])
+ p.add_argument("--shot", action="append", default=[],
+ help="shots: a camera name from the build's shots.json, or a description in words (repeatable)")
+ p.add_argument("--settings", default="{}", help='shots: JSON, e.g. {"seconds": 8, "handheld": "subtle"}')
+ a = p.parse_args()
+ if not a.app:
+ p.error("set ANYSCENE_APP=<your-fal-username>/anyscene or pass --app")
+ sys.stdout.reconfigure(encoding="utf-8")
+ os.environ["FAL_KEY"] = user_env("FAL_SERVERLESS_KEY") or user_env("FAL_KEY")
+ import fal_client
+
+ up = lambda s: s if s.startswith("http") else fal_client.upload_file(s)
+ payload = {"reference_image_urls": [up(s) for s in a.refs], "prompt": a.prompt, "effort": a.effort}
+ if a.cmd == "shots":
+ shots = [{"name": x} if " " not in x else {"description": x} for x in a.shot]
+ payload = {"build_id": a.build_id, "mode": a.mode, "shots": shots, "settings": json.loads(a.settings),
+ "effort": a.effort}
+ os.makedirs(a.out, exist_ok=True)
+ events = open(a.events or os.path.join(a.out, "events.jsonl"), "w", encoding="utf-8")
+ t0, seen = time.time(), set()
+
+ def on_update(update):
+ for log in getattr(update, "logs", None) or []:
+ msg = log.get("message", "")
+ if msg in seen:
+ continue
+ if PREFIX not in msg:
+ if any(k in msg for k in ("Traceback", "Error", "error:", "Exception")):
+ seen.add(msg)
+ print(f"[worker] {msg[:600]}", flush=True)
+ continue
+ seen.add(msg)
+ ev = json.loads(msg.split(PREFIX, 1)[1])
+ events.write(json.dumps(ev) + "\n")
+ events.flush()
+ line = f"[{(time.time() - t0) / 60:6.1f}m] {ev['stage']:<10} {ev.get('message', '')[:160]}"
+ if ev.get("preview_url"):
+ line += f"\n{'':20}image: {ev['preview_url']}"
+ print(line, flush=True)
+
+ on_enqueue = lambda rid: print(f"request {rid}\nwatch: http://localhost:3210/?watch={rid}", flush=True)
+ res = fal_client.subscribe(f"{a.app}/{a.cmd}", arguments=payload, with_logs=True, on_queue_update=on_update,
+ on_enqueue=on_enqueue, client_timeout=3 * 3600) if a.cmd != "smoke" else \
+ fal_client.subscribe(f"{a.app}/smoke", arguments=payload or {"reference_image_urls": []})
+ with open(os.path.join(a.out, f"{a.cmd}.json"), "w", encoding="utf-8") as f:
+ json.dump(res, f, indent=1)
+ if a.cmd == "shots":
+ for url in res["stills"] + res["videos"]:
+ urllib.request.urlretrieve(url, os.path.join(a.out, url.rsplit("/", 1)[-1]))
+ if a.cmd == "build":
+ for i, url in enumerate(res["stills"]):
+ urllib.request.urlretrieve(url, os.path.join(a.out, f"still_{i}.png"))
+ print(json.dumps({k: v for k, v in res.items() if k != "critiques"}, indent=1)[:3000])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/builder/gallery.py b/builder/gallery.py
new file mode 100644
index 0000000..ef0a741
--- /dev/null
+++ b/builder/gallery.py
@@ -0,0 +1,386 @@
+"""The shared builds gallery: every build anyone ran, read from the app's persistent storage (not the fal queue, which
+only the submitter's key can read). Used by builder/app.py (/builds, /build_events) and kit/app.py (/kits,
+/kit_events). Stdlib only.
+
+A build lives at <root>/<id>/ (b_... scenes, k_... kits). out/events.jsonl is its stage stream (scene_builder.emit),
+out/.alive is touched every 20 s while an attempt runs, and <root>/_index/<fingerprint>.json (builds since the retry
+fix) holds the finished response. Older builds have no index, so everything is derived from events.jsonl.
+
+Summaries are folded incrementally (only the bytes added since the last look) and cached in memory and on disk at
+<root>/_gallery/<id>.json, so a new runner does not re-read every finished build. Image URLs come from the events
+(already on the fal CDN). A finished build without an index response gets its stills/previews/panoramas uploaded
+once, on first open, and the URLs are cached in <root>/_gallery/<id>.files.json.
+"""
+
+import json
+import os
+import re
+import threading
+import time
+
+ID_RE = re.compile(r"^[bk]_[0-9a-zA-Z]{4,40}$")
+ALIVE_S = 90 # an attempt touches out/.alive every 20 s; heartbeats land every 20 s
+CAP_RE = re.compile(r"2-hour limit", re.I)
+SUMMARY_VERSION = 3
+MAX_LIST_IMAGES = 16 # previews/stills per build in the light listing record
+NON_MILESTONES = {"received", "log", "thinking", "critique", "done", "packaged", "heartbeat", "error", "previews"}
+
+_lock = threading.Lock()
+_mem: dict = {} # (root, id) -> summary state
+_index_cache: dict = {} # root -> (signature, {id: record})
+_list_cache: dict = {} # (root, limit) -> (time, result)
+
+
+# ---------------------------------------------------------------- helpers
+def _mtime(p):
+ try:
+ return os.path.getmtime(p)
+ except OSError:
+ return None
+
+
+def _gallery_dir(root):
+ d = os.path.join(root, "_gallery")
+ os.makedirs(d, exist_ok=True)
+ return d
+
+
+def _write_json(path, obj):
+ tmp = f"{path}.{os.getpid()}.{threading.get_ident()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(obj, f)
+ os.replace(tmp, path)
+
+
+def _index(root):
+ """{id: index record} from <root>/_index/*.json, re-read only when a file there changed."""
+ d = os.path.join(root, "_index")
+ try:
+ ents = [e for e in os.scandir(d) if e.name.endswith(".json")]
+ except OSError:
+ return {}
+ sig = tuple(sorted((e.name, e.stat().st_mtime, e.stat().st_size) for e in ents))
+ hit = _index_cache.get(root)
+ if hit and hit[0] == sig:
+ return hit[1]
+ out = {}
+ for e in ents:
+ try:
+ rec = json.load(open(e.path, encoding="utf-8"))
+ except Exception:
+ continue
+ bid = rec.get("build_id") or rec.get("kit_id")
+ if bid and (bid not in out or (rec.get("started") or 0) >= (out[bid].get("started") or 0)):
+ out[bid] = rec
+ _index_cache[root] = (sig, out)
+ return out
+
+
+def _started(work, rec):
+ if rec and rec.get("started"):
+ return rec["started"]
+ cands = [_mtime(os.path.join(work, p)) for p in ("input/brief.md", "input/dials.json", "ref_1.png", "input")]
+ cands = [c for c in cands if c]
+ return min(cands) if cands else (_mtime(work) or 0)
+
+
+# ---------------------------------------------------------------- fold events into a summary
+def _empty_state():
+ return {"v": SUMMARY_VERSION, "offset": 0, "given": None, "rounds": 0, "last_critique": None, "critiques": [],
+ "previews": [], "frames": 0, "cover": None, "cover_rank": 0, "last_milestone": None, "packaged": False,
+ "package_url": None, "capped": False, "failed": None, "agent_done": False, "events": 0,
+ "milestones": [], "last_t": 0, "attempts": 0}
+
+
+# what makes a good cover: a finals render beats a critic still beats any milestone beats any frame
+_RANK = {"finals": 5, "critique": 4, "previews": 2}
+
+
+def _fold(st, ev):
+ st["events"] += 1
+ stage = ev.get("stage", "")
+ if isinstance(ev.get("t"), (int, float)):
+ st["last_t"] = ev["t"]
+ if stage == "received":
+ if ev.get("reference_urls") is not None and st["given"] is None:
+ st["given"] = {k: ev.get(k) for k in ("reference_urls", "prompt", "dials", "effort", "floor_plan_url", "items")
+ if k in ev}
+ if re.match(r"(build|resuming) [bk]_", ev.get("message", "")):
+ st["attempts"] += 1
+ url = ev.get("preview_url")
+ if url:
+ st["frames"] += 1
+ rank = _RANK.get(stage, 3 if stage not in NON_MILESTONES else 1)
+ if rank >= st["cover_rank"]:
+ st["cover"], st["cover_rank"] = url, rank
+ if stage == "previews" and url and not any(p["url"] == url for p in st["previews"]):
+ st["previews"].append({"url": url, "message": (ev.get("message") or "")[:200]})
+ if stage == "critique" and ev.get("critique"):
+ c = ev["critique"]
+ slim = {k: c.get(k) for k in ("round", "scores", "passed", "summary") if k in c}
+ st["critiques"] = [x for x in st["critiques"] if x.get("round") != slim.get("round")] + [slim]
+ st["rounds"] = max(st["rounds"], int(c.get("round") or 0))
+ st["last_critique"] = slim
+ if stage not in NON_MILESTONES and stage:
+ st["last_milestone"] = {"stage": stage, "message": (ev.get("message") or "")[:300], "t": ev.get("t")}
+ if stage not in st["milestones"]:
+ st["milestones"].append(stage)
+ if stage == "done":
+ st["agent_done"] = True
+ if stage == "packaged":
+ st["packaged"] = True
+ st["package_url"] = ev.get("package_url") or st["package_url"]
+ if stage == "error" and CAP_RE.search(ev.get("message", "")):
+ st["capped"] = True
+ if ev.get("status") == "failed":
+ st["failed"] = (ev.get("message") or "")[:300]
+
+
+def _state(root, bid):
+ """The folded summary state of one build, updated with whatever was appended since the last look."""
+ ev_path = os.path.join(root, bid, "out", "events.jsonl")
+ try:
+ size = os.path.getsize(ev_path)
+ except OSError:
+ size = 0
+ key = (root, bid)
+ st = _mem.get(key)
+ disk = os.path.join(_gallery_dir(root), bid + ".json")
+ if st is None and os.path.exists(disk):
+ try:
+ st = json.load(open(disk, encoding="utf-8"))
+ if st.get("v") != SUMMARY_VERSION:
+ st = None
+ except Exception:
+ st = None
+ if st is None or size < st["offset"]:
+ st = _empty_state()
+ if size > st["offset"]:
+ with open(ev_path, "rb") as f:
+ f.seek(st["offset"])
+ chunk = f.read(size - st["offset"])
+ end = chunk.rfind(b"\n") + 1 # only whole lines; a half-written last line waits for the next look
+ for line in chunk[:end].splitlines():
+ if line.strip():
+ try:
+ _fold(st, json.loads(line))
+ except Exception:
+ pass
+ if end:
+ st["offset"] += end
+ try:
+ _write_json(disk, st)
+ except OSError:
+ pass
+ _mem[key] = st
+ return st
+
+
+def _status(root, bid, st, rec):
+ out = os.path.join(root, bid, "out")
+ fresh = max(_mtime(os.path.join(out, ".alive")) or 0, _mtime(os.path.join(out, "events.jsonl")) or 0)
+ if time.time() - fresh < ALIVE_S and not (rec and rec.get("response")):
+ return "running"
+ if st["capped"]:
+ return "capped"
+ if (rec and rec.get("response")) or st["packaged"]:
+ return "done"
+ # cut off mid-work right at a platform request timeout (30 min before it was raised, then 2 h): capped, not crashed
+ if 1770 <= st["last_t"] <= 1830 or st["last_t"] >= 7080:
+ return "capped"
+ return "stopped"
+
+
+def summary(root, bid, kind="scene"):
+ rec = _index(root).get(bid)
+ st = _state(root, bid)
+ work = os.path.join(root, bid)
+ resp = (rec or {}).get("response") or None
+ started = _started(work, rec)
+ updated = _mtime(os.path.join(work, "out", "events.jsonl")) or started
+ status = _status(root, bid, st, rec)
+ given = st["given"] or {}
+ last = st["last_critique"]
+ if resp:
+ crit = resp.get("critiques") or []
+ if crit:
+ c = crit[-1]
+ last = {k: c.get(k) for k in ("round", "scores", "passed", "summary")}
+ rounds = max(st["rounds"], len((resp or {}).get("critiques") or []))
+ if kind == "kit":
+ stills = [u for u in [(resp or {}).get("lineup_url")] if u]
+ previews = [{"url": it["thumb_url"], "message": it.get("label") or it.get("id")}
+ for it in (resp or {}).get("items", []) if it.get("thumb_url")] or st["previews"]
+ cover = (resp or {}).get("lineup_url") or st["cover"]
+ else:
+ stills = list((resp or {}).get("stills") or [])
+ previews = [{"url": p["url"], "message": p.get("name", "")} for p in (resp or {}).get("previews") or []] \
+ or st["previews"]
+ cover = (stills[0] if stills else None) or st["cover"]
+ minutes = (resp or {}).get("minutes")
+ if minutes is None:
+ minutes = round(((time.time() if status == "running" else updated) - started) / 60, 1)
+ return {
+ "id": bid, "kind": kind, "started": started, "updated": updated, "status": status,
+ "passed": bool(last and last.get("passed")),
+ "reference_urls": given.get("reference_urls") or [], "prompt": given.get("prompt") or "",
+ "dials": given.get("dials") or {}, "effort": given.get("effort"), "floor_plan_url": given.get("floor_plan_url"),
+ "items": given.get("items"), "name": (resp or {}).get("name"),
+ "critic_rounds": rounds, "last_scores": (last or {}).get("scores"), "last_summary": (last or {}).get("summary"),
+ "minutes": minutes, "cover": cover,
+ "stills": stills[:MAX_LIST_IMAGES], "previews": previews[:MAX_LIST_IMAGES],
+ "n_stills": len(stills), "n_previews": len(previews), "frames": st["frames"],
+ "milestone": st["last_milestone"], "attempts": st["attempts"], "has_response": bool(resp),
+ "agent_cost_usd": (resp or {}).get("agent_cost_usd"), "error": st["failed"],
+ "package_url": (resp or {}).get("package_url") or st["package_url"],
+ }
+
+
+def list_builds(root, kind="scene", limit=200, max_age_s=8.0):
+ """Light records of every build under root, newest first. The whole listing is reused for a few seconds."""
+ hit = _list_cache.get((root, limit))
+ if hit and time.time() - hit[0] < max_age_s:
+ return hit[1]
+ prefix = "k_" if kind == "kit" else "b_"
+ with _lock:
+ try:
+ ids = [e.name for e in os.scandir(root) if e.is_dir() and e.name.startswith(prefix) and ID_RE.match(e.name)]
+ except OSError:
+ ids = []
+ rows = []
+ for bid in ids:
+ try:
+ rows.append(summary(root, bid, kind))
+ except Exception as e: # one broken workspace must not hide the rest
+ rows.append({"id": bid, "kind": kind, "status": "stopped", "started": _mtime(os.path.join(root, bid)) or 0,
+ "error": f"{type(e).__name__}: {e}"[:200]})
+ rows.sort(key=lambda r: r.get("started") or 0, reverse=True)
+ res = {"builds": rows[:limit], "total": len(rows), "now": time.time()}
+ _list_cache[(root, limit)] = (time.time(), res)
+ return res
+
+
+# ---------------------------------------------------------------- one build: events + response
+def _files_response(root, bid, kind, uploader):
+ """A response for a finished build with no index record, built from the files in out/. Each file is uploaded once;
+ the URLs are cached next to the summary (keyed by size + mtime, so a re-render is uploaded again)."""
+ out = os.path.join(root, bid, "out")
+ cache_path = os.path.join(_gallery_dir(root), bid + ".files.json")
+ try:
+ cache = json.load(open(cache_path, encoding="utf-8"))
+ except Exception:
+ cache = {}
+ changed = False
+
+ def lst(sub, exts):
+ d = os.path.join(out, sub)
+ return [os.path.join(sub, f) for f in sorted(os.listdir(d)) if f.lower().endswith(exts)] if os.path.isdir(d) else []
+
+ if kind == "kit":
+ wanted = lst("renders", (".png", ".jpg")) + lst("renders/thumbs", (".png", ".jpg"))
+ wanted = [w for w in wanted if w.replace("\\", "/") in ("renders/lineup.png",) or "/thumbs/" in w.replace("\\", "/")]
+ else:
+ wanted = lst("stills", (".png", ".jpg")) + lst("previews", (".png", ".jpg")) + lst("panoramas", (".png", ".jpg", ".exr", ".hdr"))
+ if os.path.exists(os.path.join(out, "scene.glb")):
+ wanted.append("scene.glb")
+ todo = []
+ for rel in wanted:
+ p = os.path.join(out, rel)
+ try:
+ s = os.stat(p)
+ except OSError:
+ continue
+ k = rel.replace("\\", "/")
+ sig = [s.st_size, s.st_mtime]
+ if not (cache.get(k) and cache[k].get("sig") == sig and cache[k].get("url")):
+ todo.append((k, p, sig))
+ if todo and uploader:
+ from concurrent.futures import ThreadPoolExecutor
+
+ def up(item):
+ k, p, sig = item
+ try:
+ return k, {"sig": sig, "url": uploader(p)}
+ except Exception as e:
+ return k, {"sig": sig, "url": None, "error": str(e)[:200]}
+ with ThreadPoolExecutor(8) as ex:
+ for k, v in ex.map(up, todo):
+ cache[k] = v
+ changed = True
+ if changed:
+ try:
+ _write_json(cache_path, cache)
+ except OSError:
+ pass
+ url = lambda k: (cache.get(k) or {}).get("url")
+ pick = lambda sub: [(k, url(k)) for k in sorted(cache) if k.startswith(sub + "/") and url(k)
+ and os.path.exists(os.path.join(out, k))]
+ if kind == "kit":
+ kit = {}
+ try:
+ kit = json.load(open(os.path.join(out, "kit.json"), encoding="utf-8"))
+ except Exception:
+ pass
+ labels = {it.get("id"): it.get("label") for it in kit.get("items", []) if isinstance(it, dict)}
+ items = [{"id": os.path.splitext(os.path.basename(k))[0], "label": labels.get(os.path.splitext(os.path.basename(k))[0], ""),
+ "thumb_url": u} for k, u in pick("renders/thumbs")]
+ return {"kit_id": bid, "name": kit.get("name"), "style": kit.get("style"), "items": items,
+ "lineup_url": url("renders/lineup.png"), "kit_blend_url": None, "kit_json_url": None, "package_url": None,
+ "critiques": [], "dials": {}, "missing": [], "agent_cost_usd": None, "generation_cost_usd": None,
+ "minutes": None, "from_storage": True}
+ dials = {}
+ try:
+ dials = json.load(open(os.path.join(out, "dials.json"), encoding="utf-8"))
+ except Exception:
+ pass
+ return {"build_id": bid, "stills": [u for _, u in pick("stills")],
+ "previews": [{"name": os.path.splitext(os.path.basename(k))[0], "url": u} for k, u in pick("previews")],
+ "panorama_urls": [u for _, u in pick("panoramas")], "scene_glb_url": url("scene.glb"),
+ "scene_blend_url": None, "package_url": None, "critiques": [], "dials": dials, "missing": [],
+ "agent_cost_usd": None, "minutes": None, "from_storage": True}
+
+
+def build_events(root, bid, after=0, kind="scene", heartbeats=False, max_bytes=8 << 20, uploader=None):
+ """Events of one build from byte offset `after` (whole lines only), plus its summary. Heartbeats are dropped except
+ the newest one in the page (they repeat the milestones, which the full stream already has). The last page of a
+ build that is not running also carries `response`: the index's, else one built from out/."""
+ if not ID_RE.match(bid or ""):
+ raise ValueError("bad id")
+ ev_path = os.path.join(root, bid, "out", "events.jsonl")
+ if not os.path.isdir(os.path.join(root, bid)):
+ raise ValueError(f"no such build: {bid}")
+ after = max(0, int(after or 0))
+ events, nxt, size = [], after, 0
+ try:
+ size = os.path.getsize(ev_path)
+ except OSError:
+ pass
+ if size > after:
+ with open(ev_path, "rb") as f:
+ f.seek(after)
+ chunk = f.read(min(size - after, max_bytes))
+ end = chunk.rfind(b"\n") + 1
+ last_beat = None
+ for line in chunk[:end].splitlines():
+ if not line.strip():
+ continue
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ if ev.get("stage") == "heartbeat" and not heartbeats:
+ last_beat = ev
+ continue
+ events.append(ev)
+ if last_beat is not None:
+ events.append(last_beat)
+ nxt = after + end
+ s = summary(root, bid, kind)
+ # more: this page stopped at max_bytes, so ask again right away (otherwise poll at leisure)
+ res = {"id": bid, "events": events, "next": nxt, "size": size, "more": size - after > max_bytes, "summary": s}
+ if s["status"] != "running" and not res["more"]:
+ rec = _index(root).get(bid) or {}
+ res["response"] = rec.get("response") or _files_response(root, bid, kind, uploader)
+ if not res["response"].get("package_url") and s.get("package_url"): # the "packaged" event had it
+ res["response"]["package_url"] = s["package_url"]
+ return res
diff --git a/builder/scene_builder.py b/builder/scene_builder.py
new file mode 100644
index 0000000..25d3a1e
--- /dev/null
+++ b/builder/scene_builder.py
@@ -0,0 +1,448 @@
+"""AnyScene scene builder: one Claude agent builds the whole scene from reference images, the way SKILL.md describes.
+
+ uv run --python 3.13 --with claude-agent-sdk --with anthropic --with pydantic --with pillow \
+ python builder/scene_builder.py <reference.png> [...] --work <dir> [--prompt "..."] [--effort medium]
+
+The agent (Claude Code via the Agent SDK, Opus 5.5, effort medium by default, fast mode) works in a fresh workspace holding SKILL.md,
+CRAFT.md and the shared tools. On top of its own tools (Bash, Read, Write, Edit...) it gets:
+ report(stage, message, image) a stage event for the live UI (ANYSCENE_STAGE lines, out/events.jsonl)
+ critique(stills) an independent critic: reference vs stills, scores and ranked fixes
+Every tool call is also streamed as a short log event (PostToolUse hook). There is no time budget: a Stop hook keeps
+the agent working until the deliverables exist and the critic passes, unless three critic rounds in a row bring no
+improvement.
+"""
+
+import argparse
+import asyncio
+import base64
+import io
+import json
+import os
+import shutil
+import subprocess
+import sys
+import time
+
+from claude_agent_sdk import (AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, HookMatcher, ResultMessage,
+ TextBlock, ToolUseBlock, create_sdk_mcp_server, tool)
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REPO = os.path.dirname(HERE)
+sys.path.insert(0, os.path.join(REPO, "endpoint"))
+import planner # noqa: E402 (the critic's Claude client; imported here so fal bundles it with this module)
+PREFIX = "ANYSCENE_STAGE "
+# fal ends a request at 7200 s; warn the agent, then stop it with time left to package and upload
+CAP_WARN_S = 95 * 60
+# most critic rounds a build gets; after the last one the builder finishes its deliverables and delivers
+MAX_CRITIC_ROUNDS = 8
+CAP_STOP_S = 110 * 60
+MODEL = "anthropic/claude-opus-5.5" # through OpenRouter (OPENROUTER_API_KEY)
+DIRECT_MODEL = "claude-opus-5-5" # the same model on the Anthropic API (ANTHROPIC_API_KEY)
+
+
+def user_env(name):
+ if os.environ.get(name):
+ return os.environ[name]
+ if sys.platform == "win32":
+ parts = subprocess.run(["reg", "query", r"HKCU\Environment", "/v", name], capture_output=True, text=True).stdout.split()
+ if name in parts:
+ return parts[parts.index(name) + 2]
+ return None
+
+
+# ---------------------------------------------------------------- workspace
+TOOLKIT_DIRS = ("generate", "pipeline", "camera", "docs")
+SKIP = (".png", ".jpg", ".mp4", ".pyc", "spend.jsonl", "r2.mjs", "lan_gallery.py", "_page.mjs")
+
+
+def toolkit_files():
+ """Everything the builder's workspace starts with, as {relative path: text}: SKILL.md, CRAFT.md, the prompt and the
+ shared tools. No example scenes. Collected at deploy time so the fal app carries it."""
+ files = {"SKILL.md": open(os.path.join(REPO, "SKILL.md"), encoding="utf-8").read(),
+ "CRAFT.md": open(os.path.join(HERE, "CRAFT.md"), encoding="utf-8").read(),
+ ".builder/PROMPT.md": open(os.path.join(HERE, "PROMPT.md"), encoding="utf-8").read(),
+ ".builder/SHOTS.md": open(os.path.join(HERE, "SHOTS.md"), encoding="utf-8").read(),
+ "endpoint/refine_blender.py": open(os.path.join(REPO, "endpoint", "refine_blender.py"), encoding="utf-8").read()}
+ for d in TOOLKIT_DIRS:
+ for root, dirs, names in os.walk(os.path.join(REPO, d)):
+ dirs[:] = [x for x in dirs if x != "__pycache__"]
+ for n in names:
+ if not n.endswith(SKIP):
+ path = os.path.join(root, n)
+ files[os.path.relpath(path, REPO).replace(os.sep, "/")] = open(path, encoding="utf-8").read()
+ return files
+
+
+def make_workspace(work, refs, prompt, scene, files, dials=None):
+ os.makedirs(work, exist_ok=True)
+ for rel, text in files.items():
+ path = os.path.join(work, rel)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
+ f.write(text)
+ if rel.endswith(".sh"):
+ os.chmod(path, 0o755)
+ inp = os.path.join(work, "input")
+ os.makedirs(inp, exist_ok=True)
+ for i, r in enumerate(refs):
+ shutil.copy(r, os.path.join(inp, f"reference_{i + 1}.png"))
+ with open(os.path.join(inp, "dials.json"), "w", encoding="utf-8") as f:
+ json.dump(dials or {}, f, indent=1)
+ with open(os.path.join(inp, "brief.md"), "w", encoding="utf-8") as f:
+ f.write(prompt or "(no prompt: match the reference)\n")
+ for d in (f"scenes/{scene}/scripts", "out/stills", "out/critique"):
+ os.makedirs(os.path.join(work, d), exist_ok=True)
+ open(os.path.join(work, "generate", "spend.jsonl"), "a").close()
+
+
+# ---------------------------------------------------------------- critic
+CRITIC = """You review 3D sets for a service that turns reference images into production-ready Blender sets. The
+FIRST image is the customer's reference; the others are renders of the set built from it. The reference is a starting
+point, not a target to copy: the set must clearly be the same KIND of place (its world, era, contents, materials and
+level of detail), but the camera views, the exact lighting, the grade and the arrangement are the builder's own
+choices and must NOT be marked down for differing from the reference.
+
+The bar is a production-ready starting point: a set a studio would accept as the base an artist then refines and
+art-directs. Judge it as a whole, from normal viewing distance. Do NOT nitpick: no points off for framing that
+differs from the reference, light that differs from the reference's light, a case that could hold more pastries, a
+surface that is a little CG on close inspection, or anything an artist would tweak in ten minutes.
+
+Score each category 1-10 (7 = a solid, usable production set; 9 = exceptional):
+- layout: a believable space of the reference's kind, sensibly arranged;
+- props: the reference's notable objects are there and recognisable; nothing broken, blobby or melted;
+- screens_signage: signs, screens and labels read cleanly; no real brands; no garbled text on hero signage;
+- materials: surfaces read as real materials with fitting wear; nothing untextured or flat grey;
+- lighting: designed, motivated light that suits the place; not flat, muddy or blown out;
+- atmosphere: depth and a deliberate grade; haze where it helps;
+- plausibility: nothing floating, intersecting, impossible or stacked wrongly;
+- composition: the shots are well composed (any angles; they don't need to match the reference).
+
+Then list at most FIVE fixes, most damaging first: only problems that would stop a studio from using the set as a
+base (something broken, missing, wrong-world, unreadable or ugly at normal viewing distance). If the set is already a
+good base, say so and list fewer or none. Pass when the set is a good production base: no category below 6 and an
+average of 7 or more."""
+
+
+def critic_schema():
+ from pydantic import BaseModel, Field
+
+ class Scores(BaseModel):
+ layout: int
+ props: int
+ screens_signage: int
+ materials: int
+ lighting: int
+ atmosphere: int
+ plausibility: int
+ composition: int
+
+ class Critique(BaseModel):
+ scores: Scores
+ fixes: list[str] = Field(description="Most damaging first.")
+ summary: str
+ return Critique
+
+
+def _jpeg(path, size=1600):
+ from PIL import Image
+ img = Image.open(path).convert("RGB")
+ img.thumbnail((size, size))
+ buf = io.BytesIO()
+ img.save(buf, "JPEG", quality=88)
+ return base64.standard_b64encode(buf.getvalue()).decode()
+
+
+def run_critic(refs, stills):
+ Critique = critic_schema()
+ client, model, extra = planner._client()
+ content = []
+ for p in list(refs) + list(stills):
+ content.append({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": _jpeg(p)}})
+ content.append({"type": "text", "text": CRITIC})
+ with client.beta.messages.stream(model=model, max_tokens=16000, thinking={"type": "adaptive"},
+ output_config={"effort": "high", "format": {"type": "json_schema",
+ "schema": planner.strict_schema(Critique)}},
+ messages=[{"role": "user", "content": content}], **extra) as s:
+ msg = s.get_final_message()
+ c = Critique.model_validate_json(next(b.text for b in msg.content if b.type == "text"))
+ d = c.model_dump()
+ v = list(d["scores"].values())
+ d["passed"] = min(v) >= 6 and sum(v) / len(v) >= 7 # a good production base, not a copy of the reference
+ return d
+
+
+# ---------------------------------------------------------------- run
+class SceneBuilder:
+ # what a subclass changes for another job on the same workspace (see shots.py)
+ PROMPT_FILE = "PROMPT.md" # under .builder/
+ ASK = "Build the scene from the reference in input/. Start by reading SKILL.md."
+
+ def __init__(self, work, refs, scene, uploader=None, emit=None, effort="medium", out_rel="out"):
+ self.effort = effort
+ self.work, self.refs, self.scene = work, refs, scene
+ self.out = os.path.join(work, out_rel)
+ os.makedirs(self.out, exist_ok=True)
+ self.t0 = time.time()
+ self.upload = uploader or (lambda p: p)
+ self.events = open(os.path.join(self.out, "events.jsonl"), "a", encoding="utf-8")
+ self.log = open(os.path.join(self.out, "builder.log"), "a", encoding="utf-8")
+ self.critiques = []
+ self.milestones = [] # every milestone so far, repeated in each heartbeat so a late watcher can backfill
+ self.working = None # (description, started) of the tool call in progress
+ self.cap_warned = False
+ self.capped = False # stopped at the platform's 2-hour limit: let it end without a pass
+ self.warned = False
+ self._emit_hook = emit
+
+ # elapsed / remaining
+ def elapsed(self):
+ return time.time() - self.t0
+
+ def emit(self, stage, status="running", message="", image=None, **extra):
+ ev = {"t": round(self.elapsed(), 1), "stage": stage, "status": status, "message": message, **extra}
+ if image:
+ path = image if os.path.isabs(image) else os.path.join(self.work, image)
+ if os.path.exists(path):
+ ev["preview_url"] = self.upload(path)
+ if stage not in ("log", "thinking", "heartbeat", "received", "error", "critique", "done", "packaged"):
+ self.milestones.append({k: ev[k] for k in ("t", "stage", "status", "message", "preview_url") if k in ev})
+ print(PREFIX + json.dumps(ev), flush=True)
+ self.events.write(json.dumps(ev) + "\n")
+ self.events.flush()
+ if self._emit_hook:
+ self._emit_hook(ev)
+
+ def note(self, text):
+ self.log.write(f"[{self.elapsed() / 60:6.1f}m] {text}\n")
+ self.log.flush()
+
+ # ---- MCP tools
+ def tools(self):
+ d = self
+
+ @tool("report", "Post a stage event to the customer's live log, optionally with a rendered image.",
+ {"stage": str, "message": str, "image": str})
+ async def report(args):
+ d.emit(args["stage"], "running", args.get("message", ""), args.get("image") or None)
+ return {"content": [{"type": "text", "text": "reported"}]}
+
+ @tool("critique", "Independent critic: compares the reference with your stills (paths relative to the workspace "
+ "or absolute). Returns scores 1-10 per category, up to five fixes that matter, and "
+ "whether it passes (no category below 6, average 7+).",
+ {"type": "object", "properties": {"stills": {"type": "array", "items": {"type": "string"}}},
+ "required": ["stills"]})
+ async def critique(args):
+ if len(d.critiques) >= MAX_CRITIC_ROUNDS:
+ return {"content": [{"type": "text", "text": (
+ f"The critic has had its {MAX_CRITIC_ROUNDS} rounds; no more reviews. Stop iterating on the look: "
+ "finish every remaining deliverable (previews, shots.json, panoramas, scene.glb, dials.json, "
+ "NOTES.md, the packed scene.blend) and deliver.")}]}
+ paths = [p if os.path.isabs(p) else os.path.join(d.work, p) for p in args["stills"]]
+ missing = [p for p in paths if not os.path.exists(p)]
+ if missing:
+ return {"content": [{"type": "text", "text": f"missing: {missing}"}], "is_error": True}
+ d.emit("critique", "running", f"critic is looking at {len(paths)} stills")
+ res = await asyncio.to_thread(run_critic, d.refs, paths[:6])
+ res["round"] = len(d.critiques) + 1
+ res["stills"] = paths
+ d.critiques.append(res)
+ json.dump(res, open(os.path.join(d.work, "out", "critique", f"round_{res['round']}.json"), "w"), indent=1)
+ sc = res["scores"]
+ d.emit("critique", "done" if res["passed"] else "running",
+ f"round {res['round']}: {'PASS' if res['passed'] else 'not yet'} - "
+ + ", ".join(f"{k} {v}" for k, v in sc.items()), paths[0], critique=res)
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=1)}]}
+
+ return [report, critique]
+
+ # ---- hooks
+ @staticmethod
+ def describe(name, ti, work):
+ if name == "Bash":
+ return ti.get("description") or ti.get("command", "")[:120]
+ if name in ("Write", "Edit"):
+ return f"{'writing' if name == 'Write' else 'editing'} {os.path.relpath(ti.get('file_path', ''), work)}"
+ if name == "Read":
+ p = ti.get("file_path", "")
+ return f"{'looking at' if p.lower().endswith(('.png', '.jpg', '.jpeg')) else 'reading'} {os.path.relpath(p, work)}"
+ return name
+
+ async def pre_tool(self, inp, tool_use_id, ctx):
+ self.working = (self.describe(inp.get("tool_name", ""), inp.get("tool_input") or {}, self.work), time.time())
+ if self.elapsed() > CAP_WARN_S and not self.cap_warned:
+ self.cap_warned = True
+ return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": (
+ "The platform ends this request at 120 minutes and the build is now past 95. Before anything else, make "
+ "sure out/ holds your best current versions of every deliverable (scene.blend, stills, previews, "
+ "shots.json, dials.json, plan.json), then keep improving.")}}
+ return {}
+
+ async def heartbeat(self):
+ """Every 20 s: what is running and for how long, plus the milestones so far. Long renders otherwise look idle,
+ and a page that attaches late (fal's status call returns only the recent log) can fill in its schedule."""
+ while True:
+ await asyncio.sleep(20)
+ w = self.working
+ self.emit("heartbeat", "running", f"{self.elapsed() / 60:.0f} min in",
+ working=w[0] if w else None, working_s=round(time.time() - w[1]) if w else None,
+ milestones=self.milestones[-20:], critique_rounds=len(self.critiques))
+
+ async def post_tool(self, inp, tool_use_id, ctx):
+ self.working = None
+ name = inp.get("tool_name", "")
+ ti = inp.get("tool_input") or {}
+ quiet = name.startswith("mcp__scene__") or name in ("ToolSearch", "TodoWrite")
+ msg = None if quiet else self.describe(name, ti, self.work)
+ if msg:
+ # an image the agent opens is shown to the customer too (its test renders, sheets, plans), so the live view
+ # follows what it is looking at; the customer's own reference is left out
+ p = ti.get("file_path", "") if name == "Read" else ""
+ image = p if p.lower().endswith((".png", ".jpg", ".jpeg")) and "/input/" not in p.replace("\\", "/") else None
+ self.emit("log", "running", msg, image if image and os.path.exists(image) else None, tool=name)
+ self.note(f"{name}: {json.dumps(ti)[:400]}")
+ return {}
+
+ def missing(self):
+ out = os.path.join(self.work, "out")
+ miss = []
+ stills = [f for f in os.listdir(os.path.join(out, "stills")) if f.lower().endswith(".png")]
+ if len(stills) < 3:
+ miss.append(f"out/stills has {len(stills)} stills (need 3+)")
+ pdir = os.path.join(out, "previews")
+ previews = [f for f in os.listdir(pdir) if f.lower().endswith(".png")] if os.path.isdir(pdir) else []
+ if len(previews) < 8:
+ miss.append(f"out/previews has {len(previews)} previews (need 8+)")
+ for f in ("scene.blend", "shots.json", "plan.json", "dials.json"):
+ if not os.path.exists(os.path.join(out, f)):
+ miss.append(f"out/{f}")
+ if not self.critiques:
+ miss.append("no critique yet")
+ elif not self.critiques[-1]["passed"] and len(self.critiques) < MAX_CRITIC_ROUNDS:
+ miss.append("the last critique did not pass")
+ return miss
+
+ def stalled(self):
+ """Three critic rounds in a row without beating the best total so far: the builder is going in circles."""
+ totals = [sum(c["scores"].values()) for c in self.critiques]
+ return len(totals) >= 4 and max(totals[-3:]) <= max(totals[:-3])
+
+ async def on_stop(self, inp, tool_use_id, ctx):
+ miss = self.missing()
+ if miss and not self.stalled() and not self.capped:
+ self.note(f"STOP blocked: {miss}")
+ return {"decision": "block", "reason": "Not done: " + "; ".join(miss) + ". Keep going."}
+ return {}
+
+ def format_prompt(self, text):
+ return text.replace("{scene}", self.scene)
+
+ async def run(self, env):
+ prompt = open(os.path.join(self.work, ".builder", self.PROMPT_FILE), encoding="utf-8").read()
+ prompt = self.format_prompt(prompt)
+ server = create_sdk_mcp_server("scene", tools=self.tools())
+ beat = asyncio.create_task(self.heartbeat())
+ self.emit("received", "running", "scene builder starting")
+ result, session_id, attempt = None, None, 0
+ ask = self.ASK
+ while True:
+ opts = ClaudeAgentOptions(
+ model=env.get("ANTHROPIC_MODEL") or MODEL, effort=self.effort, permission_mode="bypassPermissions",
+ cwd=self.work,
+ system_prompt={"type": "preset", "preset": "claude_code", "append": prompt},
+ mcp_servers={"scene": server}, setting_sources=[], settings='{"fastMode": true}',
+ hooks={"PreToolUse": [HookMatcher(hooks=[self.pre_tool])], "PostToolUse": [HookMatcher(hooks=[self.post_tool])],
+ "Stop": [HookMatcher(hooks=[self.on_stop])]},
+ # tool results come back to us as single JSON lines; a full-size render read as an image is several
+ # MB, and the default 1 MB buffer kills the session
+ max_buffer_size=256 * 1024 * 1024, resume=session_id,
+ env=env, stderr=lambda l: self.note("STDERR " + l[:300]))
+ try:
+ async with ClaudeSDKClient(opts) as client:
+ async def cap_guard():
+ # fal kills the request at 2 h with nothing returned; stop the agent first so the endpoint can
+ # still package and return what is in out/
+ while self.elapsed() < CAP_STOP_S:
+ await asyncio.sleep(15)
+ self.capped = True
+ self.emit("error", "running", "stopping the builder before the platform's 2-hour limit; "
+ "packaging what it has")
+ await client.interrupt()
+ guard = asyncio.create_task(cap_guard())
+ try:
+ await client.query(ask)
+ async for m in client.receive_response():
+ session_id = getattr(m, "session_id", None) \
+ or (getattr(m, "data", None) or {}).get("session_id") or session_id
+ if isinstance(m, AssistantMessage):
+ for b in m.content:
+ if isinstance(b, TextBlock) and b.text.strip():
+ self.note("SAY " + b.text.strip()[:2000])
+ self.emit("thinking", "running", b.text.strip()[:400])
+ elif isinstance(m, ResultMessage):
+ result = m
+ finally:
+ guard.cancel()
+ break
+ except Exception as e: # the session broke (SDK or CLI error): pick the same session back up
+ import traceback
+ if self.capped:
+ break
+ attempt += 1
+ self.note("SESSION ERROR " + traceback.format_exc()[-3000:])
+ self.emit("error", "running", f"agent session error ({type(e).__name__}: {str(e)[:200]}); "
+ f"{'resuming' if attempt <= 3 and session_id else 'giving up'}")
+ if attempt > 3 or not session_id:
+ raise
+ ask = ("The previous turn was cut off by a harness error, not by you. Continue the build from where "
+ "you were; check the state of the workspace first.")
+ beat.cancel()
+ cost = getattr(result, "total_cost_usd", None)
+ self.emit("done", "done", f"scene builder finished after {self.elapsed() / 60:.0f} min"
+ + (f", agent cost ${cost:.2f}" if cost else ""), missing=self.missing(),
+ critiques=len(self.critiques))
+ return result
+
+
+def agent_env():
+ """The agent's environment. Keys come only from the environment (fal secrets on a worker): OPENROUTER_API_KEY
+ (Claude through OpenRouter, the default) or, without it, ANTHROPIC_API_KEY (the Anthropic API directly). FAL_KEY is
+ passed through for the generate/ tools. ANTHROPIC_MODEL in the result is the model id for that provider."""
+ key = user_env("OPENROUTER_API_KEY")
+ direct = None if key else user_env("ANTHROPIC_API_KEY")
+ if not key and not direct:
+ raise RuntimeError("set OPENROUTER_API_KEY or ANTHROPIC_API_KEY (a fal secret on the app)")
+ fal = user_env("FAL_KEY") or os.environ.get("FAL_KEY") or ""
+ common = {"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "BASH_MAX_TIMEOUT_MS": "600000", "FAL_KEY": fal,
+ "IS_SANDBOX": "1"} # the fal worker runs as root in its own container; Claude Code needs this to skip prompts
+ if direct:
+ os.environ["ANTHROPIC_API_KEY"] = direct # the critic (planner._client) then talks to Anthropic directly
+ return {**common, "ANTHROPIC_BASE_URL": "https://api.anthropic.com", "ANTHROPIC_API_KEY": direct,
+ "ANTHROPIC_MODEL": DIRECT_MODEL}
+ env = {**common, "ANTHROPIC_BASE_URL": "https://openrouter.ai/api", "ANTHROPIC_AUTH_TOKEN": key, "ANTHROPIC_API_KEY": "",
+ "ANTHROPIC_MODEL": MODEL, "ANTHROPIC_DEFAULT_OPUS_MODEL": MODEL,
+ "ANTHROPIC_DEFAULT_SONNET_MODEL": "anthropic/claude-sonnet-5.5",
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": "anthropic/claude-haiku-5.5", "OPENROUTER_API_KEY": key}
+ os.environ["OPENROUTER_API_KEY"] = key # the critic (planner._client) reads it
+ os.environ.pop("ANTHROPIC_API_KEY", None)
+ return env
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("refs", nargs="+")
+ p.add_argument("--work", required=True)
+ p.add_argument("--prompt", default="")
+ p.add_argument("--scene", default="scene")
+ p.add_argument("--effort", default="medium")
+ a = p.parse_args()
+ sys.stdout.reconfigure(encoding="utf-8")
+ work = os.path.abspath(a.work)
+ if not os.path.exists(os.path.join(work, "SKILL.md")):
+ make_workspace(work, a.refs, a.prompt, a.scene, toolkit_files())
+ refs = sorted(os.path.join(work, "input", f) for f in os.listdir(os.path.join(work, "input")) if f.startswith("reference_"))
+ d = SceneBuilder(work, refs, a.scene, effort=a.effort)
+ asyncio.run(d.run(agent_env()))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/builder/shots.py b/builder/shots.py
new file mode 100644
index 0000000..b5dafb0
--- /dev/null
+++ b/builder/shots.py
@@ -0,0 +1,315 @@
+"""Scene to images / scene to video: an agent shoots a 3D set (AnyShot, see anyshot/README.md).
+
+Shared by the AnyShot app (anyshot/app.py) and the scene builder's /scene2image and /scene2video (builder/app.py).
+The set is either an AnyScene build's own workspace (/data/anyscene/builder/<build_id>: the finished out/scene.blend,
+the builder's scripts, NOTES.md and its scouting cameras) or an uploaded scene unpacked into a workspace of its own
+(input/scene/). Each order gets a job folder out/shots/<job_id>/ with request.json; the agent blocks every shot with
+quick previews, then renders finals: stills on this worker's GPU, or video frames on a render farm app
+(farm/app.py, named by ANYSHOT_FARM_APP) through the farm_render tool.
+"""
+
+import asyncio
+import hashlib
+import io
+import json
+import os
+import urllib.request
+import zipfile
+
+from claude_agent_sdk import tool
+
+import scene_builder
+from scene_builder import SceneBuilder
+
+# The render farm app (farm/app.py deployed on your own account), e.g. "<your-fal-username>/blender-farm". Read when a
+# farm call is made, so a fal secret set after deploy applies. Unset: farm_render fails and the agent renders the
+# frames on its own GPU instead (slower, same result).
+FARM_APP_ENV = "ANYSHOT_FARM_APP"
+# Frames are spread over farm workers in chunks of at least FARM_MIN_CHUNK frames, up to FARM_WORKERS at once (default
+# 100, the farm app's max_concurrency). Every chunk pays a worker boot, the scene download and Blender loading the set
+# (~2 min together), so small chunks spend most of their GPU time on setup: at 5 frames a chunk that was ~75% of the
+# bill. 24 frames a chunk keeps the wall time to a few minutes while most of each worker's time goes to rendering.
+FARM_PARALLEL = int(os.environ.get("FARM_WORKERS", "100"))
+FARM_MIN_CHUNK = int(os.environ.get("FARM_MIN_CHUNK", "24"))
+# The GPU-forcing startup script every app in this repo writes on its worker (builder/blender_gpu.py)
+BLENDER_GPU_PATH = "/opt/anyscene/blender_gpu.py"
+
+
+def farm_app():
+ return os.environ.get(FARM_APP_ENV, "").strip().strip("/")
+
+
+class ShotsDirector(SceneBuilder):
+ PROMPT_FILE = "SHOTS.md"
+
+ def __init__(self, work, scene, job_id, request, resume=False, **kw):
+ super().__init__(work, [], scene, out_rel=os.path.join("out", "shots", job_id), **kw)
+ self.job_id, self.request = job_id, request
+ self.job = os.path.relpath(self.out, work).replace(os.sep, "/")
+ with open(os.path.join(self.out, "request.json"), "w", encoding="utf-8") as f:
+ json.dump(request, f, indent=1)
+ kind = (request.get("source") or {}).get("kind", "build")
+ if kind == "upload":
+ self.ASK = (f"Shoot the order in {self.job}/request.json. The set is an uploaded scene in input/scene/ (not "
+ f"an AnyScene build). Start by reading the request, camera/README.md and, if an earlier order "
+ f"left one, scenes/{scene}/NOTES.md.")
+ else:
+ self.ASK = (f"Shoot the order in {self.job}/request.json on the built scene. Start by reading "
+ f"scenes/{scene}/NOTES.md, camera/README.md and the request.")
+ if resume:
+ self.ASK += (f" This order was cut off (its request was retried) and is resuming in the same job folder: "
+ f"read {self.job}/builder.log and {self.job}/events.jsonl and look at what is already in "
+ f"{self.job}/ first. Don't redo finished work; farm_render skips frames that already exist.")
+ self.uploads = {}
+
+ def tools(self):
+ d = self
+ report = [t for t in super().tools() if t.name == "report"]
+
+ @tool("farm_render", "Render every frame of the named video shots on the render farm (up to 100 GPUs). "
+ "Reads the cameras from <job>/shots.json and the set from <job>/scene.blend if it exists, "
+ "else out/scene.blend. Frames land in <job>/frames/<shot>/frames/####.png. Returns per-shot "
+ "frame counts and timing. Already-rendered frames are skipped, so it can be called again "
+ "to fill gaps or after changing one shot.",
+ {"type": "object", "properties": {"shots": {"type": "array", "items": {"type": "string"}}},
+ "required": ["shots"]})
+ async def farm_render(args):
+ try:
+ text = await d.farm(args["shots"])
+ return {"content": [{"type": "text", "text": text}]}
+ except Exception as e:
+ return {"content": [{"type": "text", "text": f"farm_render failed: {type(e).__name__}: {e}"}],
+ "is_error": True}
+
+ return report + [farm_render]
+
+ async def farm(self, names):
+ import fal_client
+
+ app = farm_app()
+ if not app:
+ raise RuntimeError(f"no render farm configured ({FARM_APP_ENV} is not set): render the frames on this GPU")
+ shots_path = os.path.join(self.out, "shots.json")
+ cfg = json.load(open(shots_path, encoding="utf-8"))
+ defs = {s["name"]: s for s in cfg["shots"]}
+ unknown = [n for n in names if n not in defs]
+ if unknown:
+ raise ValueError(f"not in {self.job}/shots.json: {unknown}")
+ blend = os.path.join(self.out, "scene.blend")
+ if not os.path.exists(blend):
+ blend = os.path.join(self.work, "out", "scene.blend")
+ if not os.path.exists(blend):
+ raise FileNotFoundError(f"no set to send: save the packed copy as {self.job}/scene.blend first")
+
+ # bundle: the set, the camera rig, these shots and the GPU script; the farm caches it by content hash
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_STORED) as z:
+ z.write(blend, "scene.blend")
+ z.write(shots_path, "shots.json")
+ for n in ("camrig.py", "shoot.py"):
+ z.write(os.path.join(self.work, "camera", n), f"camera/{n}")
+ z.write(BLENDER_GPU_PATH, "blender_gpu.py")
+ data = buf.getvalue()
+ bundle_id = hashlib.sha256(data).hexdigest()[:16]
+ if bundle_id not in self.uploads:
+ path = os.path.join(self.out, f"bundle_{bundle_id}.zip")
+ with open(path, "wb") as f:
+ f.write(data)
+ self.uploads[bundle_id] = await asyncio.to_thread(self.upload, path)
+ os.remove(path)
+ url = self.uploads[bundle_id]
+
+ frames_dir = os.path.join(self.out, "frames")
+ total = sum(int(defs[n].get("frames", cfg.get("defaults", {}).get("frames", 120))) for n in names)
+ chunk = max(FARM_MIN_CHUNK, -(-total // FARM_PARALLEL))
+ jobs = []
+ for name in names:
+ n = int(defs[name].get("frames", cfg.get("defaults", {}).get("frames", 120)))
+ have = {f for f in range(1, n + 1) if os.path.exists(os.path.join(frames_dir, name, "frames", f"{f:04d}.png"))}
+ for a in range(1, n + 1, chunk):
+ b = min(a + chunk - 1, n)
+ if all(f in have for f in range(a, b + 1)):
+ continue
+ args = ["{bundle}/scene.blend", "--python", "{bundle}/blender_gpu.py", "--python",
+ "{bundle}/camera/shoot.py", "--", "--shots", "{bundle}/shots.json", "--out", "{out}",
+ "--only", name, "--frames", f"{a}-{b}", "--no-encode"]
+ jobs.append((name, a, b, {"bundle_url": url, "bundle_id": bundle_id, "blender_args": args}))
+ if not jobs:
+ return "every frame is already rendered"
+ self.emit("farm", "running", f"render farm: {len(jobs)} chunks of up to {chunk} frames on up to {FARM_PARALLEL} GPUs for "
+ f"{', '.join(names)}", bundle_url=url, bundle_id=bundle_id)
+
+ client = fal_client.AsyncClient(key=os.environ.get("FAL_SERVERLESS_KEY") or os.environ.get("FAL_KEY"))
+ sem = asyncio.Semaphore(FARM_PARALLEL)
+ done, failed, gpu_s = 0, [], 0.0
+
+ async def one(job):
+ nonlocal done, gpu_s
+ name, a, b, payload = job
+ async with sem:
+ for attempt in range(3):
+ try:
+ res = await client.subscribe(app, arguments=payload)
+ raw = await asyncio.to_thread(
+ lambda: urllib.request.urlopen(res["frames_url"], timeout=600).read())
+ with zipfile.ZipFile(io.BytesIO(raw)) as z:
+ for member in z.namelist(): # <shot>/frames/####.png
+ dest = os.path.normpath(os.path.join(frames_dir, member))
+ if not dest.startswith(os.path.normpath(frames_dir) + os.sep):
+ continue
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
+ with open(dest, "wb") as f:
+ f.write(z.read(member))
+ done += 1
+ gpu_s += res.get("render_seconds", 0)
+ self.emit("farm", "running", f"{name} frames {a}-{b} in ({done} of {len(jobs)} chunks)",
+ progress=round(done / len(jobs), 3), bundle_s=res.get("bundle_seconds"),
+ blender_s=res.get("render_seconds"))
+ return
+ except Exception as e:
+ err = f"{name} {a}-{b}: {type(e).__name__}: {str(e)[:200]}"
+ failed.append(err)
+
+ await asyncio.gather(*(one(j) for j in jobs))
+ counts = {n: len([f for f in os.listdir(os.path.join(frames_dir, n, "frames"))])
+ if os.path.isdir(os.path.join(frames_dir, n, "frames")) else 0 for n in names}
+ summary = (f"{done} of {len(jobs)} chunks rendered ({gpu_s / 3600:.2f} GPU-h). Frames per shot: {counts}."
+ + (f" Failed (call again to retry): {failed}" if failed else ""))
+ self.emit("farm", "done" if not failed else "running", summary)
+ return summary
+
+ def format_prompt(self, text):
+ return super().format_prompt(text).replace("{job}", self.job)
+
+ def missing(self):
+ mode = self.request.get("mode", "images")
+ # an order given only as a prompt has as many shots as the agent planned (at least one)
+ names = [s.get("name") or f"shot_{i + 1}" for i, s in enumerate(self.request.get("shots", []))] or ["planned"]
+ sub, ext = ("stills", ".png") if mode == "images" else ("video", ".mp4")
+ have = [f for f in os.listdir(os.path.join(self.out, sub))] if os.path.isdir(os.path.join(self.out, sub)) else []
+ miss = []
+ if len([f for f in have if f.endswith(ext)]) < len(names):
+ miss.append(f"{self.job}/{sub} has {len(have)} of {len(names)} {ext} files")
+ if not os.path.exists(os.path.join(self.out, "result.json")):
+ miss.append(f"{self.job}/result.json")
+ return miss
+
+ def stalled(self):
+ return False
+
+
+# ---------------------------------------------------------------- shared by the apps
+def write_toolkit(work, toolkit):
+ """Refresh the shared tools in a workspace (never a scene's own scripts or outputs)."""
+ for rel, text in toolkit.items():
+ path = os.path.join(work, rel)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
+ f.write(text)
+ if rel.endswith(".sh"):
+ os.chmod(path, 0o755)
+
+
+def build_scene_name(work):
+ """The scene folder of an AnyScene build, checking it has something to shoot."""
+ scenes = os.path.join(work, "scenes")
+ if not os.path.isdir(scenes):
+ raise ValueError("no such build")
+ scene = next((d for d in sorted(os.listdir(scenes))), "scene")
+ if not os.path.exists(os.path.join(work, "out", "scene.blend")) \
+ and not os.path.exists(os.path.join(scenes, scene, "scene.blend")):
+ # a build still running (or cut off) has no packed final yet: the agent shoots its working scene
+ raise ValueError("the build has no scene file yet")
+ return scene
+
+
+def _safe_extract(zpath, dest):
+ with zipfile.ZipFile(zpath) as z:
+ for m in z.infolist():
+ name = m.filename.replace("\\", "/")
+ if name.startswith("/") or ".." in name.split("/") or ":" in name.split("/")[0] or "__MACOSX" in name:
+ continue
+ target = os.path.join(dest, *name.split("/"))
+ if m.is_dir():
+ os.makedirs(target, exist_ok=True)
+ continue
+ os.makedirs(os.path.dirname(target), exist_ok=True)
+ with z.open(m) as src, open(target, "wb") as out:
+ while chunk := src.read(8 << 20):
+ out.write(chunk)
+
+
+def fetch_scene(work, scene_url):
+ """Download an uploaded scene once into <work>/input/scene/: a .blend as scene.blend, a .zip unpacked as it is.
+ Concurrent orders on the same upload race harmlessly (each unpacks into its own folder; the first rename wins)."""
+ dest = os.path.join(work, "input", "scene")
+ if os.path.isdir(dest):
+ return dest
+ tmp = os.path.join(work, "input", f"_dl_{os.getpid()}_{os.urandom(3).hex()}")
+ os.makedirs(tmp)
+ raw = os.path.join(tmp, "download")
+ with urllib.request.urlopen(scene_url, timeout=600) as r, open(raw, "wb") as f:
+ while chunk := r.read(8 << 20):
+ f.write(chunk)
+ with open(raw, "rb") as f:
+ head = f.read(8)
+ unpacked = os.path.join(tmp, "scene")
+ os.makedirs(unpacked)
+ if head.startswith(b"PK\x03\x04"):
+ _safe_extract(raw, unpacked)
+ elif head.startswith((b"BLENDER", b"\x28\xb5\x2f\xfd", b"\x1f\x8b")): # plain, zstd- or gzip-compressed .blend
+ name = os.path.basename(scene_url.split("?", 1)[0])
+ name = name if name.lower().endswith(".blend") and name.replace(".", "").replace("_", "").replace("-", "").isalnum() \
+ else "scene.blend"
+ os.replace(raw, os.path.join(unpacked, name))
+ else:
+ raise ValueError("scene_url must point to a .blend or a .zip holding one")
+ blends = [os.path.join(r, n) for r, _, ns in os.walk(unpacked) for n in ns if n.lower().endswith(".blend")]
+ if not blends:
+ raise ValueError("the uploaded zip holds no .blend file")
+ try:
+ os.rename(unpacked, dest)
+ except OSError:
+ if not os.path.isdir(dest):
+ raise
+ import shutil
+ shutil.rmtree(tmp, ignore_errors=True)
+ return dest
+
+
+def fetch_floor_plan(url, job_dir):
+ """The order's floor plan as <job>/floor_plan.png (any image format in)."""
+ from PIL import Image
+ src = os.path.join(job_dir, "floor_plan_src")
+ urllib.request.urlretrieve(url, src)
+ Image.open(src).convert("RGB").save(os.path.join(job_dir, "floor_plan.png"))
+ os.remove(src)
+
+
+async def shoot(work, scene, job_id, request, uploader, effort="medium", resume=False):
+ """Run the shots agent on one order. Returns (director, response dict: stills, videos, result, missing, cost)."""
+ d = ShotsDirector(work, scene, job_id, request, resume=resume, uploader=uploader, effort=effort)
+ src = request.get("source") or {}
+ d.emit("received", "running", f"{'resuming ' if resume else ''}{request.get('mode')} job {job_id} on "
+ f"{src.get('build_id') or 'an uploaded scene'}: {len(request.get('shots', []))} shot(s)",
+ source=src, mode=request.get("mode"), shots=request.get("shots"), settings=request.get("settings"),
+ dials=request.get("dials"), floor_plan_url=request.get("floor_plan_url"))
+ result = None
+ try:
+ result = await d.run(scene_builder.agent_env())
+ except Exception as e: # deliver whatever exists rather than a bare 500
+ import traceback
+ print(traceback.format_exc(), flush=True)
+ d.emit("error", "failed", f"shots stopped: {type(e).__name__}: {str(e)[:300]}")
+
+ def files(sub, ext):
+ p = os.path.join(d.out, sub)
+ return [uploader(os.path.join(p, f)) for f in sorted(os.listdir(p)) if f.lower().endswith(ext)] \
+ if os.path.isdir(p) else []
+ rpath = os.path.join(d.out, "result.json")
+ try:
+ res_json = json.load(open(rpath, encoding="utf-8")) if os.path.exists(rpath) else {}
+ except ValueError:
+ res_json = {}
+ return d, {"job_id": job_id, "stills": files("stills", ".png"), "videos": files("video", ".mp4"),
+ "result": res_json, "missing": d.missing(), "agent_cost_usd": getattr(result, "total_cost_usd", None)}
diff --git a/docs/ANYKIT.md b/docs/ANYKIT.md
new file mode 100644
index 0000000..7ac2abe
--- /dev/null
+++ b/docs/ANYKIT.md
@@ -0,0 +1,133 @@
+# AnyKit
+
+`kit/app.py`, deployed on fal Serverless as `<your-fal-username>/anykit` (private). One request = one Claude agent (Opus 5.5 via OpenRouter, fast mode, effort
+`medium` by default) on a GPU worker that builds a **kit**: a set of static 3D props in one style, at real-world
+scale, from 1-4 style reference images. Part of the AnyAll family: AnyScene builds scenes, AnyKit builds the props
+that go in them.
+
+It is agent-driven, not a fixed pipeline. The agent plans the kit, generates a style-conditioned reference per item
+(GPT Image 2.5 edit with the customer's images as input), sends every reference to Tripo H3.1 and Meshy 7.1, compares
+them under the same light, picks, normalises, fixes by script what looks wrong, renders a lineup and thumbnails, and
+loops with an independent critic until it passes. Code: `kit/` (`app.py`, `kit_builder.py`, `PROMPT.md`, `KIT.md`,
+`gen.mjs`, `tools/`). It reuses the scene builder's session, hooks, heartbeat, cap guard and container
+(`builder/scene_builder.py`, `builder/app.py`).
+
+```
+POST /kit style references (+ prompt, items, dials) -> kit (per-item GLB + LOD1 + thumbnail), kit.blend, lineup
+POST /smoke {"reference_image_urls": []} -> container, agent and critic check
+```
+
+Both run on the fal queue (`https://queue.fal.run/<your-fal-username>/anykit/kit`). A kit takes roughly 40-110 minutes; the request
+is capped at 2 hours (the agent is stopped at 110 minutes and whatever is in `out/` is packaged).
+
+```
+export ANYKIT_APP=<your-fal-username>/anykit # or pass --app
+uv run --python 3.13 --with fal-client python kit/client.py kit ref.png --prompt "1970s mission-control desk clutter" \
+ --dial count=9 --dial wear=0.4 --out kit_out
+```
+
+## Request
+
+```jsonc
+{
+ "reference_image_urls": ["https://..."], // 1-4 style references (required); more than 4 are ignored
+ "prompt": "1970s mission-control desk clutter, 8-10 items", // optional
+ "items": ["rotary desk phone", "ashtray"], // optional: built exactly, in this order
+ "dials": { "count": 9, "wear": 0.4 }, // optional, see below
+ "effort": "medium" // agent effort: low | medium | high | xhigh | max
+}
+```
+
+### Dials
+
+Plain settings the agent builds to. A dial that is set is an instruction, even when the reference says otherwise. A
+dial left out gets ONE value read from the references and prompt. There are no variants and no switchable rigs. The
+values used come back in the response's `dials`, each with its `source`.
+
+| Dial | Range | Controls |
+|---|---|---|
+| `count` | integer | how many items (default: the item list's length, else the prompt, else 8) |
+| `variety` | 0 - 1 | 0 = variations of one object family (matching mugs, jars); 1 = a broad mix that only shares the style |
+| `detail` | `low` \| `medium` \| `high` | per-item budget: low <= 20k tris, 1K textures; medium <= 100k, 2K; high <= 200k, 2K. LOD1 is ~1/4 the tris, half-size textures |
+| `wear` | 0 pristine - 1 decayed | dirt, scratches, chips, fading |
+| `wetness` | 0 dry - 1 soaked | water on surfaces |
+| `warmth` | -1 cold - 1 warm | palette colour temperature and the presentation light |
+| `look` | `clean` \| `cinematic` \| `gritty` \| `vintage` | surface finish and the presentation renders' grade |
+
+## Response
+
+```jsonc
+{
+ "kit_id": "k_3f9a1c2b7d",
+ "name": "Apollo-era flight desk",
+ "style": "one paragraph: era, palette, materials, wear, fictional maker",
+ "items": [
+ {
+ "id": "rotary_phone",
+ "label": "Rotary desk phone",
+ "dims_m": [0.22, 0.24, 0.13], // width x (X), depth y (Y), height z (Z), metres
+ "tris": 98000, "tris_lod1": 24500,
+ "generator": "meshy", // meshy | tripo-h31 (the pick)
+ "why": "sharper dial numerals; Tripo fused the handset to the cradle",
+ "glb_url": "https://...", // LOD0: metres, bottom-centre origin, front faces -Y, textures <= 2K
+ "lod1_url": "https://...",
+ "thumb_url": "https://...", // 1024 px, three-quarter front
+ "turntable_url": null // mp4, when the agent made one
+ }
+ ],
+ "lineup_url": "https://...", // 2400 x 1000: every item on a neutral ground, labels, scale bar
+ "kit_blend_url": "https://...", // asset library: every item marked as an asset, LOD1s in a hidden collection
+ "kit_json_url": "https://...", // out/kit.json (the items above + tags and the fixes made per item)
+ "package_url": "https://...", // zip: out/ (GLBs, renders, kit.blend, kit.json, dials.json, critique/),
+ // scenes/kit/ (the agent's scripts, NOTES.md), refs/kit/ (item references)
+ "critiques": [
+ { "round": 1, "passed": false, "summary": "...", "fixes": ["..."],
+ "scores": { "cohesion": 7, "reference_fidelity": 8, "brief": 8, "mesh_quality": 6,
+ "texture_quality": 7, "assembly": 7, "scale": 8, "labels": 6 } }
+ ],
+ "dials": { "wear": { "value": 0.4, "source": "customer", "means": "scuffed bakelite, worn paint on edges" } },
+ "missing": [], // deliverables not produced (empty when complete)
+ "agent_cost_usd": 18.2, // Claude agent (OpenRouter)
+ "generation_cost_usd": 31.5, // fal generation, estimated from the spend log
+ "minutes": 64.3
+}
+```
+
+The kit passes when no critic score is below 6 and the average is 7 or more: a production-ready base a studio's
+artists then refine, judged at normal viewing distance, with the reference setting the world rather than designs to
+copy. The critic lists at most five fixes, only ones that would stop a studio using the kit. `assembly` checks that parts that belong together are connected
+and seated (cords plugged in at both ends, handsets on cradles, lamp heads on arms, lids on hinges). The critic gets at
+most 8 rounds (`MAX_CRITIC_ROUNDS`, shared with the scene builder); after the 8th the kit is delivered as it stands. The critic sees the style references, the lineup, up to 10
+thumbnails and each item's dims. A kit stopped at the time cap or after three critic rounds without improvement is
+still returned, with the last critique and `missing` saying what is short.
+
+## Events
+
+Same transport and format as the scene builder, so `web/lib/builder.ts` can consume them unchanged. The worker prints
+one line per event, `ANYSCENE_STAGE {json}`, and the fal queue relays them as logs (`with_logs=true` on status or
+subscribe). Every event:
+
+```jsonc
+{ "t": 312.4, // seconds since the build started
+ "stage": "references", // see below
+ "status": "running", // running | done | failed
+ "message": "one plain sentence",
+ "preview_url": "https://..." // optional image
+ /* + stage-specific fields */ }
+```
+
+| Stage | Kind | Meaning / extra fields |
+|---|---|---|
+| `received` | system | first event; message `build k_<id>: kit from N style reference(s)`; `reference_urls`, `prompt`, `items`, `dials`, `effort` |
+| `log` | tool | one per agent tool call (`tool`: Bash, Read, Write...); `preview_url` when the agent opened an image |
+| `thinking` | note | the agent's own words |
+| `heartbeat` | status | every 20 s: `working`, `working_s`, `critique_rounds`, `milestones` (every milestone so far, for late attach) |
+| `critique` | critic | `status: running` without `critique` = the critic is looking; with `critique` = a round's result (`round`, `scores`, `passed`, `summary`, `fixes`, `stills`) |
+| `error` | system | a harness error being resumed, or the time cap; `status: failed` when the build stopped |
+| `done` | system | the agent finished; `missing`, `critiques` |
+| `packaged` | system | last event; `package_url`, `lineup_url` |
+| anything else | milestone | reported by the agent with its best current image: normally `plan`, `references`, `models`, `picks`, `prep`, `fixes`, `lineup`, `finals`, `done`, in that order, with retakes allowed |
+
+The milestone names are the agent's choice within that list; treat any unknown stage as a milestone (as
+`builder.ts` does). The `received` message uses the word `build` so the existing `/build (b_\w+)/`-style id parse can
+be widened to `/build ([bk]_\w+)/`.
diff --git a/docs/ENDPOINT.md b/docs/ENDPOINT.md
new file mode 100644
index 0000000..1c213a7
--- /dev/null
+++ b/docs/ENDPOINT.md
@@ -0,0 +1,155 @@
+# reference-to-scene
+
+A fal Serverless app that turns one or more reference images into a lit, dressed Blender scene and returns it as a
+package. Two calls, with an optional approval stop between them:
+
+```
+POST /plan reference images (+ optional floor plan, prompt) -> plan_id, floor plan, grey-box renders, prop list
+POST /plan plan_id + edit (text or JSON) -> revised plan (repeat as needed)
+POST /build plan_id (or reference images + auto_approve) -> package zip + scene.blend + props + renders
+```
+
+Both run on the fal queue and stream their progress as stage events (see Progress). The app lives in `endpoint/`;
+final renders go to the `blender-farm` app (`farm/`). A third call, `/scene-to-scene`, changes a built scene's dials
+(see Dials) and re-renders it.
+
+## Dials
+
+Ten optional controls, each changing one aspect of the scene and meaningful for any kind of place (a diner, a
+forest camp, a spaceship bridge). Unset dials are read from the references and prompt. The plan records the value
+each dial resolved to and what it means for this scene, so a caller can see "wear 0.62" and nudge it.
+
+| Group | Dial | Range | Changes (and only this) | Cost to change |
+|---|---|---|---|---|
+| Stuff | `density` | 0 - 1 | how much is in the space: items per surface and per m² | placement pass + new props |
+| | `tidiness` | 0 messy - 1 tidy | how things are arranged, not how many: scattered, tipped, piled vs aligned, stacked, put away | placement pass |
+| Surfaces | `wear` | 0 pristine - 1 decayed | age and condition: dirt, scratches, stains, rust, peeling, moss | re-render |
+| | `wetness` | 0 dry - 1 soaked | water on surfaces, puddles | re-render |
+| Environment | `time_of_day` | dawn, day, dusk, night | sky, sun or moon, daylight through openings | re-render |
+| | `weather` | clear, overcast, rain, fog, snow | sky and falling particles | re-render |
+| | `atmosphere` | 0 clear - 1 thick | particles in the air: dust, haze, smoke, steam | re-render |
+| Energy | `power` | 0 dormant - 1 live | whether the place is switched on: screens, fires, machines, practical lights, steam | re-render |
+| Look | `warmth` | -1 cold - +1 warm | colour temperature of the lights and grade | re-render |
+| | `look` | clean, cinematic, gritty, vintage | grade, grain, lens effects | re-render |
+
+The dials are independent. Two couplings are defaults only: `weather: rain` raises `wetness` unless it is set, and
+`time_of_day: night` lowers ambient light while `power` decides what is lit. "Peak service" is roughly
+`density 0.8, tidiness 0.3, power 1`; the same place "after close" is `tidiness 0.9, power 0.15`.
+
+In the plan each dial carries its value and its meaning for this scene:
+```jsonc
+"dials": {
+ "wear": { "value": 0.65, "means": "grease film on steel, chipped green paint on the cart, soot above the burners" },
+ "power": { "value": 0.9, "means": "wok burners lit, bare bulbs and neon on, steam from the stock pots" },
+ "tidiness": { "value": 0.4, "means": "stools scattered off-square, newspapers left on tables, crates stacked unevenly" }
+}
+```
+
+The build agent builds every scene as a rig: one control per dial (a strength input on the shared grime group, a
+wetness mask, an atmosphere density, named light and emitter groups for `power`, and so on), recorded in the
+package's `dials.json` with an `apply_dials.py` that sets them. `/scene-to-scene` diffs the requested dials against
+the scene's: re-render-only dials skip planning and generation; `density` and `tidiness` run a placement pass first.
+
+```jsonc
+POST /scene-to-scene
+{ "scene_id": "s_…", "dials": { "wetness": 0.0, "time_of_day": "dawn" }, // the dry morning version
+ "preview": "wear", // optional: one still at three values of this dial before committing
+ "renders": ["stills"] } // or the shots too
+```
+
+## Coordinates
+
+Metres, Z up. The origin is the floor at the room's front-left corner, seen from the street/entrance:
+X runs right along the front wall, Y runs into the room, Z up. Walls are named `front` (y = 0), `back` (y = depth),
+`left` (x = 0) and `right` (x = width). A rotation of 0 means the object's front faces -Y (towards the entrance).
+
+## Plan
+
+```jsonc
+{
+ "plan_id": "p_7f3a2c",
+ "name": "hk-dai-pai-dong",
+ "summary": "Open-air street-food stall under a tarp awning, late at night after rain",
+ "setting": "semi_outdoor", // interior | semi_outdoor | exterior
+ "time_of_day": "night", "mood": ["humid", "busy", "neon"], "palette": ["#2b3a2f", "#c0392b", "#f5b041"],
+ "room": { "width": 6.0, "depth": 8.0, "height": 3.2 },
+ "openings": [ { "wall": "front", "kind": "shopfront", "center": 3.0, // center = X on front/back walls, Y on left/right
+ "width": 5.0, "height": 2.6, "sill": 0.0 } ],
+ "objects": [
+ { "id": "kitchen_cart", "label": "green steel kitchen cart", "category": "furniture",
+ "x": 1.1, "y": 5.5, "z": 0.0, "w": 2.2, "d": 0.8, "h": 1.0, "rot": 90,
+ "source": "reference", "generate": true,
+ "prompt": "battered green-painted steel street-food kitchen cart with two wok burners",
+ "crop": [0.04, 0.18, 0.46, 0.66] } // where it is in reference image 0, normalised x0,y0,x1,y1
+ ],
+ "lights": [ { "id": "bulb_1", "kind": "practical", "x": 1.0, "y": 5.0, "z": 2.4, "color": "#ffb46b", "power": "medium" } ],
+ "reference_camera": { "position": [3.0, -2.5, 1.6], "look_at": [2.6, 5.0, 1.0], "lens_mm": 28 },
+ "notes": ["The area behind the reference camera is invented: a second row of tables and a drinks fridge."]
+}
+```
+
+Every object and light carries `source`: `reference` (visible in a reference image) or `invented` (added to complete
+the space). The floor plan draws invented items dashed, so a reviewer sees at a glance what was extrapolated.
+
+## /plan
+
+Input
+| field | type | |
+|---|---|---|
+| `reference_image_urls` | string[] (1-4) | the look: mood, materials, props |
+| `floor_plan_url` | string, optional | a sketch, photo or drawing of the layout; overrides inferred room shape and placement |
+| `prompt` | string, optional | anything the images can't show ("rain outside", "it's 1 AM", "make it twice as deep") |
+| `plan_id` + `edit` | string + string | revise an existing plan from a text instruction |
+| `plan_id` + `plan` | string + object | replace an existing plan with an edited JSON version |
+
+Output
+| field | |
+|---|---|
+| `plan_id` | id for /build or another /plan revision |
+| `plan` | the Plan JSON above |
+| `floor_plan` | top-down drawing (PNG): walls, openings, every footprint labelled, lights, reference camera |
+| `blockout` | grey-box renders (PNG): one from the reference camera, one high three-quarter overview |
+| `comparison` | reference and blockout side by side (PNG) |
+
+## /build
+
+Input: `plan_id`, or the /plan inputs plus `auto_approve: true`; `tier` (`draft` | `full`); `num_stills` (default 3);
+`walkthrough` (bool); `resolution` (default `[1920, 804]`).
+
+Output: `package` (zip), `scene_blend`, `props` (id, mesh, preview, reference crop, model), `stills`, `walkthrough`,
+`manifest`, `timings`, `cost`.
+
+Package layout
+```
+scene_package.zip
+ scene.blend packed textures, lights, cameras; opens standalone
+ props/<id>.glb cleaned, real-scale, front -Y, bottom-centre origin
+ props/<id>_ref.png the reference each prop was generated from
+ renders/still_*.png Cycles stills, including one from the reference camera
+ renders/walkthrough.mp4 handheld walk-through (if requested)
+ plan.json, manifest.json props + picks + reasons, lights, shots, costs, timings
+ README.md, LICENSE
+```
+
+## Progress
+
+Each request streams stage events through the fal queue logs, one JSON object per line prefixed `ANYSCENE_STAGE `:
+```json
+{"stage": "generating_meshes", "status": "running", "message": "41 of 80 meshes done", "progress": 0.51,
+ "preview_url": "https://..."}
+```
+Stages, in order:
+| /plan | /build |
+|---|---|
+| `received` | `received` |
+| `reading_reference` | `prop_references` (crop + clean each prop from the reference) |
+| `planning` | `generating_meshes` (all submitted at once) |
+| `drawing_floor_plan` | `layout` (shell + stand-ins, runs during mesh generation) |
+| `blockout` | `dressing` (meshes swapped in, collision check) |
+| `done` | `materials` (textures, grime, decals) |
+| | `lighting` (practicals, atmosphere, critic pass vs the reference) |
+| | `rendering` (farm: stills + walkthrough) |
+| | `packaging` |
+| | `done` |
+
+A failed stage emits `"status": "failed"` with a message, and the request fails with the same message.
diff --git a/docs/media/bakery.jpg b/docs/media/bakery.jpg
new file mode 100644
index 0000000..4ab5ca8
Binary files /dev/null and b/docs/media/bakery.jpg differ
diff --git a/docs/media/bakery_reference.jpg b/docs/media/bakery_reference.jpg
new file mode 100644
index 0000000..10a87ab
Binary files /dev/null and b/docs/media/bakery_reference.jpg differ
diff --git a/docs/media/hk.jpg b/docs/media/hk.jpg
new file mode 100644
index 0000000..7734536
Binary files /dev/null and b/docs/media/hk.jpg differ
diff --git a/docs/media/mc.jpg b/docs/media/mc.jpg
new file mode 100644
index 0000000..97207e7
Binary files /dev/null and b/docs/media/mc.jpg differ
diff --git a/docs/media/ramen.jpg b/docs/media/ramen.jpg
new file mode 100644
index 0000000..caf2e18
Binary files /dev/null and b/docs/media/ramen.jpg differ
diff --git a/docs/media/repair.jpg b/docs/media/repair.jpg
new file mode 100644
index 0000000..09c0dec
Binary files /dev/null and b/docs/media/repair.jpg differ
diff --git a/docs/media/strip.jpg b/docs/media/strip.jpg
new file mode 100644
index 0000000..30d4d82
Binary files /dev/null and b/docs/media/strip.jpg differ
diff --git a/endpoint/app.py b/endpoint/app.py
new file mode 100644
index 0000000..d4f72c6
--- /dev/null
+++ b/endpoint/app.py
@@ -0,0 +1,430 @@
+"""AnyScene reference-to-scene, as a fal Serverless app (see docs/ENDPOINT.md).
+
+ fal deploy endpoint/app.py::AnyScene --app-name anyscene --auth private
+ python endpoint/client.py plan <reference image url or path> [...] streams the stage events
+
+POST /plan reference images (+ optional floor plan, prompt), or plan_id + edit/plan -> plan, floor plan, blockout
+ renders, side-by-side comparison. Plans are kept under /data so /build and later edits can reload them.
+Each request prints stage events (stages.py) that the fal queue streams to the caller as logs.
+"""
+
+import json
+import os
+import subprocess
+import sys
+import uuid
+from pathlib import PurePosixPath
+
+import fal
+from fal.container import ContainerImage
+from pydantic import BaseModel, Field
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import floorplan # noqa: E402
+import planner # noqa: E402
+import props # noqa: E402 (bundled by value, so it must be imported here, not inside a route)
+import refine # noqa: E402
+from schema import Plan # noqa: E402
+from stages import Stages # noqa: E402
+
+if os.name == "nt":
+ # Deploying from Windows: ContainerImage's context_dir default is a WindowsPath that Linux can't unpickle
+ # (same workaround as farm/app.py).
+ _posix = PurePosixPath("/tmp")
+ ContainerImage.__dataclass_fields__["context_dir"].default = _posix
+ ContainerImage.context_dir = _posix
+ ContainerImage.__init__.__defaults__ = tuple(
+ _posix if isinstance(d, os.PathLike) else d for d in ContainerImage.__init__.__defaults__ or ()
+ )
+
+BLENDER_VERSION = "5.0.1"
+# The Blender side runs as script files; carry their source in the app so the worker can write them out.
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_read = lambda *p: open(os.path.join(_HERE, *p), encoding="utf-8").read()
+BLENDER_SCRIPTS = {
+ "blockout.py": _read("blockout.py"),
+ "assemble.py": _read("assemble.py"),
+ "refine_blender.py": _read("refine_blender.py"),
+ "camera/camrig.py": _read("..", "camera", "camrig.py"),
+ "camera/shoot.py": _read("..", "camera", "shoot.py"),
+ "gpu_prefs.py": '''import bpy
+prefs = bpy.context.preferences.addons["cycles"].preferences
+for kind in ("OPTIX", "CUDA"):
+ try:
+ prefs.compute_device_type = kind
+ prefs.get_devices()
+ if any(d.type == kind for d in prefs.devices):
+ for d in prefs.devices:
+ d.use = d.type == kind
+ break
+ except TypeError:
+ continue
+for sc in bpy.data.scenes:
+ sc.cycles.device = "GPU"
+''',
+}
+SCRIPTS_DIR = "/tmp/anyscene_scripts"
+SCENES_DIR = "/data/anyscene/scenes"
+
+DOCKERFILE = f"""
+FROM python:3.13-slim
+ENV NVIDIA_DRIVER_CAPABILITIES=all
+RUN apt-get update && apt-get install -y --no-install-recommends \\
+ curl ca-certificates xz-utils fonts-dejavu-core libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 libegl1 \\
+ libxkbcommon0 libsm6 libice6 libx11-6 libglib2.0-0 \\
+ && rm -rf /var/lib/apt/lists/*
+RUN curl -fsSL https://download.blender.org/release/Blender{BLENDER_VERSION[:3]}/blender-{BLENDER_VERSION}-linux-x64.tar.xz \\
+ | tar -xJ -C /opt \\
+ && ln -s /opt/blender-{BLENDER_VERSION}-linux-x64/blender /usr/local/bin/blender
+"""
+
+PLANS_DIR = "/data/anyscene/plans"
+
+
+class PlanRequest(BaseModel):
+ reference_image_urls: list[str] = Field(default_factory=list, description="1-4 reference images (the look).")
+ floor_plan_url: str | None = Field(None, description="Optional sketch/photo/drawing of the layout.")
+ prompt: str = Field("", description="Anything the images can't show.")
+ plan_id: str | None = Field(None, description="Revise this plan instead of starting a new one.")
+ edit: str = Field("", description="With plan_id: a change to apply, in words.")
+ plan: dict | None = Field(None, description="With plan_id: a full replacement plan (edited JSON).")
+ effort: str = Field("high", description="Claude effort for planning: low, medium, high, xhigh, max (fast mode is on).")
+
+
+class PlanResponse(BaseModel):
+ plan_id: str
+ plan: dict
+ floor_plan_url: str
+ blockout_reference_url: str
+ blockout_overview_url: str
+ comparison_url: str
+ timings: dict
+
+
+def _save(plan_id: str, plan: Plan, refs: list[str], parent: str | None):
+ os.makedirs(PLANS_DIR, exist_ok=True)
+ with open(f"{PLANS_DIR}/{plan_id}.json", "w", encoding="utf-8") as f:
+ json.dump({"plan": plan.model_dump(), "reference_image_urls": refs, "parent": parent}, f)
+
+
+def _load(plan_id: str) -> dict:
+ if not plan_id.replace("_", "").isalnum():
+ raise ValueError("bad plan_id")
+ with open(f"{PLANS_DIR}/{plan_id}.json", encoding="utf-8") as f:
+ return json.load(f)
+
+
+class BuildRequest(BaseModel):
+ plan_id: str = Field(description="An approved plan from /plan.")
+ tier: str = Field("draft", description="draft: one 3D model per prop, mesh deadline; full: both models, no deadline.")
+ mesh_deadline_s: float = Field(480, description="Draft: start assembling with stand-ins after this long.")
+ late_mesh_wait_s: float = Field(240, description="Draft: extra time for late meshes before packaging.")
+ still_samples: int = Field(128, description="Cycles samples for the stills.")
+ include_glbs: bool = Field(False, description="Also put every prop's full-resolution GLB in the package.")
+ refine: bool = Field(True, description="Light screens, lamps and glowing panels, make glass clear, texture scripted pieces.")
+ panoramas: bool = Field(True, description="Equirectangular Cycles panoramas from each camera, for the 360 view.")
+ scene_glb: bool = Field(True, description="A web-weight scene.glb (decimated, 1K textures, lights) for the 360 view.")
+
+
+class BuildResponse(BaseModel):
+ scene_id: str
+ package_url: str
+ scene_blend_url: str
+ stills: list[str]
+ panorama_urls: dict = Field(default_factory=dict)
+ scene_glb_url: str | None = None
+ props: list[dict]
+ standins_left: list[str]
+ timings: dict
+
+
+class AnyScene(fal.App):
+ machine_type = ["GPU-RTX5090", "GPU-RTXPRO6000"]
+ image = ContainerImage.from_dockerfile_str(DOCKERFILE)
+ requirements = ["pydantic", "anthropic", "pillow", "fal==1.84.0", "fal-client"]
+ local_python_modules = ["schema", "planner", "floorplan", "stages", "props", "refine"]
+ min_concurrency = 0
+ max_concurrency = 10
+ request_timeout = 3600
+ startup_timeout = 1200
+
+ def setup(self):
+ for rel, src in BLENDER_SCRIPTS.items():
+ path = os.path.join(SCRIPTS_DIR, rel)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(src)
+ self.blockout_path = os.path.join(SCRIPTS_DIR, "blockout.py")
+
+ @fal.endpoint("/build")
+ async def build(self, req: BuildRequest) -> BuildResponse:
+ import asyncio
+ import shutil
+ import time
+ import zipfile
+
+ from fal.toolkit import File
+
+
+ st = Stages()
+ t0 = time.time()
+ timings = {}
+ upload = lambda path, ctype: File.from_path(path, content_type=ctype).url
+
+ async def blender(*args, timeout=1800):
+ proc = await asyncio.to_thread(subprocess.run, ["blender", "-b", *args], capture_output=True, text=True,
+ timeout=timeout)
+ out = proc.stdout + proc.stderr
+ if proc.returncode != 0:
+ raise RuntimeError(f"blender failed ({proc.returncode}):\n{out[-2000:]}")
+ return out
+
+ try:
+ st.start("received", f"build {req.plan_id} ({req.tier})")
+ saved = _load(req.plan_id)
+ plan = Plan.model_validate(saved["plan"])
+ scene_id = "s_" + uuid.uuid4().hex[:10]
+ work = os.path.join(SCENES_DIR, scene_id)
+ os.makedirs(work, exist_ok=True)
+ with open(f"{work}/plan.json", "w", encoding="utf-8") as f:
+ json.dump(plan.model_dump(), f)
+
+ # 1-2: every prop reference and mesh at once; per-prop events feed the UI's prop shelf
+ report = lambda stage, msg, prog, **extra: st.emit(stage, "running", msg, prog, **extra)
+ gen = props.Generation(plan, saved["reference_image_urls"][0], f"{work}/props", req.tier, report)
+ gen.start()
+ left = await gen.wait(req.mesh_deadline_s if req.tier == "draft" else None)
+ timings["meshes_s"] = round(time.time() - t0, 1)
+ st.done("generating_meshes", f"{gen.done} of {len(gen.assets)} props ready, {left} still running")
+
+ # 3-4: assemble from the plan, stand-ins for anything not here yet
+ st.start("layout", "building the scene from the plan")
+ t1 = time.time()
+ await blender("--factory-startup", "--python", f"{SCRIPTS_DIR}/assemble.py", "--",
+ "build", f"{work}/plan.json", f"{work}/props/assets.json", work)
+ timings["assemble_s"] = round(time.time() - t1, 1)
+
+ async def preview(name):
+ # quick lit look from the reference camera for the live view
+ cfg = json.load(open(f"{work}/shots.json"))
+ cfg["defaults"].update(samples=16, res=[960, 402])
+ cfg["shots"] = cfg["shots"][:1]
+ json.dump(cfg, open(f"{work}/preview_shots.json", "w"))
+ shutil.rmtree(f"{work}/preview", ignore_errors=True)
+ await blender(f"{work}/scene.blend", "--python", f"{SCRIPTS_DIR}/gpu_prefs.py", "--python",
+ f"{SCRIPTS_DIR}/camera/shoot.py", "--", "--shots", f"{work}/preview_shots.json", "--out",
+ f"{work}/preview", "--frames", "1-1", "--no-encode")
+ return upload(f"{work}/preview/ref_view/frames/0001.png", "image/png")
+
+ st.done("layout", f"{len(plan.objects)} objects placed, {left} stand-ins", preview_url=await preview("layout"))
+
+ # 5: give late meshes a little longer, then swap them in
+ if left and req.tier == "draft":
+ st.start("dressing", f"waiting up to {req.late_mesh_wait_s:.0f} s for {left} late meshes")
+ left = await gen.wait(req.late_mesh_wait_s)
+ gen.snapshot()
+ out = await blender(f"{work}/scene.blend", "--python", f"{SCRIPTS_DIR}/assemble.py", "--",
+ "swap", f"{work}/props/assets.json", work)
+ swap_line = next((l for l in out.splitlines() if l.startswith("assemble: swapped")), "")
+ st.done("dressing", swap_line.replace("assemble: ", ""), preview_url=await preview("dressed"))
+
+ # 5b: refine: Claude marks screens, glass, lamps and glowing panels on each prop's front view; screen
+ # content and box textures are generated; Blender applies them
+ if req.refine:
+ st.start("refine", "finding screens, glass and lamps")
+ t5 = time.time()
+ await blender(f"{work}/scene.blend", "--python", f"{SCRIPTS_DIR}/refine_blender.py", "--",
+ "views", f"{work}/refine/views")
+ await refine.build_refine(plan, gen.assets, f"{work}/refine/views", f"{work}/refine", report)
+ out = await blender(f"{work}/scene.blend", "--python", f"{SCRIPTS_DIR}/refine_blender.py", "--",
+ "apply", f"{work}/refine/refine.json", f"{work}/refined")
+ os.replace(f"{work}/refined/scene.blend", f"{work}/scene.blend")
+ line = next((l for l in out.splitlines() if l.startswith("refine: applied")), "refine: applied")
+ timings["refine_s"] = round(time.time() - t5, 1)
+ st.done("refine", line.replace("refine: ", ""), preview_url=await preview("refined"))
+
+ # 6: final stills on this worker's GPU
+ st.start("rendering", "stills from the reference camera and two open views")
+ t2 = time.time()
+ cfg = json.load(open(f"{work}/shots.json"))
+ cfg["defaults"]["samples"] = req.still_samples
+ json.dump(cfg, open(f"{work}/shots.json", "w"))
+ await blender(f"{work}/scene.blend", "--python", f"{SCRIPTS_DIR}/gpu_prefs.py", "--python",
+ f"{SCRIPTS_DIR}/camera/shoot.py", "--", "--shots", f"{work}/shots.json", "--out",
+ f"{work}/renders", "--frames", "1-1", "--no-encode", timeout=1200)
+ stills = []
+ for shot in cfg["shots"]:
+ src = f"{work}/renders/{shot['name']}/frames/0001.png"
+ if os.path.exists(src):
+ url = upload(src, "image/png")
+ stills.append(url)
+ st.emit("rendering", "running", f"{shot['name']} done", preview_url=url)
+ timings["render_s"] = round(time.time() - t2, 1)
+ st.done("rendering", f"{len(stills)} stills")
+
+ # 6b: panoramas (GPU) and the web scene.glb (CPU) side by side, for the 360 view
+ panorama_urls, scene_glb_url = {}, None
+
+ async def panoramas():
+ await blender(f"{work}/scene.blend", "--python", f"{SCRIPTS_DIR}/gpu_prefs.py", "--python",
+ f"{SCRIPTS_DIR}/refine_blender.py", "--", "pano", f"{work}/shots.json", f"{work}/pano",
+ "--samples", "64", "--res", "2048", timeout=1200)
+ for shot in cfg["shots"]:
+ src = f"{work}/pano/pano_{shot['name']}.png"
+ if os.path.exists(src):
+ panorama_urls[shot["name"]] = upload(src, "image/png")
+ st.emit("panoramas", "running", f"360 from {shot['name']}",
+ panorama_url=panorama_urls[shot["name"]], viewpoint=shot["name"])
+
+ async def web_glb():
+ nonlocal scene_glb_url
+ await blender(f"{work}/scene.blend", "--python", f"{SCRIPTS_DIR}/refine_blender.py", "--", "glb",
+ f"{work}/web", "--tris", "60000", "--tex", "1024", timeout=1200)
+ scene_glb_url = upload(f"{work}/web/scene.glb", "model/gltf-binary")
+ st.emit("panoramas", "running", "scene.glb ready", scene_glb_url=scene_glb_url)
+
+ if req.panoramas or req.scene_glb:
+ st.start("panoramas", "360 panoramas and a web scene.glb")
+ t6 = time.time()
+ res = await asyncio.gather(*([panoramas()] if req.panoramas else []),
+ *([web_glb()] if req.scene_glb else []), return_exceptions=True)
+ errs = [str(r)[:200] for r in res if isinstance(r, Exception)]
+ timings["panoramas_s"] = round(time.time() - t6, 1)
+ st.done("panoramas", f"{len(panorama_urls)} panoramas, scene.glb {'ready' if scene_glb_url else 'skipped'}"
+ + (f" ({'; '.join(errs)})" if errs else ""))
+
+ # 7: package
+ st.start("packaging")
+ t3 = time.time()
+ pkg = f"{work}/scene_package.zip"
+ with zipfile.ZipFile(pkg, "w", zipfile.ZIP_STORED) as z:
+ z.write(f"{work}/scene.blend", "scene.blend")
+ z.write(f"{work}/plan.json", "plan.json")
+ z.write(f"{work}/props/assets.json", "manifest.json")
+ z.write(f"{work}/shots.json", "shots.json")
+ for shot in cfg["shots"]:
+ src = f"{work}/renders/{shot['name']}/frames/0001.png"
+ if os.path.exists(src):
+ z.write(src, f"renders/{shot['name']}.png")
+ for a in gen.assets.values():
+ ref = f"{work}/props/{a['id']}_ref.png"
+ if os.path.exists(ref):
+ z.write(ref, f"props/{a['id']}_ref.png")
+ if req.include_glbs:
+ for path in (a.get("meshes") or {}).values():
+ if os.path.exists(path):
+ z.write(path, f"props/{a['id']}.glb")
+ for name in ("web/scene.glb", "refine/refine.json"):
+ if os.path.exists(f"{work}/{name}"):
+ z.write(f"{work}/{name}", os.path.basename(name))
+ for name in os.listdir(f"{work}/pano") if os.path.isdir(f"{work}/pano") else []:
+ z.write(f"{work}/pano/{name}", f"panoramas/{name}")
+ z.writestr("README.md", f"# {plan.name}\n\n{plan.summary}\n\nBuilt by AnyScene reference-to-scene "
+ f"({req.tier}). Open scene.blend in Blender 5.0+. plan.json is the layout; "
+ f"manifest.json lists every prop, its reference and which 3D model made it.\n")
+ package_url = upload(pkg, "application/zip")
+ blend_url = upload(f"{work}/scene.blend", "application/octet-stream")
+ timings["package_s"] = round(time.time() - t3, 1)
+ timings["total_s"] = round(time.time() - t0, 1)
+ standins = [a["id"] for a in gen.assets.values() if not a.get("meshes")]
+ st.done("done", f"scene {scene_id} in {timings['total_s']:.0f} s", package_url=package_url)
+ await asyncio.sleep(2) # let the last stage lines reach the queue logs before COMPLETED
+ return BuildResponse(
+ scene_id=scene_id, package_url=package_url, scene_blend_url=blend_url, stills=stills,
+ panorama_urls=panorama_urls, scene_glb_url=scene_glb_url,
+ props=[{"id": a["id"], "label": a["label"], "ref_url": a.get("ref_url"),
+ "mesh_urls": a.get("mesh_urls", {}), "placements": a["objects"]} for a in gen.assets.values()],
+ standins_left=standins, timings=timings)
+ except Exception as e:
+ st.fail(str(e)[:500])
+ raise
+
+ @fal.endpoint("/plan")
+ def plan(self, req: PlanRequest) -> PlanResponse:
+ import time
+
+ from fal.toolkit import File
+ from PIL import Image
+
+ st = Stages()
+ t = {}
+ st.start("received", "plan request")
+ try:
+ t0 = time.time()
+ parent = None
+ if req.plan_id:
+ prev = _load(req.plan_id)
+ refs, parent = prev["reference_image_urls"], req.plan_id
+ st.start("planning", "revising the plan")
+ if req.plan:
+ plan = Plan.model_validate(req.plan)
+ else:
+ plan = planner.edit_plan(Plan.model_validate(prev["plan"]), req.edit, refs, req.effort)
+ else:
+ if not req.reference_image_urls:
+ raise ValueError("reference_image_urls is required for a new plan")
+ refs = req.reference_image_urls
+ st.start("reading_reference", f"{len(refs)} reference image(s)"
+ + (" + floor plan" if req.floor_plan_url else ""))
+ st.start("planning", f"laying out the whole space (effort {req.effort})")
+ plan = planner.make_plan(refs, req.floor_plan_url, req.prompt, req.effort)
+ t["planning_s"] = round(time.time() - t0, 1)
+ n_inv = sum(o.source == "invented" for o in plan.objects)
+ st.done("planning", f"{len(plan.objects)} objects ({n_inv} invented), {len(plan.lights)} lights, "
+ f"{plan.room.width:g} x {plan.room.depth:g} m {plan.setting}")
+
+ plan_id = "p_" + uuid.uuid4().hex[:10]
+ _save(plan_id, plan, refs, parent)
+ work = f"/tmp/{plan_id}"
+ os.makedirs(work, exist_ok=True)
+ with open(f"{work}/plan.json", "w", encoding="utf-8") as f:
+ json.dump(plan.model_dump(), f)
+
+ st.start("drawing_floor_plan")
+ floorplan.draw(plan, f"{work}/floor_plan.png", px_per_m=70 if max(plan.room.width, plan.room.depth) > 10 else 110)
+ fp_url = File.from_path(f"{work}/floor_plan.png", content_type="image/png").url
+ st.done("drawing_floor_plan", preview_url=fp_url)
+
+ st.start("blockout", "grey-box renders from the reference camera and an overview")
+ t1 = time.time()
+ proc = subprocess.run(["blender", "-b", "--factory-startup", "--python", self.blockout_path, "--",
+ f"{work}/plan.json", work, "--samples", "32", "--res", "1280"],
+ capture_output=True, text=True, timeout=900)
+ if proc.returncode != 0 or not os.path.exists(f"{work}/blockout_overview.png"):
+ raise RuntimeError("blockout failed:\n" + (proc.stdout + proc.stderr)[-2000:])
+ t["blockout_s"] = round(time.time() - t1, 1)
+ ref_url = File.from_path(f"{work}/blockout_reference.png", content_type="image/png").url
+ ov_url = File.from_path(f"{work}/blockout_overview.png", content_type="image/png").url
+
+ # Side by side: the first reference image next to the grey-box from the reference camera.
+ comp_path = f"{work}/comparison.png"
+ right = Image.open(f"{work}/blockout_reference.png").convert("RGB")
+ left = _fetch_image(refs[0]).convert("RGB").resize(right.size)
+ comp = Image.new("RGB", (right.width * 2, right.height))
+ comp.paste(left, (0, 0))
+ comp.paste(right, (right.width, 0))
+ comp.save(comp_path)
+ comp_url = File.from_path(comp_path, content_type="image/png").url
+ st.done("blockout", preview_url=comp_url)
+ t["total_s"] = round(time.time() - t0, 1)
+ st.done("done", f"plan {plan_id}")
+ time.sleep(2) # let the last stage lines reach the queue logs before COMPLETED
+ return PlanResponse(plan_id=plan_id, plan=plan.model_dump(), floor_plan_url=fp_url,
+ blockout_reference_url=ref_url, blockout_overview_url=ov_url, comparison_url=comp_url,
+ timings=t)
+ except Exception as e:
+ st.fail(str(e)[:500])
+ raise
+
+
+def _fetch_image(url: str):
+ import base64
+ import io
+ import urllib.request
+
+ from PIL import Image
+
+ if url.startswith("data:"):
+ return Image.open(io.BytesIO(base64.b64decode(url.split(",", 1)[1])))
+ with urllib.request.urlopen(url, timeout=60) as r:
+ return Image.open(io.BytesIO(r.read()))
diff --git a/endpoint/assemble.py b/endpoint/assemble.py
new file mode 100644
index 0000000..f04075d
--- /dev/null
+++ b/endpoint/assemble.py
@@ -0,0 +1,321 @@
+"""/build: assemble a scene .blend from a Plan, then swap generated meshes in as they arrive. Deterministic, no agent.
+
+ blender -b --factory-startup --python endpoint/assemble.py -- build plan.json assets.json out_dir
+ blender -b out_dir/scene.blend --python endpoint/assemble.py -- swap assets.json out_dir
+
+build:
+- shell: floor (and walls + ceiling for interiors) from the plan's room and openings;
+- every generated prop whose mesh has arrived: its GLB imported once, joined, turned so its front faces -Y (Tripo's
+ front is +X), scaled uniformly to the plan's size (by height for upright things, by footprint for flat ones), origin
+ at the bottom centre, then instanced (linked duplicates) at every placement;
+- every generated prop still pending: a stand-in box at its planned size, tagged so swap can replace it later;
+- everything else (counters, shelves, structure, signage): boxes in the plan's palette;
+- lights from the plan, world from time_of_day, then the grounding pass (floaters dropped onto their support);
+- writes scene.blend and shots.json (the reference camera plus two auto-framed eye-level stills) for camera/shoot.py.
+swap: replaces stand-ins whose asset has arrived since, re-runs grounding, saves. Reports what is still a stand-in.
+"""
+
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Matrix, Vector
+from mathutils.bvhtree import BVHTree
+
+STANDIN = "anyscene_standin" # custom property on stand-in boxes: the asset id they stand in for
+OBJECT_ID = "anyscene_object" # custom property on every placed prop: its plan object id
+
+
+def hex_rgb(h):
+ h = h.lstrip("#")
+ return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
+
+
+def material(name, rgb, rough=0.7):
+ m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
+ m.use_nodes = True
+ b = m.node_tree.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (*rgb, 1)
+ b.inputs["Roughness"].default_value = rough
+ return m
+
+
+def collection(name, hidden=False):
+ c = bpy.data.collections.get(name)
+ if c is None:
+ c = bpy.data.collections.new(name)
+ bpy.context.scene.collection.children.link(c)
+ if hidden:
+ bpy.context.view_layer.layer_collection.children[name].exclude = True
+ return c
+
+
+def box(name, center, size, rot=0.0, mat=None, coll=None):
+ mesh = bpy.data.meshes.new(name)
+ import bmesh
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bm.to_mesh(mesh)
+ bm.free()
+ mesh.transform(Matrix.Diagonal((*size, 1)))
+ o = bpy.data.objects.new(name, mesh)
+ o.location, o.rotation_euler = center, (0, 0, math.radians(rot))
+ if mat:
+ mesh.materials.append(mat)
+ (coll or collection("scene")).objects.link(o)
+ return o
+
+
+def load_asset(a):
+ """Import an asset's GLB once and normalise it into a single mesh object in the hidden library."""
+ lib = collection("asset_library", hidden=True)
+ if a["id"] in lib.objects:
+ ob = lib.objects[a["id"]]
+ return ob, Vector(ob["dims"])
+ model, path = next(iter(a["meshes"].items()))
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=path)
+ new = [o for o in bpy.data.objects if o not in before]
+ meshes = [o for o in new if o.type == "MESH"]
+ for o in new:
+ o.rotation_mode = "XYZ" # glTF imports come in as quaternions
+ bpy.ops.object.select_all(action="DESELECT")
+ for o in meshes:
+ o.select_set(True)
+ bpy.context.view_layer.objects.active = meshes[0]
+ if len(meshes) > 1:
+ bpy.ops.object.join()
+ ob = bpy.context.view_layer.objects.active
+ ob.parent = None
+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
+ for o in new:
+ if o != ob and o.name in bpy.data.objects:
+ bpy.data.objects.remove(o)
+ if model == "tripo-h31": # Tripo's front is +X; turn it to face -Y like everything else
+ ob.data.transform(Matrix.Rotation(math.radians(-90), 4, "Z"))
+ vs = [v.co for v in ob.data.vertices]
+ lo = Vector((min(v.x for v in vs), min(v.y for v in vs), min(v.z for v in vs)))
+ hi = Vector((max(v.x for v in vs), max(v.y for v in vs), max(v.z for v in vs)))
+ ob.data.transform(Matrix.Translation(-Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))))
+ ob.name = ob.data.name = a["id"]
+ ob["dims"] = list(hi - lo)
+ for c in ob.users_collection:
+ c.objects.unlink(ob)
+ lib.objects.link(ob)
+ return ob, hi - lo
+
+
+def place_mesh(spec, a):
+ """Instance an asset's mesh at a plan object's position, scaled uniformly to its planned size."""
+ src, dims = load_asset(a)
+ upright = spec["h"] >= 0.25 * max(spec["w"], spec["d"]) # upright: fit height; flat: fit footprint
+ s = spec["h"] / max(dims.z, 1e-4) if upright else max(spec["w"], spec["d"]) / max(dims.x, dims.y, 1e-4)
+ inst = bpy.data.objects.new(spec["id"], src.data) # linked duplicate: one mesh, many placements
+ collection("scene").objects.link(inst)
+ inst.location = (spec["x"], spec["y"], spec["z"])
+ inst.rotation_euler = (0, 0, math.radians(spec["rot"]))
+ inst.scale = (s, s, s)
+ inst[OBJECT_ID] = spec["id"]
+ return inst
+
+
+def ground(objects):
+ """Drop each object onto whatever is under its lowest points (same method as pipeline/grounding.py)."""
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ trees = {}
+ for o in collection("scene").objects:
+ if o.type == "MESH":
+ me = o.evaluated_get(dg).to_mesh()
+ if me.polygons:
+ mw = o.matrix_world
+ trees[o.name] = BVHTree.FromPolygons([mw @ v.co for v in me.vertices], [p.vertices[:] for p in me.polygons])
+ o.evaluated_get(dg).to_mesh_clear()
+ dropped = 0
+ for inst in objects:
+ me = inst.evaluated_get(dg).to_mesh()
+ vs = [inst.matrix_world @ v.co for v in me.vertices]
+ inst.evaluated_get(dg).to_mesh_clear()
+ if not vs:
+ continue
+ zmin = min(v.z for v in vs)
+ feet = [v for v in vs if v.z <= zmin + 0.015][::max(1, len(vs) // 400)]
+ gaps = [t.ray_cast(f + Vector((0, 0, 0.002)), Vector((0, 0, -1)), 5.0)[3]
+ for f in feet for name, t in trees.items() if name != inst.name]
+ gaps = [g - 0.002 for g in gaps if g is not None]
+ if gaps and 0.01 < min(gaps) < 3.0:
+ inst.location.z -= min(gaps)
+ dropped += 1
+ return dropped
+
+
+def build(plan, assets, out):
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ sc.cycles.samples, sc.cycles.use_denoising = 64, True
+ sc.view_settings.view_transform = "AgX"
+ sc["anyscene_plan"] = json.dumps(plan)
+
+ pal = [hex_rgb(c) for c in plan.get("palette") or ["#8a8478"]]
+ m_floor = material("floor", tuple(c * 0.6 for c in pal[0]), 0.6)
+ m_wall = material("wall", tuple(0.35 + 0.4 * c for c in pal[min(1, len(pal) - 1)]), 0.85)
+ m_box = [material(f"box_{i}", tuple(0.25 + 0.6 * c for c in p), 0.6) for i, p in enumerate(pal)]
+ m_standin = material("standin", (0.55, 0.55, 0.58), 0.9)
+
+ R = plan["room"]
+ W, D, H = R["width"], R["depth"], R["height"]
+ box("floor", (W / 2, D / 2, -0.05), (W + 6, D + 6, 0.1), mat=m_floor)
+ if plan["setting"] == "interior":
+ T = 0.12
+ walls = {"front": ((0, 0), (1, 0), W), "back": ((0, D), (1, 0), W), "left": ((0, 0), (0, 1), D), "right": ((W, 0), (0, 1), D)}
+ for wall, (origin, axis, length) in walls.items():
+ ops = sorted((o for o in plan["openings"] if o["wall"] == wall), key=lambda o: o["center"])
+ pieces, a = [], 0.0
+ for o in ops:
+ s, e = o["center"] - o["width"] / 2, o["center"] + o["width"] / 2
+ pieces.append((a, s, 0, H))
+ if o["sill"] > 0:
+ pieces.append((s, e, 0, o["sill"]))
+ if o["sill"] + o["height"] < H:
+ pieces.append((s, e, o["sill"] + o["height"], H))
+ a = e
+ pieces.append((a, length, 0, H))
+ for i, (s, e, z0, z1) in enumerate(pieces):
+ if e - s > 0.01 and z1 - z0 > 0.01:
+ mid = (s + e) / 2
+ size = (e - s, T, z1 - z0) if axis[0] else (T, e - s, z1 - z0)
+ box(f"wall_{wall}_{i}", (origin[0] + axis[0] * mid, origin[1] + axis[1] * mid, (z0 + z1) / 2), size, mat=m_wall)
+ box("ceiling", (W / 2, D / 2, H + 0.05), (W, D, 0.1), mat=m_wall)
+
+ by_object = {oid: a for a in assets.values() for oid in a["objects"]}
+ placed, standins = [], 0
+ for spec in plan["objects"]:
+ if spec["w"] <= 0 or spec["d"] <= 0 or spec["h"] <= 0 or spec["category"] == "decal":
+ continue
+ a = by_object.get(spec["id"])
+ if a and a.get("meshes") and not a.get("failed"):
+ try:
+ placed.append(place_mesh(spec, a))
+ continue
+ except RuntimeError as e: # a broken or truncated GLB: stand in for it instead of failing the build
+ print(f"assemble: {a['id']} mesh failed to import ({str(e)[:80]}), using a stand-in")
+ a["meshes"] = {}
+ if a: # generated prop not here yet (or broken): a stand-in box at its planned size, swapped in later
+ o = box(spec["id"], (spec["x"], spec["y"], spec["z"] + spec["h"] / 2), (spec["w"], spec["d"], spec["h"]),
+ spec["rot"], m_standin)
+ o[STANDIN], o[OBJECT_ID] = a["id"], spec["id"]
+ standins += 1
+ else:
+ box(spec["id"], (spec["x"], spec["y"], spec["z"] + spec["h"] / 2), (spec["w"], spec["d"], spec["h"]),
+ spec["rot"], m_box[hash(spec["category"]) % len(m_box)])
+
+ for li in plan["lights"]:
+ data = bpy.data.lights.new(li["id"], "POINT")
+ data.energy = {"low": 25, "medium": 80, "high": 220}[li["power"]] * (2.5 if li["kind"] in ("street", "window") else 1)
+ data.color, data.shadow_soft_size = hex_rgb(li["color"]), 0.12
+ lo = bpy.data.objects.new(li["id"], data)
+ lo.location = (li["x"], li["y"], li["z"])
+ collection("lights").objects.link(lo)
+
+ world = bpy.data.worlds.new("world")
+ world.use_nodes = True
+ tod = plan.get("time_of_day", "night").lower()
+ sky = {"dawn": ((0.55, 0.45, 0.42), 0.6), "day": ((0.6, 0.72, 0.9), 1.6), "dusk": ((0.45, 0.32, 0.38), 0.5)}
+ rgb, strength = next((v for k, v in sky.items() if k in tod), ((0.03, 0.04, 0.07), 0.25))
+ world.node_tree.nodes["Background"].inputs[0].default_value = (*rgb, 1)
+ world.node_tree.nodes["Background"].inputs[1].default_value = strength
+ sc.world = world
+
+ dropped = ground(placed)
+ print(f"assemble: {len(placed)} props placed, {standins} stand-ins pending, {dropped} dropped onto their support")
+
+ rc = plan["reference_camera"]
+ still = lambda name, pos, aim, lens: {"name": name, "move": "static", "frames": 1, "focus": {"mode": "none"},
+ "keys": [{"t": 0, "pos": pos, "aim": aim, "lens": lens}]}
+ views = auto_views(W, D, rc["position"])
+ shots = {"defaults": {"fps": 24, "res": [1920, 804], "aspect": "2.39", "samples": 128, "shutter": 0, "fstop": 4.0},
+ "shots": [still("ref_view", rc["position"], rc["look_at"], rc["lens_mm"])]
+ + [still(f"view_{i + 1}", pos, aim, 24) for i, (pos, aim) in enumerate(views)]}
+ json.dump(shots, open(os.path.join(out, "shots.json"), "w"), indent=1)
+ save(out)
+
+
+def auto_views(W, D, ref_pos, n=2):
+ """Pick n eye-level camera spots in open space (at least 0.6 m from any surface) with a clear line of sight to the
+ middle of the space, as far from the reference camera and each other as possible, so the stills show other angles."""
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ verts, polys = [], []
+ for o in collection("scene").objects:
+ if o.type != "MESH" or o.name in ("floor", "ceiling"):
+ continue
+ me = o.evaluated_get(dg).to_mesh()
+ base, mw = len(verts), o.matrix_world
+ verts += [mw @ v.co for v in me.vertices]
+ polys += [[base + i for i in p.vertices] for p in me.polygons]
+ o.evaluated_get(dg).to_mesh_clear()
+ bvh = BVHTree.FromPolygons(verts, polys) if polys else None
+ target = Vector((W / 2, D / 2, 1.0))
+ cands = []
+ for i in range(1, 12):
+ for j in range(1, 12):
+ p = Vector((W * i / 12, D * j / 12, 1.6))
+ if bvh:
+ near = bvh.find_nearest(p)
+ if near[0] is not None and near[3] < 0.6:
+ continue
+ to = target - p
+ hit = bvh.ray_cast(p, to.normalized(), to.length)
+ if hit[0] is not None:
+ continue
+ cands.append(p)
+ picked = [Vector(ref_pos)]
+ out = []
+ for _ in range(n):
+ if not cands:
+ break
+ best = max(cands, key=lambda c: min((c - q).length for q in picked))
+ picked.append(best)
+ out.append(([round(best.x, 3), round(best.y, 3), round(best.z, 3)], [target.x, target.y, target.z]))
+ return out
+
+
+def swap(assets, out):
+ """Replace stand-ins whose asset has arrived, then re-ground what changed."""
+ swapped, still = [], 0
+ plan = json.loads(bpy.context.scene["anyscene_plan"])
+ specs = {o["id"]: o for o in plan["objects"]}
+ for o in list(collection("scene").objects):
+ aid = o.get(STANDIN)
+ if not aid:
+ continue
+ a = assets.get(aid)
+ if a and a.get("meshes") and not a.get("failed"):
+ spec = specs[o[OBJECT_ID]]
+ bpy.data.objects.remove(o)
+ swapped.append(place_mesh(spec, a))
+ else:
+ still += 1
+ dropped = ground(swapped)
+ print(f"assemble: swapped in {len(swapped)} meshes, {still} stand-ins left, {dropped} dropped onto their support")
+ save(out)
+
+
+def save(out):
+ bpy.ops.file.pack_all()
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out, "scene.blend"), compress=True)
+ print("assemble: wrote", os.path.join(out, "scene.blend"))
+
+
+if __name__ == "__main__":
+ argv = sys.argv[sys.argv.index("--") + 1:]
+ cmd = argv[0]
+ if cmd == "build":
+ plan, assets, out = json.load(open(argv[1], encoding="utf-8")), json.load(open(argv[2], encoding="utf-8"))["assets"], os.path.abspath(argv[3])
+ os.makedirs(out, exist_ok=True)
+ build(plan, assets, out)
+ elif cmd == "swap":
+ swap(json.load(open(argv[1], encoding="utf-8"))["assets"], os.path.abspath(argv[2]))
diff --git a/endpoint/blockout.py b/endpoint/blockout.py
new file mode 100644
index 0000000..9a91e42
--- /dev/null
+++ b/endpoint/blockout.py
@@ -0,0 +1,157 @@
+"""Grey-box a Plan in Blender and render it: one view from the reference camera, one high three-quarter overview.
+
+ blender -b --factory-startup --python endpoint/blockout.py -- plan.json out_dir [--samples 32] [--res 1280]
+
+Walls (with their openings cut), a box per object at its real size and rotation, and a small glowing marker per light.
+Objects seen in the reference are plain clay; invented ones get a faint warm tint, matching the floor plan's colours.
+"""
+
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+plan = json.load(open(argv[0], encoding="utf-8"))
+out = os.path.abspath(argv[1])
+samples = int(argv[argv.index("--samples") + 1]) if "--samples" in argv else 32
+res = int(argv[argv.index("--res") + 1]) if "--res" in argv else 1280
+os.makedirs(out, exist_ok=True)
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+sc = bpy.context.scene
+sc.render.engine = "CYCLES"
+sc.cycles.samples = samples
+sc.cycles.use_denoising = True
+sc.view_settings.view_transform = "AgX"
+# GPU if there is one (OptiX, then CUDA); otherwise Cycles falls back to the CPU.
+prefs = bpy.context.preferences.addons["cycles"].preferences
+for kind in ("OPTIX", "CUDA"):
+ try:
+ prefs.compute_device_type = kind
+ prefs.get_devices()
+ if any(d.type == kind for d in prefs.devices):
+ for d in prefs.devices:
+ d.use = d.type == kind
+ sc.cycles.device = "GPU"
+ break
+ except TypeError:
+ continue
+
+world = bpy.data.worlds.new("w")
+world.use_nodes = True
+world.node_tree.nodes["Background"].inputs[0].default_value = (0.55, 0.58, 0.62, 1)
+world.node_tree.nodes["Background"].inputs[1].default_value = 0.6
+sc.world = world
+
+
+def mat(name, rgb, emit=0.0):
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ b = m.node_tree.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (*rgb, 1)
+ b.inputs["Roughness"].default_value = 0.8
+ if emit:
+ b.inputs["Emission Color"].default_value = (*rgb, 1)
+ b.inputs["Emission Strength"].default_value = emit
+ return m
+
+
+M_WALL = mat("wall", (0.72, 0.71, 0.69))
+M_FLOOR = mat("floor", (0.45, 0.45, 0.46))
+M_REF = mat("seen", (0.80, 0.80, 0.80))
+M_INV = mat("invented", (0.86, 0.74, 0.58))
+
+
+def box(name, center, size, rot_deg=0.0, material=M_WALL):
+ bpy.ops.mesh.primitive_cube_add(size=1, location=center)
+ o = bpy.context.object
+ o.name = name
+ o.scale = size
+ o.rotation_euler.z = math.radians(rot_deg)
+ o.data.materials.append(material)
+ return o
+
+
+R = plan["room"]
+W, D, H = R["width"], R["depth"], R["height"]
+T = 0.12 # wall thickness
+box("floor", (W / 2, D / 2, -0.05), (W + 2, D + 2, 0.1), material=M_FLOOR)
+
+# Walls: each wall is split into solid pieces around its openings (below the sill, above the head, between them).
+walls = {"front": ((0, 0), (1, 0), W), "back": ((0, D), (1, 0), W), "left": ((0, 0), (0, 1), D), "right": ((W, 0), (0, 1), D)}
+# Open-air settings get no enclosing walls: their facades, awnings and railings come from the plan's structure objects.
+if plan["setting"] != "interior":
+ walls = {}
+for wall, (origin, axis, length) in walls.items():
+ ops = sorted((o for o in plan["openings"] if o["wall"] == wall), key=lambda o: o["center"])
+ cuts, a = [], 0.0
+ for o in ops:
+ s, e = o["center"] - o["width"] / 2, o["center"] + o["width"] / 2
+ cuts.append((a, s, 0, H)) # full-height piece before the opening
+ if o["sill"] > 0:
+ cuts.append((s, e, 0, o["sill"])) # below a window
+ if o["sill"] + o["height"] < H:
+ cuts.append((s, e, o["sill"] + o["height"], H)) # above the opening
+ a = e
+ cuts.append((a, length, 0, H))
+ for i, (s, e, z0, z1) in enumerate(cuts):
+ if e - s < 0.01 or z1 - z0 < 0.01:
+ continue
+ mid = (s + e) / 2
+ cx, cy = origin[0] + axis[0] * mid, origin[1] + axis[1] * mid
+ size = (e - s, T, z1 - z0) if axis[0] else (T, e - s, z1 - z0)
+ box(f"wall_{wall}_{i}", (cx, cy, (z0 + z1) / 2), size)
+
+for ob in (o for o in plan["objects"] if o["w"] > 0 and o["d"] > 0 and o["h"] > 0):
+ if ob["category"] == "structure" and ob["z"] <= 0.01 and ob["h"] < 0.05:
+ continue # ground-level surfaces (street, puddles) are already the floor
+ box(ob["id"], (ob["x"], ob["y"], ob["z"] + ob["h"] / 2), (ob["w"], ob["d"], ob["h"]), ob["rot"],
+ M_REF if ob["source"] == "reference" else M_INV)
+
+COLORS = {}
+for li in plan["lights"]:
+ hexc = li["color"].lstrip("#")
+ rgb = tuple(int(hexc[i:i + 2], 16) / 255 for i in (0, 2, 4))
+ power = {"low": 40, "medium": 120, "high": 300}[li["power"]]
+ data = bpy.data.lights.new(li["id"], "POINT")
+ data.energy, data.color, data.shadow_soft_size = power, rgb, 0.15
+ lo = bpy.data.objects.new(li["id"], data)
+ lo.location = (li["x"], li["y"], li["z"])
+ sc.collection.objects.link(lo)
+ bpy.ops.mesh.primitive_uv_sphere_add(radius=0.05, location=(li["x"], li["y"], li["z"]))
+ bpy.context.object.data.materials.append(mat(f"glow_{li['id']}", rgb, emit=8))
+
+
+def camera(name, pos, look, lens):
+ cd = bpy.data.cameras.new(name)
+ cd.lens, cd.sensor_width = lens, 36
+ co = bpy.data.objects.new(name, cd)
+ sc.collection.objects.link(co)
+ co.location = Vector(pos)
+ co.rotation_euler = (Vector(look) - Vector(pos)).to_track_quat("-Z", "Y").to_euler()
+ return co
+
+
+def render(cam, path, w, h):
+ sc.camera = cam
+ sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = w, h, 100
+ sc.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+ print("blockout: wrote", path)
+
+
+rc = plan["reference_camera"]
+render(camera("cam_reference", rc["position"], rc["look_at"], rc["lens_mm"]), os.path.join(out, "blockout_reference.png"),
+ res, int(res * 9 / 16))
+# Overview: high three-quarter from the front-left, aimed at the middle of the space; the front wall is hidden
+# so the interior reads like a dollhouse.
+for o in bpy.data.objects:
+ if o.name.startswith("wall_front"):
+ o.hide_render = True
+span = max(W, D)
+render(camera("cam_overview", (W / 2 + 0.15 * span, -0.55 * span, 1.35 * span + H), (W / 2, D / 2, 0.6), 30),
+ os.path.join(out, "blockout_overview.png"), res, int(res * 9 / 16))
diff --git a/endpoint/client.py b/endpoint/client.py
new file mode 100644
index 0000000..71831b3
--- /dev/null
+++ b/endpoint/client.py
@@ -0,0 +1,103 @@
+"""Call the AnyScene endpoint and print its stage events live.
+
+ uv run --with fal-client python endpoint/client.py plan <image path or url> [...] [--prompt "..."] [--out DIR]
+ uv run --with fal-client python endpoint/client.py edit <plan_id> "move the counter to the left wall" [--out DIR]
+
+Local image paths are uploaded to fal storage first. Outputs (plan.json and the images) are saved to --out.
+Uses FAL_SERVERLESS_KEY (the Serverless account the app is deployed under), falling back to FAL_KEY.
+"""
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+import time
+import urllib.request
+
+# The fal app id, <owner>/<app>: set ANYSCENE_APP=<your-fal-username>/anyscene, or pass --app. No default.
+APP_ENV = "ANYSCENE_APP"
+PREFIX = "ANYSCENE_STAGE "
+
+
+def user_env(name):
+ if os.environ.get(name):
+ return os.environ[name]
+ if sys.platform == "win32":
+ parts = subprocess.run(["reg", "query", r"HKCU\Environment", "/v", name], capture_output=True, text=True).stdout.split()
+ if name in parts:
+ return parts[parts.index(name) + 2]
+ return None
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("cmd", choices=["plan", "edit", "build"])
+ p.add_argument("--tier", default="draft")
+ p.add_argument("--events", help="also write every stage event (JSON lines) here, e.g. to drive a UI replay")
+ p.add_argument("args", nargs="+")
+ p.add_argument("--prompt", default="")
+ p.add_argument("--effort", default="high")
+ p.add_argument("--floor-plan")
+ p.add_argument("--out", default="anyscene_out")
+ p.add_argument("--app", help="fal app id (default: $ANYSCENE_APP)")
+ a = p.parse_args()
+ app = (a.app or user_env(APP_ENV) or "").strip().strip("/")
+ if not app:
+ p.error(f"set {APP_ENV}=<your-fal-username>/anyscene or pass --app")
+ sys.stdout.reconfigure(encoding="utf-8") # stage marks (✓ ✗) on a Windows console
+ os.environ["FAL_KEY"] = user_env("FAL_SERVERLESS_KEY") or user_env("FAL_KEY")
+ import fal_client
+
+ up = lambda s: s if s.startswith("http") else fal_client.upload_file(s)
+ if a.cmd == "plan":
+ payload = {"reference_image_urls": [up(s) for s in a.args], "prompt": a.prompt, "effort": a.effort}
+ if a.floor_plan:
+ payload["floor_plan_url"] = up(a.floor_plan)
+ elif a.cmd == "edit":
+ payload = {"plan_id": a.args[0], "edit": " ".join(a.args[1:]), "effort": a.effort}
+ else:
+ payload = {"plan_id": a.args[0], "tier": a.tier}
+
+ t0 = time.time()
+ seen = set()
+ events = open(a.events, "w", encoding="utf-8") if a.events else None
+
+ def on_update(update):
+ for log in getattr(update, "logs", None) or []:
+ msg = log.get("message", "")
+ if PREFIX not in msg or msg in seen:
+ continue
+ seen.add(msg)
+ ev = json.loads(msg.split(PREFIX, 1)[1])
+ if events:
+ events.write(json.dumps({"t": round(time.time() - t0, 1), **ev}) + "\n")
+ events.flush()
+ mark = {"running": "…", "done": "✓", "failed": "✗"}.get(ev["status"], "·")
+ if ev.get("prop") and ev["prop"].get("status") == "meshing":
+ continue # one line per prop is enough: print it when its mesh lands
+ line = f"[{time.time() - t0:6.1f}s] {mark} {ev['stage']:<20} {ev.get('message', '')}"
+ if ev.get("preview_url"):
+ line += f"\n{'':32}preview: {ev['preview_url']}"
+ print(line, flush=True)
+
+ route = "build" if a.cmd == "build" else "plan"
+ res = fal_client.subscribe(f"{app}/{route}", arguments=payload, with_logs=True, on_queue_update=on_update)
+ os.makedirs(a.out, exist_ok=True)
+ if route == "build":
+ with open(os.path.join(a.out, "build.json"), "w", encoding="utf-8") as f:
+ json.dump(res, f, indent=1)
+ for i, url in enumerate(res["stills"]):
+ urllib.request.urlretrieve(url, os.path.join(a.out, f"still_{i}.png"))
+ print(f"\nscene_id {res['scene_id']} timings {res['timings']}\npackage {res['package_url']}\n"
+ f"stand-ins left: {res['standins_left']}\nsaved to {a.out}")
+ return
+ with open(os.path.join(a.out, "plan.json"), "w", encoding="utf-8") as f:
+ json.dump(res["plan"], f, indent=1, ensure_ascii=False)
+ for key in ("floor_plan_url", "blockout_reference_url", "blockout_overview_url", "comparison_url"):
+ urllib.request.urlretrieve(res[key], os.path.join(a.out, key.replace("_url", ".png")))
+ print(f"\nplan_id {res['plan_id']} timings {res['timings']} saved to {a.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/endpoint/floorplan.py b/endpoint/floorplan.py
new file mode 100644
index 0000000..86cd64c
--- /dev/null
+++ b/endpoint/floorplan.py
@@ -0,0 +1,117 @@
+"""Draw a Plan as a top-down floor plan PNG: walls and openings, labelled footprints (invented items dashed), lights,
+and the reference camera with its field of view."""
+
+import math
+
+from PIL import Image, ImageDraw, ImageFont
+
+from schema import Plan
+
+BG = (246, 243, 236)
+INK = (40, 38, 34)
+WALL = (30, 28, 26)
+REF = (52, 98, 160) # objects seen in the reference
+INV = (176, 112, 46) # invented objects
+LIGHT = (232, 170, 30)
+CAM = (192, 57, 43)
+CAT_FILL = {"structure": 0.10, "furniture": 0.22, "fixture": 0.18, "prop": 0.30, "clutter": 0.12,
+ "decal": 0.05, "signage": 0.08}
+
+
+def _font(size):
+ for name in ("arial.ttf", "DejaVuSans.ttf", "segoeui.ttf"):
+ try:
+ return ImageFont.truetype(name, size)
+ except OSError:
+ continue
+ return ImageFont.load_default()
+
+
+def _dashed(d, pts, fill, width=2, dash=7, gap=5):
+ for (x0, y0), (x1, y1) in zip(pts, pts[1:] + pts[:1]):
+ length = math.hypot(x1 - x0, y1 - y0)
+ if length < 1e-6:
+ continue
+ n = max(1, int(length // (dash + gap)))
+ for i in range(n):
+ a, b = i * (dash + gap) / length, min(1, (i * (dash + gap) + dash) / length)
+ d.line([(x0 + (x1 - x0) * a, y0 + (y1 - y0) * a), (x0 + (x1 - x0) * b, y0 + (y1 - y0) * b)],
+ fill=fill, width=width)
+
+
+def draw(plan: Plan, path: str, px_per_m: int = 110) -> str:
+ r = plan.room
+ margin = 140
+ W, H = int(r.width * px_per_m + 2 * margin), int(r.depth * px_per_m + 2 * margin + 60)
+ img = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(img, "RGBA")
+ # plan space -> image: x right, y up the page (entrance at the bottom)
+ P = lambda x, y: (margin + x * px_per_m, H - margin - 30 - y * px_per_m)
+
+ # grid, 1 m
+ for gx in range(int(r.width) + 1):
+ d.line([P(gx, 0), P(gx, r.depth)], fill=(225, 220, 210), width=1)
+ for gy in range(int(r.depth) + 1):
+ d.line([P(0, gy), P(r.width, gy)], fill=(225, 220, 210), width=1)
+
+ # walls (outdoor settings get a light outline)
+ wall_w = 7 if plan.setting == "interior" else 3
+ corners = [P(0, 0), P(r.width, 0), P(r.width, r.depth), P(0, r.depth)]
+ d.line(corners + [corners[0]], fill=WALL, width=wall_w)
+ for o in plan.openings: # gap in the wall + a thin line for its extent
+ a, b = o.center - o.width / 2, o.center + o.width / 2
+ seg = {"front": (P(a, 0), P(b, 0)), "back": (P(a, r.depth), P(b, r.depth)),
+ "left": (P(0, a), P(0, b)), "right": (P(r.width, a), P(r.width, b))}[o.wall]
+ d.line(seg, fill=BG, width=wall_w + 2)
+ d.line(seg, fill=(120, 150, 190) if o.kind in ("window", "shopfront") else (150, 140, 120), width=2)
+
+ small, mid = _font(13), _font(16)
+ # footprints, biggest first so small props draw on top
+ for ob in sorted((o for o in plan.objects if o.w > 0 and o.d > 0), key=lambda o: -o.w * o.d):
+ col = REF if ob.source == "reference" else INV
+ c, s = math.cos(math.radians(ob.rot)), math.sin(math.radians(ob.rot))
+ pts = [P(ob.x + dx * c - dy * s, ob.y + dx * s + dy * c)
+ for dx, dy in ((-ob.w / 2, -ob.d / 2), (ob.w / 2, -ob.d / 2), (ob.w / 2, ob.d / 2), (-ob.w / 2, ob.d / 2))]
+ d.polygon(pts, fill=col + (int(255 * CAT_FILL.get(ob.category, 0.2)),))
+ if ob.source == "invented":
+ _dashed(d, pts, col)
+ else:
+ d.polygon(pts, outline=col, width=2)
+ # front marker
+ centre = P(ob.x, ob.y)
+ tip = P(ob.x + s * (ob.d / 2), ob.y - c * (ob.d / 2))
+ d.line([centre, tip], fill=col, width=1)
+ if ob.category != "structure" and (ob.w * ob.d > 0.25 or ob.category == "fixture"):
+ tw = d.textlength(ob.id, font=small)
+ d.text((centre[0] - tw / 2, centre[1] - 7), ob.id, font=small, fill=INK)
+
+ for li in plan.lights:
+ x, y = P(li.x, li.y)
+ rad = {"low": 5, "medium": 7, "high": 9}[li.power]
+ d.ellipse([x - rad, y - rad, x + rad, y + rad], fill=LIGHT + (230,), outline=(120, 80, 0), width=1)
+
+ cam = plan.reference_camera
+ cx, cy = P(cam.position[0], cam.position[1])
+ ang = math.atan2(cam.look_at[1] - cam.position[1], cam.look_at[0] - cam.position[0])
+ half = math.atan(18 / cam.lens_mm)
+ reach = 2.2 * px_per_m
+ for a in (ang - half, ang + half):
+ d.line([(cx, cy), (cx + reach * math.cos(a), cy - reach * math.sin(a))], fill=CAM, width=2)
+ d.ellipse([cx - 6, cy - 6, cx + 6, cy + 6], fill=CAM)
+ d.text((cx + 9, cy + 4), f"reference camera {cam.lens_mm:.0f} mm", font=small, fill=CAM)
+
+ # title + legend
+ d.text((margin, 24), f"{plan.name} · {r.width:.1f} × {r.depth:.1f} m, {r.height:.1f} m high", font=_font(22), fill=INK)
+ lx, ly = margin, 58
+ for col, text, dashed in ((REF, "seen in reference", False), (INV, "invented", True)):
+ box = [lx, ly, lx + 26, ly + 14]
+ d.rectangle(box, fill=col + (60,))
+ (_dashed(d, [(box[0], box[1]), (box[2], box[1]), (box[2], box[3]), (box[0], box[3])], col) if dashed
+ else d.rectangle(box, outline=col, width=2))
+ d.text((lx + 34, ly - 2), text, font=mid, fill=INK)
+ lx += 210
+ d.ellipse([lx, ly + 1, lx + 12, ly + 13], fill=LIGHT)
+ d.text((lx + 20, ly - 2), "light", font=mid, fill=INK)
+ d.text((margin, H - 40), "entrance / front ↓ grid = 1 m", font=small, fill=(120, 115, 105))
+ img.save(path)
+ return path
diff --git a/endpoint/planner.py b/endpoint/planner.py
new file mode 100644
index 0000000..1895d60
--- /dev/null
+++ b/endpoint/planner.py
@@ -0,0 +1,142 @@
+"""Reference images -> Plan, and Plan + edit -> Plan, with Claude (vision + structured output)."""
+
+import base64
+import json
+import mimetypes
+import os
+import urllib.request
+
+import anthropic
+
+from schema import Plan
+
+MODEL = "claude-opus-5-5"
+
+SYSTEM = """You are the production designer for a photoreal Blender scene. From reference images you write a precise,
+buildable layout plan for the whole space, in real-world metres.
+
+Rules:
+- Use the coordinate system in the schema: origin at the floor's front-left corner seen from the entrance, X right,
+ Y into the space, Z up. rot 0 = the object faces -Y (towards the entrance).
+- Real places are small and dense. Use true sizes (a bar stool seat is ~0.45 m high, a counter ~0.9-1.0 m, a door
+ ~0.9 x 2.1 m). Density sells realism: plan 40-90 objects including clutter.
+- Cover the whole space, not just what the image shows. Anything not visible in a reference is source "invented";
+ invent it in the same style so a walk-through anywhere in the space looks right. Say what you invented in notes.
+- Mark generate=true for objects with character (appliances, tools, crockery, signs with objects, furniture with
+ detail). Use generate=false for walls, plain counters, shelves, boxes, paper and other simple geometry.
+- Prompts describe one object, its condition and materials. Never name real brands; signage text must be fictional.
+- Every object with generate=false gets a material: what its surface looks like in this scene, specific enough to
+ generate a tileable texture from (colour, finish, wear), e.g. "nicotine-yellowed beige enamelled steel, scuffed".
+- Give a crop for every object visible in reference image 0.
+- Reuse assets: identical objects share one asset key (all the red stools are one asset). Repeats cost nothing, so
+ build density from repeated assets with varied placement and rotation, and keep distinct designs for heroes.
+- Place the reference camera so a render from it would reproduce reference image 0's framing.
+- Objects must not overlap each other or the walls (except items resting on furniture, which use z > 0).
+- The ground is implicit: never add the floor, street or pavement as an object. Awnings, canopies and signboards are
+ thin (h 0.05-0.15 m) and sit at their real height (z). Building facades are thin slabs (d 0.2-0.4 m) at the edge.
+- For interior settings the room walls are built from room + openings; do not add walls as objects."""
+
+
+def _image_block(url: str) -> dict:
+ """Send every image inline as a JPEG of at most 2000 px: it keeps requests under the image size limit and works the
+ same whether the call goes to Anthropic directly or through OpenRouter."""
+ import io
+
+ from PIL import Image
+
+ if url.startswith("http"):
+ with urllib.request.urlopen(url, timeout=60) as r:
+ raw = r.read()
+ elif url.startswith("data:"):
+ raw = base64.b64decode(url.split(",", 1)[1])
+ else:
+ with open(url, "rb") as f:
+ raw = f.read()
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
+ img.thumbnail((2000, 2000))
+ buf = io.BytesIO()
+ img.save(buf, "JPEG", quality=90)
+ return {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg",
+ "data": base64.standard_b64encode(buf.getvalue()).decode()}}
+
+
+def strict_schema(model) -> dict:
+ """Pydantic's JSON schema in the strict form structured outputs need: every object closed and fully required."""
+ schema = model.model_json_schema()
+
+ def walk(node):
+ if isinstance(node, dict):
+ node.pop("default", None)
+ node.pop("title", None)
+ if node.get("type") == "object" and "properties" in node:
+ node["additionalProperties"] = False
+ node["required"] = list(node["properties"])
+ for v in node.values():
+ walk(v)
+ elif isinstance(node, list):
+ for v in node:
+ walk(v)
+
+ walk(schema)
+ return schema
+
+
+def _client() -> tuple[anthropic.Anthropic, str, dict]:
+ """Anthropic directly when ANTHROPIC_API_KEY is set; otherwise OpenRouter's Anthropic-compatible endpoint with
+ OPENROUTER_API_KEY. base_url is always explicit, because a stray ANTHROPIC_BASE_URL in the environment (Claude Code
+ sets one) would otherwise redirect the SDK."""
+ if os.environ.get("ANTHROPIC_API_KEY"):
+ extra = {"betas": ["server-side-fallback-2026-07-01", "fast-mode-2026-02-01"], "fallbacks": "default",
+ "speed": "fast"}
+ return anthropic.Anthropic(base_url="https://api.anthropic.com"), MODEL, extra
+ key = os.environ.get("OPENROUTER_API_KEY")
+ if not key:
+ raise RuntimeError("set ANTHROPIC_API_KEY or OPENROUTER_API_KEY")
+ # Fast mode passes through OpenRouter (checked: usage.speed == "fast", ~2.5x output speed); server-side fallbacks
+ # are an Anthropic API feature, so through OpenRouter a refusal is reported as a failure.
+ return (anthropic.Anthropic(base_url="https://openrouter.ai/api", auth_token=key, api_key=None),
+ os.environ.get("OPENROUTER_MODEL", "anthropic/claude-opus-5.5"),
+ {"betas": ["fast-mode-2026-02-01"], "speed": "fast"})
+
+
+def _call(content: list[dict], effort: str = "high") -> Plan:
+ client, model, extra = _client()
+ with client.beta.messages.stream(
+ model=model,
+ max_tokens=64000,
+ thinking={"type": "adaptive"},
+ output_config={"effort": effort, "format": {"type": "json_schema", "schema": strict_schema(Plan)}},
+ system=SYSTEM,
+ messages=[{"role": "user", "content": content}],
+ **extra,
+ ) as stream:
+ msg = stream.get_final_message()
+ if msg.stop_reason == "refusal":
+ raise RuntimeError(f"planning declined: {msg.stop_details}")
+ if msg.stop_reason == "max_tokens":
+ raise RuntimeError("plan was cut off (max_tokens)")
+ text = next(b.text for b in msg.content if b.type == "text")
+ return Plan.model_validate_json(text)
+
+
+def make_plan(reference_urls: list[str], floor_plan_url: str | None = None, prompt: str = "",
+ effort: str = "high") -> Plan:
+ content = []
+ for i, u in enumerate(reference_urls):
+ content += [{"type": "text", "text": f"Reference image {i}:"}, _image_block(u)]
+ if floor_plan_url:
+ content += [{"type": "text", "text": "Floor plan provided by the user. Follow it for the room shape and where "
+ "things go; use the reference images for the look and the props:"},
+ _image_block(floor_plan_url)]
+ content.append({"type": "text", "text": "Write the plan." + (f"\n\nExtra direction: {prompt}" if prompt else "")})
+ return _call(content, effort)
+
+
+def edit_plan(plan: Plan, edit: str, reference_urls: list[str], effort: str = "high") -> Plan:
+ content = []
+ for i, u in enumerate(reference_urls):
+ content += [{"type": "text", "text": f"Reference image {i}:"}, _image_block(u)]
+ content.append({"type": "text", "text": "Current plan:\n" + json.dumps(plan.model_dump(), indent=1)
+ + f"\n\nApply this change and return the full revised plan. Keep everything else as it is.\n"
+ f"Change: {edit}"})
+ return _call(content, effort)
diff --git a/endpoint/props.py b/endpoint/props.py
new file mode 100644
index 0000000..80abd15
--- /dev/null
+++ b/endpoint/props.py
@@ -0,0 +1,186 @@
+"""/build stages 1-2: a product reference and a 3D mesh for every unique generated prop in a Plan, all submitted at once.
+
+Objects that share a prompt share one asset (two identical chairs are generated once and placed twice). A prop that is
+visible in reference image 0 gets its reference by cropping it out and cleaning the crop into a product shot with
+GPT Image 2.5 edit, so it keeps the reference's look; the rest come from their prompt via text-to-image.
+"""
+
+import asyncio
+import io
+import json
+import os
+import re
+import time
+import urllib.request
+
+import fal_client
+from PIL import Image
+
+from schema import Plan
+
+REF_EDIT = "openai/gpt-image-2.5/sunburst/edit"
+REF_T2I = "openai/gpt-image-2.5/sunburst/text-to-image"
+MESH = {
+ "tripo-h31": ("tripo3d/h3.1/image-to-3d", {"pbr": True, "texture": True, "geometry_quality": "detailed",
+ "texture_quality": "detailed", "auto_size": True, "orientation": "align_image"}),
+ "meshy": ("meshy/v7.1/image-to-3d", {"enable_pbr": True, "should_texture": True, "geometry_resolution": "4k",
+ "topology": "triangle", "should_remesh": True, "target_polycount": 150000,
+ "symmetry_mode": "auto"}),
+}
+SCAN = ("No real-world brand names or logos. Product reference photograph for 3D scanning. The entire object fully "
+ "visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft "
+ "even diffuse studio lighting, no harsh shadows, no other objects, no hands, sharp focus, true-to-life materials.")
+
+
+def assets_for(plan: Plan) -> dict[str, dict]:
+ """Unique generated assets keyed by asset id, each with the objects that use it and the best crop to start from."""
+ out = {}
+ for ob in plan.objects:
+ if not ob.generate or ob.w <= 0 or ob.h <= 0:
+ continue
+ # The plan's asset key groups identical objects; older plans without one group by the id's stem.
+ key = getattr(ob, "asset", "") or re.sub(r"(_(\d+|left|right|fg|bg|front|back|[a-z]))+$", "", ob.id)
+ a = out.setdefault(key, {"id": key, "prompt": ob.prompt or ob.label,
+ "label": ob.label, "category": ob.category, "objects": [], "crop": None, "size": 0})
+ a["objects"].append(ob.id)
+ size = max(ob.w, ob.d, ob.h)
+ a["size"] = max(a["size"], size)
+ if ob.crop and (a["crop"] is None or (ob.crop[2] - ob.crop[0]) * (ob.crop[3] - ob.crop[1]) > a["crop_area"]):
+ a["crop"], a["crop_area"] = ob.crop, (ob.crop[2] - ob.crop[0]) * (ob.crop[3] - ob.crop[1])
+ # make asset ids unique
+ seen = {}
+ for a in out.values():
+ n = seen.get(a["id"], 0)
+ seen[a["id"]] = n + 1
+ if n:
+ a["id"] = f"{a['id']}_{n + 1}"
+ return {a["id"]: a for a in out.values()}
+
+
+def pick_model(a: dict, tier: str) -> list[str]:
+ """Draft: one model per prop, Tripo by default since it finishes in ~3.5 min against Meshy's 8-10; Meshy only for
+ small consumer items (under ~30 cm), where its sharper printed labels won in the reference scenes.
+ Full: both, and the builder picks."""
+ if tier == "full":
+ return ["tripo-h31", "meshy"]
+ small_item = a["category"] in ("prop", "clutter") and a["size"] < 0.3
+ return ["meshy"] if small_item else ["tripo-h31"]
+
+
+def _crop(ref: Image.Image, box: list[float]) -> Image.Image:
+ w, h = ref.size
+ x0, y0, x1, y1 = box
+ pad_x, pad_y = 0.15 * (x1 - x0), 0.15 * (y1 - y0)
+ return ref.crop((max(0, int((x0 - pad_x) * w)), max(0, int((y0 - pad_y) * h)),
+ min(w, int((x1 + pad_x) * w)), min(h, int((y1 + pad_y) * h))))
+
+
+async def _run(endpoint: str, args: dict, retries: int = 2) -> dict:
+ for attempt in range(retries + 1):
+ try:
+ h = await fal_client.submit_async(endpoint, args)
+ return await h.get()
+ except Exception:
+ if attempt == retries:
+ raise
+ await asyncio.sleep(5 * (attempt + 1))
+
+
+async def _reference(a: dict, ref_img: Image.Image | None, out_dir: str) -> dict:
+ prompt = f"{a['prompt']}. {SCAN}"
+ if a["crop"] and ref_img is not None:
+ crop_url = await fal_client.upload_image_async(_crop(ref_img, a["crop"]), "jpeg")
+ res = await _run(REF_EDIT, {"image_urls": [crop_url], "image_size": "square_hd", "quality": "high",
+ "prompt": f"Recreate the {a['label']} shown in this crop as a clean, complete object. "
+ f"Keep its exact design, colours, materials and condition. {prompt}"})
+ a["ref_source"] = "crop"
+ else:
+ res = await _run(REF_T2I, {"prompt": prompt, "image_size": "square_hd", "quality": "high", "num_images": 1,
+ "output_format": "png"})
+ a["ref_source"] = "prompt"
+ a["ref_url"] = res["images"][0]["url"]
+ await asyncio.to_thread(urllib.request.urlretrieve, a["ref_url"], os.path.join(out_dir, f"{a['id']}_ref.png"))
+ return a
+
+
+async def _mesh(a: dict, model: str, out_dir: str) -> tuple[str, str]:
+ endpoint, opts = MESH[model]
+ res = await _run(endpoint, {**opts, "image_url": a["ref_url"]})
+ glb = re.search(r"https://[^\"]+?\.glb[^\"]*", json.dumps(res)).group(0)
+ a.setdefault("mesh_urls", {})[model] = glb
+ path = os.path.join(out_dir, model, f"{a['id']}.glb")
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ # Download beside the target and rename when complete, so a half-written file is never picked up.
+ await asyncio.to_thread(urllib.request.urlretrieve, glb, path + ".part")
+ with open(path + ".part", "rb") as f:
+ if f.read(4) != b"glTF":
+ raise RuntimeError(f"{a['id']}: {model} returned something that is not a GLB")
+ os.replace(path + ".part", path)
+ return model, path
+
+
+class Generation:
+ """Every prop's reference and mesh, all in flight at once. The build doesn't wait for all of them: it assembles with
+ stand-in boxes straight away, calls wait() with a deadline, swaps in whatever has landed, and checks again before
+ packaging. assets.json always reflects what is done; unfinished assets are marked "pending"."""
+
+ def __init__(self, plan: Plan, reference_url: str, out_dir: str, tier: str, report):
+ os.makedirs(out_dir, exist_ok=True)
+ self.out_dir, self.tier, self.report = out_dir, tier, report
+ self.assets = assets_for(plan)
+ self.ref_img = None
+ if reference_url.startswith("http"):
+ with urllib.request.urlopen(reference_url, timeout=60) as r:
+ self.ref_img = Image.open(io.BytesIO(r.read())).convert("RGB")
+ elif reference_url:
+ self.ref_img = Image.open(reference_url).convert("RGB")
+ self.t0, self.done, self.tasks = time.time(), 0, {}
+
+ def start(self):
+ n_place = sum(len(a["objects"]) for a in self.assets.values())
+ self.report("prop_references", f"{len(self.assets)} unique props ({n_place} placements)", 0.0)
+ for a in self.assets.values():
+ a["pending"] = True
+ self.tasks[a["id"]] = asyncio.create_task(self._one(a))
+ self.snapshot()
+
+ async def _one(self, a):
+ try:
+ await _reference(a, self.ref_img, self.out_dir)
+ # live UI: the prop shelf gets this prop's reference image as soon as it exists
+ self.report("prop_references", f"{a['id']} reference ready", None,
+ prop={"id": a["id"], "label": a["label"], "ref_url": a["ref_url"], "status": "meshing"})
+ a["meshes"] = dict(await asyncio.gather(*[_mesh(a, m, self.out_dir) for m in pick_model(a, self.tier)]))
+ except Exception as e:
+ a["failed"], a["error"] = True, str(e)[:200]
+ a["pending"] = False
+ self.done += 1
+ model = next(iter(a.get("mesh_urls", {})), None)
+ self.report("generating_meshes", f"{self.done} of {len(self.assets)} props have meshes",
+ self.done / len(self.assets),
+ prop={"id": a["id"], "label": a["label"], "ref_url": a.get("ref_url"), "model": model,
+ "mesh_url": a.get("mesh_urls", {}).get(model),
+ "status": "failed" if a.get("failed") else "done"})
+ self.snapshot()
+
+ async def wait(self, timeout_s: float | None) -> int:
+ """Wait until everything is done or timeout_s passes; returns how many assets are still pending."""
+ pending = [t for t in self.tasks.values() if not t.done()]
+ if pending:
+ await asyncio.wait(pending, timeout=timeout_s)
+ left = sum(not t.done() for t in self.tasks.values())
+ self.report("generating_meshes", f"{self.done} of {len(self.assets)} done after {time.time() - self.t0:.0f} s"
+ + (f", {left} still running (stand-ins for now)" if left else ""), self.done / len(self.assets))
+ return left
+
+ def snapshot(self):
+ with open(os.path.join(self.out_dir, "assets.json"), "w", encoding="utf-8") as f:
+ json.dump({"assets": self.assets}, f, indent=1)
+
+
+async def generate(plan: Plan, reference_url: str, out_dir: str, tier: str, report) -> dict[str, dict]:
+ """Everything at once and wait for all of it (used for tests and the full tier)."""
+ g = Generation(plan, reference_url, out_dir, tier, report)
+ g.start()
+ await g.wait(None)
+ return g.assets
diff --git a/endpoint/refine.py b/endpoint/refine.py
new file mode 100644
index 0000000..a06b57d
--- /dev/null
+++ b/endpoint/refine.py
@@ -0,0 +1,132 @@
+"""/build refine stage, orchestration: what refine_blender.py `apply` needs, all of it requested at once.
+
+1. Surfaces: Claude looks at each prop's straight-on front view and marks its screens, glass, lamps and glowing
+ panels (normalised boxes), with what each screen should show in this scene.
+2. Screen content: one generated image per screen (GPT Image 2.5), from Claude's description and the scene's look.
+3. Box textures: one tileable texture per distinct material description on the plan's scripted objects.
+Writes refine.json for refine_blender.py.
+"""
+
+import asyncio
+import base64
+import hashlib
+import io
+import json
+import os
+import urllib.request
+from typing import Literal
+
+import fal_client
+from PIL import Image
+from pydantic import BaseModel, Field
+
+import planner
+from schema import Plan
+
+IMAGE = "openai/gpt-image-2.5/sunburst/text-to-image"
+
+
+class Surface(BaseModel):
+ kind: Literal["screen", "glass", "lamp", "glow"] = Field(
+ description="screen: a display that should light up (CRT, monitor, TV, scope, readout). glass: a pane, lens, "
+ "cover or bottle that should be see-through. lamp: a bulb, tube or shade that emits light. "
+ "glow: a backlit sign, indicator bank or dial face that glows softly.")
+ box: list[float] = Field(description="Normalised [x0, y0, x1, y1] in this image, y down, tight around the surface.")
+ content: str = Field("", description="For screens: what it shows in this scene, e.g. 'green phosphor telemetry "
+ "table with orbit numbers'. Empty otherwise.")
+ color: str = Field("", description="For lamps: the light's hex colour, e.g. #ffc98a. Empty otherwise.")
+
+
+class Surfaces(BaseModel):
+ surfaces: list[Surface]
+
+
+PROMPT = """This is a straight-on front view of a 3D prop, a {label}, for a scene: {summary}
+
+Mark every surface on it that needs special treatment in a photoreal render: screens that should light up, glass that
+should be see-through, lamps or bulbs that emit light, and backlit panels that glow. Boxes must be tight around each
+surface and inside the prop. Mark nothing if the prop has none of these; most props have none. For each screen, say
+what it should show in this scene, in the period and style of the scene."""
+
+
+def _jpeg_b64(path: str) -> str:
+ img = Image.open(path).convert("RGB")
+ img.thumbnail((1024, 1024))
+ buf = io.BytesIO()
+ img.save(buf, "JPEG", quality=88)
+ return base64.standard_b64encode(buf.getvalue()).decode()
+
+
+def _surfaces(view_png: str, label: str, summary: str) -> list[dict]:
+ client, model, extra = planner._client()
+ content = [{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": _jpeg_b64(view_png)}},
+ {"type": "text", "text": PROMPT.format(label=label, summary=summary)}]
+ with client.beta.messages.stream(model=model, max_tokens=8000, thinking={"type": "adaptive"},
+ output_config={"effort": "medium", "format": {"type": "json_schema",
+ "schema": planner.strict_schema(Surfaces)}},
+ messages=[{"role": "user", "content": content}], **extra) as s:
+ msg = s.get_final_message()
+ if msg.stop_reason != "end_turn":
+ return []
+ out = Surfaces.model_validate_json(next(b.text for b in msg.content if b.type == "text")).surfaces
+ return [x.model_dump() for x in out if len(x.box) == 4 and x.box[2] > x.box[0] and x.box[3] > x.box[1]]
+
+
+async def _image(prompt: str, path: str, size: str = "landscape_4_3") -> str:
+ h = await fal_client.submit_async(IMAGE, {"prompt": prompt, "image_size": size, "quality": "medium", "num_images": 1,
+ "output_format": "png"})
+ res = await h.get()
+ await asyncio.to_thread(urllib.request.urlretrieve, res["images"][0]["url"], path)
+ return path
+
+
+async def build_refine(plan: Plan, assets: dict, views_dir: str, out_dir: str, report) -> dict:
+ os.makedirs(out_dir, exist_ok=True)
+ meta = json.load(open(os.path.join(views_dir, "views.json")))
+ summary = f"{plan.summary} ({plan.time_of_day}; mood: {', '.join(plan.mood)})"
+
+ # 1. surfaces on every prop, in parallel
+ ids = [aid for aid in meta if os.path.exists(os.path.join(views_dir, f"{aid}.png"))]
+ labels = {a["id"]: a["label"] for a in assets.values()}
+ report("refine", f"finding screens, glass and lamps on {len(ids)} props", 0.05)
+ found = await asyncio.gather(*[asyncio.to_thread(_surfaces, os.path.join(views_dir, f"{aid}.png"),
+ labels.get(aid, aid), summary) for aid in ids],
+ return_exceptions=True)
+ surfaces = {aid: (r if isinstance(r, list) else []) for aid, r in zip(ids, found)}
+ n = {k: sum(s["kind"] == k for v in surfaces.values() for s in v) for k in ("screen", "glass", "lamp", "glow")}
+ report("refine", f"{n['screen']} screens, {n['glass']} glass, {n['lamp']} lamps, {n['glow']} glowing panels", 0.4)
+
+ # 2 + 3. screen content and box textures, all at once
+ jobs = []
+ for aid, ss in surfaces.items():
+ for k, s in enumerate(ss):
+ if s["kind"] == "screen":
+ p = os.path.join(out_dir, f"screen_{aid}_{k}.png")
+ s["image"] = p
+ jobs.append(_image(f"Flat, straight-on screen content to display on a {labels.get(aid, aid)}: "
+ f"{s['content'] or 'a period-appropriate display'}. Fill the frame edge to edge with the "
+ f"screen image only, no bezel, no device, no reflections. Fictional text only, no real "
+ f"brands. Scene: {summary}", p))
+ textures, materials = {}, {}
+ for ob in plan.objects:
+ if not ob.generate and getattr(ob, "material", "") and ob.category != "decal":
+ key = hashlib.md5(ob.material.lower().encode()).hexdigest()[:10]
+ if key not in materials:
+ p = os.path.join(out_dir, f"tile_{key}.png")
+ materials[key] = p
+ jobs.append(_image(f"Seamless tileable texture, flat and evenly lit, straight-on, no perspective, no "
+ f"objects, filling the whole frame: {ob.material}. Photographic surface detail.",
+ p, "square_hd"))
+ textures[ob.id] = {"image": materials[key], "tile_m": 0.8, "material": ob.material}
+ report("refine", f"generating {len(jobs)} screen images and textures", 0.5)
+ results = await asyncio.gather(*jobs, return_exceptions=True)
+ failed = sum(isinstance(r, Exception) for r in results)
+ for ss in surfaces.values(): # drop screens whose image failed
+ for s in ss:
+ if s["kind"] == "screen" and not os.path.exists(s.get("image", "")):
+ s.pop("image", None)
+ textures = {k: v for k, v in textures.items() if os.path.exists(v["image"])}
+ report("refine", f"{len(jobs) - failed} of {len(jobs)} images ready", 0.8)
+ spec = {"views": meta, "surfaces": surfaces, "textures": textures}
+ json.dump(spec, open(os.path.join(out_dir, "refine.json"), "w"), indent=1)
+ return spec
diff --git a/endpoint/refine_blender.py b/endpoint/refine_blender.py
new file mode 100644
index 0000000..70a49a3
--- /dev/null
+++ b/endpoint/refine_blender.py
@@ -0,0 +1,334 @@
+"""/build refine stage, Blender side. Works on a scene.blend written by assemble.py.
+
+ blender -b scene.blend --python refine_blender.py -- views out_dir
+ straight-on front render of every prop in the asset library (+ views.json: how each image maps to the mesh),
+ for Claude to mark screens, glass and lamps on.
+ blender -b scene.blend --python refine_blender.py -- apply refine.json out_dir
+ applies refine.json: per-prop surfaces (emissive screens with generated content and scanlines, real glass,
+ lit lamps with a light per placement, glowing panels) and tileable textures on the scripted pieces; saves.
+ blender -b scene.blend --python refine_blender.py -- pano shots.json out_dir [--samples 64] [--res 2048]
+ equirectangular Cycles panoramas from each still's camera position: the exact Blender lighting, for a 360 view.
+ blender -b scene.blend --python refine_blender.py -- glb out_dir [--tris 60000]
+ the assembled scene as a decimated glTF with its lights (KHR_lights_punctual), for a real-time 3D view.
+
+A prop's front view looks along +Y at its front face (props are normalised to face -Y with the origin at the bottom
+centre), so a box marked on the image maps straight back to X/Z on the mesh and is projected onto it with rays.
+"""
+
+import hashlib
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Matrix, Vector
+from mathutils.bvhtree import BVHTree
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+cmd = argv[0]
+opt = lambda k, d: type(d)(argv[argv.index(k) + 1]) if k in argv else d
+
+
+def library():
+ c = bpy.data.collections.get("asset_library")
+ return list(c.objects) if c else []
+
+
+def scene_objects():
+ c = bpy.data.collections.get("scene")
+ return list(c.objects) if c else []
+
+
+def bounds(ob):
+ vs = [v.co for v in ob.data.vertices]
+ lo = Vector((min(v.x for v in vs), min(v.y for v in vs), min(v.z for v in vs)))
+ hi = Vector((max(v.x for v in vs), max(v.y for v in vs), max(v.z for v in vs)))
+ return lo, hi
+
+
+def gpu():
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ for kind in ("OPTIX", "CUDA"):
+ try:
+ prefs.compute_device_type = kind
+ prefs.get_devices()
+ if any(d.type == kind for d in prefs.devices):
+ for d in prefs.devices:
+ d.use = d.type == kind
+ bpy.context.scene.cycles.device = "GPU"
+ return
+ except TypeError:
+ continue
+
+
+# ---------------------------------------------------------------- views
+def views(out):
+ os.makedirs(out, exist_ok=True)
+ sc = bpy.data.scenes.new("refine_views")
+ sc.render.engine = "BLENDER_WORKBENCH"
+ sc.display.shading.light = "FLAT"
+ sc.display.shading.color_type = "TEXTURE"
+ sc.render.film_transparent = False
+ sc.world = bpy.data.worlds.new("v")
+ cam_data = bpy.data.cameras.new("vcam")
+ cam_data.type = "ORTHO"
+ cam = bpy.data.objects.new("vcam", cam_data)
+ sc.collection.objects.link(cam)
+ sc.camera = cam
+ meta = {}
+ for ob in library():
+ for o in list(sc.collection.objects):
+ if o != cam:
+ sc.collection.objects.unlink(o)
+ sc.collection.objects.link(ob)
+ lo, hi = bounds(ob)
+ w, h = (hi.x - lo.x) * 1.08, (hi.z - lo.z) * 1.08
+ cx, cz = (lo.x + hi.x) / 2, (lo.z + hi.z) / 2
+ aspect = max(0.25, min(4.0, w / max(h, 1e-4)))
+ sc.render.resolution_x, sc.render.resolution_y = (768, max(64, int(768 / aspect))) if aspect >= 1 else (max(64, int(768 * aspect)), 768)
+ cam_data.ortho_scale = max(w, h)
+ cam.location = (cx, lo.y - 5.0, cz)
+ cam.rotation_euler = (math.radians(90), 0, 0) # looks along +Y, at the front face
+ sc.render.filepath = os.path.join(out, f"{ob.name}.png")
+ bpy.ops.render.render(write_still=True, scene=sc.name)
+ fw, fh = (cam_data.ortho_scale, cam_data.ortho_scale / aspect) if aspect >= 1 else (cam_data.ortho_scale * aspect, cam_data.ortho_scale)
+ meta[ob.name] = {"x0": cx - fw / 2, "x1": cx + fw / 2, "z0": cz - fh / 2, "z1": cz + fh / 2, "y0": lo.y - 1.0}
+ sc.collection.objects.unlink(ob)
+ json.dump(meta, open(os.path.join(out, "views.json"), "w"), indent=1)
+ print(f"refine: {len(meta)} front views")
+
+
+# ---------------------------------------------------------------- materials
+def node_mat(name):
+ m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
+ m.use_nodes = True
+ return m, m.node_tree.nodes, m.node_tree.links
+
+
+def screen_material(name, image_path):
+ m, n, l = node_mat(name)
+ b = n["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.01, 0.012, 0.01, 1)
+ b.inputs["Roughness"].default_value = 0.12 # glassy tube face
+ uv = n.new("ShaderNodeUVMap")
+ uv.uv_map = "screen_uv"
+ tex = n.new("ShaderNodeTexImage")
+ tex.image = bpy.data.images.load(image_path, check_existing=True)
+ l.new(uv.outputs["UV"], tex.inputs["Vector"])
+ wave = n.new("ShaderNodeTexWave") # scanlines across the screen
+ wave.bands_direction = "Y"
+ wave.inputs["Scale"].default_value = 220
+ l.new(uv.outputs["UV"], wave.inputs["Vector"])
+ ramp = n.new("ShaderNodeMapRange")
+ ramp.inputs["To Min"].default_value, ramp.inputs["To Max"].default_value = 0.72, 1.0
+ l.new(wave.outputs["Fac"], ramp.inputs["Value"])
+ mul = n.new("ShaderNodeMix")
+ mul.data_type, mul.blend_type = "RGBA", "MULTIPLY"
+ mul.inputs["Factor"].default_value = 1.0
+ l.new(tex.outputs["Color"], mul.inputs[6])
+ l.new(ramp.outputs["Result"], mul.inputs[7])
+ l.new(mul.outputs[2], b.inputs["Emission Color"])
+ b.inputs["Emission Strength"].default_value = 3.5
+ return m
+
+
+def glass_material():
+ m, n, _ = node_mat("refine_glass")
+ b = n["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.9, 0.95, 0.95, 1)
+ b.inputs["Transmission Weight"].default_value = 1.0
+ b.inputs["Roughness"].default_value = 0.04
+ b.inputs["IOR"].default_value = 1.45
+ return m
+
+
+def lamp_material(color):
+ m, n, _ = node_mat("refine_lamp_" + color.lstrip("#"))
+ b = n["Principled BSDF"]
+ rgb = tuple(int(color.lstrip("#")[i:i + 2], 16) / 255 for i in (0, 2, 4))
+ b.inputs["Base Color"].default_value = (*rgb, 1)
+ b.inputs["Emission Color"].default_value = (*rgb, 1)
+ b.inputs["Emission Strength"].default_value = 12.0
+ return m
+
+
+def glow_material(ob):
+ """Glowing panel (backlit sign, indicator bank): its own albedo becomes emission."""
+ src = ob.data.materials[0] if ob.data.materials else None
+ m = src.copy() if src else bpy.data.materials.new("refine_glow")
+ m.name = f"refine_glow_{ob.name}"
+ m.use_nodes = True
+ n, l = m.node_tree.nodes, m.node_tree.links
+ b = next((x for x in n if x.type == "BSDF_PRINCIPLED"), None)
+ if b:
+ col = b.inputs["Base Color"]
+ if col.is_linked:
+ l.new(col.links[0].from_socket, b.inputs["Emission Color"])
+ else:
+ b.inputs["Emission Color"].default_value = col.default_value
+ b.inputs["Emission Strength"].default_value = 2.0
+ return m
+
+
+def tile_material(name, image_path, tile_m):
+ m, n, l = node_mat(name)
+ b = n["Principled BSDF"]
+ b.inputs["Roughness"].default_value = 0.65
+ coord = n.new("ShaderNodeTexCoord")
+ mapping = n.new("ShaderNodeMapping")
+ mapping.inputs["Scale"].default_value = (1 / tile_m, 1 / tile_m, 1 / tile_m)
+ tex = n.new("ShaderNodeTexImage")
+ tex.image = bpy.data.images.load(image_path, check_existing=True)
+ tex.projection, tex.projection_blend = "BOX", 0.25
+ l.new(coord.outputs["Object"], mapping.inputs["Vector"])
+ l.new(mapping.outputs["Vector"], tex.inputs["Vector"])
+ l.new(tex.outputs["Color"], b.inputs["Base Color"])
+ return m
+
+
+# ---------------------------------------------------------------- apply
+def faces_in_box(ob, meta, box):
+ """Polygons of `ob` hit by rays shot along +Y through the box (normalised image coords, y down)."""
+ tree = BVHTree.FromObject(ob, bpy.context.evaluated_depsgraph_get(), deform=False)
+ x0 = meta["x0"] + box[0] * (meta["x1"] - meta["x0"])
+ x1 = meta["x0"] + box[2] * (meta["x1"] - meta["x0"])
+ z1 = meta["z1"] - box[1] * (meta["z1"] - meta["z0"])
+ z0 = meta["z1"] - box[3] * (meta["z1"] - meta["z0"])
+ hits, n = set(), 24
+ for i in range(n + 1):
+ for j in range(n + 1):
+ x, z = x0 + (x1 - x0) * i / n, z0 + (z1 - z0) * j / n
+ loc, nor, idx, _ = tree.ray_cast(Vector((x, meta["y0"], z)), Vector((0, 1, 0)), 50)
+ if idx is not None and nor.y < 0.2: # front-facing faces only
+ hits.add(idx)
+ return hits, (x0, x1, z0, z1)
+
+
+def assign(ob, faces, mat, uv_rect=None):
+ me = ob.data
+ if mat.name not in [m.name for m in me.materials if m]:
+ me.materials.append(mat)
+ slot = [m.name if m else "" for m in me.materials].index(mat.name)
+ if uv_rect:
+ uvl = me.uv_layers.get("screen_uv") or me.uv_layers.new(name="screen_uv")
+ x0, x1, z0, z1 = uv_rect
+ for p in me.polygons:
+ if p.index in faces:
+ p.material_index = slot
+ if uv_rect:
+ for li in p.loop_indices:
+ co = me.vertices[me.loops[li].vertex_index].co
+ uvl.data[li].uv = ((co.x - x0) / max(x1 - x0, 1e-4), (co.z - z0) / max(z1 - z0, 1e-4))
+
+
+def apply(spec, out):
+ os.makedirs(out, exist_ok=True)
+ meta = spec["views"]
+ lib = {o.name: o for o in library()}
+ placements = {}
+ for o in scene_objects():
+ if o.type == "MESH" and o.data.name in lib:
+ placements.setdefault(o.data.name, []).append(o)
+ counts = {"screen": 0, "glass": 0, "lamp": 0, "glow": 0, "lights": 0, "textured": 0}
+ for aid, surfaces in spec["surfaces"].items():
+ ob = lib.get(aid)
+ if ob is None or aid not in meta:
+ continue
+ for k, s in enumerate(surfaces):
+ faces, rect = faces_in_box(ob, meta[aid], s["box"])
+ if not faces:
+ continue
+ kind = s["kind"]
+ if kind == "screen" and s.get("image"):
+ assign(ob, faces, screen_material(f"refine_screen_{aid}_{k}", s["image"]), rect)
+ elif kind == "glass":
+ assign(ob, faces, glass_material())
+ elif kind == "lamp":
+ color = s.get("color", "#ffc98a")
+ assign(ob, faces, lamp_material(color))
+ c = sum((ob.data.polygons[i].center for i in faces), Vector()) / len(faces)
+ for inst in placements.get(aid, []): # one real light per placement, just in front of the bulb
+ data = bpy.data.lights.new(f"refine_light_{inst.name}_{k}", "POINT")
+ data.energy, data.shadow_soft_size = 35.0, 0.05
+ data.color = tuple(int(color.lstrip("#")[i:i + 2], 16) / 255 for i in (0, 2, 4))
+ lo = bpy.data.objects.new(data.name, data)
+ lo.location = inst.matrix_world @ (c + Vector((0, -0.04, -0.02)))
+ bpy.data.collections["scene"].objects.link(lo)
+ counts["lights"] += 1
+ elif kind == "glow":
+ assign(ob, faces, glow_material(ob))
+ counts[kind] = counts.get(kind, 0) + 1
+ for oid, tex in spec.get("textures", {}).items():
+ o = bpy.data.objects.get(oid)
+ if o and o.type == "MESH" and tex.get("image"):
+ name = "refine_tile_" + hashlib.md5(tex["image"].encode()).hexdigest()[:8]
+ m = bpy.data.materials.get(name) or tile_material(name, tex["image"], tex.get("tile_m", 0.8))
+ o.data.materials.clear()
+ o.data.materials.append(m)
+ counts["textured"] += 1
+ print("refine: applied " + ", ".join(f"{v} {k}" for k, v in counts.items()))
+ bpy.ops.file.pack_all()
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out, "scene.blend"), compress=True)
+
+
+# ---------------------------------------------------------------- panoramas
+def pano(shots_path, out):
+ gpu()
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ sc.cycles.samples = opt("--samples", 64)
+ sc.cycles.use_denoising = True
+ res = opt("--res", 2048)
+ sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = res, res // 2, 100
+ cam_data = bpy.data.cameras.new("pano")
+ cam_data.type = "PANO"
+ cam_data.panorama_type = "EQUIRECTANGULAR"
+ cam = bpy.data.objects.new("pano", cam_data)
+ sc.collection.objects.link(cam)
+ sc.camera = cam
+ os.makedirs(out, exist_ok=True)
+ for shot in json.load(open(shots_path))["shots"]:
+ k = shot["keys"][0]
+ pos, aim = Vector(k["pos"]), Vector(k["aim"])
+ yaw = math.atan2(aim.y - pos.y, aim.x - pos.x) - math.pi / 2
+ cam.location = pos
+ cam.rotation_euler = (math.radians(90), 0, yaw) # level, facing the shot's aim, so the seam sits behind
+ sc.render.filepath = os.path.join(out, f"pano_{shot['name']}.png")
+ bpy.ops.render.render(write_still=True)
+ print("refine: panorama", shot["name"])
+
+
+# ---------------------------------------------------------------- glb
+def glb(out, tris_cap):
+ os.makedirs(out, exist_ok=True)
+ bpy.ops.object.select_all(action="DESELECT")
+ done = set()
+ for o in scene_objects():
+ if o.type == "MESH" and o.data.name not in done:
+ n = sum(len(p.vertices) - 2 for p in o.data.polygons)
+ if n > tris_cap:
+ dec = o.modifiers.new("refine_decimate", "DECIMATE")
+ dec.ratio = tris_cap / n
+ done.add(o.data.name)
+ o.select_set(o.type in ("MESH", "LIGHT"))
+ tex = opt("--tex", 1024) # generated meshes carry 4K sets; a browser viewer needs far less
+ for im in bpy.data.images:
+ if max(im.size) > tex:
+ s = tex / max(im.size)
+ im.scale(max(1, int(im.size[0] * s)), max(1, int(im.size[1] * s)))
+ path = os.path.join(out, "scene.glb")
+ bpy.ops.export_scene.gltf(filepath=path, use_selection=True, export_apply=True, export_lights=True,
+ export_draco_mesh_compression_enable=True, export_image_format="JPEG", export_cameras=False)
+ print("refine: wrote", path, f"{os.path.getsize(path) / 1e6:.0f} MB")
+
+
+if __name__ == "__main__":
+ if cmd == "views":
+ views(argv[1])
+ elif cmd == "apply":
+ apply(json.load(open(argv[1], encoding="utf-8")), argv[2])
+ elif cmd == "pano":
+ pano(argv[1], argv[2])
+ elif cmd == "glb":
+ glb(argv[1], opt("--tris", 60000))
diff --git a/endpoint/schema.py b/endpoint/schema.py
new file mode 100644
index 0000000..48e47ae
--- /dev/null
+++ b/endpoint/schema.py
@@ -0,0 +1,86 @@
+"""The scene plan: the editable layout the /plan call returns and /build consumes. See docs/ENDPOINT.md.
+
+Metres, Z up. Origin = floor at the room's front-left corner seen from the entrance: X right along the front wall,
+Y into the room. Walls: front (y=0), back (y=depth), left (x=0), right (x=width). rot 0 = object faces -Y.
+"""
+
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+Source = Literal["reference", "invented"]
+Wall = Literal["front", "back", "left", "right"]
+
+
+class Room(BaseModel):
+ width: float = Field(description="Extent along X in metres (the front wall).")
+ depth: float = Field(description="Extent along Y in metres (into the space).")
+ height: float = Field(description="Ceiling or awning height in metres.")
+
+
+class Opening(BaseModel):
+ wall: Wall
+ kind: Literal["door", "window", "shopfront", "opening"]
+ center: float = Field(description="Centre position along the wall in metres: the X coordinate for front/back "
+ "walls, the Y coordinate for left/right walls.")
+ width: float
+ height: float
+ sill: float = Field(0.0, description="Height of the bottom edge above the floor.")
+
+
+class SceneObject(BaseModel):
+ id: str = Field(description="snake_case, unique, e.g. kitchen_cart, stool_red_3.")
+ label: str = Field(description="Short human description.")
+ asset: str = Field("", description="snake_case asset key. Identical objects (a set of chairs, a row of stools, matching "
+ "mugs) share one key and are generated once; give every distinct design its own.")
+ category: Literal["structure", "furniture", "fixture", "prop", "clutter", "decal", "signage"]
+ x: float = Field(description="Footprint centre X.")
+ y: float = Field(description="Footprint centre Y.")
+ z: float = Field(0.0, description="Height of the object's base (0 = on the floor; a counter-top prop sits higher).")
+ w: float = Field(description="Size along the object's own X (width) in metres.")
+ d: float = Field(description="Size along the object's own Y (depth) in metres.")
+ h: float = Field(description="Height in metres.")
+ rot: float = Field(0.0, description="Rotation about Z in degrees; 0 = faces -Y (the entrance).")
+ source: Source
+ generate: bool = Field(description="True if this object should be generated as a 3D mesh; False for simple "
+ "geometry built by script (walls, counters, shelves, boxes, paper).")
+ prompt: str = Field("", description="For generated objects: one-object description with condition and materials, "
+ "no brand names.")
+ material: str = Field("", description="For objects that are NOT generated (counters, walls, shelves, panels, boxes): "
+ "the surface as a texture description, e.g. \"scuffed beige enamelled steel\". "
+ "Empty for generated objects.")
+ crop: list[float] | None = Field(None, description="Where the object appears in reference image 0, as normalised "
+ "[x0, y0, x1, y1]; null if not visible.")
+
+
+class Light(BaseModel):
+ id: str
+ kind: Literal["practical", "neon", "window", "street", "screen", "fire", "fill"]
+ x: float
+ y: float
+ z: float
+ color: str = Field(description="Hex colour, e.g. #ffb46b.")
+ power: Literal["low", "medium", "high"]
+ attached_to: str = Field("", description="Object id the light belongs to, if any.")
+ source: Source
+
+
+class Camera(BaseModel):
+ position: list[float] = Field(description="[x, y, z] in metres.")
+ look_at: list[float] = Field(description="[x, y, z] point the camera aims at.")
+ lens_mm: float = Field(description="Focal length on a 36 mm-wide sensor.")
+
+
+class Plan(BaseModel):
+ name: str = Field(description="kebab-case scene name, e.g. hk-dai-pai-dong.")
+ summary: str
+ setting: Literal["interior", "semi_outdoor", "exterior"]
+ time_of_day: str
+ mood: list[str]
+ palette: list[str] = Field(description="3-6 hex colours that define the look.")
+ room: Room
+ openings: list[Opening]
+ objects: list[SceneObject]
+ lights: list[Light]
+ reference_camera: Camera = Field(description="Best estimate of where the camera stood for reference image 0.")
+ notes: list[str] = Field(description="What was invented beyond the reference, and any assumptions.")
diff --git a/endpoint/stages.py b/endpoint/stages.py
new file mode 100644
index 0000000..c00afe0
--- /dev/null
+++ b/endpoint/stages.py
@@ -0,0 +1,35 @@
+"""Stage events: one JSON object per line on stdout, prefixed so clients can pick them out of the fal queue logs."""
+
+import json
+import sys
+import time
+
+PREFIX = "ANYSCENE_STAGE "
+
+
+class Stages:
+ def __init__(self, request_id: str = ""):
+ self.request_id = request_id
+ self.t0 = time.time()
+ self.current = None
+
+ def emit(self, stage: str, status: str = "running", message: str = "", progress: float | None = None,
+ preview_url: str | None = None, **extra):
+ event = {"stage": stage, "status": status, "message": message, "elapsed_s": round(time.time() - self.t0, 1)}
+ if progress is not None:
+ event["progress"] = round(progress, 3)
+ if preview_url:
+ event["preview_url"] = preview_url
+ event.update(extra)
+ print(PREFIX + json.dumps(event), flush=True)
+ sys.stdout.flush()
+ self.current = stage
+
+ def start(self, stage, message=""):
+ self.emit(stage, "running", message)
+
+ def done(self, stage, message="", **extra):
+ self.emit(stage, "done", message, **extra)
+
+ def fail(self, message):
+ self.emit(self.current or "unknown", "failed", message)
diff --git a/endpoint/test/plan_sample.json b/endpoint/test/plan_sample.json
new file mode 100644
index 0000000..0cbcde9
--- /dev/null
+++ b/endpoint/test/plan_sample.json
@@ -0,0 +1,35 @@
+{
+ "name": "test-street-stall",
+ "summary": "Hand-written sample plan for testing the floor plan and blockout renderers",
+ "setting": "semi_outdoor",
+ "time_of_day": "night",
+ "mood": ["humid", "neon"],
+ "palette": ["#2b3a2f", "#c0392b", "#f5b041"],
+ "room": {"width": 6.0, "depth": 7.0, "height": 3.0},
+ "openings": [{"wall": "front", "kind": "shopfront", "center": 3.0, "width": 5.2, "height": 2.7, "sill": 0.0},
+ {"wall": "back", "kind": "door", "center": 4.8, "width": 0.9, "height": 2.1, "sill": 0.0}],
+ "objects": [
+ {"id": "kitchen_cart", "label": "green steel cart", "category": "furniture", "x": 0.6, "y": 4.6, "z": 0.0, "w": 2.4, "d": 0.8, "h": 1.0, "rot": 90, "source": "reference", "generate": true, "prompt": "", "crop": [0.0, 0.2, 0.4, 0.7]},
+ {"id": "wok_range", "label": "two-burner wok range", "category": "fixture", "x": 0.6, "y": 2.6, "z": 0.0, "w": 1.2, "d": 0.75, "h": 0.85, "rot": 90, "source": "reference", "generate": true, "prompt": "", "crop": null},
+ {"id": "shelf_back", "label": "steel shelving", "category": "furniture", "x": 2.4, "y": 6.75, "z": 0.0, "w": 2.0, "d": 0.4, "h": 1.9, "rot": 180, "source": "invented", "generate": false, "prompt": "", "crop": null},
+ {"id": "fridge", "label": "drinks fridge", "category": "fixture", "x": 5.55, "y": 5.9, "z": 0.0, "w": 0.7, "d": 0.7, "h": 1.85, "rot": 270, "source": "invented", "generate": true, "prompt": "", "crop": null},
+ {"id": "table_1", "label": "round folding table", "category": "furniture", "x": 2.6, "y": 2.0, "z": 0.0, "w": 0.9, "d": 0.9, "h": 0.74, "rot": 0, "source": "reference", "generate": true, "prompt": "", "crop": null},
+ {"id": "table_2", "label": "round folding table", "category": "furniture", "x": 4.4, "y": 2.4, "z": 0.0, "w": 0.9, "d": 0.9, "h": 0.74, "rot": 0, "source": "reference", "generate": true, "prompt": "", "crop": null},
+ {"id": "table_3", "label": "round folding table", "category": "furniture", "x": 3.6, "y": 4.3, "z": 0.0, "w": 0.9, "d": 0.9, "h": 0.74, "rot": 0, "source": "invented", "generate": true, "prompt": "", "crop": null},
+ {"id": "stool_1", "label": "red plastic stool", "category": "furniture", "x": 2.0, "y": 1.6, "z": 0.0, "w": 0.32, "d": 0.32, "h": 0.45, "rot": 10, "source": "reference", "generate": true, "prompt": "", "crop": null},
+ {"id": "stool_2", "label": "red plastic stool", "category": "furniture", "x": 3.2, "y": 2.5, "z": 0.0, "w": 0.32, "d": 0.32, "h": 0.45, "rot": 30, "source": "reference", "generate": true, "prompt": "", "crop": null},
+ {"id": "stool_3", "label": "red plastic stool", "category": "furniture", "x": 4.9, "y": 1.8, "z": 0.0, "w": 0.32, "d": 0.32, "h": 0.45, "rot": 0, "source": "reference", "generate": true, "prompt": "", "crop": null},
+ {"id": "stool_4", "label": "red plastic stool", "category": "furniture", "x": 3.0, "y": 4.8, "z": 0.0, "w": 0.32, "d": 0.32, "h": 0.45, "rot": 0, "source": "invented", "generate": true, "prompt": "", "crop": null},
+ {"id": "teapot", "label": "enamel teapot", "category": "prop", "x": 2.6, "y": 2.0, "z": 0.74, "w": 0.2, "d": 0.15, "h": 0.18, "rot": 0, "source": "reference", "generate": true, "prompt": "", "crop": null},
+ {"id": "gas_cylinder", "label": "LPG cylinder", "category": "prop", "x": 0.35, "y": 6.3, "z": 0.0, "w": 0.32, "d": 0.32, "h": 0.6, "rot": 0, "source": "invented", "generate": true, "prompt": "", "crop": null},
+ {"id": "sign_board", "label": "menu sign board", "category": "signage", "x": 1.4, "y": 3.6, "z": 2.1, "w": 1.8, "d": 0.05, "h": 0.6, "rot": 90, "source": "reference", "generate": false, "prompt": "", "crop": null}
+ ],
+ "lights": [
+ {"id": "bulb_1", "kind": "practical", "x": 1.2, "y": 3.0, "z": 2.5, "color": "#ffb46b", "power": "medium", "attached_to": "", "source": "reference"},
+ {"id": "bulb_2", "kind": "practical", "x": 1.2, "y": 5.0, "z": 2.5, "color": "#ffb46b", "power": "medium", "attached_to": "", "source": "reference"},
+ {"id": "neon_1", "kind": "neon", "x": 5.8, "y": 3.5, "z": 2.6, "color": "#ff3b6b", "power": "high", "attached_to": "", "source": "invented"},
+ {"id": "fridge_glow", "kind": "screen", "x": 5.2, "y": 5.9, "z": 1.0, "color": "#d8ecff", "power": "low", "attached_to": "fridge", "source": "invented"}
+ ],
+ "reference_camera": {"position": [4.6, -1.6, 1.55], "look_at": [1.6, 4.5, 1.0], "lens_mm": 28},
+ "notes": ["Back half of the stall (shelving, fridge, gas cylinder, third table) is invented."]
+}
diff --git a/farm/.bundles.json b/farm/.bundles.json
new file mode 100644
index 0000000..a7403cd
--- /dev/null
+++ b/farm/.bundles.json
@@ -0,0 +1,12 @@
+{
+ "mission-control-1970s": {
+ "id": "58e4b9dd67215e25",
+ "key": "farm/bundles/mission-control-1970s/58e4b9dd67215e25.zip",
+ "time": "2026-10-30 22:15"
+ },
+ "hk-dai-pai-dong": {
+ "id": "ba33fd200d7ad0b2",
+ "key": "farm/bundles/hk-dai-pai-dong/ba33fd200d7ad0b2.zip",
+ "time": "2026-10-30 22:33"
+ }
+}
\ No newline at end of file
diff --git a/farm/app.py b/farm/app.py
new file mode 100644
index 0000000..8fb8b4f
--- /dev/null
+++ b/farm/app.py
@@ -0,0 +1,232 @@
+"""AnyScene render farm: headless Blender on fal serverless GPUs.
+
+One request = one chunk of frames. The scene arrives as a self-contained bundle (see farm/pack.py) behind a short-lived
+download URL; each runner downloads a bundle once to its own local disk, so later chunks of the same scene on that
+runner start rendering straight away. Frames go back as a zip on fal's file store, so the worker never holds storage credentials.
+
+ fal deploy farm/app.py::BlenderFarm # or: fal run farm/app.py::BlenderFarm for a throwaway URL
+ fal deploy farm/app.py::BlenderFarm --app-name blender-farm-2 --auth private
+ (adds `outputs`, which the Blender add-on in blender_addon/
+ uses to get non-PNG frames back; requests without it behave as before)
+ uv run --with fal-client --with boto3 python farm/submit.py ... (see farm/README.md)
+"""
+
+import hashlib
+import os
+import shutil
+import subprocess
+import time
+import urllib.request
+import zipfile
+from pathlib import Path, PurePosixPath
+
+import fal
+from fal.container import ContainerImage
+
+from pydantic import BaseModel, Field
+
+if os.name == "nt":
+ # Deploying from Windows: ContainerImage's context_dir default is the cwd as a WindowsPath, evaluated at import.
+ # It gets pickled along with the app and Linux can't unpickle a WindowsPath, so swap it for a POSIX path.
+ _posix = PurePosixPath("/tmp")
+ ContainerImage.__dataclass_fields__["context_dir"].default = _posix
+ ContainerImage.context_dir = _posix # dataclasses also keep the default as a class attribute
+ ContainerImage.__init__.__defaults__ = tuple(
+ _posix if isinstance(d, os.PathLike) else d for d in ContainerImage.__init__.__defaults__ or ()
+ )
+
+BLENDER_VERSION = "5.0.1"
+
+DOCKERFILE = f"""
+FROM python:3.13-slim
+# Expose the driver's graphics libraries too: OptiX (libnvoptix) ships with them, not with plain compute.
+ENV NVIDIA_DRIVER_CAPABILITIES=all
+RUN apt-get update && apt-get install -y --no-install-recommends \\
+ curl ca-certificates xz-utils libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 libegl1 \\
+ libxkbcommon0 libsm6 libice6 libx11-6 libglib2.0-0 \\
+ && rm -rf /var/lib/apt/lists/*
+RUN curl -fsSL https://download.blender.org/release/Blender{BLENDER_VERSION[:3]}/blender-{BLENDER_VERSION}-linux-x64.tar.xz \\
+ | tar -xJ -C /opt \\
+ && ln -s /opt/blender-{BLENDER_VERSION}-linux-x64/blender /usr/local/bin/blender
+"""
+
+# A plain string: a Path built here would be pickled as WindowsPath when deploying from Windows.
+# Local disk, not /data: a bundle on the shared /data mount is read by every worker at once, and on a 42-worker fan-out
+# of a 1.6 GB set that contention held each worker ~30 min before its first frame (alone, the same set renders its first
+# frame in 17 s). Each worker downloads the bundle from the CDN instead, which serves parallel downloads well.
+CACHE_DIR = "/tmp/anyscene-farm/bundles"
+
+# OptiX compiles its kernels on a worker's first Cycles render (~2 min) into a local sqlite cache. Without help every
+# new worker pays that before its first frame, which on a 100-worker fan-out was most of the bill. Keep the cache on
+# /data per GPU model, start each worker from it, warm it in setup() and save it back when it grows.
+OPTIX_CACHE_LOCAL_DIR = "/var/tmp/OptixCache_root"
+OPTIX_CACHE_SHARED_DIR = "/data/anyscene-farm/optix"
+WARMUP = """import bpy
+prefs = bpy.context.preferences.addons["cycles"].preferences
+prefs.compute_device_type = "OPTIX"
+prefs.get_devices()
+for d in prefs.devices:
+ d.use = d.type == "OPTIX"
+s = bpy.context.scene
+s.render.engine = "CYCLES"; s.cycles.device = "GPU"; s.cycles.samples = 4
+s.render.resolution_x = s.render.resolution_y = 64
+glass = bpy.data.materials.new("glass"); glass.use_nodes = True
+nt = glass.node_tree; nt.links.new(nt.nodes.new("ShaderNodeBsdfGlass").outputs[0], nt.nodes["Material Output"].inputs[0])
+bpy.ops.mesh.primitive_cube_add(size=4)
+haze = bpy.data.materials.new("haze"); haze.use_nodes = True
+nt = haze.node_tree; nt.links.new(nt.nodes.new("ShaderNodeVolumePrincipled").outputs[0], nt.nodes["Material Output"].inputs["Volume"])
+bpy.context.object.data.materials.append(haze)
+bpy.ops.mesh.primitive_uv_sphere_add(location=(0, 0, 0.5))
+bpy.context.object.data.materials.append(glass)
+bpy.ops.render.render()
+print("WARMUP done")
+"""
+
+
+def optix_shared_dir(device: str) -> str:
+ """The shared cache for this GPU model and driver: kernels compiled on one don't load on another."""
+ slug = "".join(c if c.isalnum() else "_" for c in device)[:80]
+ return f"{OPTIX_CACHE_SHARED_DIR}/{slug}"
+
+
+def load_optix_cache(device: str):
+ src = optix_shared_dir(device)
+ if os.path.isdir(src):
+ shutil.copytree(src, OPTIX_CACHE_LOCAL_DIR, dirs_exist_ok=True)
+
+
+def save_optix_cache(device: str):
+ """Copy this worker's cache to /data if it has grown (atomic per file; concurrent workers just race)."""
+ if not os.path.isdir(OPTIX_CACHE_LOCAL_DIR):
+ return
+ dst = optix_shared_dir(device)
+ os.makedirs(dst, exist_ok=True)
+ for name in os.listdir(OPTIX_CACHE_LOCAL_DIR):
+ a, b = os.path.join(OPTIX_CACHE_LOCAL_DIR, name), os.path.join(dst, name)
+ if os.path.isfile(a) and (not os.path.exists(b) or os.path.getsize(a) > os.path.getsize(b)):
+ tmp = f"{b}.{os.getpid()}.tmp"
+ shutil.copy(a, tmp)
+ os.replace(tmp, b)
+
+
+class RenderJob(BaseModel):
+ bundle_url: str = Field(description="Download URL of the scene bundle zip (e.g. a presigned R2 link).")
+ bundle_id: str = Field(description="Content hash of the bundle; runners cache bundles by this id.")
+ blender_args: list[str] = Field(
+ description="Arguments after `blender -b`. {bundle} expands to the unpacked bundle dir, {out} to the output dir."
+ )
+ timeout_s: int = Field(3000, description="Kill Blender after this many seconds.")
+ outputs: list[str] = Field(
+ ["**/*.png"],
+ description="Glob patterns (relative to {out}) of the files to return. The default is the original PNG-only "
+ "behaviour; ['frames/**/*'] returns EXR, JPEG, TIFF... exactly as Blender wrote them.",
+ )
+
+
+class RenderResult(BaseModel):
+ frames_url: str = Field(description="Zip of the rendered frames on fal storage.")
+ frame_count: int
+ render_seconds: float
+ bundle_seconds: float
+ device: str
+ log_tail: str
+
+
+def fetch_bundle(url: str, bundle_id: str) -> Path:
+ """Download and unpack a bundle once per cache; concurrent requests on the same runner wait on a lock."""
+ import fcntl # Linux-only; the worker runs Linux, but `fal deploy` imports this module locally too
+
+ CACHE = Path(CACHE_DIR)
+
+ if not bundle_id.isalnum():
+ raise ValueError("bundle_id must be alphanumeric")
+ dest = CACHE / bundle_id
+ if (dest / ".ready").exists():
+ return dest
+ CACHE.mkdir(parents=True, exist_ok=True)
+ with open(CACHE / f"{bundle_id}.lock", "w") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ if (dest / ".ready").exists():
+ return dest
+ tmp = CACHE / f"{bundle_id}.part"
+ shutil.rmtree(tmp, ignore_errors=True)
+ tmp.mkdir()
+ zpath = tmp / "bundle.zip"
+ sha = hashlib.sha256()
+ with urllib.request.urlopen(url, timeout=600) as r, open(zpath, "wb") as f:
+ while chunk := r.read(8 << 20):
+ sha.update(chunk)
+ f.write(chunk)
+ if not sha.hexdigest().startswith(bundle_id):
+ raise ValueError(f"bundle hash mismatch: got {sha.hexdigest()[:16]}")
+ with zipfile.ZipFile(zpath) as z:
+ z.extractall(tmp / "b")
+ zpath.unlink()
+ shutil.rmtree(dest, ignore_errors=True)
+ (tmp / "b").rename(dest)
+ shutil.rmtree(tmp, ignore_errors=True)
+ (dest / ".ready").touch()
+ return dest
+
+
+class BlenderFarm(fal.App):
+ # RTX 5090 (32 GB) by default: $2.50/h vs $4.00/h for the RTX PRO 6000 (96 GB) at about 10% fewer cores. Switch to
+ # "GPU-RTXPRO6000" for sets that need more than 32 GB of VRAM.
+ machine_type = "GPU-RTX5090"
+ # No COPY steps, so no build context is needed; a pure POSIX path keeps the pickled app loadable on Linux when
+ # it is deployed from Windows (the default context_dir is a WindowsPath).
+ image = ContainerImage.from_dockerfile_str(DOCKERFILE, context_dir=PurePosixPath("/tmp"))
+ requirements = ["pydantic", "fal==1.84.0"] # fal.toolkit for uploading the frames zip
+ min_concurrency = 0
+ keep_alive = 300 # a burst of orders reuses warm workers (booted, kernels compiled) instead of booting new ones
+ max_concurrency = 100 # account cap raised to 100 (Max Concurrency Cap); FARM_WORKERS on the shots app matches
+ request_timeout = 3600
+ startup_timeout = 1800
+
+ def setup(self):
+ smi = subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version,memory.total", "--format=csv,noheader"],
+ capture_output=True, text=True)
+ self.device = smi.stdout.strip() or "unknown GPU"
+ ver = subprocess.run(["blender", "-b", "--version"], capture_output=True, text=True)
+ load_optix_cache(self.device)
+ t = time.time()
+ r = subprocess.run(["blender", "-b", "--factory-startup", "--python-expr", WARMUP], capture_output=True,
+ text=True, timeout=900)
+ warm = f"OptiX warm-up {'ok' if 'WARMUP done' in r.stdout else 'FAILED'} in {time.time() - t:.0f} s"
+ save_optix_cache(self.device)
+ print("farm ready:", self.device, "|", ver.stdout.splitlines()[0] if ver.stdout else ver.stderr[-200:], "|", warm)
+
+ @fal.endpoint("/")
+ def render(self, job: RenderJob) -> RenderResult:
+ # Imported here, not at module level: fal.toolkit holds Path constants that pickle as WindowsPath when the
+ # app is deployed from Windows, and the Linux worker then can't load the app.
+ from fal.toolkit import File
+
+ t0 = time.time()
+ bundle = fetch_bundle(job.bundle_url, job.bundle_id)
+ t1 = time.time()
+ out = Path(f"/tmp/out-{os.getpid()}-{int(t1 * 1000)}")
+ out.mkdir(parents=True)
+ args = [a.replace("{bundle}", str(bundle)).replace("{out}", str(out)) for a in job.blender_args]
+ proc = subprocess.run(["blender", "-b", *args], capture_output=True, text=True, timeout=job.timeout_s, cwd=bundle)
+ t2 = time.time()
+ save_optix_cache(self.device) # a scene can need kernels the warm-up didn't compile
+ log = (proc.stdout + proc.stderr)[-4000:]
+ pngs = sorted({p for pat in job.outputs for p in out.glob(pat) if p.is_file()})
+ if proc.returncode != 0 or not pngs:
+ raise RuntimeError(f"blender exited {proc.returncode} with {len(pngs)} frames\n{log}")
+ zpath = out.with_suffix(".zip")
+ with zipfile.ZipFile(zpath, "w", zipfile.ZIP_STORED) as z: # image formats are already compressed
+ for p in pngs:
+ z.write(p, p.relative_to(out).as_posix())
+ result = RenderResult(
+ frames_url=File.from_path(zpath, content_type="application/zip").url,
+ frame_count=len(pngs),
+ render_seconds=round(t2 - t1, 1),
+ bundle_seconds=round(t1 - t0, 1),
+ device=self.device,
+ log_tail=log[-1500:],
+ )
+ shutil.rmtree(out, ignore_errors=True)
+ zpath.unlink(missing_ok=True)
+ return result
diff --git a/farm/farm.py b/farm/farm.py
new file mode 100644
index 0000000..ab59845
--- /dev/null
+++ b/farm/farm.py
@@ -0,0 +1,177 @@
+"""Render a scene's shots on the fal farm (farm/app.py) instead of the local GPU.
+
+ uv run --with fal-client --with boto3 python farm/farm.py bundle <scene> pack + upload, prints the bundle id
+ uv run --with fal-client --with boto3 python farm/farm.py render <scene> --app <owner/app> [--shots a,b] [--frames 1-24]
+ [--chunk 24] [--out DIR]
+
+<scene> is a folder under scenes/; its farm settings live in farm/jobs/<scene>.json:
+ {"blend": "mc.blend", the scene file (never modified; packed into a copy)
+ "scripts": ["scripts/gpu_prefs.py"], run before camera/shoot.py, in order (paths relative to the scene)
+ "per_shot_scripts": {"scripts/nocurl.py": {"except": ["orbital_push"]}}}
+Frames land in <out>/<shot>/frames/####.png, the same layout camera/shoot.py writes locally, so the scene's grade
+step runs on them unchanged. Existing frames are skipped, so a render can be resumed or topped up.
+"""
+
+import argparse
+import concurrent.futures as cf
+import hashlib
+import io
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+import zipfile
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+STATE = ROOT / "farm" / ".bundles.json" # scene -> last uploaded bundle (id, key)
+BUCKET = "anyscene-packs" # private; bundles are fetched through presigned links
+
+
+def user_env(name):
+ if os.environ.get(name):
+ return os.environ[name]
+ if sys.platform == "win32":
+ out = subprocess.run(["reg", "query", r"HKCU\Environment", "/v", name], capture_output=True, text=True).stdout
+ parts = out.split()
+ if name in parts:
+ return parts[parts.index(name) + 2]
+ return None
+
+
+def s3():
+ import boto3
+ from botocore.config import Config
+
+ return boto3.client(
+ "s3", region_name="auto", endpoint_url=f"https://{user_env('R2_ACCOUNT_ID')}.r2.cloudflarestorage.com",
+ aws_access_key_id=user_env("R2_ACCESS_KEY_ID"), aws_secret_access_key=user_env("R2_SECRET_ACCESS_KEY"),
+ config=Config(signature_version="s3v4"),
+ )
+
+
+def blender():
+ exe = os.environ.get("BLENDER") or shutil.which("blender") or r"C:\Program Files\Blender Foundation\Blender 5.0\blender.exe"
+ if not Path(exe).exists() and not shutil.which(exe):
+ sys.exit("Blender not found; set BLENDER")
+ return exe
+
+
+def job_config(scene):
+ return json.loads((ROOT / "farm" / "jobs" / f"{scene}.json").read_text())
+
+
+def cmd_bundle(scene):
+ cfg = job_config(scene)
+ sdir = ROOT / "scenes" / scene
+ stage = Path(tempfile.mkdtemp(prefix=f"farm-{scene}-"))
+ print(f"packing {cfg['blend']} (the scene file is only read)...", flush=True)
+ r = subprocess.run([blender(), "-b", str(sdir / cfg["blend"]), "--python", str(ROOT / "farm" / "pack.py"), "--",
+ str(stage / "scene.blend")], capture_output=True, text=True)
+ for line in (r.stdout + r.stderr).splitlines():
+ if line.startswith("pack:") or "Error" in line:
+ print(" ", line)
+ if r.returncode != 0 or not (stage / "scene.blend").exists():
+ sys.exit("pack failed")
+ shutil.copytree(ROOT / "camera", stage / "camera", ignore=shutil.ignore_patterns("__pycache__", "test", "examples"))
+ shutil.copy(sdir / "shots.json", stage / "shots.json")
+ for s in cfg.get("scripts", []) + list(cfg.get("per_shot_scripts", {})):
+ shutil.copy(sdir / s, stage / Path(s).name)
+ zpath = stage.with_suffix(".zip")
+ with zipfile.ZipFile(zpath, "w", zipfile.ZIP_STORED) as z: # the .blend is already compressed
+ for p in sorted(stage.rglob("*")):
+ if p.is_file():
+ z.write(p, p.relative_to(stage).as_posix())
+ sha = hashlib.sha256(zpath.read_bytes()).hexdigest()
+ bundle_id, key = sha[:16], f"farm/bundles/{scene}/{sha[:16]}.zip"
+ print(f"uploading {zpath.stat().st_size / 1e6:.0f} MB as {BUCKET}/{key}", flush=True)
+ s3().upload_file(str(zpath), BUCKET, key)
+ state = json.loads(STATE.read_text()) if STATE.exists() else {}
+ state[scene] = {"id": bundle_id, "key": key, "time": time.strftime("%Y-%m-%d %H:%M")}
+ STATE.write_text(json.dumps(state, indent=1))
+ shutil.rmtree(stage, ignore_errors=True)
+ zpath.unlink()
+ print("bundle", bundle_id)
+
+
+def chunks(n, chunk, frames=None):
+ a0, b0 = (map(int, frames.split("-")) if frames else (1, n))
+ for a in range(a0, b0 + 1, chunk):
+ yield a, min(a + chunk - 1, b0)
+
+
+def cmd_render(scene, app, shots, frames, chunk, out, workers):
+ # The farm app lives on a Serverless-enabled account, which may differ from the FAL_KEY used for generation.
+ if user_env("FAL_SERVERLESS_KEY"):
+ os.environ["FAL_KEY"] = user_env("FAL_SERVERLESS_KEY")
+ import fal_client
+
+ cfg = job_config(scene)
+ bundle = json.loads(STATE.read_text())[scene]
+ url = s3().generate_presigned_url("get_object", Params={"Bucket": BUCKET, "Key": bundle["key"]}, ExpiresIn=6 * 3600)
+ defs = {s["name"]: s for s in json.loads((ROOT / "scenes" / scene / "shots.json").read_text())["shots"]}
+ shots = shots.split(",") if shots else list(defs)
+ out = Path(out or ROOT / "scenes" / scene / "out" / "shots")
+
+ jobs = []
+ for shot in shots:
+ have = {int(p.stem) for p in (out / shot / "frames").glob("*.png")}
+ for a, b in chunks(defs[shot]["frames"], chunk, frames):
+ if all(f in have for f in range(a, b + 1)):
+ continue
+ pre = []
+ for s in cfg.get("scripts", []):
+ pre += ["--python", "{bundle}/" + Path(s).name]
+ for s, rule in cfg.get("per_shot_scripts", {}).items():
+ if shot not in rule.get("except", []):
+ pre += ["--python", "{bundle}/" + Path(s).name]
+ args = ["{bundle}/scene.blend", *pre, "--python", "{bundle}/camera/shoot.py", "--",
+ "--shots", "{bundle}/shots.json", "--out", "{out}", "--only", shot, "--frames", f"{a}-{b}", "--no-encode"]
+ jobs.append((shot, a, b, {"bundle_url": url, "bundle_id": bundle["id"], "blender_args": args}))
+ print(f"{len(jobs)} chunks for {scene} on {app} (bundle {bundle['id']})", flush=True)
+
+ def run(job):
+ shot, a, b, payload = job
+ t0 = time.time()
+ res = fal_client.subscribe(app, arguments=payload)
+ data = urllib.request.urlopen(res["frames_url"], timeout=600).read()
+ with zipfile.ZipFile(io.BytesIO(data)) as z:
+ for name in z.namelist(): # <shot>/frames/####.png
+ dest = out / name
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(z.read(name))
+ return (f"{shot} {a}-{b}: {res['frame_count']} frames, render {res['render_seconds']} s, bundle {res['bundle_seconds']} s,"
+ f" wall {time.time() - t0:.0f} s on {res['device']}")
+
+ t0 = time.time()
+ with cf.ThreadPoolExecutor(workers) as pool:
+ for fut in cf.as_completed([pool.submit(run, j) for j in jobs]):
+ try:
+ print(fut.result(), flush=True)
+ except Exception as e: # keep going; a rerun picks up missing chunks
+ print("FAILED:", str(e)[:1500], flush=True)
+ print(f"done in {time.time() - t0:.0f} s; frames in {out}")
+
+
+if __name__ == "__main__":
+ p = argparse.ArgumentParser()
+ sub = p.add_subparsers(dest="cmd", required=True)
+ b = sub.add_parser("bundle")
+ b.add_argument("scene")
+ r = sub.add_parser("render")
+ r.add_argument("scene")
+ r.add_argument("--app", required=True)
+ r.add_argument("--shots")
+ r.add_argument("--frames")
+ r.add_argument("--chunk", type=int, default=24)
+ r.add_argument("--out")
+ r.add_argument("--workers", type=int, default=20)
+ a = p.parse_args()
+ if a.cmd == "bundle":
+ cmd_bundle(a.scene)
+ else:
+ cmd_render(a.scene, a.app, a.shots, a.frames, a.chunk, a.out, a.workers)
diff --git a/farm/jobs/hk-dai-pai-dong.json b/farm/jobs/hk-dai-pai-dong.json
new file mode 100644
index 0000000..6156b58
--- /dev/null
+++ b/farm/jobs/hk-dai-pai-dong.json
@@ -0,0 +1,4 @@
+{
+ "blend": "hk.blend",
+ "scripts": ["scripts/gpu_prefs.py"]
+}
diff --git a/farm/jobs/mission-control-1970s.json b/farm/jobs/mission-control-1970s.json
new file mode 100644
index 0000000..9cff564
--- /dev/null
+++ b/farm/jobs/mission-control-1970s.json
@@ -0,0 +1,5 @@
+{
+ "blend": "mc.blend",
+ "scripts": ["scripts/gpu_prefs.py"],
+ "per_shot_scripts": { "scripts/nocurl.py": { "except": ["orbital_push"] } }
+}
diff --git a/farm/pack.py b/farm/pack.py
new file mode 100644
index 0000000..0dae6db
--- /dev/null
+++ b/farm/pack.py
@@ -0,0 +1,45 @@
+"""Make a scene .blend self-contained for the render farm (run inside Blender, never on the working file in place).
+
+ blender -b scene.blend --python farm/pack.py -- <out.blend>
+
+Packs images, fonts, sounds and volumes into the file, makes linked library data local, and refuses to write the
+bundle if anything still points outside it (fluid/particle caches have to be shipped next to the .blend instead; the
+script prints them). The input file is never saved.
+"""
+
+import os
+import sys
+
+import bpy
+
+out = sys.argv[sys.argv.index("--") + 1]
+
+if bpy.data.libraries:
+ print("pack: making linked data local from", [l.filepath for l in bpy.data.libraries])
+ bpy.ops.object.make_local(type="ALL")
+
+bpy.ops.file.pack_all()
+
+problems = []
+for mod_owner in bpy.data.objects:
+ for m in mod_owner.modifiers:
+ if m.type == "FLUID" and m.fluid_type == "DOMAIN":
+ problems.append(f"fluid cache {mod_owner.name}: {bpy.path.abspath(m.domain_settings.cache_directory)}")
+for img in bpy.data.images:
+ if img.source in {"FILE", "SEQUENCE", "TILED"} and not img.packed_file and img.filepath and img.users:
+ problems.append(f"image not packed: {img.name} -> {img.filepath}")
+for v in bpy.data.volumes:
+ if not v.packed_file and v.filepath:
+ problems.append(f"volume not packed: {v.name} -> {v.filepath}")
+for lib in bpy.data.libraries:
+ problems.append(f"library still linked: {lib.filepath}")
+
+print("pack: external paths left:", len(problems))
+for p in problems:
+ print("pack: ", p)
+if any(not p.startswith("fluid cache") for p in problems):
+ sys.exit(1)
+
+os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
+bpy.ops.wm.save_as_mainfile(filepath=os.path.abspath(out), copy=True, compress=True)
+print("pack: wrote", out, f"{os.path.getsize(out) / 1e6:.0f} MB")
diff --git a/generate/fal.mjs b/generate/fal.mjs
index 3b10117..8a6ea54 100644
--- a/generate/fal.mjs
+++ b/generate/fal.mjs
@@ -7,13 +7,13 @@
// Commands
// image --out refs/tokyo-electronics-repair/concept_a --prompt "..." [--variant flare|sunburst] [--size landscape_16_9] [--quality high] [--n 1]
// -> <out>_<i>.png + <out>.json (keeps the fal URL so 3D endpoints can reuse it)
-// 3d --model tripo-h31|tripo-p2|meshy --ref refs/props/x.json --out assets/gen/<model>/<id>
+// 3d --model tripo-h31|tripo-p2|meshy --ref refs/props/x.json --out assets/gen/<model>/<id> [--face-limit 150000]
// -> <out>/model.glb + result.json
// spend -> totals so far
//
// All paid calls append {time, endpoint, est_usd, request_id, ...} to generate/spend.jsonl.
-import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
+import { appendFile, mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, join, resolve } from 'node:path';
@@ -61,7 +61,7 @@ const { positionals, values: a } = parseArgs({
options: {
out: { type: 'string' }, prompt: { type: 'string' }, variant: { type: 'string', default: 'flare' },
size: { type: 'string', default: 'landscape_16_9' }, quality: { type: 'string', default: 'high' }, n: { type: 'string', default: '1' },
- model: { type: 'string' }, ref: { type: 'string' },
+ model: { type: 'string' }, ref: { type: 'string' }, 'face-limit': { type: 'string' }, force: { type: 'boolean' },
},
});
@@ -82,15 +82,34 @@ async function call(url, init = {}) {
return text ? JSON.parse(text) : null;
}
-/** Queue-submit, poll, return result. Logs spend as soon as the request is accepted. */
-async function run(endpoint, input, { est, meta = {}, timeoutMin = 30 }) {
+/** Queue-submit, poll, return result. Logs spend as soon as the request is accepted.
+ * With `pending` (a file path), the submitted job is recorded there until its result is in. If a run is cut off (the
+ * process or the whole worker dies) and the same command runs again, it picks the recorded job back up instead of
+ * paying for a new one. */
+async function run(endpoint, input, { est, meta = {}, timeoutMin = 30, pending = null }) {
if (!KEY) throw new Error('FAL_KEY is not set (user environment variable)');
- const spent = (await readSpend()).reduce((s, r) => s + r.est_usd, 0);
- if (spent + est > TOTAL_CAP) throw new Error(`BUDGET: total would reach $${(spent + est).toFixed(2)} > $${TOTAL_CAP}. Stop and report.`);
const t0 = performance.now();
- const job = await call(`https://queue.fal.run/${endpoint}`, { method: 'POST', body: JSON.stringify(input) });
- await logSpend({ endpoint, est_usd: est, request_id: job.request_id, ...meta });
- console.log(`queued ${endpoint} ${job.request_id}`);
+ let job = null;
+ if (pending && existsSync(pending)) {
+ try {
+ job = JSON.parse(await readFile(pending, 'utf8'));
+ await call(job.status_url); // still known to the queue?
+ console.log(`resuming ${endpoint} ${job.request_id}`);
+ } catch {
+ job = null; // expired or unknown: submit again
+ }
+ }
+ if (!job) {
+ const spent = (await readSpend()).reduce((s, r) => s + r.est_usd, 0);
+ if (spent + est > TOTAL_CAP) throw new Error(`BUDGET: total would reach $${(spent + est).toFixed(2)} > $${TOTAL_CAP}. Stop and report.`);
+ job = await call(`https://queue.fal.run/${endpoint}`, { method: 'POST', body: JSON.stringify(input) });
+ await logSpend({ endpoint, est_usd: est, request_id: job.request_id, ...meta });
+ if (pending) {
+ await mkdir(dirname(pending), { recursive: true });
+ await writeFile(pending, JSON.stringify(job));
+ }
+ console.log(`queued ${endpoint} ${job.request_id}`);
+ }
for (;;) {
await new Promise((r) => setTimeout(r, 4000));
const st = await call(job.status_url);
@@ -118,9 +137,15 @@ function need(name) {
async function cmdImage() {
const out = resolve(REPO, need('out'));
+ // already made (a resumed build re-running its batch): never pay twice. --force regenerates.
+ if (!a.force && existsSync(`${out}.json`) && [...Array(+a.n).keys()].every((i) => existsSync(`${out}_${i}.png`))) {
+ console.log(`exists ${a.out}_0.png (skipped; --force to regenerate)`);
+ return;
+ }
const endpoint = `openai/gpt-image-2.5/${a.variant}/text-to-image`;
const input = { prompt: need('prompt'), image_size: a.size, quality: a.quality, num_images: +a.n, output_format: 'png' };
- const { result, request_id, seconds } = await run(endpoint, input, { est: EST.image * +a.n, meta: { kind: 'image', out: a.out } });
+ const { result, request_id, seconds } = await run(endpoint, input, { est: EST.image * +a.n, meta: { kind: 'image', out: a.out },
+ pending: `${out}.pending.json` });
const files = [];
for (const [i, img] of (result.images ?? []).entries()) {
const f = `${out}_${i}.png`;
@@ -128,6 +153,7 @@ async function cmdImage() {
files.push({ file: f, url: img.url, width: img.width, height: img.height });
}
await writeFile(`${out}.json`, JSON.stringify({ endpoint, request_id, seconds, input, files }, null, 2));
+ await unlink(`${out}.pending.json`).catch(() => {});
console.log(`saved ${files.map((f) => f.file).join(', ')}`);
}
@@ -136,14 +162,22 @@ async function cmd3d() {
if (!spec) throw new Error(`--model must be one of ${Object.keys(MODELS3D).join(', ')}`);
const ref = JSON.parse(await readFile(resolve(REPO, need('ref')), 'utf8'));
const out = resolve(REPO, need('out'));
+ if (!a.force && existsSync(join(out, 'model.glb'))) {
+ console.log(`exists ${a.out}/model.glb (skipped; --force to regenerate)`);
+ return;
+ }
const input = { ...spec.input, image_url: ref.files[0].url };
- const { result, request_id, seconds } = await run(spec.endpoint, input, { est: EST[a.model], meta: { kind: '3d', model: a.model, out: a.out } });
+ // Tripo otherwise returns ~2M triangles per prop: slow to import, compare and decimate. Meshy ignores it.
+ if (a['face-limit'] && a.model.startsWith('tripo')) input.face_limit = Number(a['face-limit']);
+ const { result, request_id, seconds } = await run(spec.endpoint, input, { est: EST[a.model], meta: { kind: '3d', model: a.model, out: a.out },
+ pending: join(out, 'pending.json') });
await mkdir(out, { recursive: true });
await writeFile(join(out, 'result.json'), JSON.stringify({ endpoint: spec.endpoint, request_id, seconds, input, result }, null, 2));
// Tripo returns model_mesh / pbr_model, Meshy returns model_glb; take the first GLB we find.
const glb = JSON.stringify(result).match(/https:\/\/[^"]+?\.glb[^"]*/)?.[0];
if (!glb) throw new Error('no GLB in response: ' + JSON.stringify(result).slice(0, 500));
await download(glb, join(out, 'model.glb'));
+ await unlink(join(out, 'pending.json')).catch(() => {});
console.log(`saved ${a.out}/model.glb (${seconds.toFixed(0)} s)`);
}
diff --git a/kit/KIT.md b/kit/KIT.md
new file mode 100644
index 0000000..8aa7558
--- /dev/null
+++ b/kit/KIT.md
@@ -0,0 +1,48 @@
+# What makes a kit good
+
+A kit is judged as a set. One beautiful item and one off-style item is a failed kit; eight solid items that all look
+like the same world is a good one. These are the things that decide it, and what the scene builds learned about the
+generators (see also `CRAFT.md`).
+
+## Cohesion comes from the references, not the 3D models
+
+- Tripo and Meshy copy the reference image. If the references don't match each other, nothing later will fix it.
+ Generate every item reference with the customer's style image as an input image (`kit/gen.mjs edit`), with one
+ shared style paragraph (era, palette, materials, wear, fictional maker) pasted into every prompt.
+- Check the references together, on one sheet, before any 3D: same camera, same light, same level of wear, same
+ palette. Regenerate the outliers. This is the cheapest place to fix cohesion.
+- The style reference is often a whole scene. Its items are a guide to the world, not a list to copy unless the
+ customer asked for exactly those things.
+
+## The generators (from ~150 props in the scene builds)
+
+- Meshy 7.1 wins about 70% of the time: small consumer items, sharper printed labels. Its front faces -Y.
+- Tripo H3.1 wins big hard-surface heroes where real geometry matters (knobs, bezels, dents). Its front faces +X,
+ and with `orientation: align_image` its glTF node also carries a +-20-30 deg Z rotation that matches the reference
+ photo's three-quarter view: drop it before turning the mesh (`normalize.py` and `compare.py` do). Raw it is ~2M
+ tris: generate with `--face-limit` (150000 heroes, 60000 small items).
+- Both bake glass opaque, fake screens into the texture, invent depth for boxy things and put real brands on labels.
+ Expect all four. Meshy speckles flat panels: look at the clay render, not just the beauty.
+- References come back with real brands even when told not to. Check every one.
+
+## Scale
+
+- Every item gets a real height (or dims for boxy things) before prep. Look up typical sizes rather than guessing:
+ a desk phone is ~0.12 m tall, a coffee mug ~0.095 m, a ring binder ~0.32 m, a desk lamp ~0.45 m.
+- Check scale in the lineup: items side by side must make sense relative to each other and to the scale bar.
+
+## Prep
+
+- Orientation: decide from the probe or compare renders which way each model faces; `normalize.py --yaw` fixes
+ anything that isn't front -Y after the generator's rotation.
+- glTF imports use quaternion rotation; images arrive packed, and calling `pack()` on an unmodified packed image drops
+ its data (magenta render). Only repack images you changed.
+- Glass: give the glass part a real transmissive material (mask by UV island or by material) and keep labels opaque.
+- Brands: repaint the brand's texels (fill with the label's ground colour plus grain) and flatten the same texels in
+ the normal map, or regenerate the item with a fictional brand.
+
+## Presentation
+
+- The lineup is the kit's cover. Items sorted for a readable silhouette rhythm, a scale bar, labels legible, nothing
+ cut off, light that shows the materials. Thumbnails: three-quarter front, filling the frame.
+- Look at every render you make. A script that ran proves nothing.
diff --git a/kit/PROMPT.md b/kit/PROMPT.md
new file mode 100644
index 0000000..fca61bd
--- /dev/null
+++ b/kit/PROMPT.md
@@ -0,0 +1,136 @@
+# AnyKit builder (endpoint mode)
+
+You are running inside the AnyKit endpoint. A customer gave you 1-4 style reference images (and maybe a prompt, an
+item list and dials) and is paying for a **kit**: a set of static 3D props that clearly belong together, in the
+reference's style, at real-world scale, ready to drop into a game or a Blender scene. Nobody will help you: you are
+the art director, the 3D generalist and the QA. Read `KIT.md` first (what a kit is and what goes wrong), then
+`SKILL.md` steps 3-6 (references -> Tripo and Meshy -> same-light compare -> prep): that is your process. The rest of
+`SKILL.md` (rooms, lighting a set, shots) is not part of this job.
+
+This is not a fixed pipeline. The tools in `kit/tools/` and `pipeline/` are starting points. Look at every result
+yourself (Read the PNG); when something is wrong, write the script that fixes it in `scenes/kit/scripts/`, run it,
+and look again.
+
+## Inputs (`input/`)
+
+- `reference_*.png`: the style reference(s). `style_urls.json`: the same images as fal URLs (use these as image inputs
+ for `kit/gen.mjs edit`).
+- `brief.md`: the customer's prompt (may be empty: then the kit is the props that fill the reference's world).
+- `items.json`: the item list, if the customer gave one (build exactly these, in this order). Empty: choose the items.
+- `dials.json`: the dials the customer set (below).
+
+## The job
+
+Target: **25-35 minutes for a 10-item kit.** A kit has no room, dressing, lighting or grade; the time goes to waiting
+on generators and to Blender launches, so stream the work and batch the Blender sessions (see Speed).
+
+1. **Plan the kit** (`out/plan.json`, report stage `plan`, within ~2 minutes): the kit's name, one paragraph on its
+ shared style (era, palette, materials, wear, level of detail, the fictional brand every label uses), and every
+ item: `id` (snake_case), `label`, real-world `h` in metres and `dims` for boxy things, hero or small, and the
+ prompt you will use. Choose items that cover a range of sizes and silhouettes and read as one set.
+2. **References, right once** (stage `references`): one image per item, all launched at once, each generated with the
+ style reference(s) as input images (`node kit/gen.mjs edit --image <style url> ... --prompt "<item>. In the exact
+ style, era, palette and materials of the reference image. <scan template from SKILL.md step 4>"`). Put them on
+ ONE sheet and check it before any 3D: wrong object, a real brand, a different style, more than one object,
+ cropped, garbled hero text. Regenerate only those real failures, then start 3D. A second 3D round costs far more
+ than a second look at the sheet.
+3. **3D, both generators** (stage `models`): every reference to Tripo H3.1 AND Meshy 7.1 at once, in the background
+ (`node generate/fal.mjs 3d --model tripo-h31|meshy --ref refs/kit/<id>.json --out assets/gen/<model>/<id>`).
+ Tripo: always pass `--face-limit 150000` for hero items and `--face-limit 60000` for small ones (raw Tripo is ~2M
+ tris and makes every later step 10x slower). Retry the ones that fail.
+4. **Stream: compare, pick, prep each item as its meshes land.** Don't wait for all 20. Poll with short checks
+ (`ls assets/gen/*/*/model.glb`, every 20-30 s, a few seconds per check), never `sleep 200`. Each time new GLBs
+ are in:
+ - `kit/tools/compare.py -- --ids <ready ids>`: ONE Blender session renders reference | Tripo beauty | Tripo clay |
+ Meshy beauty | Meshy clay for every ready item (quick Cycles + Workbench clay) into `scenes/kit/compare/<id>.png`
+ in seconds. Pick by looking (shape in the clay, texture sharpness, labels, glass) and write the pick and a
+ one-line why into `scenes/kit/prep.json` (stage `picks`). Regenerate an item only if it is bad in both.
+ - `kit/tools/normalize.py -- --jobs scenes/kit/prep.json`: ONE Blender session preps every picked item that isn't
+ prepped yet -> `out/items/<id>/<id>.glb` + `<id>_lod1.glb` + `stats.json`, AND rewrites `out/kit.json` from
+ them in the same pass (stage `prep`). Real metres, bottom-centre origin, front facing -Y (Tripo is unposed and
+ turned for you), textures <= 2K, tris within the `detail` budget (`max_tris` per item).
+ - `kit/tools/present.py -- --only thumbs --ids <new ids>`: the new items' thumbnails.
+ Never launch Blender once per item: a launch plus a GLB import costs more than the render.
+5. **Fixes** (stage `fixes`): what the generators got wrong (opaque glass, fake screens, brands, speckled flats),
+ fixed with scripts in `scenes/kit/scripts/` that work on all affected items in one session, then re-export.
+ **Assembly:** parts that belong together must be physically connected and seated: cords and cables plugged in at
+ both ends, handsets on their cradles, lamp heads on their arms, lids on their hinges, nothing hovering or
+ intersecting. Generators often leave a coiled cord ending in mid-air or a handset floating above its cradle.
+ Look at every item from a close angle that shows its joints (not only the three-quarter thumbnail), and fix by
+ script: snap or bridge cord ends to their sockets, re-seat parts, remove stray floating bits.
+6. **Critic early** (below): as soon as a first pass of every item is prepped with thumbnails, render a quick lineup
+ (`present.py --only lineup --samples 32`) and call `critique` with it and the thumbnails. Start fixing what it
+ says while the final lineup renders.
+7. **Present** (stage `lineup`): `kit/tools/present.py` -> `out/renders/lineup.png` (all items side by side on a
+ neutral ground with a scale bar) and `out/renders/thumbs/<id>.png`. Look at them as the customer will.
+8. **Library**: `kit/tools/library.py` -> `out/kit.blend` (every item an asset, LOD1s alongside, packed).
+9. Critique again after fixes, until it passes. Then report `finals` and `done`.
+
+Run Blender as `blender -b --factory-startup --python <script> -- <args>`; it renders on the GPU automatically. One
+Cycles job at a time (`pipeline/gpu_run.sh blender ...`). Keep test renders small; never let a Bash call run longer
+than ~9 minutes, background long jobs and check on them.
+
+## Deliverables (`out/`)
+
+- `items/<id>/<id>.glb`, `items/<id>/<id>_lod1.glb`, `items/<id>/stats.json` for every item.
+- `kit.json`: `{"name", "style", "prompt", "items": [{"id", "label", "dims_m": [w, d, h], "tris", "tris_lod1",
+ "generator": "meshy"|"tripo-h31", "why", "tags": [...], "fixes": [...]}]}`. dims and tris come from the item's
+ `stats.json`; `why` is the one line on the pick; `fixes` lists what you changed by script (may be empty).
+- `renders/lineup.png`, `renders/thumbs/<id>.png` (and `renders/turntables/<id>.mp4` if you make them).
+- `kit.blend` (+ `blender_assets.cats.txt`).
+- `dials.json`: every dial as built (below).
+- `plan.json`, and `scenes/kit/NOTES.md`: what you hit, one line each.
+
+## Dials
+
+The dials are settings you build to, not features to build. `input/dials.json` holds the ones the customer set:
+- `count` (integer): how many items. Default: the length of the item list, else what the prompt says, else 8.
+- `variety` (0-1): how different the items may be from each other. 0 = variations of one object family (a set of
+ matching mugs, jars, boxes); 1 = a broad mix of object types that only share the style.
+- `detail` (`low` | `medium` | `high`): poly and texture budget per item. low: <= 20k tris, 1K textures; medium:
+ <= 100k tris, 2K textures; high: <= 200k tris, 2K textures. LOD1 is about a quarter of LOD0.
+- `wear` (0 pristine - 1 decayed), `wetness` (0 dry - 1 soaked): condition, written into every reference prompt and
+ fixed by script where the generators miss it.
+- `warmth` (-1 cold - 1 warm): the palette's colour temperature, and the presentation light (`present.py --warmth`).
+- `look` (`clean` | `cinematic` | `gritty` | `vintage`): the presentation renders' grade and the surface finish.
+
+A dial the customer set is an instruction: build exactly that, even when the reference says otherwise. A dial left out:
+pick the ONE value the reference shows, and build that. Build one version of the kit, no variants. Write
+`out/dials.json`: for each of the seven dials, `{"value": ..., "source": "customer" | "reference", "means": "<one
+short line on what it meant for this kit>"}`.
+
+## Speed
+
+The customer is waiting and the platform stops the request at 2 hours; aim for 25-35 minutes. The fal account has
+no rate limit and no budget cap: launch every reference at once, then every Tripo AND Meshy job at once
+(`xargs -P 48`). Meshy takes up to ~10 min, Tripo ~3-5; ~10-20% fail transiently, so retry those at once.
+- Stream: compare, pick, prep and thumbnail each item as its meshes land; the first Tripo meshes arrive minutes
+ before the last Meshy ones.
+- Batch Blender: one session per pass over many items (`compare.py`, `normalize.py --jobs`, `present.py`), not one
+ launch per item. kit.json comes out of the prep session; don't spend a separate pass on it.
+- Wait with short polls, never long sleeps.
+- Decimation is cheap only on small meshes: keep Tripo at its `--face-limit`.
+
+## Quality gate: the critic
+
+`critique(images)` sends the style reference, your lineup (first) and up to 10 thumbnails, plus `out/kit.json`, to an
+independent critic. It scores cohesion, reference fidelity, brief, mesh quality, texture quality, assembly, scale and
+labels, and lists at most five fixes: only what would stop a studio using the kit as a base. The bar is a
+production-ready base that a studio's artists then refine, judged at normal viewing distance; the reference sets the
+world, not designs to copy. It passes with no category below 6 and an average of 7 or more.
+Call it on your first complete kit, fix the top problems, re-render, call it again. You are
+done when it passes, or after its 8th round (it then refuses more reviews: finish and
+deliver). Don't argue with it; fix things (regenerate an item, rescale it, repaint a label, replace it).
+
+## Reporting
+
+The customer watches a live log. Every image you open with Read is shown to them automatically. Call
+`report(stage, message, image)` at every milestone with your best current image: `plan`, `references`, `models`,
+`picks`, `prep`, `fixes`, `lineup`, `critique`, `finals`, `done`. One plain sentence each, e.g. "Picked Meshy for 7
+of 9 items; Tripo for the reel-to-reel, whose knobs are real geometry."
+
+## Rules
+
+- Never print or log keys. They are in the environment (`FAL_KEY`).
+- No real brands anywhere: invent one fictional maker for the kit and use it on every label.
+- Work only inside this workspace.
diff --git a/kit/app.py b/kit/app.py
new file mode 100644
index 0000000..1576fe1
--- /dev/null
+++ b/kit/app.py
@@ -0,0 +1,359 @@
+"""AnyKit as a fal Serverless app: one request = one Claude agent building a cohesive prop kit on a GPU worker.
+
+ fal deploy kit/app.py::AnyKitApp --app-name anykit --auth private
+ python kit/client.py kit <style reference path or url> [...] --prompt "..." [--items "a,b"] [--dial count=9]
+
+POST /kit style reference images (+ prompt, item list, dials) -> per-item GLB + LOD1 + thumbnail, kit.blend,
+ lineup render, kit.json, package zip, critic rounds, dials as built.
+The agent (kit_builder.py) streams ANYSCENE_STAGE lines the fal queue relays as logs (docs/ANYKIT.md).
+Same container, GPU wrapper and OptiX cache as the scene builder (builder/app.py).
+"""
+
+import json
+import os
+import sys
+from pathlib import PurePosixPath
+
+import fal
+from fal.container import ContainerImage
+from pydantic import BaseModel, Field
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_REPO = os.path.dirname(_HERE)
+sys.path.insert(0, _HERE)
+sys.path.insert(0, os.path.join(_REPO, "builder"))
+sys.path.insert(0, os.path.join(_REPO, "endpoint"))
+import planner # noqa: E402,F401 (the critic's Claude client; module level so fal bundles it)
+import schema # noqa: E402,F401
+import scene_builder # noqa: E402,F401
+import kit_builder # noqa: E402
+import gallery # noqa: E402 (shared with the scene builder: /kits, /kit_events)
+
+if os.name == "nt":
+ # Deploying from Windows: ContainerImage's context_dir default is a WindowsPath Linux can't unpickle.
+ _posix = PurePosixPath("/tmp")
+ ContainerImage.__dataclass_fields__["context_dir"].default = _posix
+ ContainerImage.context_dir = _posix
+ ContainerImage.__init__.__defaults__ = tuple(
+ _posix if isinstance(d, os.PathLike) else d for d in ContainerImage.__init__.__defaults__ or ()
+ )
+
+TOOLKIT = kit_builder.toolkit_files()
+BLENDER_GPU = open(os.path.join(_REPO, "builder", "blender_gpu.py"), encoding="utf-8").read()
+OPTIX_CACHE_LOCAL = "/var/tmp/OptixCache_root/optix7cache.db"
+OPTIX_CACHE_SHARED = "/data/anyscene/cache/optix7cache.db" # shared with the scene builder
+WARMUP = """import bpy
+s = bpy.context.scene
+s.render.engine = "CYCLES"; s.cycles.samples = 4; s.render.resolution_x = s.render.resolution_y = 64
+m = bpy.data.materials.new("glass"); m.use_nodes = True; m.node_tree.nodes.new("ShaderNodeBsdfGlass")
+bpy.ops.mesh.primitive_uv_sphere_add(location=(0, 0, 0.5))
+bpy.context.object.data.materials.append(m)
+bpy.ops.render.render()
+print("WARMUP done")
+"""
+
+
+def save_optix_cache():
+ import shutil
+ if os.path.exists(OPTIX_CACHE_LOCAL) and (not os.path.exists(OPTIX_CACHE_SHARED)
+ or os.path.getsize(OPTIX_CACHE_LOCAL) > os.path.getsize(OPTIX_CACHE_SHARED)):
+ os.makedirs(os.path.dirname(OPTIX_CACHE_SHARED), exist_ok=True)
+ tmp = f"{OPTIX_CACHE_SHARED}.{os.getpid()}.tmp"
+ shutil.copy(OPTIX_CACHE_LOCAL, tmp)
+ os.replace(tmp, OPTIX_CACHE_SHARED)
+
+
+BLENDER_WRAPPER = '#!/bin/sh\nexec /usr/local/bin/blender.real --python /opt/anyscene/blender_gpu.py "$@"\n'
+KITS_DIR = "/data/anyscene/kit"
+BLENDER_VERSION = "5.0.1"
+
+# identical to the scene builder's, so the image layers are shared
+DOCKERFILE = f"""
+FROM python:3.13-slim
+ENV NVIDIA_DRIVER_CAPABILITIES=all
+RUN apt-get update && apt-get install -y --no-install-recommends \\
+ curl ca-certificates xz-utils git procps fonts-dejavu-core libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 \\
+ libegl1 libxkbcommon0 libsm6 libice6 libx11-6 libglib2.0-0 ffmpeg nodejs ripgrep zip \\
+ && rm -rf /var/lib/apt/lists/*
+RUN curl -fsSL https://download.blender.org/release/Blender{BLENDER_VERSION[:3]}/blender-{BLENDER_VERSION}-linux-x64.tar.xz \\
+ | tar -xJ -C /opt \\
+ && ln -s /opt/blender-{BLENDER_VERSION}-linux-x64/blender /usr/local/bin/blender.real
+"""
+
+
+class KitRequest(BaseModel):
+ reference_image_urls: list[str] = Field(description="1-4 style reference images: the world the kit belongs to.")
+ prompt: str = Field("", description="What the kit is, e.g. '1970s mission-control desk clutter'.")
+ items: list[str] = Field(default_factory=list, description="Optional item list; built exactly, in order.")
+ effort: str = Field("medium", description="Claude effort for the builder: low, medium, high, xhigh, max.")
+ dials: dict[str, float | int | str] = Field(default_factory=dict, description=(
+ "Kit dials (docs/ANYKIT.md); any left out are read from the reference. count: integer. variety, wear, "
+ "wetness: 0-1. warmth: -1 (cold) to 1 (warm). detail: low|medium|high. look: clean|cinematic|gritty|vintage."))
+ fresh: bool = Field(False, description="Build again even if an identical request already finished.")
+
+
+class KitItem(BaseModel):
+ id: str
+ label: str = ""
+ dims_m: list[float] = Field(default_factory=list, description="[width x, depth y, height z] in metres.")
+ tris: int | None = None
+ tris_lod1: int | None = None
+ generator: str | None = None
+ why: str | None = None
+ glb_url: str | None = None
+ lod1_url: str | None = None
+ thumb_url: str | None = None
+ turntable_url: str | None = None
+
+
+class KitResponse(BaseModel):
+ kit_id: str
+ name: str | None
+ style: str | None
+ items: list[KitItem]
+ lineup_url: str | None
+ kit_blend_url: str | None
+ kit_json_url: str | None
+ package_url: str | None
+ critiques: list[dict]
+ dials: dict = Field(default_factory=dict, description="Every dial as built: value, source, means (out/dials.json).")
+ missing: list[str]
+ agent_cost_usd: float | None
+ generation_cost_usd: float | None
+ minutes: float
+
+
+class GalleryRequest(BaseModel):
+ limit: int = Field(200, description="Most kits to list, newest first.")
+
+
+class KitEventsRequest(BaseModel):
+ kit_id: str = Field(description="A kit id (k_...) from /kits.")
+ after: int = Field(0, description="Byte offset into the kit's event stream: 0, then the previous call's `next`.")
+ heartbeats: bool = Field(False, description="Include every heartbeat (default: only the newest in each page).")
+
+
+class AnyKitApp(fal.App):
+ machine_type = ["GPU-RTX5090", "GPU-RTXPRO6000"]
+ image = ContainerImage.from_dockerfile_str(DOCKERFILE)
+ requirements = ["pydantic", "anthropic", "pillow", "fal==1.84.0", "fal-client", "claude-agent-sdk==0.2.176"]
+ local_python_modules = ["kit_builder", "scene_builder", "planner", "schema", "gallery"]
+ min_concurrency = 0
+ max_concurrency = 10
+ request_timeout = 7200
+ startup_timeout = 1200
+
+ def setup(self):
+ import shutil
+ import subprocess
+ import time
+ os.makedirs("/opt/anyscene", exist_ok=True)
+ with open("/opt/anyscene/blender_gpu.py", "w") as f:
+ f.write(BLENDER_GPU)
+ with open("/usr/local/bin/blender", "w") as f:
+ f.write(BLENDER_WRAPPER)
+ os.chmod("/usr/local/bin/blender", 0o755)
+ if os.path.exists(OPTIX_CACHE_SHARED):
+ os.makedirs(os.path.dirname(OPTIX_CACHE_LOCAL), exist_ok=True)
+ shutil.copy(OPTIX_CACHE_SHARED, OPTIX_CACHE_LOCAL)
+ t = time.time()
+ r = subprocess.run(["blender", "-b", "--factory-startup", "--python-expr", WARMUP], capture_output=True, text=True,
+ timeout=900)
+ print(f"setup: OptiX warm-up {'ok' if 'WARMUP done' in r.stdout else 'FAILED'} in {time.time() - t:.0f} s", flush=True)
+ save_optix_cache()
+
+ # fal naming: target fal-ai/anykit/ref2kit; /kit stays as an alias.
+ @fal.endpoint("/ref2kit")
+ async def ref2kit(self, req: KitRequest) -> KitResponse:
+ """Style reference images (+ prompt, items, dials) -> a cohesive kit of production-ready props."""
+ return await self._kit(req)
+
+ @fal.endpoint("/kit")
+ async def kit(self, req: KitRequest) -> KitResponse:
+ return await self._kit(req)
+
+ async def _kit(self, req: KitRequest) -> KitResponse:
+ import asyncio
+ import hashlib
+ import time
+ import uuid
+
+ t0 = time.time()
+ # Retry-safe, as in builder/app.py: fal's queue re-runs a request that times out or loses its worker, so an
+ # identical request returns the finished kit, waits on a live attempt, or resumes a dead one in place.
+ fp = hashlib.sha256(json.dumps({"refs": req.reference_image_urls, "prompt": req.prompt, "items": req.items,
+ "dials": req.dials, "effort": req.effort}, sort_keys=True).encode()).hexdigest()[:20]
+ index = os.path.join(KITS_DIR, "_index", fp + ".json")
+ os.makedirs(os.path.dirname(index), exist_ok=True)
+ resume = False
+ if not req.fresh and os.path.exists(index):
+ told = False
+ while True:
+ rec = json.load(open(index))
+ if rec.get("response"):
+ print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": "done", "status": "done", "message":
+ f"identical request: returning finished kit {rec['kit_id']}"}), flush=True)
+ return KitResponse(**rec["response"])
+ alive = os.path.join(KITS_DIR, rec["kit_id"], "out", ".alive")
+ if not os.path.exists(alive) or time.time() - os.path.getmtime(alive) > 90:
+ break # its attempt died: resume it below
+ if not told:
+ print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": "received", "status": "running", "message":
+ f"identical request: attached to kit {rec['kit_id']}, still running"}), flush=True)
+ told = True
+ await asyncio.sleep(20)
+ kit_id, resume = rec["kit_id"], True
+ else:
+ kit_id = "k_" + uuid.uuid4().hex[:10]
+ json.dump({"kit_id": kit_id, "fingerprint": fp, "started": time.time()}, open(index, "w"))
+ work = os.path.join(KITS_DIR, kit_id)
+ os.makedirs(os.path.join(work, "out"), exist_ok=True)
+
+ async def keep_alive(): # proves this attempt is alive to any retry of the same request
+ while True:
+ open(os.path.join(work, "out", ".alive"), "w").close()
+ await asyncio.sleep(20)
+ alive_task = asyncio.create_task(keep_alive())
+ try:
+ return await self._kit_in(req, kit_id, work, index, resume, t0)
+ finally:
+ alive_task.cancel()
+
+ async def _kit_in(self, req, kit_id, work, index, resume, t0) -> KitResponse:
+ import asyncio
+ import time
+ import urllib.request
+ import zipfile
+
+ from fal.toolkit import File
+ from PIL import Image
+
+ os.makedirs(os.path.join(work, "input"), exist_ok=True)
+ upload = lambda p: File.from_path(p).url
+ if resume: # the workspace is there: refresh the shared tools, keep the kit's own scripts and assets
+ for rel, text in TOOLKIT.items():
+ path = os.path.join(work, rel)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
+ f.write(text)
+ else:
+ pngs = []
+ for i, url in enumerate(req.reference_image_urls[:4]):
+ src = os.path.join(work, "input", f"src_{i + 1}")
+ urllib.request.urlretrieve(url, src)
+ out = os.path.join(work, f"ref_{i + 1}.png")
+ Image.open(src).convert("RGB").save(out)
+ pngs.append(out)
+ kit_builder.make_workspace(work, pngs, req.prompt, TOOLKIT, req.dials, req.items,
+ req.reference_image_urls[:4])
+ refs = sorted(os.path.join(work, "input", f) for f in os.listdir(os.path.join(work, "input"))
+ if f.startswith("reference_") and f.endswith(".png"))
+
+ b = kit_builder.KitBuilder(work, refs, uploader=upload, effort=req.effort)
+ if resume:
+ b.ASK = ("This kit build was cut off (its request was retried) and is resuming in the same workspace. Read "
+ "out/builder.log, out/events.jsonl and scenes/kit/NOTES.md to see how far it got. Everything "
+ "already generated is on disk, and generate/fal.mjs and kit/gen.mjs skip finished outputs and pick "
+ "up jobs that were in flight, so re-running your batch scripts costs nothing for done items. Don't "
+ "start over: continue from the current state to the deliverables.")
+ b.emit("received", "running", f"{'resuming' if resume else 'build'} {kit_id}: kit from {len(refs)} style reference(s)",
+ reference_urls=req.reference_image_urls, prompt=req.prompt, items=req.items, dials=req.dials,
+ effort=req.effort)
+ result = None
+ try:
+ result = await b.run(kit_builder.agent_env())
+ except Exception as e:
+ import traceback
+ print(traceback.format_exc(), flush=True)
+ b.emit("error", "failed", f"kit build stopped: {type(e).__name__}: {str(e)[:300]}")
+
+ out = os.path.join(work, "out")
+ url_if = lambda p: upload(p) if os.path.exists(p) else None
+ kit = b.kit() or {}
+ items = []
+ for it in kit.get("items", []):
+ i = it.get("id", "")
+ d = os.path.join(out, "items", i)
+ items.append(KitItem(
+ id=i, label=it.get("label", ""), dims_m=it.get("dims_m") or [], tris=it.get("tris"),
+ tris_lod1=it.get("tris_lod1"), generator=it.get("generator"), why=it.get("why"),
+ glb_url=url_if(os.path.join(d, f"{i}.glb")), lod1_url=url_if(os.path.join(d, f"{i}_lod1.glb")),
+ thumb_url=url_if(os.path.join(out, "renders", "thumbs", f"{i}.png")),
+ turntable_url=url_if(os.path.join(out, "renders", "turntables", f"{i}.mp4"))))
+ pkg = os.path.join(work, f"{kit_id}.zip")
+ with zipfile.ZipFile(pkg, "w", zipfile.ZIP_DEFLATED) as z:
+ for root, _, names in os.walk(out):
+ for n in names:
+ z.write(os.path.join(root, n), os.path.relpath(os.path.join(root, n), work))
+ for sub in ("scenes/kit", "refs/kit"):
+ for root, _, names in os.walk(os.path.join(work, sub)):
+ for n in names:
+ if n.endswith((".py", ".json", ".md", ".sh", ".png")):
+ z.write(os.path.join(root, n), os.path.relpath(os.path.join(root, n), work))
+ dials_path = os.path.join(out, "dials.json")
+ res = KitResponse(
+ kit_id=kit_id, name=kit.get("name"), style=kit.get("style"), items=items,
+ lineup_url=url_if(os.path.join(out, "renders", "lineup.png")),
+ kit_blend_url=url_if(os.path.join(out, "kit.blend")), kit_json_url=url_if(os.path.join(out, "kit.json")),
+ package_url=upload(pkg),
+ critiques=[{k: c[k] for k in ("round", "scores", "passed", "summary", "fixes")} for c in b.critiques],
+ dials=json.load(open(dials_path)) if os.path.exists(dials_path) else {},
+ missing=b.missing(), agent_cost_usd=getattr(result, "total_cost_usd", None),
+ generation_cost_usd=kit_builder.generation_spend(work), minutes=round((time.time() - t0) / 60, 1))
+ save_optix_cache()
+ rec = json.load(open(index))
+ rec.update(response=res.model_dump(), finished=time.time())
+ json.dump(rec, open(index, "w"))
+ b.emit("packaged", "done", f"package ready after {res.minutes:.0f} min", package_url=res.package_url,
+ lineup_url=res.lineup_url)
+ await asyncio.sleep(2) # let the last stage lines reach the queue logs before COMPLETED
+ return res
+
+ # The shared gallery (builder/gallery.py): every kit anyone ran, read from storage.
+ @fal.endpoint("/kits")
+ async def kits(self, req: GalleryRequest) -> dict:
+ """Every kit on this app's storage, newest first: status, inputs, critic, lineup and thumbnail URLs."""
+ import asyncio
+ return await asyncio.to_thread(gallery.list_builds, KITS_DIR, "kit", max(1, min(req.limit, 1000)))
+
+ @fal.endpoint("/kit_events")
+ async def kit_events(self, req: KitEventsRequest) -> dict:
+ """One kit's stage events from byte offset `after`, its summary, and on the first page of a finished kit its
+ response."""
+ import asyncio
+
+ from fal.toolkit import File
+ return await asyncio.to_thread(gallery.build_events, KITS_DIR, req.kit_id, req.after, "kit",
+ req.heartbeats, 8 << 20, lambda p: File.from_path(p).url)
+
+ @fal.endpoint("/smoke")
+ async def smoke(self, req: KitRequest) -> dict:
+ """Container check: tools present, the agent starts and runs Bash/Blender/node, the kit critic answers."""
+ import subprocess
+ vers = {c[0]: subprocess.run(c, capture_output=True, text=True).stdout.splitlines()[:1]
+ for c in (["blender", "--version"], ["node", "--version"], ["ffmpeg", "-version"], ["nvidia-smi", "-L"])}
+ from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, ResultMessage, TextBlock
+ work = "/tmp/smoke"
+ os.makedirs(work, exist_ok=True)
+ said, cost = [], None
+ opts = ClaudeAgentOptions(model=kit_builder.MODEL, effort="low", permission_mode="bypassPermissions", cwd=work,
+ setting_sources=[], settings='{"fastMode": true}', env=kit_builder.agent_env())
+ async with ClaudeSDKClient(opts) as c:
+ await c.query("Run `blender -b --python-expr \"import bpy; print('BPY', bpy.app.version_string)\"` and "
+ "`node -e \"console.log(typeof fetch)\"`, then reply with both outputs in one line.")
+ async for m in c.receive_response():
+ if isinstance(m, AssistantMessage):
+ said += [b.text for b in m.content if isinstance(b, TextBlock)]
+ elif isinstance(m, ResultMessage):
+ cost = m.total_cost_usd
+ from PIL import Image
+ Image.new("RGB", (256, 128), (40, 60, 50)).save(f"{work}/plate.png")
+ try:
+ crit = kit_builder.run_critic([f"{work}/plate.png"], [f"{work}/plate.png"], "smoke test: a grey plate",
+ "- plate: test plate, 20 x 20 x 2 cm, 2 tris")
+ critic = {"ok": True, "scores": crit["scores"]}
+ except Exception as e:
+ critic = {"ok": False, "error": f"{type(e).__name__}: {e}"[:300]}
+ toolkit = sorted(k for k in TOOLKIT if k.startswith(("kit/", "KIT", ".builder")))
+ return {"versions": vers, "agent": said[-1] if said else None, "cost": cost, "critic": critic,
+ "toolkit": toolkit}
diff --git a/kit/client.py b/kit/client.py
new file mode 100644
index 0000000..71b019c
--- /dev/null
+++ b/kit/client.py
@@ -0,0 +1,107 @@
+"""Call AnyKit and print its live log.
+
+ uv run --python 3.13 --with fal-client python kit/client.py kit <style image path or url> [...] \
+ --prompt "1970s mission-control desk clutter" [--items "a,b,c"] [--dial count=9 --dial wear=0.4] [--out DIR]
+ uv run --python 3.13 --with fal-client python kit/client.py smoke
+
+Local images are uploaded to fal storage first. Every stage event goes to <out>/events.jsonl (for UI replay); the
+response, the lineup and the thumbnails are saved to --out. Uses FAL_SERVERLESS_KEY (the account the app is under).
+"""
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+import time
+import urllib.request
+
+# The fal app id, <owner>/<app>: set ANYKIT_APP=<your-fal-username>/anykit, or pass --app. No default.
+APP_ENV = "ANYKIT_APP"
+PREFIX = "ANYSCENE_STAGE "
+
+
+def user_env(name):
+ if os.environ.get(name):
+ return os.environ[name]
+ if sys.platform == "win32":
+ parts = subprocess.run(["reg", "query", r"HKCU\Environment", "/v", name], capture_output=True, text=True).stdout.split()
+ if name in parts:
+ return parts[parts.index(name) + 2]
+ return None
+
+
+def dial(s):
+ k, v = s.split("=", 1)
+ for cast in (int, float):
+ try:
+ return k, cast(v)
+ except ValueError:
+ pass
+ return k, v
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("cmd", choices=["kit", "smoke"])
+ p.add_argument("refs", nargs="*")
+ p.add_argument("--prompt", default="")
+ p.add_argument("--items", default="")
+ p.add_argument("--dial", action="append", default=[])
+ p.add_argument("--effort", default="medium")
+ p.add_argument("--out", default="kit_out")
+ p.add_argument("--app", help="fal app id (default: $ANYKIT_APP)")
+ a = p.parse_args()
+ app = (a.app or user_env(APP_ENV) or "").strip().strip("/")
+ if not app:
+ p.error(f"set {APP_ENV}=<your-fal-username>/anykit or pass --app")
+ sys.stdout.reconfigure(encoding="utf-8")
+ os.environ["FAL_KEY"] = user_env("FAL_SERVERLESS_KEY") or user_env("FAL_KEY")
+ import fal_client
+
+ os.makedirs(a.out, exist_ok=True)
+ if a.cmd == "smoke":
+ res = fal_client.subscribe(f"{app}/smoke", arguments={"reference_image_urls": []}, client_timeout=3600)
+ json.dump(res, open(os.path.join(a.out, "smoke.json"), "w"), indent=1)
+ print(json.dumps(res, indent=1))
+ return
+ up = lambda s: s if s.startswith("http") else fal_client.upload_file(s)
+ payload = {"reference_image_urls": [up(s) for s in a.refs], "prompt": a.prompt, "effort": a.effort,
+ "items": [s.strip() for s in a.items.split(",") if s.strip()], "dials": dict(map(dial, a.dial))}
+ events = open(os.path.join(a.out, "events.jsonl"), "w", encoding="utf-8")
+ t0, seen = time.time(), set()
+
+ def on_update(update):
+ for log in getattr(update, "logs", None) or []:
+ msg = log.get("message", "")
+ if msg in seen:
+ continue
+ seen.add(msg)
+ if PREFIX not in msg:
+ if any(k in msg for k in ("Traceback", "Error", "error:", "Exception")):
+ print(f"[worker] {msg[:600]}", flush=True)
+ continue
+ ev = json.loads(msg.split(PREFIX, 1)[1])
+ events.write(json.dumps(ev) + "\n")
+ events.flush()
+ if ev["stage"] == "heartbeat":
+ continue
+ line = f"[{(time.time() - t0) / 60:6.1f}m] {ev['stage']:<10} {ev.get('message', '')[:160]}"
+ if ev.get("preview_url"):
+ line += f"\n{'':20}image: {ev['preview_url']}"
+ print(line, flush=True)
+
+ res = fal_client.subscribe(f"{app}/kit", arguments=payload, with_logs=True, on_queue_update=on_update,
+ on_enqueue=lambda rid: print(f"request {rid}", flush=True), client_timeout=8 * 3600)
+ with open(os.path.join(a.out, "kit.json"), "w", encoding="utf-8") as f:
+ json.dump(res, f, indent=1)
+ if res.get("lineup_url"):
+ urllib.request.urlretrieve(res["lineup_url"], os.path.join(a.out, "lineup.png"))
+ for it in res.get("items", []):
+ if it.get("thumb_url"):
+ urllib.request.urlretrieve(it["thumb_url"], os.path.join(a.out, f"thumb_{it['id']}.png"))
+ print(json.dumps({k: v for k, v in res.items() if k not in ("critiques", "items")}, indent=1)[:3000])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/kit/gen.mjs b/kit/gen.mjs
new file mode 100644
index 0000000..15eb3b0
--- /dev/null
+++ b/kit/gen.mjs
@@ -0,0 +1,102 @@
+// Style-conditioned item references for AnyKit: GPT Image 2.5 edit with the customer's style reference(s) as input
+// images, so every item is drawn in the same world. Writes the same <out>.json as generate/fal.mjs `image`, so
+// `node generate/fal.mjs 3d --ref <out>.json ...` takes it straight to Tripo / Meshy. Spend goes to generate/spend.jsonl.
+//
+// node kit/gen.mjs edit --out refs/kit/<id> --prompt "..." --image input/reference_1.png [--image <url|path> ...]
+// [--variant sunburst|flare] [--quality high] [--n 1] [--size auto|square_hd|...] [--force]
+//
+// Re-running is free: an existing <out>.json is skipped (--force regenerates), and a job submitted by a run that
+// was cut off (<out>.pending.json) is polled to the end instead of paid for again.
+//
+// --image takes URLs or local paths (sent inline as data URIs). input/style_urls.json holds the customer's
+// references as fal URLs; prefer those.
+
+import { access, appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { dirname, extname, join, resolve } from 'node:path';
+import { parseArgs } from 'node:util';
+
+const KEY = process.env.FAL_KEY || process.env.FAL_API_KEY;
+const HERE = dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1'));
+const REPO = resolve(HERE, '..');
+const SPEND_LOG = join(REPO, 'generate', 'spend.jsonl');
+const EST = 0.3;
+
+const { positionals, values: a } = parseArgs({
+ allowPositionals: true,
+ options: {
+ out: { type: 'string' }, prompt: { type: 'string' }, image: { type: 'string', multiple: true },
+ variant: { type: 'string', default: 'sunburst' }, quality: { type: 'string', default: 'high' },
+ n: { type: 'string', default: '1' }, size: { type: 'string' }, force: { type: 'boolean', default: false },
+ },
+});
+
+async function call(url, init = {}) {
+ const res = await fetch(url, { ...init, headers: { authorization: `Key ${KEY}`, 'content-type': 'application/json' } });
+ const text = await res.text();
+ if (!res.ok) throw new Error(`${res.status} ${url}: ${text.slice(0, 600)}`);
+ return text ? JSON.parse(text) : null;
+}
+
+async function asUrl(s) {
+ if (/^(https?|data):/.test(s)) return s;
+ const buf = await readFile(resolve(REPO, s));
+ const mime = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' }[extname(s).toLowerCase()] || 'image/png';
+ return `data:${mime};base64,${buf.toString('base64')}`;
+}
+
+async function edit() {
+ if (!KEY) throw new Error('FAL_KEY is not set');
+ if (!a.out || !a.prompt || !a.image?.length) throw new Error('--out, --prompt and at least one --image are required');
+ const out = resolve(REPO, a.out);
+ const exists = (f) => access(f).then(() => true, () => false);
+ if (!a.force && await exists(`${out}.json`)) {
+ console.log(`exists ${a.out}.json (skipped; --force to regenerate)`);
+ return;
+ }
+ const endpoint = `openai/gpt-image-2.5/${a.variant}/edit`;
+ const input = { prompt: a.prompt, image_urls: await Promise.all(a.image.map(asUrl)), quality: a.quality,
+ num_images: +a.n, output_format: 'png', ...(a.size ? { image_size: a.size } : {}) };
+ const t0 = performance.now();
+ const pending = `${out}.pending.json`;
+ let job;
+ if (!a.force && await exists(pending)) {
+ job = JSON.parse(await readFile(pending, 'utf8'));
+ console.log(`resuming ${endpoint} ${job.request_id}`);
+ } else {
+ job = await call(`https://queue.fal.run/${endpoint}`, { method: 'POST', body: JSON.stringify(input) });
+ await mkdir(dirname(out), { recursive: true });
+ await writeFile(pending, JSON.stringify(job));
+ await mkdir(dirname(SPEND_LOG), { recursive: true });
+ await appendFile(SPEND_LOG, JSON.stringify({ time: new Date().toISOString(), endpoint, est_usd: EST * +a.n,
+ request_id: job.request_id, kind: 'image', out: a.out }) + '\n');
+ console.log(`queued ${endpoint} ${job.request_id}`);
+ }
+ for (;;) {
+ await new Promise((r) => setTimeout(r, 3000));
+ const st = await call(job.status_url);
+ if (st.status === 'COMPLETED') break;
+ if (performance.now() - t0 > 15 * 60_000) throw new Error(`timed out; request ${job.request_id}`);
+ }
+ const result = await call(job.response_url);
+ const files = [];
+ await mkdir(dirname(out), { recursive: true });
+ for (const [i, img] of (result.images ?? []).entries()) {
+ const f = `${out}_${i}.png`;
+ const r = await fetch(img.url);
+ await writeFile(f, Buffer.from(await r.arrayBuffer()));
+ files.push({ file: f, url: img.url, width: img.width, height: img.height });
+ }
+ if (!files.length) throw new Error('no images in response: ' + JSON.stringify(result).slice(0, 400));
+ const seconds = (performance.now() - t0) / 1000;
+ // inputs can be multi-MB data URIs: keep only their kind in the record
+ const record = { ...input, image_urls: input.image_urls.map((u) => (u.startsWith('data:') ? 'data:(inline)' : u)) };
+ await writeFile(`${out}.json`, JSON.stringify({ endpoint, request_id: job.request_id, seconds, input: record, files }, null, 2));
+ await rm(pending, { force: true });
+ console.log(`saved ${files.map((f) => f.file).join(', ')} (${seconds.toFixed(0)} s)`);
+}
+
+if (positionals[0] !== 'edit') {
+ console.error('usage: node kit/gen.mjs edit --out ... --prompt ... --image ... (see header)');
+ process.exit(1);
+}
+await edit();
diff --git a/kit/kit_builder.py b/kit/kit_builder.py
new file mode 100644
index 0000000..408b827
--- /dev/null
+++ b/kit/kit_builder.py
@@ -0,0 +1,336 @@
+"""AnyKit: one Claude agent builds a cohesive kit of static 3D props from style reference image(s).
+
+Same machinery as the scene builder (builder/scene_builder.py): an Agent SDK session (Opus 5.5, fast mode, OpenRouter),
+report/critique MCP tools, PreToolUse/PostToolUse/Stop hooks, a heartbeat, the 2-hour cap guard and resume on session
+errors. What differs: the workspace (kit prompt, KIT.md, kit tools), the critic's rubric (kit cohesion, not a set), and
+what "done" means (out/kit.json, per-item GLB + LOD1 + thumbnail, out/kit.blend, out/renders/lineup.png, a passing
+critique).
+
+ uv run --python 3.13 --with claude-agent-sdk --with anthropic --with pydantic --with pillow \
+ python kit/kit_builder.py <reference.png> [...] --work <dir> [--prompt "..."] [--items "a,b,c"]
+"""
+
+import argparse
+import asyncio
+import json
+import os
+import sys
+
+from claude_agent_sdk import (AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, HookMatcher, ResultMessage,
+ TextBlock, create_sdk_mcp_server, tool)
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REPO = os.path.dirname(HERE)
+sys.path.insert(0, os.path.join(REPO, "builder"))
+sys.path.insert(0, os.path.join(REPO, "endpoint"))
+import planner # noqa: E402 (the critic's Claude client; module level so fal bundles it)
+import scene_builder # noqa: E402
+from scene_builder import CAP_STOP_S, CAP_WARN_S, MAX_CRITIC_ROUNDS, MODEL, PREFIX, agent_env, user_env # noqa: E402,F401
+
+DIALS = ("count", "variety", "detail", "wear", "wetness", "warmth", "look")
+
+
+# ---------------------------------------------------------------- workspace
+def toolkit_files():
+ """The scene builder's toolkit (SKILL.md, generate/, pipeline/, camera/, docs/) with the kit's prompt, KIT.md and
+ kit tools on top. Read at deploy time so the fal app carries it."""
+ files = {k: v for k, v in scene_builder.toolkit_files().items() if not k.startswith(".builder/")}
+ files[".builder/PROMPT.md"] = open(os.path.join(HERE, "PROMPT.md"), encoding="utf-8").read()
+ files["KIT.md"] = open(os.path.join(HERE, "KIT.md"), encoding="utf-8").read()
+ files["kit/gen.mjs"] = open(os.path.join(HERE, "gen.mjs"), encoding="utf-8").read()
+ for n in sorted(os.listdir(os.path.join(HERE, "tools"))):
+ if n.endswith(".py"):
+ files[f"kit/tools/{n}"] = open(os.path.join(HERE, "tools", n), encoding="utf-8").read()
+ return files
+
+
+def make_workspace(work, refs, prompt, files, dials=None, items=None, ref_urls=None):
+ scene_builder.make_workspace(work, refs, prompt, "kit", files, dials)
+ inp = os.path.join(work, "input")
+ with open(os.path.join(inp, "items.json"), "w", encoding="utf-8") as f:
+ json.dump(items or [], f, indent=1)
+ with open(os.path.join(inp, "style_urls.json"), "w", encoding="utf-8") as f:
+ json.dump(ref_urls or [], f, indent=1)
+ for d in ("out/items", "out/renders/thumbs", "refs/kit"):
+ os.makedirs(os.path.join(work, d), exist_ok=True)
+ # the scene builder's stills dir is not part of a kit
+ try:
+ os.rmdir(os.path.join(work, "out", "stills"))
+ except OSError:
+ pass
+
+
+# ---------------------------------------------------------------- critic
+CRITIC = """You review 3D prop kits for a service that turns style reference images into production-ready asset kits.
+The first {n_refs} image(s) are the customer's STYLE REFERENCE. They asked for: {brief}
+
+The remaining images are the delivered kit: first a lineup render (every item side by side on a neutral ground, with
+a scale bar; its label under each item), then per-item thumbnails. The kit's manifest:
+{manifest}
+
+The reference is a starting point for the world, not a target to copy: the kit must clearly belong to the same world
+(era, materials, palette, design language), but which items were chosen, their exact designs and the presentation
+are the builder's own choices and must NOT be marked down for differing from the reference.
+
+The bar is a production-ready base: a kit a studio would accept as the starting point its artists then refine. Judge
+it as a whole, from normal viewing distance. Do NOT nitpick: no points off for a creative choice that differs from
+the reference, a surface that is a little CG on close inspection, or anything an artist would tweak in ten minutes.
+
+Score each category 1-10 (7 = a solid, usable production kit; 9 = exceptional):
+- cohesion: the items read as one set: shared palette, material language, era, wear and level of detail;
+- reference_fidelity: the kit belongs in the reference's world;
+- brief: the items are what the customer asked for (prompt, item list, count), nothing off-topic;
+- mesh_quality: clean recognisable shapes; nothing broken, blobby or melted;
+- texture_quality: believable textured surfaces; nothing untextured, smeared or flat grey;
+- assembly: parts that belong together are physically connected and seated: cords and cables plugged in at
+ both ends, handsets on their cradles, lamp heads on their arms, lids on their hinges, nothing hovering or
+ intersecting;
+- scale: each item's real-world size (manifest dims, scale bar) is right, alone and relative to the others;
+- labels: no real brands; no garbled text on hero labels.
+
+Then list at most FIVE fixes, most damaging first: only problems that would stop a studio from using the kit as a
+base (an item broken, melted or with disconnected parts, garbled hero labels, wrong world, untextured, badly wrong
+scale). If the kit is already a good base, say so and list fewer or none. Pass when the kit is a good production
+base: no category below 6 and an average of 7 or more."""
+
+
+def critic_schema():
+ from pydantic import BaseModel, Field
+
+ class Scores(BaseModel):
+ cohesion: int
+ reference_fidelity: int
+ brief: int
+ mesh_quality: int
+ texture_quality: int
+ assembly: int
+ scale: int
+ labels: int
+
+ class Critique(BaseModel):
+ scores: Scores
+ fixes: list[str] = Field(description="At most five, most damaging first; may be empty.")
+ summary: str
+ return Critique
+
+
+def manifest_text(work):
+ try:
+ kit = json.load(open(os.path.join(work, "out", "kit.json"), encoding="utf-8"))
+ except Exception:
+ return "(out/kit.json not written yet)"
+ rows = []
+ for it in kit.get("items", []):
+ d = it.get("dims_m") or []
+ dims = " x ".join(f"{v * 100:.0f}" for v in d) + " cm (w x d x h)" if len(d) == 3 else "?"
+ rows.append(f"- {it.get('id')}: {it.get('label', '')}, {dims}, {it.get('tris', '?')} tris")
+ return "\n".join(rows) or "(no items)"
+
+
+def run_critic(refs, images, brief, manifest):
+ Critique = critic_schema()
+ client, model, extra = planner._client()
+ content = []
+ for p in list(refs) + list(images):
+ content.append({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg",
+ "data": scene_builder._jpeg(p)}})
+ content.append({"type": "text", "text": CRITIC.format(n_refs=len(refs), brief=brief, manifest=manifest)})
+ with client.beta.messages.stream(model=model, max_tokens=16000, thinking={"type": "adaptive"},
+ output_config={"effort": "high", "format": {"type": "json_schema",
+ "schema": planner.strict_schema(Critique)}},
+ messages=[{"role": "user", "content": content}], **extra) as s:
+ msg = s.get_final_message()
+ c = Critique.model_validate_json(next(b.text for b in msg.content if b.type == "text"))
+ d = c.model_dump()
+ v = list(d["scores"].values())
+ d["passed"] = min(v) >= 6 and sum(v) / len(v) >= 7 # a good production base, same rule as the scene critic
+ return d
+
+
+# ---------------------------------------------------------------- run
+class KitBuilder(scene_builder.SceneBuilder):
+ """The scene builder's session, hooks, heartbeat and cap guard, with the kit's tools, critic and definition of done."""
+
+ ASK = "Build the kit from the style reference in input/. Start by reading KIT.md, then SKILL.md steps 3-6."
+
+ def __init__(self, work, refs, uploader=None, emit=None, effort="medium"):
+ super().__init__(work, refs, "kit", uploader=uploader, emit=emit, effort=effort)
+
+ def brief(self):
+ txt = open(os.path.join(self.work, "input", "brief.md"), encoding="utf-8").read().strip()
+ items = json.load(open(os.path.join(self.work, "input", "items.json"), encoding="utf-8"))
+ dials = json.load(open(os.path.join(self.work, "input", "dials.json"), encoding="utf-8"))
+ return (txt + (f"\nItems requested: {', '.join(items)}" if items else "")
+ + (f"\nDials: {json.dumps(dials)}" if dials else ""))
+
+ def tools(self):
+ d = self
+
+ @tool("report", "Post a stage event to the customer's live log, optionally with a rendered image.",
+ {"stage": str, "message": str, "image": str})
+ async def report(args):
+ d.emit(args["stage"], "running", args.get("message", ""), args.get("image") or None)
+ return {"content": [{"type": "text", "text": "reported"}]}
+
+ @tool("critique", "Independent kit critic: compares the style reference with your lineup and thumbnails "
+ "(paths relative to the workspace or absolute; the lineup FIRST, then up to 10 thumbnails). "
+ "It also reads out/kit.json for dims. Returns scores 1-10 per category, up to five fixes that "
+ "matter, and whether it passes (no category below 6, average 7+). At most "
+ f"{MAX_CRITIC_ROUNDS} rounds.",
+ {"type": "object", "properties": {"images": {"type": "array", "items": {"type": "string"}}},
+ "required": ["images"]})
+ async def critique(args):
+ if len(d.critiques) >= MAX_CRITIC_ROUNDS:
+ return {"content": [{"type": "text", "text": (
+ f"The critic has had its {MAX_CRITIC_ROUNDS} rounds; no more reviews. Stop iterating on the look: "
+ "finish every remaining deliverable (items/<id>/<id>.glb and _lod1.glb, renders/lineup.png, "
+ "renders/thumbs/, kit.json, kit.blend, dials.json, NOTES.md) and deliver.")}]}
+ paths = [p if os.path.isabs(p) else os.path.join(d.work, p) for p in args["images"]]
+ missing = [p for p in paths if not os.path.exists(p)]
+ if missing:
+ return {"content": [{"type": "text", "text": f"missing: {missing}"}], "is_error": True}
+ d.emit("critique", "running", f"critic is looking at the lineup and {len(paths) - 1} item renders")
+ res = await asyncio.to_thread(run_critic, d.refs, paths[:11], d.brief(), manifest_text(d.work))
+ res["round"] = len(d.critiques) + 1
+ res["stills"] = paths
+ d.critiques.append(res)
+ json.dump(res, open(os.path.join(d.work, "out", "critique", f"round_{res['round']}.json"), "w"), indent=1)
+ sc = res["scores"]
+ d.emit("critique", "done" if res["passed"] else "running",
+ f"round {res['round']}: {'PASS' if res['passed'] else 'not yet'} - "
+ + ", ".join(f"{k} {v}" for k, v in sc.items()), paths[0], critique=res)
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=1)}]}
+
+ return [report, critique]
+
+ async def pre_tool(self, inp, tool_use_id, ctx):
+ import time
+ self.working = (self.describe(inp.get("tool_name", ""), inp.get("tool_input") or {}, self.work), time.time())
+ if self.elapsed() > CAP_WARN_S and not self.cap_warned:
+ self.cap_warned = True
+ return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": (
+ "The platform ends this request at 120 minutes and the kit is now past 95. Before anything else, make "
+ "sure out/ holds your best current version of every deliverable (kit.json, items/<id>/<id>.glb and "
+ "_lod1.glb, renders/lineup.png, renders/thumbs/, kit.blend, dials.json), then keep improving.")}}
+ return {}
+
+ def kit(self):
+ try:
+ return json.load(open(os.path.join(self.work, "out", "kit.json"), encoding="utf-8"))
+ except Exception:
+ return None
+
+ def missing(self):
+ out = os.path.join(self.work, "out")
+ miss = []
+ kit = self.kit()
+ if not kit or not kit.get("items"):
+ miss.append("out/kit.json with an items list")
+ else:
+ for it in kit["items"]:
+ i = it.get("id", "?")
+ for rel in (f"items/{i}/{i}.glb", f"items/{i}/{i}_lod1.glb", f"renders/thumbs/{i}.png"):
+ if not os.path.exists(os.path.join(out, rel)):
+ miss.append(f"out/{rel}")
+ for k in ("label", "dims_m", "tris", "generator", "why"):
+ if k not in it:
+ miss.append(f"kit.json item {i} has no {k}")
+ for f in ("kit.blend", "renders/lineup.png", "dials.json"):
+ if not os.path.exists(os.path.join(out, f)):
+ miss.append(f"out/{f}")
+ if not self.critiques:
+ miss.append("no critique yet")
+ elif not self.critiques[-1]["passed"] and len(self.critiques) < MAX_CRITIC_ROUNDS:
+ miss.append("the last critique did not pass")
+ return miss
+
+ async def run(self, env):
+ prompt = open(os.path.join(self.work, ".builder", "PROMPT.md"), encoding="utf-8").read()
+ server = create_sdk_mcp_server("scene", tools=self.tools()) # "scene": the base post_tool quiets mcp__scene__*
+ beat = asyncio.create_task(self.heartbeat())
+ self.emit("received", "running", "kit builder starting")
+ result, session_id, attempt = None, None, 0
+ ask = self.ASK
+ while True:
+ opts = ClaudeAgentOptions(
+ model=env.get("ANTHROPIC_MODEL") or MODEL, effort=self.effort, permission_mode="bypassPermissions",
+ cwd=self.work,
+ system_prompt={"type": "preset", "preset": "claude_code", "append": prompt},
+ mcp_servers={"scene": server}, setting_sources=[], settings='{"fastMode": true}',
+ hooks={"PreToolUse": [HookMatcher(hooks=[self.pre_tool])],
+ "PostToolUse": [HookMatcher(hooks=[self.post_tool])],
+ "Stop": [HookMatcher(hooks=[self.on_stop])]},
+ max_buffer_size=256 * 1024 * 1024, resume=session_id,
+ env=env, stderr=lambda l: self.note("STDERR " + l[:300]))
+ try:
+ async with ClaudeSDKClient(opts) as client:
+ async def cap_guard():
+ while self.elapsed() < CAP_STOP_S:
+ await asyncio.sleep(15)
+ self.capped = True
+ self.emit("error", "running", "stopping the kit builder before the platform's 2-hour limit; "
+ "packaging what it has")
+ await client.interrupt()
+ guard = asyncio.create_task(cap_guard())
+ try:
+ await client.query(ask)
+ async for m in client.receive_response():
+ session_id = getattr(m, "session_id", None) \
+ or (getattr(m, "data", None) or {}).get("session_id") or session_id
+ if isinstance(m, AssistantMessage):
+ for b in m.content:
+ if isinstance(b, TextBlock) and b.text.strip():
+ self.note("SAY " + b.text.strip()[:2000])
+ self.emit("thinking", "running", b.text.strip()[:400])
+ elif isinstance(m, ResultMessage):
+ result = m
+ finally:
+ guard.cancel()
+ break
+ except Exception as e:
+ import traceback
+ if self.capped:
+ break
+ attempt += 1
+ self.note("SESSION ERROR " + traceback.format_exc()[-3000:])
+ self.emit("error", "running", f"agent session error ({type(e).__name__}: {str(e)[:200]}); "
+ f"{'resuming' if attempt <= 3 and session_id else 'giving up'}")
+ if attempt > 3 or not session_id:
+ raise
+ ask = ("The previous turn was cut off by a harness error, not by you. Continue the kit from where "
+ "you were; check the state of the workspace first.")
+ beat.cancel()
+ cost = getattr(result, "total_cost_usd", None)
+ self.emit("done", "done", f"kit builder finished after {self.elapsed() / 60:.0f} min"
+ + (f", agent cost ${cost:.2f}" if cost else ""), missing=self.missing(),
+ critiques=len(self.critiques))
+ return result
+
+
+def generation_spend(work):
+ try:
+ rows = [json.loads(l) for l in open(os.path.join(work, "generate", "spend.jsonl"), encoding="utf-8") if l.strip()]
+ except OSError:
+ return 0.0
+ return round(sum(r.get("est_usd", 0) for r in rows), 2)
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("refs", nargs="+")
+ p.add_argument("--work", required=True)
+ p.add_argument("--prompt", default="")
+ p.add_argument("--items", default="")
+ p.add_argument("--effort", default="medium")
+ a = p.parse_args()
+ sys.stdout.reconfigure(encoding="utf-8")
+ work = os.path.abspath(a.work)
+ if not os.path.exists(os.path.join(work, "KIT.md")):
+ make_workspace(work, a.refs, a.prompt, toolkit_files(), items=[s for s in a.items.split(",") if s])
+ refs = sorted(os.path.join(work, "input", f) for f in os.listdir(os.path.join(work, "input")) if f.startswith("reference_")
+ and f.endswith(".png"))
+ asyncio.run(KitBuilder(work, refs, effort=a.effort).run(agent_env()))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/kit/tools/compare.py b/kit/tools/compare.py
new file mode 100644
index 0000000..a450d20
--- /dev/null
+++ b/kit/tools/compare.py
@@ -0,0 +1,208 @@
+"""Tripo vs Meshy for kit items, in ONE Blender session: one sheet per item, ready the moment its meshes land.
+
+ blender -b --factory-startup --python kit/tools/compare.py -- [--ids a,b] [--gen assets/gen] [--refs refs/kit] \
+ [--out scenes/kit/compare] [--res 512] [--samples 24] [--clay workbench|cycles]
+
+Per item: reference | tripo beauty | tripo clay | meshy beauty | meshy clay, written to <out>/<id>.png, with the
+tris and dims of each model in <out>/<id>.json. Beauty is a quick Cycles render; clay is Workbench (shows what is
+real geometry; `--clay cycles` if Workbench can't open a context). Both models are turned to face -Y first (Tripo
+-90 deg), so the views match. Items whose sheet is newer than both GLBs are skipped, so call it again as more land.
+"""
+
+import json
+import math
+import os
+import sys
+
+import bpy
+import numpy as np
+from mathutils import Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+opt = lambda k, d: type(d)(argv[argv.index(k) + 1]) if k in argv else d
+GEN = os.path.abspath(opt("--gen", "assets/gen"))
+REFS = os.path.abspath(opt("--refs", "refs/kit"))
+OUT = os.path.abspath(opt("--out", "scenes/kit/compare"))
+RES = opt("--res", 512)
+SAMPLES = opt("--samples", 24)
+CLAY = opt("--clay", "workbench")
+IDS = [s for s in opt("--ids", "").split(",") if s]
+MODELS = ("tripo-h31", "meshy")
+os.makedirs(OUT, exist_ok=True)
+
+
+def glb(model, iid):
+ return os.path.join(GEN, model, iid, "model.glb")
+
+
+def ids():
+ found = set(IDS)
+ if not found:
+ for m in MODELS:
+ d = os.path.join(GEN, m)
+ if os.path.isdir(d):
+ found |= {i for i in os.listdir(d) if os.path.exists(glb(m, i))}
+ return sorted(found)
+
+
+def reset():
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ sc = bpy.context.scene
+ sc.render.resolution_x = sc.render.resolution_y = RES
+ sc.view_settings.view_transform = "AgX"
+ w = bpy.data.worlds.new("w")
+ sc.world = w
+ w.use_nodes = True
+ w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.5, 0.5, 0.52, 1)
+ w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.6
+ return sc
+
+
+def light(name, loc, energy, size):
+ d = bpy.data.lights.new(name, "AREA")
+ d.energy, d.size = energy, size
+ o = bpy.data.objects.new(name, d)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = loc
+ o.rotation_euler = (-Vector(loc)).to_track_quat("-Z", "Y").to_euler()
+
+
+def bounds(objs):
+ """Tight world bounds from the vertices (a rotated object's bound_box is loose: Tripo meshes carry a rotation)."""
+ los, his = [], []
+ for o in objs:
+ co = np.empty(len(o.data.vertices) * 3, np.float32)
+ o.data.vertices.foreach_get("co", co)
+ m = np.array(o.matrix_world, np.float32)
+ w = co.reshape(-1, 3) @ m[:3, :3].T + m[:3, 3]
+ los.append(w.min(0))
+ his.append(w.max(0))
+ return Vector(np.min(los, 0).tolist()), Vector(np.max(his, 0).tolist())
+
+
+def unpose(objs):
+ """Tripo's orientation=align_image puts a Z rotation (about +-20-30 deg) on the glTF node to match the reference
+ photo's three-quarter view. Drop it so the mesh sits in Tripo's canonical frame (front +X)."""
+ for o in objs:
+ o.rotation_mode = "QUATERNION"
+ o.rotation_quaternion = (1, 0, 0, 0)
+ bpy.context.view_layer.update()
+
+
+def stats(objs, size):
+ t = 0
+ for o in objs:
+ o.data.calc_loop_triangles()
+ t += len(o.data.loop_triangles)
+ return {"tris": t, "raw_size": [round(v, 3) for v in size]}
+
+
+def render_model(model, iid, prefix):
+ sc = reset()
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=glb(model, iid))
+ new = [o for o in bpy.data.objects if o not in before]
+ objs = [o for o in new if o.type == "MESH"]
+ if model.startswith("tripo"):
+ unpose(new)
+ lo, hi = bounds(objs)
+ st = stats(objs, hi - lo)
+ root = bpy.data.objects.new("root", None)
+ sc.collection.objects.link(root)
+ for o in new:
+ if o.parent is None:
+ o.parent = root
+ s = 1.0 / max(hi - lo)
+ c = (lo + hi) / 2
+ root.scale = (s, s, s)
+ if model.startswith("tripo"):
+ root.rotation_euler.z = math.radians(-90)
+ bpy.context.view_layer.update()
+ lo, hi = bounds(objs)
+ root.location -= Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))
+ bpy.context.view_layer.update()
+ lo, hi = bounds(objs)
+ centre, radius = (lo + hi) / 2, (hi - lo).length / 2
+ light("key", (2.2, -2.6, 3.0), 260, 1.6)
+ light("fill", (-3.0, -1.5, 1.6), 70, 2.5)
+ light("rim", (-1.0, 3.0, 2.5), 160, 1.2)
+ cd = bpy.data.cameras.new("cam")
+ cd.lens = 70
+ cam = bpy.data.objects.new("cam", cd)
+ sc.collection.objects.link(cam)
+ sc.camera = cam
+ az, el = math.radians(-30), math.radians(18)
+ cam.location = centre + Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) \
+ * (radius / math.sin(cd.angle / 2) * 1.02)
+ cam.rotation_euler = (centre - cam.location).to_track_quat("-Z", "Y").to_euler()
+ sc.render.engine = "CYCLES"
+ sc.cycles.device = "GPU"
+ sc.cycles.samples = SAMPLES
+ sc.cycles.use_denoising = True
+ sc.render.filepath = prefix + "_beauty.png"
+ bpy.ops.render.render(write_still=True)
+ if CLAY == "workbench":
+ sc.render.engine = "BLENDER_WORKBENCH"
+ sh = sc.display.shading
+ sh.light, sh.color_type, sh.show_cavity = "STUDIO", "SINGLE", True
+ sh.single_color = (0.6, 0.6, 0.6)
+ else:
+ clay = bpy.data.materials.new("clay")
+ clay.use_nodes = True
+ clay.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.55, 0.55, 0.55, 1)
+ for o in objs:
+ o.data.materials.clear()
+ o.data.materials.append(clay)
+ sc.cycles.samples = 16
+ sc.render.filepath = prefix + "_clay.png"
+ bpy.ops.render.render(write_still=True)
+ return st
+
+
+def pixels(path):
+ """An RGBA float array (RES x RES), or grey when the file is missing."""
+ if not path or not os.path.exists(path):
+ return np.full((RES, RES, 4), 0.25, np.float32)
+ img = bpy.data.images.load(path)
+ w, h = img.size
+ f = RES / max(w, h)
+ img.scale(max(1, int(w * f)), max(1, int(h * f)))
+ w, h = img.size
+ a = np.empty(w * h * 4, np.float32)
+ img.pixels.foreach_get(a)
+ a = a.reshape(h, w, 4)
+ bpy.data.images.remove(img)
+ cell = np.full((RES, RES, 4), 0.25, np.float32)
+ y0, x0 = (RES - h) // 2, (RES - w) // 2
+ cell[y0:y0 + h, x0:x0 + w] = a
+ return cell
+
+
+for iid in ids():
+ sheet = os.path.join(OUT, f"{iid}.png")
+ srcs = [glb(m, iid) for m in MODELS if os.path.exists(glb(m, iid))]
+ if os.path.exists(sheet) and all(os.path.getmtime(sheet) > os.path.getmtime(s) for s in srcs) \
+ and len(srcs) == len(MODELS):
+ print("skip", iid)
+ continue
+ info = {}
+ cells = [os.path.join(REFS, f"{iid}_0.png")]
+ for m in MODELS:
+ prefix = os.path.join(OUT, "_r", f"{iid}_{m}")
+ os.makedirs(os.path.dirname(prefix), exist_ok=True)
+ if os.path.exists(glb(m, iid)):
+ try:
+ info[m] = render_model(m, iid, prefix)
+ cells += [prefix + "_beauty.png", prefix + "_clay.png"]
+ continue
+ except Exception as e:
+ info[m] = {"error": repr(e)}
+ cells += [None, None]
+ row = np.concatenate([pixels(p) for p in cells], axis=1)
+ out = bpy.data.images.new("sheet", row.shape[1], row.shape[0], alpha=True)
+ out.pixels.foreach_set(row.ravel())
+ out.filepath_raw = sheet
+ out.file_format = "PNG"
+ out.save()
+ json.dump(info, open(os.path.join(OUT, f"{iid}.json"), "w"), indent=1)
+ print("SHEET", iid, json.dumps(info), flush=True)
diff --git a/kit/tools/library.py b/kit/tools/library.py
new file mode 100644
index 0000000..a5ca662
--- /dev/null
+++ b/kit/tools/library.py
@@ -0,0 +1,99 @@
+"""kit.blend: a Blender asset library holding every kit item, each marked as an asset with a preview, label, tags
+and its LOD1 alongside.
+
+ blender -b --factory-startup --python kit/tools/library.py -- --kit out/kit.json --items out/items --out out/kit.blend
+
+Each item is one object named <id> (LOD0) in a collection named after the kit, laid out in a row so the file is also
+browsable; <id>_lod1 sits in a hidden "LOD1" collection. Everything is packed. A blender_assets.cats.txt with one
+catalog for the kit is written next to the .blend, and every asset is assigned to it.
+"""
+
+import json
+import os
+import sys
+import uuid
+
+import bpy
+from mathutils import Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+opt = lambda k, d: argv[argv.index(k) + 1] if k in argv else d
+KIT = os.path.abspath(opt("--kit", "out/kit.json"))
+ITEMS = os.path.abspath(opt("--items", "out/items"))
+OUT = os.path.abspath(opt("--out", "out/kit.blend"))
+kit = json.load(open(KIT))
+name = kit.get("name") or "Kit"
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+sc = bpy.context.scene
+main = bpy.data.collections.new(name)
+sc.collection.children.link(main)
+lods = bpy.data.collections.new("LOD1")
+sc.collection.children.link(lods)
+cat_id = str(uuid.uuid5(uuid.NAMESPACE_DNS, "anykit/" + name))
+
+
+def load(path, obname, coll):
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=path)
+ new = [o for o in bpy.data.objects if o not in before]
+ meshes = [o for o in new if o.type == "MESH"]
+ for o in bpy.context.selected_objects:
+ o.select_set(False)
+ for o in meshes:
+ mw = o.matrix_world.copy()
+ o.parent = None
+ o.matrix_world = mw
+ o.select_set(True)
+ bpy.context.view_layer.objects.active = meshes[0]
+ if len(meshes) > 1:
+ bpy.ops.object.join()
+ ob = bpy.context.view_layer.objects.active
+ bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
+ for o in new:
+ if o.name in bpy.data.objects and o is not ob:
+ bpy.data.objects.remove(o)
+ ob.name = ob.data.name = obname
+ for c in ob.users_collection:
+ c.objects.unlink(ob)
+ coll.objects.link(ob)
+ return ob
+
+
+x = 0.0
+for it in kit["items"]:
+ d = os.path.join(ITEMS, it["id"])
+ ob = load(os.path.join(d, f"{it['id']}.glb"), it["id"], main)
+ lo = min((ob.matrix_world @ Vector(c)).x for c in ob.bound_box)
+ hi = max((ob.matrix_world @ Vector(c)).x for c in ob.bound_box)
+ ob.location.x = x - lo
+ x += (hi - lo) + 0.1
+ ob.asset_mark()
+ ad = ob.asset_data
+ ad.description = it.get("label", it["id"])
+ ad.catalog_id = cat_id
+ for t in it.get("tags", []) + [name]:
+ ad.tags.new(t, skip_if_exists=True)
+ for k in ("dims_m", "tris", "generator"):
+ if k in it:
+ ob[k] = it[k]
+ ob["label"] = it.get("label", it["id"])
+ lod_path = os.path.join(d, f"{it['id']}_lod1.glb")
+ if os.path.exists(lod_path):
+ lod = load(lod_path, f"{it['id']}_lod1", lods)
+ lod.location = ob.location
+ ob["lod1"] = lod.name
+ with bpy.context.temp_override(id=ob):
+ try:
+ bpy.ops.ed.lib_id_generate_preview()
+ except Exception as e: # previews need a GPU context in some builds; the asset still works without one
+ print("preview skipped", it["id"], e)
+
+lods.hide_render = True
+lods.hide_viewport = True
+bpy.ops.file.pack_all()
+os.makedirs(os.path.dirname(OUT), exist_ok=True)
+bpy.ops.wm.save_as_mainfile(filepath=OUT, compress=True)
+with open(os.path.join(os.path.dirname(OUT), "blender_assets.cats.txt"), "w") as f:
+ f.write(f"VERSION 1\n\n{cat_id}:{name}:{name}\n")
+print("LIBRARY", OUT, len(kit["items"]), "assets")
diff --git a/kit/tools/normalize.py b/kit/tools/normalize.py
new file mode 100644
index 0000000..6ca5ff5
--- /dev/null
+++ b/kit/tools/normalize.py
@@ -0,0 +1,191 @@
+"""Generator GLB -> kit item: real metres, bottom-centre origin, front facing -Y, textures <= 2K, plus a LOD1.
+
+One item:
+ blender -b --factory-startup --python kit/tools/normalize.py -- \
+ --glb assets/gen/meshy/<id>/model.glb --gen meshy --id <id> --out out/items/<id> \
+ (--h 0.32 | --fit 0.40 0.30 0.32) [--yaw 0] [--tex 2048] [--max-tris 100000] [--lod1 0.25]
+
+Many items in ONE Blender session, and kit.json written in the same pass (the fast path):
+ blender -b --factory-startup --python kit/tools/normalize.py -- --jobs scenes/kit/prep.json \
+ [--items out/items] [--kit out/kit.json] [--tex 2048] [--max-tris 100000] [--lod1 0.25]
+ prep.json: {"name": "...", "style": "...", "prompt": "...",
+ "items": [{"id", "label", "glb", "gen", "h" | "fit": [x, y, z], "yaw"?, "max_tris"?, "why", "tags"?,
+ "fixes"?}, ...]}
+ Items whose GLB is missing are skipped (run it again as more land); kit.json is rewritten from every item that has
+ a stats.json, in prep.json's order, so it is always current.
+
+Writes out/items/<id>/<id>.glb, <id>_lod1.glb (about 1/4 the tris, half-size textures) and stats.json (dims_m, tris,
+tris_lod1, textures).
+
+--gen tripo rotates the mesh -90 deg about Z first (Tripo's front faces +X; Meshy's already faces -Y). --yaw adds
+a further rotation (degrees, about Z) when a model's front is somewhere else. --h scales uniformly to that height.
+--fit X Y Z scales each axis to exact dims (for boxy props whose depth the generator invented). A starting point:
+copy it into scenes/kit/scripts/ and change it when an item needs more.
+"""
+
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Matrix, Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+
+
+def opt(k, d=None, n=1, cast=str):
+ if k not in argv:
+ return d
+ i = argv.index(k)
+ vals = [cast(v) for v in argv[i + 1:i + 1 + n]]
+ return vals[0] if n == 1 else vals
+
+
+TEX = opt("--tex", 2048, cast=int)
+MAX_TRIS = opt("--max-tris", 100000, cast=int)
+LOD1 = opt("--lod1", 0.25, cast=float)
+
+
+def bbox(ob):
+ vs = [v.co for v in ob.data.vertices]
+ lo = Vector((min(v.x for v in vs), min(v.y for v in vs), min(v.z for v in vs)))
+ hi = Vector((max(v.x for v in vs), max(v.y for v in vs), max(v.z for v in vs)))
+ return lo, hi
+
+
+def tris(ob):
+ ob.data.calc_loop_triangles()
+ return len(ob.data.loop_triangles)
+
+
+def decimate(ob, target):
+ t = tris(ob)
+ if t <= target:
+ return
+ m = ob.modifiers.new("dec", "DECIMATE")
+ m.ratio = target / t
+ m.use_collapse_triangulate = True
+ with bpy.context.temp_override(object=ob, active_object=ob):
+ bpy.ops.object.modifier_apply(modifier=m.name)
+
+
+def export(path):
+ bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", use_selection=True, export_apply=True,
+ export_image_format="AUTO", export_yup=True)
+
+
+def normalize(glb, gen, iid, out, h=None, fit=None, yaw=0.0, max_tris=MAX_TRIS):
+ glb, out = os.path.abspath(glb), os.path.abspath(out)
+ os.makedirs(out, exist_ok=True)
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=glb)
+ meshes = [o for o in bpy.context.scene.objects if o.type == "MESH"]
+ if not meshes:
+ raise RuntimeError(f"no meshes in {glb}")
+ if gen.startswith("tripo"):
+ # Tripo's orientation=align_image puts a Z rotation (~+-20-30 deg) on the node to match the reference photo's
+ # three-quarter view; drop it so the mesh is in Tripo's canonical frame (front +X) before the -90 below
+ for o in bpy.context.scene.objects:
+ o.rotation_mode = "QUATERNION"
+ o.rotation_quaternion = (1, 0, 0, 0)
+ bpy.context.view_layer.update()
+ # bake every transform (glTF parents, quaternion rotations) into the mesh data, then join into one object
+ for o in bpy.context.scene.objects:
+ o.select_set(False)
+ for o in meshes:
+ mw = o.matrix_world.copy()
+ o.parent = None
+ o.data.transform(mw)
+ o.matrix_world = Matrix.Identity(4)
+ for o in [o for o in bpy.context.scene.objects if o.type != "MESH"]:
+ bpy.data.objects.remove(o)
+ vl = bpy.context.view_layer
+ for o in meshes:
+ o.select_set(True)
+ vl.objects.active = meshes[0]
+ if len(meshes) > 1:
+ bpy.ops.object.join()
+ ob = vl.objects.active
+ ob.name = ob.data.name = iid
+ ob.rotation_mode = "XYZ"
+ # orientation: rotate the mesh data, never the object
+ rot = (-90.0 if gen.startswith("tripo") else 0.0) + (yaw or 0.0)
+ if rot:
+ ob.data.transform(Matrix.Rotation(math.radians(rot), 4, "Z"))
+ # decimate before anything else touches 2M-tri Tripo meshes
+ decimate(ob, max_tris)
+ lo, hi = bbox(ob)
+ size = hi - lo
+ if fit:
+ s = Vector([fit[i] / max(size[i], 1e-6) for i in range(3)])
+ elif h:
+ s = Vector([h / max(size.z, 1e-6)] * 3)
+ else:
+ s = Vector((1, 1, 1))
+ ob.data.transform(Matrix.Translation(-Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))))
+ ob.data.transform(Matrix.Diagonal((s.x, s.y, s.z, 1)))
+ lo, hi = bbox(ob)
+ # textures: downscale anything over TEX, and repack ONLY those (pack() on an untouched packed image drops its data)
+ textures = {}
+ for img in bpy.data.images:
+ if img.size[0] == 0:
+ continue
+ w, hh = img.size
+ if max(w, hh) > TEX:
+ f = TEX / max(w, hh)
+ img.scale(max(1, int(w * f)), max(1, int(hh * f)))
+ img.pack()
+ textures[img.name] = list(img.size)
+ bpy.ops.object.select_all(action="SELECT")
+ export(os.path.join(out, f"{iid}.glb"))
+ t0 = tris(ob)
+ decimate(ob, max(500, int(t0 * LOD1)))
+ for img in bpy.data.images: # LOD1 textures at half resolution
+ if img.size[0] > 256:
+ img.scale(max(1, img.size[0] // 2), max(1, img.size[1] // 2))
+ img.pack()
+ export(os.path.join(out, f"{iid}_lod1.glb"))
+ stats = {"id": iid, "source_glb": glb, "generator": gen, "rot_deg": rot, "dims_m": [round(v, 4) for v in hi - lo],
+ "tris": t0, "tris_lod1": tris(ob), "textures": textures}
+ json.dump(stats, open(os.path.join(out, "stats.json"), "w"), indent=1)
+ print("NORMALIZED", json.dumps(stats), flush=True)
+ return stats
+
+
+if "--jobs" in argv:
+ jobs = json.load(open(opt("--jobs")))
+ items_dir = os.path.abspath(opt("--items", "out/items"))
+ kit_path = os.path.abspath(opt("--kit", "out/kit.json"))
+ force = "--force" in argv
+ for j in jobs["items"]:
+ out = os.path.join(items_dir, j["id"])
+ st = os.path.join(out, "stats.json")
+ if not os.path.exists(j["glb"]):
+ print("WAITING", j["id"], "(no GLB yet)", flush=True)
+ continue
+ if not force and os.path.exists(st) and os.path.getmtime(st) > os.path.getmtime(j["glb"]) \
+ and os.path.getmtime(st) > os.path.getmtime(opt("--jobs")):
+ continue # already prepped from this GLB and these settings
+ try:
+ normalize(j["glb"], j.get("gen", "meshy"), j["id"], out, j.get("h"), j.get("fit"), j.get("yaw", 0),
+ j.get("max_tris", MAX_TRIS))
+ except Exception as e: # keep going; report it
+ print("FAILED", j["id"], repr(e), flush=True)
+ items = []
+ for j in jobs["items"]:
+ st = os.path.join(items_dir, j["id"], "stats.json")
+ if not os.path.exists(st):
+ continue
+ s = json.load(open(st))
+ items.append({"id": j["id"], "label": j.get("label", j["id"]), "dims_m": s["dims_m"], "tris": s["tris"],
+ "tris_lod1": s["tris_lod1"], "generator": j.get("gen", s["generator"]), "why": j.get("why", ""),
+ "tags": j.get("tags", []), "fixes": j.get("fixes", [])})
+ kit = {k: jobs.get(k, "") for k in ("name", "style", "prompt")}
+ kit["items"] = items
+ os.makedirs(os.path.dirname(kit_path), exist_ok=True)
+ json.dump(kit, open(kit_path, "w"), indent=1)
+ print("KIT", kit_path, len(items), "of", len(jobs["items"]), "items", flush=True)
+else:
+ normalize(opt("--glb"), opt("--gen", "meshy"), opt("--id"), opt("--out"), opt("--h", None, cast=float),
+ opt("--fit", None, n=3, cast=float), opt("--yaw", 0.0, cast=float))
diff --git a/kit/tools/present.py b/kit/tools/present.py
new file mode 100644
index 0000000..15fe1fb
--- /dev/null
+++ b/kit/tools/present.py
@@ -0,0 +1,237 @@
+"""Kit presentation renders: the lineup (every item side by side on a neutral ground, with a scale bar and labels),
+a thumbnail per item, and optionally a turntable per item.
+
+ blender -b --factory-startup --python kit/tools/present.py -- --kit out/kit.json --items out/items --out out/renders \
+ [--only lineup|thumbs|turntable] [--samples 128] [--warmth 0] [--turntable 48] [--ids a,b]
+
+Reads item ids and labels from kit.json ("items": [{"id", "label"}, ...]) and loads out/items/<id>/<id>.glb as they
+are (already normalised: metres, bottom-centre origin, facing -Y). Writes lineup.png, thumbs/<id>.png and
+turntables/<id>.mp4 (needs ffmpeg). A starting point: copy it into scenes/kit/scripts/ to change the look.
+"""
+
+import json
+import math
+import os
+import shutil
+import subprocess
+import sys
+
+import bpy
+from mathutils import Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+opt = lambda k, d: type(d)(argv[argv.index(k) + 1]) if k in argv else d
+KIT = os.path.abspath(opt("--kit", "out/kit.json"))
+ITEMS = os.path.abspath(opt("--items", "out/items"))
+OUT = os.path.abspath(opt("--out", "out/renders"))
+ONLY = opt("--only", "")
+SAMPLES = opt("--samples", 128)
+WARMTH = opt("--warmth", 0.0)
+TURN = opt("--turntable", 0)
+IDS = [s for s in opt("--ids", "").split(",") if s]
+os.makedirs(OUT, exist_ok=True)
+
+kit = json.load(open(KIT))
+items = [it for it in kit["items"] if not IDS or it["id"] in IDS]
+
+
+def kelvin_rgb(k):
+ # rough blackbody tint, good enough for a warm/cool key
+ t = k / 100
+ r = 1.0 if t <= 66 else max(0, min(1, 1.292936 * (t - 60) ** -0.1332047592))
+ g = max(0, min(1, (0.39008157876 * math.log(t) - 0.63184144) if t <= 66 else 1.129890861 * (t - 60) ** -0.0755148492))
+ b = 1.0 if t >= 66 else (0 if t <= 19 else max(0, min(1, 0.54320678911 * math.log(t - 10) - 1.19625408914)))
+ return (r, g, b)
+
+
+def setup():
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ sc.cycles.device = "GPU"
+ sc.cycles.samples = SAMPLES
+ sc.cycles.use_denoising = True
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "AgX - Medium High Contrast"
+ w = bpy.data.worlds.new("w")
+ sc.world = w
+ w.use_nodes = True
+ w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.36, 0.37, 0.38, 1)
+ w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.35
+ # neutral ground + curved backdrop (a sweep), so the horizon never shows
+ bpy.ops.mesh.primitive_plane_add(size=1)
+ g = bpy.context.object
+ g.name = "ground"
+ g.scale = (60, 60, 1)
+ gm = bpy.data.materials.new("ground")
+ gm.use_nodes = True
+ p = gm.node_tree.nodes["Principled BSDF"]
+ p.inputs["Base Color"].default_value = (0.42, 0.42, 0.42, 1)
+ p.inputs["Roughness"].default_value = 0.85
+ g.data.materials.append(gm)
+ return sc
+
+
+def light(name, loc, target, energy, size, color=(1, 1, 1)):
+ d = bpy.data.lights.new(name, "AREA")
+ d.energy, d.size, d.color = energy, size, color
+ o = bpy.data.objects.new(name, d)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = loc
+ o.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
+ return o
+
+
+def studio(centre, radius):
+ key_k = 5600 + 1800 * -WARMTH # warmth 1 -> ~3800 K, -1 -> ~7400 K
+ c = Vector(centre)
+ s = max(radius, 0.2)
+ light("key", c + Vector((1.6, -2.2, 2.4)) * s, c, 220 * s * s, 1.6 * s, kelvin_rgb(key_k))
+ light("fill", c + Vector((-2.6, -1.4, 1.2)) * s, c, 60 * s * s, 2.5 * s, kelvin_rgb(key_k + 1500))
+ light("rim", c + Vector((-0.8, 2.6, 2.2)) * s, c, 140 * s * s, 1.4 * s)
+
+
+def load(item):
+ path = os.path.join(ITEMS, item["id"], f"{item['id']}.glb")
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=path)
+ new = [o for o in bpy.data.objects if o not in before]
+ root = bpy.data.objects.new(item["id"], None)
+ bpy.context.scene.collection.objects.link(root)
+ for o in new:
+ if o.parent is None:
+ o.parent = root
+ bpy.context.view_layer.update()
+ return root, [o for o in new if o.type == "MESH"]
+
+
+def bounds(objs):
+ pts = [o.matrix_world @ Vector(c) for o in objs for c in o.bound_box]
+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
+ return lo, hi
+
+
+def camera(lens=50):
+ d = bpy.data.cameras.new("cam")
+ d.lens = lens
+ o = bpy.data.objects.new("cam", d)
+ bpy.context.scene.collection.objects.link(o)
+ bpy.context.scene.camera = o
+ return o
+
+
+def aim(cam, centre, az, el, dist):
+ a, e = math.radians(az), math.radians(el)
+ cam.location = Vector(centre) + Vector((math.sin(a) * math.cos(e), -math.cos(a) * math.cos(e), math.sin(e))) * dist
+ cam.rotation_euler = (Vector(centre) - cam.location).to_track_quat("-Z", "Y").to_euler()
+
+
+def mat(name, rgb, emit=0.0):
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ p = m.node_tree.nodes["Principled BSDF"]
+ p.inputs["Base Color"].default_value = (*rgb, 1)
+ p.inputs["Roughness"].default_value = 0.6
+ return m
+
+
+def text(body, loc, size, m):
+ c = bpy.data.curves.new("t", "FONT")
+ c.body, c.size, c.align_x = body, size, "CENTER"
+ o = bpy.data.objects.new("label_" + body[:20], c)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = loc
+ o.rotation_euler = (math.pi / 2, 0, 0) # stand it up, facing the camera (-Y)
+ o.data.materials.append(m)
+ return o
+
+
+def lineup():
+ sc = setup()
+ loaded = [(it, *load(it)) for it in items]
+ heights = [bounds(m)[1].z for _, _, m in loaded]
+ gap = max(0.06, 0.12 * max(heights))
+ x = 0.0
+ depth = 0.0
+ for it, root, meshes in loaded:
+ lo, hi = bounds(meshes)
+ w = hi.x - lo.x
+ root.location.x = x + w / 2 - (lo.x + hi.x) / 2
+ x += w + gap
+ depth = max(depth, hi.y - lo.y)
+ bpy.context.view_layer.update()
+ allm = [o for _, _, m in loaded for o in m]
+ lo, hi = bounds(allm)
+ total = hi.x - lo.x
+ # scale bar: alternating 10 cm (or 1 cm for tiny kits) blocks, a "nice" length about a fifth of the width
+ nice = min((0.05, 0.1, 0.2, 0.25, 0.5, 1.0, 2.0, 5.0), key=lambda v: abs(v - total / 5))
+ step = nice / 10 if nice <= 0.25 else 0.1
+ dark, light_m, ink = mat("bar_dark", (0.03, 0.03, 0.03)), mat("bar_light", (0.85, 0.85, 0.85)), mat("ink", (0.04, 0.04, 0.04))
+ by = lo.y - max(0.06, depth * 0.35)
+ th = max(0.004, nice / 40)
+ for i in range(round(nice / step)):
+ bpy.ops.mesh.primitive_cube_add(size=1, location=(lo.x + step * (i + 0.5), by, 0.001))
+ b = bpy.context.object
+ b.scale = (step, th * 2, 0.002)
+ b.data.materials.append(dark if i % 2 == 0 else light_m)
+ label = f"{nice * 100:.0f} cm" if nice < 1 else f"{nice:g} m"
+ t = text(label, (lo.x + nice / 2, by - th, th * 1.5), th * 4, ink)
+ # item labels on the ground in front of each item
+ lsize = max(0.01, min(0.04, gap * 0.22))
+ for it, root, meshes in loaded:
+ l2, h2 = bounds(meshes)
+ text(it.get("label", it["id"])[:28], ((l2.x + h2.x) / 2, l2.y - lsize * 1.5, 0.003), lsize, ink)
+ bpy.context.view_layer.update()
+ lo2, hi2 = bounds(allm)
+ centre = Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2 - 0.1 * depth, (hi2.z) * 0.42))
+ sc.render.resolution_x, sc.render.resolution_y = 2400, 1000
+ cam = camera(50)
+ fov_h = cam.data.angle
+ width = max(total * 1.2, (hi2.z) * 2.4 * 1.5)
+ dist = (width / 2) / math.tan(fov_h / 2) + depth
+ aim(cam, centre, 0, 14, dist)
+ studio(centre, max(total, hi2.z) * 0.6)
+ sc.render.filepath = os.path.join(OUT, "lineup.png")
+ bpy.ops.render.render(write_still=True)
+ print("LINEUP", sc.render.filepath)
+
+
+def per_item(turntable=False):
+ for it in items:
+ sc = setup()
+ root, meshes = load(it)
+ lo, hi = bounds(meshes)
+ centre = (lo + hi) / 2
+ radius = (hi - lo).length / 2
+ studio(centre, radius * 1.4)
+ cam = camera(70)
+ dist = radius / math.sin(cam.data.angle / 2) * 1.05
+ if not turntable:
+ sc.render.resolution_x = sc.render.resolution_y = 1024
+ aim(cam, centre, -30, 20, dist)
+ os.makedirs(os.path.join(OUT, "thumbs"), exist_ok=True)
+ sc.render.filepath = os.path.join(OUT, "thumbs", f"{it['id']}.png")
+ bpy.ops.render.render(write_still=True)
+ continue
+ sc.render.resolution_x = sc.render.resolution_y = 640
+ sc.cycles.samples = min(SAMPLES, 48)
+ tmp = os.path.join(OUT, "turntables", f"_{it['id']}")
+ os.makedirs(tmp, exist_ok=True)
+ for f in range(TURN):
+ aim(cam, centre, -30 + 360 * f / TURN, 18, dist)
+ sc.render.filepath = os.path.join(tmp, f"{f:04d}.png")
+ bpy.ops.render.render(write_still=True)
+ mp4 = os.path.join(OUT, "turntables", f"{it['id']}.mp4")
+ subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-framerate", "24", "-i", os.path.join(tmp, "%04d.png"),
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", mp4], check=True)
+ shutil.rmtree(tmp)
+
+
+if ONLY in ("", "lineup"):
+ lineup()
+if ONLY in ("", "thumbs"):
+ per_item()
+if ONLY == "turntable" or (TURN and ONLY == ""):
+ TURN = TURN or 48
+ per_item(turntable=True)
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..d87fabd
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,562 @@
+{
+ "name": "anyscene",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "anyscene",
+ "version": "1.0.0",
+ "license": "ISC",
+ "dependencies": {
+ "@aws-sdk/client-s3": "^3.1161.0",
+ "@aws-sdk/lib-storage": "^3.1161.0"
+ }
+ },
+ "node_modules/@aws-sdk/checksums": {
+ "version": "3.1002.1",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1002.1.tgz",
+ "integrity": "sha512-CXNESwkQC9jdrUG6cKXBfudVt1frGcYQykcCYbNclVrsewuGMbo3PlFjRteMe4OftNAqhyc3xC2jTz7SUqLasQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/client-s3": {
+ "version": "3.1161.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1161.0.tgz",
+ "integrity": "sha512-iRZGMsJnYRrI98O+U6o5fHeLPQTP+Dc/w0mWLcBLQcEQ10DA06+XQj0WmdRiCM7vIso7QEtN1fsj9Vzo5/R3LQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/checksums": "^3.1002.1",
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/credential-provider-node": "^3.972.92",
+ "@aws-sdk/middleware-sdk-s3": "^3.972.85",
+ "@aws-sdk/signature-v4-multi-region": "^3.996.51",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/fetch-http-handler": "^5.8.0",
+ "@smithy/node-http-handler": "^4.14.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/core": {
+ "version": "3.979.1",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.979.1.tgz",
+ "integrity": "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "^3.975.0",
+ "@aws-sdk/xml-builder": "^3.972.42",
+ "@aws/lambda-invoke-store": "^0.3.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/signature-v4": "^5.7.5",
+ "@smithy/types": "^4.19.0",
+ "bowser": "^2.11.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-env": {
+ "version": "3.972.80",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.80.tgz",
+ "integrity": "sha512-uO5TiSvb6j1w9RTe5z28OaOmsrOxVQUPaC5+wZl50RfOXcrYD/KgnS8I9lfyGXc7sGbkCopK6VnhNIAoLqfewQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-http": {
+ "version": "3.972.82",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.82.tgz",
+ "integrity": "sha512-vQzlDHlC24Yz42p+rT4NBoP/5VdetkBoujbOLq9h6QYWC8THuZSPYnXIR9OP3XcOrdMgPBBipOrdssfxnIiWUg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/fetch-http-handler": "^5.8.0",
+ "@smithy/node-http-handler": "^4.14.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-ini": {
+ "version": "3.973.25",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.25.tgz",
+ "integrity": "sha512-b5xl71uCRdWsu7P1VeGpiGuCf6zfYETsSNOv8AmYVTrsgbvTJRXdmmOPVfxkvGGVNsiKkGctClQW3jAn0SZLug==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/credential-provider-env": "^3.972.80",
+ "@aws-sdk/credential-provider-http": "^3.972.82",
+ "@aws-sdk/credential-provider-login": "^3.972.87",
+ "@aws-sdk/credential-provider-process": "^3.972.80",
+ "@aws-sdk/credential-provider-sso": "^3.973.24",
+ "@aws-sdk/credential-provider-web-identity": "^3.972.86",
+ "@aws-sdk/nested-clients": "^3.997.54",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/credential-provider-imds": "^4.5.2",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-login": {
+ "version": "3.972.87",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.87.tgz",
+ "integrity": "sha512-C4ZFmcwM+Zj14Z8huVUk54Gv4uzT1ZdzG9cY3Gdh8FePakq7Bss1OFsgZjAhWFOkFOGpBvFBeu0OWjWf8HNKRQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/nested-clients": "^3.997.54",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-node": {
+ "version": "3.972.92",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.92.tgz",
+ "integrity": "sha512-jC3zmOo7Qxlk+oBivvSsS1Ph7sFGm0QfuhqDGbqgRXi4cxUYMG+dWtBwS2XYYXgc8TIVXJiwgQ65sbNpbYupTA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/credential-provider-env": "^3.972.80",
+ "@aws-sdk/credential-provider-http": "^3.972.82",
+ "@aws-sdk/credential-provider-ini": "^3.973.25",
+ "@aws-sdk/credential-provider-process": "^3.972.80",
+ "@aws-sdk/credential-provider-sso": "^3.973.24",
+ "@aws-sdk/credential-provider-web-identity": "^3.972.86",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/credential-provider-imds": "^4.5.2",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-process": {
+ "version": "3.972.80",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.80.tgz",
+ "integrity": "sha512-xqfixO5aclje7tbQJDias+iNND5wp/3QZixCdZcVQpgWPTZ0V5DfTW9A804A5Z7ezu7sH3WRO+vzUjtiJBA8yg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-sso": {
+ "version": "3.973.24",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.24.tgz",
+ "integrity": "sha512-nlg3BKG03Cgzvv/dMnhxvDJPhAhQSpaN0RUdwgU7ziwkasoev7iI8el8Xy4Rd5sqzgaDUbV269fOXck5SargqA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/nested-clients": "^3.997.54",
+ "@aws-sdk/token-providers": "3.1161.0",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-web-identity": {
+ "version": "3.972.86",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.86.tgz",
+ "integrity": "sha512-zKTyLJBEyfQBVlYqT6Jt+mYV4r8kGbWM7dn6v4Y4MRARizhYafjDXP/iMu76UMRhToSPNmIKX1XAb24gtpBFIA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/nested-clients": "^3.997.54",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/lib-storage": {
+ "version": "3.1161.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/lib-storage/-/lib-storage-3.1161.0.tgz",
+ "integrity": "sha512-ROSytGylVRtkUsp64mpzryv1Puvgo6jAm4RWTW2m3kC4SSsjrvhqZa5uPKfz116a0U1kk/hBz9S1eBItkyd++w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "buffer": "5.6.0",
+ "events": "3.3.0",
+ "stream-browserify": "3.0.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "peerDependencies": {
+ "@aws-sdk/client-s3": "^3.1161.0"
+ }
+ },
+ "node_modules/@aws-sdk/middleware-sdk-s3": {
+ "version": "3.972.85",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.85.tgz",
+ "integrity": "sha512-Kyl2G6zhIS9qFoeLdlxvXFrWyc6g9D9ZCIRJnGkkfX6JZhxCZB5ebXBc7GKEeetrnhXcail6ALZT0lKbojcaNA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/signature-v4-multi-region": "^3.996.51",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/nested-clients": {
+ "version": "3.997.54",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.54.tgz",
+ "integrity": "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/signature-v4-multi-region": "^3.996.51",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/fetch-http-handler": "^5.8.0",
+ "@smithy/node-http-handler": "^4.14.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/signature-v4-multi-region": {
+ "version": "3.996.51",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.51.tgz",
+ "integrity": "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/signature-v4": "^5.7.5",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/token-providers": {
+ "version": "3.1161.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1161.0.tgz",
+ "integrity": "sha512-ypbXSofNcSHwf/KA40bFCXJb0MLaAKrfT7sot4dFaA+2lsuXNah4zLRJIAU7Qmvs9PFJ6rnY0bZFEC+mE7attA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.979.1",
+ "@aws-sdk/nested-clients": "^3.997.54",
+ "@aws-sdk/types": "^3.975.0",
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/types": {
+ "version": "3.975.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.975.0.tgz",
+ "integrity": "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/xml-builder": {
+ "version": "3.972.42",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.42.tgz",
+ "integrity": "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws/lambda-invoke-store": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",
+ "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/core": {
+ "version": "3.38.0",
+ "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.38.0.tgz",
+ "integrity": "sha512-aLyyCnK2p4yvNA2TaM+5owXqb+rZGSiUKEsNP329AzeYnERtAz7NrlTbRsaxqmZ0ooxwoID8LMm959UGQQDIsg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/credential-provider-imds": {
+ "version": "4.5.2",
+ "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",
+ "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "@smithy/types": "^4.17.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/fetch-http-handler": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz",
+ "integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.3",
+ "@smithy/types": "^4.18.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/node-http-handler": {
+ "version": "4.14.0",
+ "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.14.0.tgz",
+ "integrity": "sha512-j24RS5V9J52u0z81RpgF7H55p4bS6UCEIxF4ZYzTYh6M9hzXvjAIAYwgLobqf7vJq3xib5VXc7nX3YesV8Rx4A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/signature-v4": {
+ "version": "5.7.5",
+ "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.5.tgz",
+ "integrity": "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.38.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/types": {
+ "version": "4.19.0",
+ "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz",
+ "integrity": "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/bowser": {
+ "version": "2.15.0",
+ "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.15.0.tgz",
+ "integrity": "sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ==",
+ "license": "MIT"
+ },
+ "node_modules/buffer": {
+ "version": "5.6.0",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.6.0.tgz",
+ "integrity": "sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==",
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.0.2",
+ "ieee754": "^1.1.4"
+ }
+ },
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/stream-browserify": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-3.0.0.tgz",
+ "integrity": "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "~2.0.4",
+ "readable-stream": "^3.5.0"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..0cc6b53
--- /dev/null
+++ b/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "anyscene",
+ "version": "1.0.0",
+ "description": "Photoreal Blender scenes from a one-paragraph brief, built by AI agents.",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/apekshik/anyscene.git"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "bugs": {
+ "url": "https://github.com/apekshik/anyscene/issues"
+ },
+ "homepage": "https://github.com/apekshik/anyscene#readme",
+ "private": "true",
+ "type": "module",
+ "dependencies": {
+ "@aws-sdk/client-s3": "^3.1161.0",
+ "@aws-sdk/lib-storage": "^3.1161.0"
+ }
+}
diff --git a/pipeline/env.sh b/pipeline/env.sh
index dc2db48..4e45dd1 100644
--- a/pipeline/env.sh
+++ b/pipeline/env.sh
@@ -5,6 +5,8 @@ ANYSCENE_ROOT_POSIX="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Blender and ffmpeg on Windows want C:/... paths, not Git Bash's /c/...
ROOT_ABS="$(cd "$ANYSCENE_ROOT_POSIX" && (pwd -W 2>/dev/null || pwd))"
export ANYSCENE_ROOT="$ROOT_ABS"
+# Machine-specific overrides (BLENDER=..., FFMPEG=...) go in pipeline/env.local.sh, which is gitignored.
+[ -f "$ANYSCENE_ROOT_POSIX/pipeline/env.local.sh" ] && . "$ANYSCENE_ROOT_POSIX/pipeline/env.local.sh"
if [ -z "$BLENDER" ]; then
for c in blender \
diff --git a/pipeline/grounding.py b/pipeline/grounding.py
new file mode 100644
index 0000000..c41d5a2
--- /dev/null
+++ b/pipeline/grounding.py
@@ -0,0 +1,130 @@
+"""Find props that float above (or sink into) whatever they should rest on, measured at their actual contact points.
+
+ blender -b scene.blend --python pipeline/grounding.py -- [--report out.json] [--fix] [--tol 0.01] [--save out.blend]
+
+For each mesh object (or GLB import root with mesh children) it takes the lowest vertices in world space - chair feet,
+stool legs, a pot's base ring - and casts a ray straight down from just above each, ignoring the object itself.
+ gap = distance from those contact points to the nearest surface below (positive = floating)
+A bounding-box check misses floaters whenever the box bottom isn't where the object touches down (splayed legs,
+decimated feet, an origin offset), which is how chairs end up hovering.
+
+--fix moves each floating object down by its smallest contact gap (so at least one foot touches) and prints what moved.
+It never moves an object up and skips anything parented to another object (it moves with its parent).
+"""
+
+import json
+import sys
+
+import bpy
+from mathutils import Vector
+from mathutils.bvhtree import BVHTree
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+opt = lambda k, d=None: argv[argv.index(k) + 1] if k in argv else d
+TOL = float(opt("--tol", 0.01))
+FIX = "--fix" in argv
+SKIP_PREFIX = ("CR_", "camrig", "wall", "floor", "ceiling", "street", "road", "pavement", "ground", "rain", "steam",
+ "haze", "smoke", "decal", "flame", "glow", "light", "neon", "sign")
+
+# Things that legitimately hang: checked only if --all is passed.
+HANGING = ("aircon", "clock", "speaker_wall", "tv_ceiling", "extinguisher", "poster", "sign", "lamp_pendant", "pendant",
+ "bulb", "lantern", "noren", "awning", "fan_wall", "shelf_wall", "hook", "calendar", "menu", "blind", "curtain",
+ "cable", "wire", "pipe", "ledge", "bracket", "frame", "transom", "bezel", "door", "window", "mount")
+# Volumes and particles are not surfaces: never count them as something to rest on.
+NOT_SURFACE = ("haze", "drizzle", "rain", "steam", "smoke", "fog", "mist", "vapor", "vapour", "plume", "volume", "flame")
+PREFIX = opt("--prefix") # e.g. "hk_": only check this scene's generated props
+
+
+def wanted(o):
+ n = o.name.lower()
+ if o.parent is not None or not o.visible_get() or o.hide_render or n.startswith(SKIP_PREFIX):
+ return False
+ if not (o.type == "MESH" or any(c.type == "MESH" for c in o.children_recursive)):
+ return False
+ if PREFIX and not n.startswith(PREFIX):
+ return False
+ return "--all" in argv or not any(k in n for k in HANGING)
+
+
+dg = bpy.context.evaluated_depsgraph_get()
+roots = [o for o in bpy.context.scene.objects if wanted(o)]
+MAX_GAP = float(opt("--max-gap", 0.6)) # bigger gaps are almost always deliberate (wall-hung); report separately
+
+
+def world_verts(root):
+ vs = []
+ for o in [root, *root.children_recursive]:
+ if o.type != "MESH":
+ continue
+ ev = o.evaluated_get(dg)
+ me = ev.to_mesh()
+ mw = o.matrix_world
+ vs += [mw @ v.co for v in me.vertices]
+ ev.to_mesh_clear()
+ return vs
+
+
+# One BVH per object so a ray can skip the object it starts from.
+trees = {}
+for o in bpy.context.scene.objects:
+ if o.type == "MESH" and o.visible_get() and not o.hide_render and not any(k in o.name.lower() for k in NOT_SURFACE):
+ ev = o.evaluated_get(dg)
+ me = ev.to_mesh()
+ if len(me.polygons):
+ mw = o.matrix_world
+ trees[o.name] = BVHTree.FromPolygons([mw @ v.co for v in me.vertices], [p.vertices[:] for p in me.polygons])
+ ev.to_mesh_clear()
+
+
+def nearest_below(p, own):
+ best = None
+ for name, t in trees.items():
+ if name in own:
+ continue
+ hit = t.ray_cast(p, Vector((0, 0, -1)), 50.0)
+ if hit[0] is not None and (best is None or hit[3] < best[0]):
+ best = (hit[3], name)
+ return best
+
+
+report = []
+for root in roots:
+ vs = world_verts(root)
+ if len(vs) < 4:
+ continue
+ zmin = min(v.z for v in vs)
+ height = max(v.z for v in vs) - zmin
+ if height < 0.02:
+ continue
+ # contact candidates: lowest 1.5 cm (or 3 % of the height), thinned to at most 40 points
+ band = max(0.015, 0.03 * height)
+ feet = [v for v in vs if v.z <= zmin + band]
+ feet = feet[:: max(1, len(feet) // 40)]
+ own = {o.name for o in [root, *root.children_recursive]}
+ gaps = []
+ for f in feet:
+ hit = nearest_below(f + Vector((0, 0, 0.002)), own)
+ if hit:
+ gaps.append((hit[0] - 0.002, hit[1]))
+ if not gaps:
+ report.append({"object": root.name, "issue": "nothing below", "z": round(zmin, 3)})
+ continue
+ g, under = min(gaps)
+ if TOL < g <= MAX_GAP:
+ report.append({"object": root.name, "issue": "floating", "gap_cm": round(g * 100, 1), "on": under})
+ if FIX and root.parent is None:
+ root.location.z -= g
+ report[-1]["fixed"] = True
+ elif g < -0.03:
+ report.append({"object": root.name, "issue": "sunk", "depth_cm": round(-g * 100, 1), "on": under})
+
+floating = [r for r in report if r["issue"] == "floating"]
+print(f"grounding: {len(roots)} objects checked, {len(floating)} floating > {TOL * 100:.0f} cm, "
+ f"{sum(r['issue'] == 'sunk' for r in report)} sunk > 3 cm, {sum(r['issue'] == 'nothing below' for r in report)} with nothing below")
+for r in sorted(floating, key=lambda r: -r["gap_cm"]):
+ print(f"grounding: FLOAT {r['object']:<40} {r['gap_cm']:>6.1f} cm above {r['on']}" + (" -> fixed" if r.get("fixed") else ""))
+if opt("--report"):
+ json.dump(report, open(opt("--report"), "w"), indent=1)
+if FIX and opt("--save"):
+ bpy.ops.wm.save_as_mainfile(filepath=opt("--save"), copy=True)
+ print("grounding: saved", opt("--save"))
diff --git a/pipeline/r2.mjs b/pipeline/r2.mjs
new file mode 100644
index 0000000..77d6c7f
--- /dev/null
+++ b/pipeline/r2.mjs
@@ -0,0 +1,82 @@
+// Cloudflare R2 (S3 API) uploads for scene packages and site media.
+// node pipeline/r2.mjs ls [prefix] list objects (sizes, keys)
+// node pipeline/r2.mjs put <local file|dir> <key|prefix/> upload; a directory uploads recursively,
+// files already there with the same size are skipped
+// Credentials come from the environment: R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET
+// (anyscene-public for site media and free scenes, anyscene-packs for paid packs).
+// On Windows they are read from the user environment in the registry, so shells opened earlier still see them.
+
+import { execFileSync } from 'node:child_process';
+import { createReadStream, readdirSync, statSync } from 'node:fs';
+import { basename, extname, join, relative, sep } from 'node:path';
+import { ListObjectsV2Command, S3Client } from '@aws-sdk/client-s3';
+import { Upload } from '@aws-sdk/lib-storage';
+
+function userEnv(name) {
+ if (process.env[name]) return process.env[name];
+ if (process.platform !== 'win32') return undefined;
+ try {
+ const out = execFileSync('reg', ['query', 'HKCU\\Environment', '/v', name], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
+ return out.match(new RegExp(`${name}\\s+REG_\\w+\\s+(\\S+)`))?.[1];
+ } catch {
+ return undefined;
+ }
+}
+
+const [ACCOUNT, KEY, SECRET, BUCKET] = ['R2_ACCOUNT_ID', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_BUCKET'].map(userEnv);
+if (!ACCOUNT || !KEY || !SECRET || !BUCKET) throw new Error('set R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY and R2_BUCKET');
+const s3 = new S3Client({ region: 'auto', endpoint: `https://${ACCOUNT}.r2.cloudflarestorage.com`, credentials: { accessKeyId: KEY, secretAccessKey: SECRET } });
+
+const TYPES = {
+ '.mp4': 'video/mp4', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp',
+ '.json': 'application/json', '.zip': 'application/zip', '.md': 'text/markdown; charset=utf-8', '.txt': 'text/plain; charset=utf-8',
+ '.blend': 'application/octet-stream', '.glb': 'model/gltf-binary',
+};
+
+async function list(prefix = '') {
+ const out = new Map();
+ let token;
+ do {
+ const r = await s3.send(new ListObjectsV2Command({ Bucket: BUCKET, Prefix: prefix, ContinuationToken: token }));
+ for (const o of r.Contents ?? []) out.set(o.Key, o.Size);
+ token = r.IsTruncated ? r.NextContinuationToken : undefined;
+ } while (token);
+ return out;
+}
+
+const mb = (n) => `${(n / 1e6).toFixed(1)} MB`;
+
+async function put(local, key) {
+ const st = statSync(local);
+ const files = st.isDirectory()
+ ? readdirSync(local, { recursive: true }).map(String).filter((f) => statSync(join(local, f)).isFile())
+ .map((f) => [join(local, f), key.replace(/\/?$/, '/') + f.split(sep).join('/')])
+ : [[local, key.endsWith('/') ? key + basename(local) : key]];
+ const have = await list(st.isDirectory() ? key : '');
+ let sent = 0;
+ for (const [file, k] of files) {
+ const size = statSync(file).size;
+ if (have.get(k) === size) { console.log(`skip ${k}`); continue; }
+ const up = new Upload({
+ client: s3, queueSize: 4, partSize: 32 * 1024 * 1024,
+ params: { Bucket: BUCKET, Key: k, Body: createReadStream(file), ContentType: TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream' },
+ });
+ await up.done();
+ sent += size;
+ console.log(`put ${k} (${mb(size)})`);
+ }
+ console.log(`done: ${files.length} files, ${mb(sent)} uploaded`);
+}
+
+const [cmd, a, b] = process.argv.slice(2);
+if (cmd === 'ls') {
+ const objs = await list(a ?? '');
+ let total = 0;
+ for (const [k, s] of objs) { console.log(`${mb(s).padStart(10)} ${k}`); total += s; }
+ console.log(`${objs.size} objects, ${mb(total)}`);
+} else if (cmd === 'put' && a && b) {
+ await put(a, b);
+} else {
+ console.error('usage: node pipeline/r2.mjs ls [prefix] | put <file|dir> <key|prefix/>');
+ process.exit(1);
+}
diff --git a/pipeline/render_compare.py b/pipeline/render_compare.py
index 9f6ed45..6f94fc3 100644
--- a/pipeline/render_compare.py
+++ b/pipeline/render_compare.py
@@ -12,7 +12,13 @@ import bpy
from mathutils import Vector
ROOT, OUT = map(os.path.abspath, sys.argv[sys.argv.index("--") + 1:][:2])
-HDRI = bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")
+# Blender's bundled studio HDRI. bpy.utils.system_resource() returns "" for this in 5.0.1, so build the path from the
+# version folder that sits next to the binary (Contents/Resources on macOS).
+_VER = "%d.%d" % bpy.app.version[:2]
+_BIN = os.path.dirname(bpy.app.binary_path)
+HDRI = next((p for p in (os.path.join(_BIN, _VER), os.path.join(_BIN, "..", "Resources", _VER))
+ if os.path.isdir(p)), os.path.join(_BIN, _VER))
+HDRI = os.path.join(HDRI, "datafiles", "studiolights", "world", "studio.exr")
RES = 900
PROBE = bool(os.environ.get("PROBE"))
# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.
diff --git a/scenes/hk-dai-pai-dong/NOTES.md b/scenes/hk-dai-pai-dong/NOTES.md
new file mode 100644
index 0000000..9c700c9
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/NOTES.md
@@ -0,0 +1,105 @@
+# Dai pai dong — notes
+
+A semi-outdoor scene: a short Hong Kong street (pavement, kerb, road, tenements both sides, harbour card at the end)
+with the stall under a corrugated awning. 80 manifest props → 78 placed generated picks (2 retired), 183 placements (v2).
+
+Pipeline (run from the repo root; every Blender call goes through `scripts/blend.sh` or `scripts/shoot.sh`,
+both of which use `pipeline/gpu_run.sh` + `gpu_prefs.py`):
+
+1. `uv run --no-project python -I scenes/hk-dai-pai-dong/scripts/manifest.py` → `assets.json` (80 props incl. `_nb`, 14 textures).
+2. `node scenes/hk-dai-pai-dong/scripts/gen.mjs --stage refs`, check the sheets, then `--stage 3d` (Tripo H3.1 + Meshy 7.1, pool 12).
+3. `bash scenes/hk-dai-pai-dong/scripts/compare.sh` (12 props per GPU-queue call) + `review.sh <tag>` (sheets of unpicked props)
+ → `node scenes/hk-dai-pai-dong/scripts/pick.mjs id model "why"` → `picks.json`.
+4. `blend.sh` + `prep.py -- --only ...` → `props/<id>.blend`.
+5. `bash scenes/hk-dai-pai-dong/scripts/blend.sh build -- --save [--preview street,wok,table,walk,flame,top] [--clay]`:
+ shell → dress → resolve + validate (`out/validate.txt`) → grime → lights → fx → post → `hk.blend`.
+6. `check_path.py` on shots, `shoot.sh --framing`, then `render_finals.sh` (24-frame chunks, grade, frame-count check),
+ `stills.py` for hero stills, `render_bts.sh` for the four dollhouse clips.
+
+## Gotchas
+- No system Python on this box: helper scripts run with `uv run --no-project python -I` (Pillow via `--with pillow`).
+ Open JSON with `encoding="utf-8"`: picks/assets carry Chinese text and Windows defaults to cp1252.
+- `bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")` returns `""` in 5.0.1, so the shared
+ `render_compare.py` fails every render with "Cannot read ''". The local `scripts/compare.py` joins the path by hand.
+- `read_factory_settings()` inside a build script resets user prefs too: re-select OptiX after it (build.py does),
+ or the gpu_prefs pre-script is undone and Cycles renders on the CPU.
+- `against="x-"` takes the wall coordinate, not the prop centre: passing the centre left the cart and range 0.4 m off the shelves.
+- Wok wells: a lowest-point height map over the generated range found the front gutter, and a guess from the compare
+ renders was 25 cm off. A top-down ortho Workbench render of the placed range (2 mm/px) gave the real wells: 45% of depth,
+ 25% / 75% of width (`dress.burner_wells`). Seat woks by the mean of their lowest vertices: the long-handled wok's bbox
+ centre is ~20 cm off its bowl. Both slips were only visible in a close still, not the 32-spp previews: render a close-up.
+- `pipeline/env.sh` sets `FFMPEG=ffmpeg` when unset, so exporting the CapCut path *after* sourcing it does nothing and
+ every encode fails with "ffmpeg: command not found". Export it before, and in child scripts check `command -v`.
+- Changing set dressing mid-render means wiping the shot's frames: a chunked take mixes old and new positions otherwise.
+- Lying-flat props (wok tools, strainer, umbrella) need a max-dimension size (`m`), not `h`: by height the tools were 1.7 m long.
+- Stools around tables must drop from below the table top (start_z 0.6), or they land on the table edge.
+- Shelf props: pack along the shelf by real footprint *then* drop; dropping first let plates land on the rice cooker next door.
+- A placement deleted with `bpy.data.objects.remove` must not be the cached library root: instances are always copies now.
+- The stall's own tenement had ground-floor pilasters running through the back shelves: pilasters inside the stall start at 3.2 m.
+- Generated street lamp is centred on its bbox, so the pole is not at the origin: find the pole base from the lowest vertices.
+- Wok flame = emission-only Principled Volume ring around each well. Too-small ring = hidden under the wok; low-contrast noise
+ = orange fog. Vertically stretched 4D noise with a tight ramp reads as tongues.
+- Steam is a procedural plume volume, not Mantaflow: the walkthroughs are 408–480-frame uncut takes and a Mantaflow cache
+ that long can't be baked inside the 10-minute GPU-queue budget. Volume boxes have object motion blur off anyway.
+- Bare bulbs at 1.95 m and the stall sign board (orig. bottom 1.93 m) were inside the walk path's 0.45 m clearance; the board
+ now sits on the beam (bottom ~2.1 m).
+- fal: Meshy 7.1 ~8–20 min/job vs Tripo ~3.5 min; the fal account is shared with the other scene's session. 158 jobs took ~4 h.
+ Meshy failed 3× on `hk_crate_stack` (fal "downstream_service_error" 500) → Tripo-only pick.
+- Both generators turned the racing newspaper's printed horses into 3D figurines: retired; a direct-modelled folded slab
+ textured with the reference photo replaces it.
+- Brand check: only the beer crate ref came back branded ("RIVERTON Brewing Co."): `hk_beer_crate_nb`. Shop/neon names were
+ checked against real HK businesses/brands; dropped 榮華, 利群, 華豐, 金鳳, 聯發, 德昌, 永利, 新華, 深夜食堂.
+- Final frames: ~14 s each at 1920×804, 48 spp, with haze/steam/flame volumes and drizzle (rest of the shared GPU queue on top).
+
+- Grounding (v2, after Apek spotted floating chairs): `_drop` rested the *bbox* on the highest hit under the footprint, so
+ a stool whose box clipped a table edge sat 74 cm up with its feet over the road, and the road tables (base 15 cm lower)
+ were taller than the stools' fixed 0.6 m drop start, so 11 stools stood *on* the t3–t5 table tops (grounded, so no
+ float check caught it). Now: drop by footprint, then `settle()` down by the smallest clearance of the feet and a spread
+ of all vertices (feet alone sank plates into table rims); stools drop from table base + 0.5 m; hanging props are
+ `no_support`; the validator's FLOAT uses contact points (as `pipeline/grounding.py`) and a GROUND rule says stools/tables
+ must stand on pavement/road. A pass-through ray stepping 1 mm past the prop's own surface skipped supports closer than
+ that and mis-measured every gap: step 10 µm. The 54 cm fried-rice platter had no room on t1 (it sat on the cups): dropped.
+- Bulb glass emission 60 → 18 (burnt out to a white disc). Wok flames: tongues hug the bowl, full strength under the wok,
+ gone ~5 cm above the well rim, finer vertically stretched noise, blue jets broken by noise; the old wide ring stood off
+ the bowl as an orange curtain. `scripts/flame_try.py` swaps the flame/bulb materials into a build for quick look-dev.
+
+## Results (2026-10-30)
+- Picks: 69 Meshy 7.1, 9 Tripo H3.1, 2 retired (newspaper → direct-modelled; beer crate → `_nb`). Validator: 0 open, 3 accepted.
+- fal spend for this scene: 261 calls, ~$140 est (97 GPT Image 2.5 refs/textures, 85 Meshy, 79 Tripo).
+- Shots (`out/shots/<shot>_graded.mp4`, 1920×804, 48 spp, ffmpeg grade): s1_street_crane 5 s, h1_walk_in_to_wok 20 s,
+ s2_teapot_wok_rack 6 s, s3_wok_push 4 s, h2_walk_tables_neon 17 s, s4_neon_tilt 5 s; reel `out/shots/hk_dai_pai_dong_reel.mp4`
+ (57 s) and `hk_dai_pai_dong_reel_small.mp4` (<30 MB). Hero stills `out/stills/*_graded.png` (64 spp).
+- Breakdown: `breakdown/hk-dai-pai-dong/clips/{a_layout,b_props,c_materials,d_lighting}` (144/240/144/240 frames + mp4).
+- Part of h2 and all of s1–s4 were found already rendered when `render_finals.sh` reached them (frames at ~1.5 s/frame
+ wall time, not by this session's driver). They match the current hk.blend and shots.json (checked by eye), so they were kept.
+- Clay passes inherit the night exposure (+0.4 EV) and wash out: bts.py sets −0.7 EV for clay.
+
+## SKILL.md: what was wrong, missing or unclear for a semi-outdoor scene
+1. **Step 1 assumes a room** ("room size", "door at y=0, deep along +Y", ceiling). A street needs: street axis, facade
+ planes on both sides, kerb/road heights, how far the modelled street runs before a backdrop card, and what is overhead
+ (awning) instead of a ceiling. I documented the conventions in `brief.md`; SKILL.md should say what to write for open sites.
+2. **Step 7 "Shell and layout" has no guidance for facades.** At street scale, buildings are 16–27 m tall and mostly seen
+ at grazing angles: generated orthographic facade photos on planes + 3D ledges/pilasters/AC units/signs worked; say so.
+ Also: ground-floor architecture (pilasters, fascias) collides with set dressing that backs onto it.
+3. **Step 8 drop rays: "start below anything overhead"** needs a per-prop drop height, not one per scene. Outdoors there are
+ several overhead layers (awning, sign boards, hanging bulbs, shelves, table tops for stools).
+4. **Step 11 says Mantaflow steam**, but the same SKILL asks for long uncut walkthroughs. Those two conflict with the
+ 10-minute GPU-queue rule (a 500-frame cache won't bake in one call). Say when a procedural volume is the better choice.
+5. **Step 11 has no fire.** Wok flames / gas jets / candles need guidance (emission volume vs mesh, light flicker drivers).
+6. **Rain vs drizzle and wet ground** are one line in the SKILL; wet pavement (puddle mask, roughness, ripples) is the
+ most important material outdoors and deserves a step.
+7. **Step 5 compare**: the shared `render_compare.py` is broken on 5.0.1 (HDRI path, above), and its Tripo "front" view is a
+ side view unless `yaw.json` is filled in — say so, or fix the shared script.
+8. **Step 12 path check**: the 0.45 m clearance rule fights bulbs on cords and sign boards at head height on a street stall.
+ Worth saying "raise set pieces to clear the walk, or route around".
+9. **Step 15 dollhouse for open sites**: "hide the ceiling and near walls" doesn't apply. What worked: orbit on the open
+ (street) side only, hide the awning tarp and rafters, hide everything on the far pavement/far buildings for the whole orbit,
+ hide cross-street cables. The SPEC's 120° orbit around a "room's vertical axis" should allow a partial orbit for open sites.
+10. **Budget/time table**: fal Meshy throughput collapses when two sessions share one account; plan ~4 h for 158 jobs, and
+ start the scene shell while generation runs (the order in the SKILL suggests waiting).
+11. **No step mentions sky/backdrop.** Outdoors at night the sky and the far end of the street are in most frames.
+12. **Gate wording "agree on the look"** at step 2 is fine, but for an approved concept with a real landmark in it (here the
+ harbour tower), the SKILL should say to keep landmarks soft/unrecognisable or regenerate the backdrop without them.
+13. **Step 8 has no contact check.** A footprint/bbox raycast drop puts props on whatever is highest under the box, not
+ under the feet; say to settle by the lowest vertices and run `pipeline/grounding.py` after every dressing pass, with
+ a rule that furniture stands on the ground. Low-angle stills (knee height) are the visual check.
diff --git a/scenes/hk-dai-pai-dong/assets.json b/scenes/hk-dai-pai-dong/assets.json
new file mode 100644
index 0000000..c7cae36
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/assets.json
@@ -0,0 +1,646 @@
+{
+ "room": {
+ "kind": "street",
+ "width_x": 13.6,
+ "depth_y": 50,
+ "height_z": 22,
+ "note": "Semi-outdoor. Street along +Y. Stall-side facade x=-4, pavement x -4..0 (z 0), kerb x=0, road x 0..7.4 (z -0.15), far pavement to x 9.6, far facade x 9.6. See brief.md."
+ },
+ "scan_template": "No real-world brand names or logos. Product reference photograph for 3D scanning. The entire object fully visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft even diffuse studio lighting, no harsh shadows, no other objects, no hands, realistic used and worn condition, sharp focus, true-to-life materials.",
+ "generate": [
+ {
+ "id": "hk_kitchen_cart",
+ "h": 1.0,
+ "tier": "hero",
+ "prompt": "A battered Hong Kong dai pai dong street-food kitchen cart: a long low steel cabinet painted dark green with peeling chipped paint, rust streaks and dents, hinged side doors with padlock hasps, a stainless-steel counter top with greasy stains and a raised back splash, small wheels.",
+ "dims": [
+ 1.9,
+ 0.85,
+ 1.0
+ ]
+ },
+ {
+ "id": "hk_wok_range",
+ "h": 0.85,
+ "tier": "hero",
+ "prompt": "A Chinese commercial two-hole wok range: a stainless-steel cabinet with two deep cast-iron jet burner rings in round wok wells, a swing water faucet and a gutter along the front, gas valves with long lever handles, heavily blackened, grease-streaked and heat-discoloured.",
+ "dims": [
+ 1.5,
+ 0.85,
+ 0.85
+ ]
+ },
+ {
+ "id": "hk_wok_a",
+ "h": 0.2,
+ "tier": "hero",
+ "prompt": "A large round-bottomed blackened carbon-steel Cantonese wok, about 45 cm across, with two small riveted loop handles, seasoned and charred outside, glossy oily patina inside."
+ },
+ {
+ "id": "hk_wok_rice",
+ "h": 0.22,
+ "tier": "hero",
+ "prompt": "A blackened carbon-steel wok with fried rice with egg, green onion and char siu tossed in it and a long-handled steel wok ladle resting inside, glistening with oil."
+ },
+ {
+ "id": "hk_wok_tools",
+ "tier": "mid",
+ "prompt": "A Cantonese wok ladle and a wok spatula with long steel shafts and wooden grips, plus a bamboo wok brush, lying together, greasy and worn.",
+ "m": 0.5
+ },
+ {
+ "id": "hk_spider_strainer",
+ "tier": "mid",
+ "prompt": "A large wire-mesh spider strainer with a long bamboo handle, brass wire basket darkened with oil.",
+ "m": 0.55
+ },
+ {
+ "id": "hk_stockpot",
+ "h": 0.45,
+ "tier": "hero",
+ "prompt": "A large heavily used aluminium stockpot about 45 cm tall with riveted handles, dented sides, soot and heat discolouration, a warped lid half on."
+ },
+ {
+ "id": "hk_stockpot_small",
+ "h": 0.26,
+ "tier": "mid",
+ "prompt": "A medium dented aluminium saucepot with a long handle and a battered lid, soot stains."
+ },
+ {
+ "id": "hk_steamer_stack",
+ "h": 0.32,
+ "tier": "mid",
+ "prompt": "A stack of three round bamboo dim sum steamer baskets with a lid, darkened and stained from years of use."
+ },
+ {
+ "id": "hk_claypot",
+ "h": 0.16,
+ "tier": "mid",
+ "prompt": "A small glazed Chinese claypot with a lid and a wire handle frame, charred black bottom, for claypot rice."
+ },
+ {
+ "id": "hk_rice_cooker",
+ "h": 0.42,
+ "tier": "mid",
+ "prompt": "A big commercial electric rice cooker, dented aluminium body with a domed lid and a side lever, no logo, grimy."
+ },
+ {
+ "id": "hk_tea_urn",
+ "h": 0.55,
+ "tier": "mid",
+ "prompt": "A stainless-steel hot water urn with a tap at the front and a domed lid, water stains, plain with no logo."
+ },
+ {
+ "id": "hk_cleaver_block",
+ "h": 0.16,
+ "tier": "mid",
+ "prompt": "A thick round tree-trunk chopping block, scarred and concave from use, with a Chinese rectangular cleaver lying on it."
+ },
+ {
+ "id": "hk_hanging_utensils",
+ "h": 0.7,
+ "tier": "mid",
+ "prompt": "A greasy steel rod with S-hooks holding hanging kitchen tools: two ladles, a perforated skimmer, a wire spider strainer, a pair of long bamboo chopsticks and a wok brush.",
+ "dims": [
+ 0.9,
+ 0.12,
+ 0.7
+ ]
+ },
+ {
+ "id": "hk_sauce_shelf",
+ "h": 0.42,
+ "tier": "mid",
+ "prompt": "A small greasy two-tier steel wall shelf crowded with sauce bottles and jars: soy sauce, oyster sauce, chili oil, Shaoxing wine, sesame oil, tins of salt, all with plain hand-lettered Chinese paper labels, grimy.",
+ "dims": [
+ 0.9,
+ 0.25,
+ 0.42
+ ]
+ },
+ {
+ "id": "hk_oil_tin",
+ "h": 0.34,
+ "tier": "mid",
+ "prompt": "A large square tin of cooking oil with a pour spout, dented and oily, label in faded red Chinese text of a fictional brand."
+ },
+ {
+ "id": "hk_lpg_cylinder",
+ "h": 0.75,
+ "tier": "hero",
+ "prompt": "A tall grey steel LPG gas cylinder with a valve guard collar, a regulator and an orange rubber gas hose, scuffed and rusty at the base, no brand."
+ },
+ {
+ "id": "hk_veg_basket",
+ "h": 0.24,
+ "tier": "mid",
+ "prompt": "A red plastic basket heaped with fresh choy sum greens and spring onions, water drops."
+ },
+ {
+ "id": "hk_prawn_tray",
+ "h": 0.07,
+ "tier": "mid",
+ "prompt": "A stainless-steel tray of raw grey prawns and sliced squid on ice."
+ },
+ {
+ "id": "hk_aromatics_bowls",
+ "h": 0.1,
+ "tier": "mid",
+ "prompt": "Three small stainless bowls of chopped garlic, sliced ginger and red chilli, a wet spoon."
+ },
+ {
+ "id": "hk_bowl_stack",
+ "h": 0.3,
+ "tier": "mid",
+ "prompt": "A tall stack of white Chinese melamine rice bowls with a thin blue rim pattern, slightly scratched."
+ },
+ {
+ "id": "hk_plate_stack",
+ "h": 0.22,
+ "tier": "mid",
+ "prompt": "A stack of oval white melamine serving plates with a red border pattern, scratched."
+ },
+ {
+ "id": "hk_dish_rack",
+ "h": 0.45,
+ "tier": "mid",
+ "prompt": "A stainless wire dish drying rack full of wet white bowls and plates and a cluster of chopsticks."
+ },
+ {
+ "id": "hk_wash_basin",
+ "h": 0.3,
+ "tier": "mid",
+ "prompt": "A big round red plastic wash basin full of soapy water and dirty bowls and plates."
+ },
+ {
+ "id": "hk_tub_blue",
+ "h": 0.3,
+ "tier": "mid",
+ "prompt": "A large blue plastic storage tub with a loose lid, scuffed."
+ },
+ {
+ "id": "hk_crate_stack",
+ "h": 0.6,
+ "tier": "mid",
+ "prompt": "Two stacked worn plastic bread crates, one blue and one red, holding cabbages and bags of bean sprouts."
+ },
+ {
+ "id": "hk_styrofoam_box",
+ "h": 0.3,
+ "tier": "mid",
+ "prompt": "A white styrofoam cooler box with a lid, taped with brown tape, dirty and dented, handwritten Chinese marker on the side."
+ },
+ {
+ "id": "hk_rice_sack",
+ "h": 0.55,
+ "tier": "mid",
+ "prompt": "A woven white polypropylene 25 kg rice sack, slumped, printed with a fictional red Chinese rice brand and a green field emblem."
+ },
+ {
+ "id": "hk_cardboard_boxes",
+ "h": 0.6,
+ "tier": "mid",
+ "prompt": "A stack of three worn wet-cornered cardboard produce boxes printed with fictional Chinese supplier names."
+ },
+ {
+ "id": "hk_jars_preserved",
+ "h": 0.25,
+ "tier": "mid",
+ "prompt": "Three big glass jars of preserved vegetables and pickled chillies with red plastic lids."
+ },
+ {
+ "id": "hk_thermos",
+ "h": 0.36,
+ "tier": "mid",
+ "prompt": "A vintage Chinese tin thermos flask painted red with a peony flower pattern and a cork stopper, chipped paint."
+ },
+ {
+ "id": "hk_takeaway_boxes",
+ "h": 0.22,
+ "tier": "clutter",
+ "prompt": "A stack of white foam takeaway clamshell boxes and a roll of thin red-and-white striped plastic bags."
+ },
+ {
+ "id": "hk_fan",
+ "h": 0.55,
+ "tier": "mid",
+ "prompt": "An old oscillating electric table fan with a cream metal cage and grime on the blades, no logo."
+ },
+ {
+ "id": "hk_radio",
+ "h": 0.16,
+ "tier": "clutter",
+ "prompt": "A small old transistor radio with a silver telescopic antenna, cracked plastic case, fictional brand name."
+ },
+ {
+ "id": "hk_fire_extinguisher",
+ "h": 0.55,
+ "tier": "mid",
+ "prompt": "A red dry-powder fire extinguisher with a black hose and a Chinese instruction label, dusty."
+ },
+ {
+ "id": "hk_menu_board_a",
+ "h": 0.9,
+ "tier": "mid",
+ "prompt": "A weathered wooden menu board painted cream with red and black hand-brushed Chinese dish names and prices in vertical columns, rain-stained.",
+ "dims": [
+ 0.6,
+ 0.03,
+ 0.9
+ ]
+ },
+ {
+ "id": "hk_menu_board_b",
+ "h": 0.5,
+ "tier": "mid",
+ "prompt": "A faded yellow plastic menu sign with handwritten red Chinese dish names and prices in marker, curling tape at the corners.",
+ "dims": [
+ 0.8,
+ 0.03,
+ 0.5
+ ]
+ },
+ {
+ "id": "hk_enamel_shade",
+ "h": 0.18,
+ "tier": "mid",
+ "prompt": "A dark green enamel industrial lamp shade with a bare tungsten bulb and a cloth-covered cord, chipped enamel, rust."
+ },
+ {
+ "id": "hk_fluoro_fitting",
+ "h": 0.08,
+ "tier": "mid",
+ "prompt": "A bare single fluorescent tube light fitting with a white metal batten, dusty and spotted with grease.",
+ "dims": [
+ 1.25,
+ 0.12,
+ 0.08
+ ]
+ },
+ {
+ "id": "hk_table_round",
+ "h": 0.74,
+ "tier": "hero",
+ "prompt": "A Hong Kong folding round dining table with a scratched stainless-steel top and a thin rolled rim, folding steel tube legs, worn and wet with raindrops.",
+ "dims": [
+ 0.95,
+ 0.95,
+ 0.74
+ ]
+ },
+ {
+ "id": "hk_table_square",
+ "h": 0.72,
+ "tier": "mid",
+ "prompt": "A small square folding table with a green laminated top with chipped edges and folding steel legs, wet.",
+ "dims": [
+ 0.75,
+ 0.75,
+ 0.72
+ ]
+ },
+ {
+ "id": "hk_stool_red",
+ "h": 0.45,
+ "tier": "hero",
+ "prompt": "A classic red plastic stool with a round seat with a hand hole in the middle and four splayed legs, scuffed and slightly faded, raindrops."
+ },
+ {
+ "id": "hk_stool_stack",
+ "h": 0.95,
+ "tier": "mid",
+ "prompt": "A leaning stack of six red plastic stools, scuffed, wet."
+ },
+ {
+ "id": "hk_stool_blue",
+ "h": 0.45,
+ "tier": "mid",
+ "prompt": "A blue plastic square stool with a perforated seat, scuffed and faded."
+ },
+ {
+ "id": "hk_enamel_teapot",
+ "h": 0.2,
+ "tier": "hero",
+ "prompt": "A white enamel teapot with a red peony flower pattern, chipped black edges and a bail handle, tea stains."
+ },
+ {
+ "id": "hk_tea_cups",
+ "h": 0.08,
+ "tier": "mid",
+ "prompt": "Four small thick white restaurant tea cups and a plastic bowl of hot water for rinsing chopsticks."
+ },
+ {
+ "id": "hk_condiment_caddy",
+ "h": 0.2,
+ "tier": "hero",
+ "prompt": "A small stainless steel condiment caddy holding a soy sauce bottle, a chilli oil jar with a spoon, a white pepper shaker and a toothpick holder, greasy, plain labels."
+ },
+ {
+ "id": "hk_soy_bottles",
+ "h": 0.24,
+ "tier": "mid",
+ "prompt": "Two glass sauce dispenser bottles with red plastic caps, one with dark soy sauce, one with red vinegar, smeared."
+ },
+ {
+ "id": "hk_chopstick_cup",
+ "h": 0.24,
+ "tier": "mid",
+ "prompt": "A dented stainless-steel cylinder cup full of bamboo chopsticks and a few white plastic soup spoons."
+ },
+ {
+ "id": "hk_toilet_roll",
+ "h": 0.12,
+ "tier": "clutter",
+ "prompt": "A roll of pink toilet paper used as napkins sitting in a plastic holder, slightly damp."
+ },
+ {
+ "id": "hk_newspaper",
+ "h": 0.03,
+ "tier": "mid",
+ "prompt": "A folded Chinese-language racing newspaper with horse racing tables and photos, creased, a pen lying on it, fictional masthead."
+ },
+ {
+ "id": "hk_dish_fried_rice",
+ "h": 0.08,
+ "tier": "mid",
+ "prompt": "An oval white plate of Yangzhou fried rice with shrimp, egg and char siu, half eaten, a porcelain spoon in it."
+ },
+ {
+ "id": "hk_dish_beef_hofun",
+ "h": 0.08,
+ "tier": "mid",
+ "prompt": "An oval plate of dry-fried beef ho fun flat rice noodles with bean sprouts and spring onion, glossy dark."
+ },
+ {
+ "id": "hk_dish_clams",
+ "h": 0.08,
+ "tier": "mid",
+ "prompt": "A plate of stir-fried clams in black bean and chilli sauce, shells open, glistening."
+ },
+ {
+ "id": "hk_dish_greens",
+ "h": 0.06,
+ "tier": "mid",
+ "prompt": "A plate of blanched choy sum greens with oyster sauce drizzled over."
+ },
+ {
+ "id": "hk_dish_salt_squid",
+ "h": 0.08,
+ "tier": "mid",
+ "prompt": "A plate of salt and pepper fried squid with fried garlic and red chilli."
+ },
+ {
+ "id": "hk_milk_tea",
+ "h": 0.14,
+ "tier": "clutter",
+ "prompt": "A thick white Hong Kong cha chaan teng mug of milk tea, tan colour, on a saucer."
+ },
+ {
+ "id": "hk_lemon_tea",
+ "h": 0.17,
+ "tier": "clutter",
+ "prompt": "A tall glass of iced lemon tea with lemon slices, ice and a straw, condensation."
+ },
+ {
+ "id": "hk_beer_bottles",
+ "h": 0.3,
+ "tier": "mid",
+ "prompt": "Two large green beer bottles with a fictional label reading 金龍啤酒 and a short glass of beer with foam."
+ },
+ {
+ "id": "hk_beer_crate",
+ "h": 0.32,
+ "tier": "mid",
+ "prompt": "A yellow plastic beer crate holding twelve empty green bottles with fictional labels."
+ },
+ {
+ "id": "hk_ashtray",
+ "h": 0.04,
+ "tier": "clutter",
+ "prompt": "A crushed tin ashtray with cigarette butts and ash."
+ },
+ {
+ "id": "hk_bowl_congee",
+ "h": 0.1,
+ "tier": "clutter",
+ "prompt": "A white melamine bowl of congee with century egg and green onion and a plastic spoon."
+ },
+ {
+ "id": "hk_street_lamp",
+ "h": 8.5,
+ "tier": "hero",
+ "prompt": "A tall grey steel Hong Kong street lamp post with a long curved outreach arm and a flat rectangular lantern head, rust streaks, small numbered plate."
+ },
+ {
+ "id": "hk_guard_railing",
+ "h": 1.0,
+ "tier": "mid",
+ "prompt": "A section of Hong Kong roadside pedestrian guard railing: grey painted steel tube railing with vertical bars between two posts, chipped paint, rust.",
+ "dims": [
+ 2.0,
+ 0.1,
+ 1.0
+ ]
+ },
+ {
+ "id": "hk_water_barrier",
+ "h": 0.8,
+ "tier": "mid",
+ "prompt": "A plastic water-filled road barrier, alternating red and white, dirty, scuffed, rain wet.",
+ "dims": [
+ 1.3,
+ 0.45,
+ 0.8
+ ]
+ },
+ {
+ "id": "hk_traffic_cone",
+ "h": 0.7,
+ "tier": "clutter",
+ "prompt": "An orange traffic cone with reflective white bands, dirty and scuffed."
+ },
+ {
+ "id": "hk_parked_car",
+ "h": 1.45,
+ "tier": "hero",
+ "prompt": "A generic 1990s boxy four-door saloon car in dark red, rain-wet, no badges, no logos, no number plate text, dirt on the sills.",
+ "dims": [
+ 1.75,
+ 4.4,
+ 1.45
+ ]
+ },
+ {
+ "id": "hk_scooter",
+ "h": 1.15,
+ "tier": "mid",
+ "prompt": "A small generic delivery motor scooter with a delivery box on the back, no logos, wet, scuffed."
+ },
+ {
+ "id": "hk_hand_trolley",
+ "h": 1.1,
+ "tier": "mid",
+ "prompt": "A steel two-wheel hand trolley loaded with flattened cardboard and a crate, straps, worn."
+ },
+ {
+ "id": "hk_trash_bin",
+ "h": 0.95,
+ "tier": "mid",
+ "prompt": "A large green plastic wheelie rubbish bin with the lid half open, a black bag poking out, grimy."
+ },
+ {
+ "id": "hk_bin_bags",
+ "h": 0.6,
+ "tier": "clutter",
+ "prompt": "Three tied black rubbish bags in a heap, wet and glossy."
+ },
+ {
+ "id": "hk_umbrella",
+ "tier": "clutter",
+ "prompt": "A closed wet black folding umbrella leaning, slightly crumpled.",
+ "m": 0.95
+ },
+ {
+ "id": "hk_shrine",
+ "h": 0.5,
+ "tier": "mid",
+ "prompt": "A small red Chinese street shrine box for the earth god on the ground with a gold inscription, incense sticks in a pot, oranges and a small cup, burnt candle wax."
+ },
+ {
+ "id": "hk_aircon_unit",
+ "h": 0.4,
+ "tier": "mid",
+ "prompt": "An old window air conditioner unit, beige metal case with rust stains and a grille, dripping water, no logo.",
+ "dims": [
+ 0.66,
+ 0.6,
+ 0.4
+ ]
+ },
+ {
+ "id": "hk_electric_box",
+ "h": 0.55,
+ "tier": "mid",
+ "prompt": "A grey steel electrical meter box on a wall with conduits coming out, rusty, a few stickers with Chinese text, no brand.",
+ "dims": [
+ 0.45,
+ 0.2,
+ 0.55
+ ]
+ },
+ {
+ "id": "hk_mop_bucket",
+ "h": 0.7,
+ "tier": "clutter",
+ "prompt": "A grey mop leaning in a battered red plastic bucket."
+ },
+ {
+ "id": "hk_plastic_bag_hang",
+ "h": 0.4,
+ "tier": "clutter",
+ "prompt": "A red-and-white striped thin plastic shopping bag hanging from a hook with something heavy inside."
+ },
+ {
+ "id": "hk_bird_cage",
+ "h": 0.45,
+ "tier": "clutter",
+ "prompt": "A round bamboo bird cage with a cloth cover partly lifted, hanging hook on top."
+ },
+ {
+ "id": "hk_water_bucket",
+ "h": 0.32,
+ "tier": "clutter",
+ "prompt": "A battered aluminium bucket half full of water."
+ },
+ {
+ "id": "hk_beer_crate_nb",
+ "h": 0.32,
+ "tier": "mid",
+ "prompt": "A yellow plastic beer crate holding twelve empty green beer bottles, the crate moulded with the fictional Chinese brewery name 金龍啤酒 only, no English text, scuffed and dirty.",
+ "replaces": "hk_beer_crate"
+ }
+ ],
+ "textures": [
+ {
+ "id": "hk_tex_skyline",
+ "size": "landscape_16_9",
+ "prompt": "Wide night photograph across a harbour toward a dense high-rise city skyline on the far shore, very soft and out of focus as if shot through rain with a long lens, lights reduced to soft blurred bokeh, low clouds glowing orange and magenta from the city lights, misty, no recognisable landmark towers, no readable text. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_facade_a",
+ "size": "portrait_16_9",
+ "prompt": "Straight-on orthographic elevation photograph of an old 1960s Hong Kong tenement building facade at night, six floors of windows with rusty metal grilles, a few warm lit windows, laundry poles, air conditioner units, mould stains on grey-green mosaic tiles, flat front view, no perspective, no signs, no text. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_facade_b",
+ "size": "portrait_16_9",
+ "prompt": "Straight-on orthographic elevation photograph of an old Hong Kong residential tenement facade at night, cream painted concrete stained with black rain streaks, rows of aluminium windows with security grilles, potted plants on ledges, two lit windows with fluorescent light, flat front view, no perspective, no signs, no text. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_facade_c",
+ "size": "portrait_16_9",
+ "prompt": "Straight-on orthographic elevation photograph of a narrow old Hong Kong tenement at night with enclosed balconies with metal cages, faded pink paint, water stains, a few lit windows, hanging laundry, flat front view, no perspective, no signs, no text. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_shutter_a",
+ "size": "landscape_4_3",
+ "prompt": "Flat straight-on photo of a closed corrugated steel roller shutter of a Hong Kong shop at night, grey, dented, rust streaks, a small padlock at the bottom, flat lit, fills the frame, no readable shop name. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_shutter_b",
+ "size": "landscape_4_3",
+ "prompt": "Flat straight-on photo of a closed green-painted roller shutter of a Hong Kong hardware shop, peeling paint, old paper notices taped on it with handwritten Chinese, rust, fills the frame. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_stall_sign",
+ "size": "landscape_16_9",
+ "prompt": "Flat front view of a weathered painted shop sign board for a Hong Kong street-food stall: cream background, large red brush-calligraphy Chinese characters 旺記小炒 on the left and smaller black vertical columns of dish names on the right, rust stains, grease, chipped edges, fills the frame exactly, fictional business. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_posters",
+ "size": "square_hd",
+ "prompt": "Flat lay of six weathered torn paper posters and notices on a white background, spaced apart: a Chinese opera performance poster with fictional names, a handwritten room-for-rent notice 吉房出租, a plumbing service sticker with a phone number, a faded movie poster with a fictional title, a missing cat notice, a lucky red paper with gold characters. Fictional text only. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_menu_strips",
+ "size": "landscape_16_9",
+ "prompt": "Flat front view of a row of twelve vertical red and yellow paper menu strips with hand-brushed black Chinese dish names and prices like 豉椒炒蜆 $68 and 乾炒牛河 $62, taped side by side on a wall, grease spots, fills the frame. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_lightbox_a",
+ "size": "portrait_4_3",
+ "prompt": "Flat front view of a vertical Hong Kong shop lightbox sign, white panel with large red Chinese characters 長發飯店 and a thin green border, slightly dirty, evenly backlit, fills the frame, fictional business, no other text. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_lightbox_b",
+ "size": "portrait_4_3",
+ "prompt": "Flat front view of a vertical Hong Kong lightbox sign, yellow panel with large black Chinese characters 和興五金 and a red stripe, dirty, evenly backlit, fills the frame, fictional business. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_lightbox_c",
+ "size": "portrait_4_3",
+ "prompt": "Flat front view of a vertical Hong Kong lightbox sign, blue panel with white Chinese characters 美珍冰室 and a painted coffee cup icon, dirty, evenly backlit, fills the frame, fictional business. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_asphalt",
+ "size": "square_hd",
+ "prompt": "Top-down seamless texture of wet old asphalt road surface with dark puddles, oil sheen, cracks and patched areas, overcast flat lighting, no markings. No real-world brand names or logos."
+ },
+ {
+ "id": "hk_tex_pavement",
+ "size": "square_hd",
+ "prompt": "Top-down seamless texture of Hong Kong pavement made of small square grey and red concrete paving bricks, wet, worn, stained, chewing gum spots, flat lighting. No real-world brand names or logos."
+ }
+ ],
+ "direct": [
+ "street/road/kerb/pavement",
+ "tenement facades, windows, balconies",
+ "awning frame + corrugated tarp",
+ "steel shelves",
+ "bare bulbs + cords",
+ "neon text (msjh.ttc text objects)",
+ "drains, puddles",
+ "wok flames",
+ "cables"
+ ]
+}
\ No newline at end of file
diff --git a/scenes/hk-dai-pai-dong/brief.md b/scenes/hk-dai-pai-dong/brief.md
new file mode 100644
index 0000000..60e5edb
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/brief.md
@@ -0,0 +1,51 @@
+# Hong Kong dai pai dong, late night after rain
+
+**Place.** A licensed dai pai dong (open-air cooked-food stall) on the pavement of a narrow old street in a Hong Kong
+tenement district (Sham Shui Po / Sheung Wan feel). A battered green steel kitchen cart with roaring wok burners
+against a tenement wall, a corrugated-tarp awning on steel poles, folding round tables and red plastic stools on
+the pavement and spilling into the road. The street runs downhill toward the harbour; the far skyline is a soft
+backdrop only.
+
+**Time / weather.** About 1:30 AM. It has just rained hard; now a light drizzle. Everything wet, puddles in the road.
+
+**Mood words.** steamy, neon-soaked, worn, warm-in-the-cold, alive-after-hours.
+
+**Lens style.** Anamorphic-feel 2.39:1, 24–40 mm for the walks, 85–135 mm for the wok/teapot details. Messy handheld
+walk takes, long and uncut.
+
+## Coordinates (metres, Z up)
+It is a street, not a room; the "door" convention becomes "the walk-in side".
+- The street runs along **+Y** (receding toward the harbour). Model y −14 … +36; beyond that a skyline card at y ≈ +140.
+- **Stall side** (left looking down the street): tenement facade plane at **x = −4.0**, pavement x −4 … 0 at z = 0,
+ kerb face at x = 0 (15 cm drop), road x 0 … 7.4 at z = −0.15, far pavement x 7.4 … 9.6 at z = 0, far facades at x = 9.6.
+- **Stall footprint:** x −4.0 … −1.6, y −0.5 … 6.0. Kitchen cart + wok range along the facade (front faces +X, into the street).
+- **Awning:** corrugated tarp from the facade at z 3.1 sloping to z 2.55 at x = −0.2, y −1 … 7; steel poles at x −0.3.
+- **Seating:** 4 round tables + 1 square table with 16–20 stools on the pavement (x −1.5 … 0) and in the road (x 0.4 … 3.2).
+- **Walk-in side:** the road, y < −2. The handheld walk starts out in the road and walks toward the woks (−X).
+
+## Zones
+1. Wok station (cart, wok range with two burners, flames, steam, utensils rail, sauce shelf above).
+2. Prep/back shelves along the wall (bowls, pots, rice cooker, tubs, jars), crates and gas cylinders underneath.
+3. Seating under and beyond the awning (tables, stools, teapots, dishes, toilet-roll napkins, newspapers).
+4. Street: kerb, guard railing, water barrier, parked car and scooter, street lamp, drains, puddles.
+5. Facades: shuttered shops at ground level, neon/lightbox signs stacked above, AC units, windows, laundry poles.
+
+## Hero spots
+- **H1 wok:** 0.9 m from the wok range, eye level, flames and steam, sauce shelf behind.
+- **H2 table:** low over the nearest round table toward the stall (teapot, soy bottles, newspaper foreground).
+- **H3 street:** from the road, y ≈ −8, the whole stall under its awning with the neon stack above (concept angle).
+
+## Practicals
+- 5–6 bare tungsten bulbs on cords under the awning (2700 K), one enamel-shaded bulb over the wok.
+- Two wok-burner flames (blue core, orange lick when tossing) — emissive volumes/meshes + small orange point lights.
+- A fluorescent tube over the back shelves (cool white, slightly green).
+- Neon/lightbox signs on the facades (red, cyan, pink, amber) — fictional names only.
+- Sodium/LED street lamp over the road, shuttered-shop security lights, a few lit tenement windows.
+- Sky: low cloud lit orange-magenta from the city. Wet ground gives every light a long reflection.
+
+## Atmosphere
+Steam from the woks and stockpot (Mantaflow), light haze, drizzle particles, wet pavement with puddles.
+
+## Signage (all fictional)
+Stall: 「旺記小炒」 (Wong Kee stir-fry). Neon: 「深夜食堂」→ replaced by fictional 「夜來香」, 「金華大押」-style pawn
+sign → 「永利押」, 「長發飯店」, 「和記五金」→「和興五金」, 「美珍冰室」. No real business names, no real brands.
diff --git a/scenes/hk-dai-pai-dong/picks.json b/scenes/hk-dai-pai-dong/picks.json
new file mode 100644
index 0000000..7db1776
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/picks.json
@@ -0,0 +1,323 @@
+{
+ "hk_kitchen_cart": {
+ "model": "meshy",
+ "reason": "Paint chipping, padlock hasps and casters match the ref; clay shows the doors as real geometry."
+ },
+ "hk_rice_cooker": {
+ "model": "meshy",
+ "reason": "Crisper dents and side clamps; Tripo slightly soft."
+ },
+ "hk_spider_strainer": {
+ "model": "tripo-h31",
+ "reason": "Bamboo handle split and binding modelled; wire basket reads better."
+ },
+ "hk_steamer_stack": {
+ "model": "tripo-h31",
+ "reason": "Darker stains closer to the well-used ref; weave equal on both."
+ },
+ "hk_stockpot": {
+ "model": "tripo-h31",
+ "reason": "Dents are real geometry in clay; soot band matches the ref."
+ },
+ "hk_stockpot_small": {
+ "model": "tripo-h31",
+ "reason": "Dented side and soot; Meshy body too clean."
+ },
+ "hk_tea_urn": {
+ "model": "meshy",
+ "reason": "Brushed steel and tap closest to the ref; Tripo lid too black."
+ },
+ "hk_wok_a": {
+ "model": "meshy",
+ "reason": "Black seasoned bowl like the ref; Tripo hammered bronze look is off."
+ },
+ "hk_wok_range": {
+ "model": "meshy",
+ "reason": "Burner wells, gutter and scorch marks all present; front reads like the ref."
+ },
+ "hk_wok_rice": {
+ "model": "meshy",
+ "reason": "Black wok with legible rice; Tripo wok came out tan and the rice pinkish."
+ },
+ "hk_wok_tools": {
+ "model": "meshy",
+ "reason": "Ladle, spatula and brush faithful to the ref; Tripo mixed up the spatula."
+ },
+ "hk_aromatics_bowls": {
+ "model": "meshy",
+ "reason": "Garlic, ginger and chilli read clearly; spoon kept; Tripo contents muddy."
+ },
+ "hk_claypot": {
+ "model": "tripo-h31",
+ "reason": "Glaze drips and charred base closest to the ref; both modelled the wire handle."
+ },
+ "hk_cleaver_block": {
+ "model": "meshy",
+ "reason": "Cleaver lies flat on a concave scarred top like the ref; Tripo cleaver stands upright."
+ },
+ "hk_hanging_utensils": {
+ "model": "meshy",
+ "reason": "All six tools on the rail incl. chopsticks and brush; clay shows separated hooks."
+ },
+ "hk_lpg_cylinder": {
+ "model": "meshy",
+ "reason": "Regulator and orange hose modelled; rust ring at the base matches."
+ },
+ "hk_oil_tin": {
+ "model": "meshy",
+ "reason": "Fictional label legible and dents present; Tripo label smeared."
+ },
+ "hk_prawn_tray": {
+ "model": "tripo-h31",
+ "reason": "Prawns more defined and separate in clay; Meshy squid rings blobby."
+ },
+ "hk_sauce_shelf": {
+ "model": "meshy",
+ "reason": "Two tiers with hand-lettered bottles and jars; Tripo made a thin side-view rack."
+ },
+ "hk_bowl_stack": {
+ "model": "meshy",
+ "reason": "Blue rim band crisp on every bowl; clay shows separate bowls."
+ },
+ "hk_dish_rack": {
+ "model": "meshy",
+ "reason": "Fuller rack with plates, bowls and chopstick caddy like the ref."
+ },
+ "hk_fire_extinguisher": {
+ "model": "meshy",
+ "reason": "Chinese instruction label legible; Tripo lost the label."
+ },
+ "hk_plate_stack": {
+ "model": "meshy",
+ "reason": "Oval plates with red border; both fine, Meshy rims sharper."
+ },
+ "hk_rice_sack": {
+ "model": "meshy",
+ "reason": "Fictional print sharp and slumped shape; back mirrors the print but faces the wall."
+ },
+ "hk_styrofoam_box": {
+ "model": "meshy",
+ "reason": "Proportions and the hand-written 海鮮 match; Tripo box too cubic."
+ },
+ "hk_thermos": {
+ "model": "meshy",
+ "reason": "Peony pattern on the body; Tripo lost the flowers."
+ },
+ "hk_tub_blue": {
+ "model": "meshy",
+ "reason": "Lid and scuffs closest; both similar, Meshy shape wider like the ref."
+ },
+ "hk_wash_basin": {
+ "model": "meshy",
+ "reason": "Saturated red tub with bowls; Tripo washed out pink."
+ },
+ "hk_enamel_shade": {
+ "model": "meshy",
+ "reason": "Deep enamel green with chips like the ref; Tripo too pale and clean."
+ },
+ "hk_enamel_teapot": {
+ "model": "meshy",
+ "reason": "Peony and chipped black edges; handle and spout shapes closer."
+ },
+ "hk_fan": {
+ "model": "meshy",
+ "reason": "Blades visible behind the cage, front reads like the ref; Tripo fan faces sideways."
+ },
+ "hk_fluoro_fitting": {
+ "model": "meshy",
+ "reason": "Tube and end caps visible; Tripo batten closed."
+ },
+ "hk_jars_preserved": {
+ "model": "meshy",
+ "reason": "Three jars with distinct pickles and chillies like the ref; Tripo jars all the same."
+ },
+ "hk_menu_board_a": {
+ "model": "meshy",
+ "reason": "Legible fictional menu on a weathered A-frame; back face mirrors the text, so it stands with its back to the wall."
+ },
+ "hk_menu_board_b": {
+ "model": "meshy",
+ "reason": "Hand-lettered red text crisp; both models added an easel, so it stands on the top shelf instead of hanging."
+ },
+ "hk_radio": {
+ "model": "meshy",
+ "reason": "Front panel, dial and fictional NovaTone badge; Tripo front blank."
+ },
+ "hk_stool_blue": {
+ "model": "meshy",
+ "reason": "Perforated seat in geometry, scuffed legs."
+ },
+ "hk_stool_red": {
+ "model": "meshy",
+ "reason": "Hand hole and splayed legs, saturated red with wet sheen; hero stool."
+ },
+ "hk_stool_stack": {
+ "model": "meshy",
+ "reason": "Six stacked stools with readable gaps; Tripo similar but softer."
+ },
+ "hk_table_round": {
+ "model": "meshy",
+ "reason": "Rolled rim and wet stainless top; Tripo top too bright, legs thinner than ref."
+ },
+ "hk_table_square": {
+ "model": "meshy",
+ "reason": "Green laminate with chipped edges; proportions match."
+ },
+ "hk_takeaway_boxes": {
+ "model": "meshy",
+ "reason": "Clamshells and striped bag roll; Tripo stack too small."
+ },
+ "hk_tea_cups": {
+ "model": "tripo-h31",
+ "reason": "Tea in the cups and the clear rinse bowl reads as clear plastic; Meshy bowl opaque."
+ },
+ "hk_ashtray": {
+ "model": "meshy",
+ "reason": "Crushed tin with butts and ash; Tripo similar, Meshy rim deformation closer."
+ },
+ "hk_beer_bottles": {
+ "model": "meshy",
+ "reason": "Fictional 金龍 label legible, foam on the glass; Tripo lost the labels."
+ },
+ "hk_bowl_congee": {
+ "model": "meshy",
+ "reason": "Century egg and green onion read; spoon angle matches."
+ },
+ "hk_chopstick_cup": {
+ "model": "tripo-h31",
+ "reason": "Dents in the cup are geometry and spoons are separate; Meshy cup too clean."
+ },
+ "hk_condiment_caddy": {
+ "model": "meshy",
+ "reason": "Soy, chilli oil, pepper and toothpicks all present with plain labels; Tripo bottles merged."
+ },
+ "hk_dish_beef_hofun": {
+ "model": "meshy",
+ "reason": "Wider plate, glossy noodles, bean sprouts visible."
+ },
+ "hk_dish_clams": {
+ "model": "meshy",
+ "reason": "Open shells and chilli read; Tripo clams muddy."
+ },
+ "hk_dish_fried_rice": {
+ "model": "meshy",
+ "reason": "Shrimp, egg and spoon like the ref, half-eaten edge."
+ },
+ "hk_dish_greens": {
+ "model": "meshy",
+ "reason": "Choy sum stalks and oyster sauce sheen; Tripo leaves only."
+ },
+ "hk_dish_salt_squid": {
+ "model": "meshy",
+ "reason": "Rings and chilli legible; similar, Meshy plate rim better."
+ },
+ "hk_guard_railing": {
+ "model": "meshy",
+ "reason": "Straight posts and feet like the ref; Tripo mesh thin and bent."
+ },
+ "hk_lemon_tea": {
+ "model": "meshy",
+ "reason": "Lemon slices and ice visible through the glass; straw intact."
+ },
+ "hk_milk_tea": {
+ "model": "meshy",
+ "reason": "Thick mug and saucer proportions closer."
+ },
+ "hk_parked_car": {
+ "model": "meshy",
+ "reason": "Boxy saloon with wet paint and no badges; Tripo body softer and wheels small."
+ },
+ "hk_soy_bottles": {
+ "model": "meshy",
+ "reason": "Both bottles present (Tripo merged them into one)."
+ },
+ "hk_street_lamp": {
+ "model": "meshy",
+ "reason": "Curved outreach arm and head cleaner; Tripo pole kinked."
+ },
+ "hk_toilet_roll": {
+ "model": "meshy",
+ "reason": "Pink roll with the hanging sheet and holder like the ref."
+ },
+ "hk_traffic_cone": {
+ "model": "meshy",
+ "reason": "Reflective bands and dirty base; Tripo smaller base."
+ },
+ "hk_water_barrier": {
+ "model": "meshy",
+ "reason": "Red/white pattern and fill caps; Tripo washed out."
+ },
+ "hk_newspaper": {
+ "model": "retired",
+ "reason": "Both models extruded the racing photos into 3D horse figurines; replaced by a direct-modelled folded paper textured with the reference image."
+ },
+ "hk_aircon_unit": {
+ "model": "meshy",
+ "reason": "Front grille and knobs like the ref (back has a stray print, but it faces the facade)."
+ },
+ "hk_bin_bags": {
+ "model": "meshy",
+ "reason": "Three tied glossy bags; Tripo shows two."
+ },
+ "hk_bird_cage": {
+ "model": "meshy",
+ "reason": "Bamboo bars visible under the lifted cloth like the ref; Tripo fully covered."
+ },
+ "hk_electric_box": {
+ "model": "meshy",
+ "reason": "Meter window, warning stickers and conduits; Tripo front blank."
+ },
+ "hk_hand_trolley": {
+ "model": "meshy",
+ "reason": "Strapped cardboard and crate, wheels round."
+ },
+ "hk_mop_bucket": {
+ "model": "meshy",
+ "reason": "Mop head and wringer basket read; similar, Meshy bucket redder."
+ },
+ "hk_plastic_bag_hang": {
+ "model": "meshy",
+ "reason": "Stripe pattern crisp, hook modelled."
+ },
+ "hk_scooter": {
+ "model": "meshy",
+ "reason": "Delivery box and full bodywork; no logos."
+ },
+ "hk_shrine": {
+ "model": "meshy",
+ "reason": "土地公 plaque, incense pot and oranges; Tripo lost the inscription."
+ },
+ "hk_trash_bin": {
+ "model": "meshy",
+ "reason": "Lid ajar with bag poking out like the ref."
+ },
+ "hk_umbrella": {
+ "model": "meshy",
+ "reason": "Crumpled canopy and strap; similar, Meshy cleaner silhouette."
+ },
+ "hk_water_bucket": {
+ "model": "meshy",
+ "reason": "Water surface and dents; bail handle correct."
+ },
+ "hk_beer_crate_nb": {
+ "model": "meshy",
+ "reason": "Fictional 金龍啤酒 moulding legible and bottles separate; Tripo lost the lettering."
+ },
+ "hk_cardboard_boxes": {
+ "model": "meshy",
+ "reason": "All three printed fictional supplier labels legible; Tripo boxes blank."
+ },
+ "hk_veg_basket": {
+ "model": "meshy",
+ "reason": "Choy sum and spring onions read separately in a mesh basket; similar, Meshy greens fuller."
+ },
+ "hk_crate_stack": {
+ "model": "tripo-h31",
+ "reason": "Tripo only: Meshy failed three times with a fal downstream 500."
+ },
+ "hk_beer_crate": {
+ "model": "retired",
+ "debranded_by": "hk_beer_crate_nb",
+ "reason": "Reference printed a brand-like English name (RIVERTON Brewing Co.); never generated in 3D, replaced by hk_beer_crate_nb."
+ }
+}
\ No newline at end of file
diff --git a/scenes/hk-dai-pai-dong/scripts/bake_steam.py b/scenes/hk-dai-pai-dong/scripts/bake_steam.py
new file mode 100644
index 0000000..8889676
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/bake_steam.py
@@ -0,0 +1,33 @@
+"""Bake the Mantaflow steam domains of scenes/tokyo-ramen-shop/ramen.blend (CPU) and save the .blend.
+
+blender -b scenes/tokyo-ramen-shop/ramen.blend --python scenes/tokyo-ramen-shop/scripts/bake_steam.py -- [--res-scale 1.0] [--end 150] [--only steam_bowl]
+"""
+import os
+import shutil
+import sys
+import time
+
+import bpy
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+scale = float(argv[argv.index("--res-scale") + 1]) if "--res-scale" in argv else 1.0
+end = int(argv[argv.index("--end") + 1]) if "--end" in argv else None
+only = argv[argv.index("--only") + 1].split(",") if "--only" in argv else None
+
+for o in bpy.data.objects:
+ mod = next((m for m in o.modifiers if m.type == "FLUID" and m.fluid_type == "DOMAIN"), None)
+ if not mod or (only and o.name not in only):
+ continue
+ ds = mod.domain_settings
+ if scale != 1.0:
+ ds.resolution_max = max(24, int(ds.resolution_max * scale))
+ if end is not None:
+ ds.cache_frame_end = end
+ # free_all runs as an async job that would delete the new cache after the bake, so clear the folder directly.
+ shutil.rmtree(bpy.path.abspath(ds.cache_directory), ignore_errors=True)
+ t0 = time.time()
+ with bpy.context.temp_override(object=o, active_object=o, selected_objects=[o]):
+ r = bpy.ops.fluid.bake_all()
+ print(f"BAKE {o.name} res {ds.resolution_max} frames {ds.cache_frame_start}..{ds.cache_frame_end} {r} in {time.time() - t0:.0f}s", flush=True)
+bpy.ops.wm.save_mainfile()
+print("SAVED", bpy.data.filepath)
diff --git a/scenes/hk-dai-pai-dong/scripts/blend.sh b/scenes/hk-dai-pai-dong/scripts/blend.sh
new file mode 100644
index 0000000..7ba629c
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/blend.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+# Every Blender run for this scene goes through here: shared GPU queue, GPU prefs first.
+# bash scenes/hk-dai-pai-dong/scripts/blend.sh [file.blend] --python script.py -- args...
+# bash scenes/hk-dai-pai-dong/scripts/blend.sh build -- --stages shell --preview street --clay
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+S="$ANYSCENE_ROOT/scenes/hk-dai-pai-dong/scripts"
+if [ "$1" = "build" ]; then
+ shift
+ exec bash pipeline/gpu_run.sh "$BLENDER" -b --factory-startup --python "$S/gpu_prefs.py" --python "$S/build.py" "$@"
+fi
+F="$1"; shift
+exec bash pipeline/gpu_run.sh "$BLENDER" -b "$F" --python "$S/gpu_prefs.py" "$@"
diff --git a/scenes/hk-dai-pai-dong/scripts/bts.py b/scenes/hk-dai-pai-dong/scripts/bts.py
new file mode 100644
index 0000000..67bb5b4
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/bts.py
@@ -0,0 +1,335 @@
+"""Behind-the-scenes dollhouse clips (breakdown/SPEC.md) for an open street stall, from a copy of hk.blend (never saved).
+
+blender -b scenes/hk-dai-pai-dong/hk.blend --python .../gpu_prefs.py --python .../bts.py -- <clip> [--pass clay|plain|full]
+ [--frames a-b] [--samples n] [--out dir] [--still f]
+clip: a_layout | b_props | c_materials | d_lighting
+
+"Dollhouse" for an open stall: a high 120-degree orbit around the stall and the street with the awning tarp hidden,
+on the street side of the stall (the tenement wall behind the kitchen is the backdrop). The far-side buildings and
+everything over the far pavement would sit between the camera and the stall, so they are hidden for the whole orbit.
+"""
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+CLIP = argv[0]
+
+
+def opt(k, d=None):
+ return argv[argv.index(k) + 1] if k in argv else d
+
+
+PASS = opt("--pass", {"a_layout": "clay", "b_props": "clay", "c_materials": "full", "d_lighting": "night"}[CLIP])
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+OUT = os.path.abspath(opt("--out", os.path.join(ROOT, "breakdown", "hk-dai-pai-dong", "clips", CLIP)))
+CENTER = Vector((-0.4, 2.6, 0.6))
+FRAMES = {"a_layout": 144, "b_props": 240, "c_materials": 144, "d_lighting": 240}
+N = FRAMES[CLIP]
+SPAN = {"a_layout": (-62, -32), "b_props": (-32, -2), "c_materials": (-2, 28), "d_lighting": (28, 58)}[CLIP]
+DIST, ELEV, LENS = 15.5, math.radians(38), 30
+
+sc = bpy.context.scene
+sc.animation_data_clear()
+sc.view_settings.exposure = 0.0
+sc.frame_start, sc.frame_end = 1, N
+sc.render.fps = 24
+sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = 1920, 1080, 100
+sc.render.use_compositing = False # no grade, no lens fx (spec)
+sc.render.use_motion_blur = False
+sc.render.image_settings.file_format = "PNG"
+sc.render.image_settings.color_depth = "8"
+sc.render.film_transparent = False
+
+objs = list(bpy.data.objects)
+
+
+def coll_objs(*names):
+ out = set()
+ for n in names:
+ c = bpy.data.collections.get(n)
+ if c:
+ out |= set(c.all_objects)
+ return out
+
+
+def bbox(o):
+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]
+ return (Vector([min(p[i] for p in pts) for i in range(3)]), Vector([max(p[i] for p in pts) for i in range(3)]))
+
+
+def hide(os_):
+ for o in os_:
+ o.hide_render = True
+ o.hide_viewport = True
+
+
+LIGHTS = {o for o in objs if o.type == "LIGHT"}
+CAMS = {o for o in objs if o.type == "CAMERA"}
+VOLUMES = {o for o in objs if o.name.startswith(("haze", "steam_", "drizzle", "awning_drips", "wok_flame"))}
+SHELL = coll_objs("shell", "street", "stall") - VOLUMES
+SIGNS = coll_objs("signs")
+DETAIL = coll_objs("street_detail")
+DECALS = {o for o in objs if o.get("decal") or o.name.startswith(("menu_strips", "stall_sign", "fascia_text"))}
+AWNING = {o for o in objs if o.name.startswith(("awning_tarp", "awn_rafter"))}
+FAR = {o for o in objs if o.type in ("MESH", "CURVE", "FONT") and o.parent is None and bbox(o)[0].x > 6.9}
+CABLES = {o for o in objs if o.name.startswith("cable_x")}
+SKY = {o for o in objs if o.name.startswith(("skyline_card", "harbour_water"))}
+hide(AWNING | FAR | CABLES)
+lamp = bpy.data.objects.get("street_lamp")
+if lamp:
+ hide([lamp])
+
+
+def angle_at(f):
+ t = (f - 1) / (N - 1)
+ a0, a1 = SPAN
+ v = 1 / 0.875
+ if CLIP == "a_layout": # ease in only
+ u = v * t * t / 0.5 if t < 0.25 else v * (0.125 + (t - 0.25))
+ elif CLIP == "d_lighting": # ease out only
+ s = 1 - t
+ u = 1 - (v * s * s / 0.5 if s < 0.25 else v * (0.125 + (s - 0.25)))
+ else:
+ u = t
+ return math.radians(a0 + (a1 - a0) * u)
+
+
+cd = bpy.data.cameras.new("bts_cam")
+cd.lens = LENS
+cd.sensor_width = 36
+cd.clip_start = 0.1
+cd.clip_end = 400
+cd.dof.use_dof = False
+cd.shift_y = -0.06 # bottom 140 px stays clear for captions
+cam = bpy.data.objects.new("bts_cam", cd)
+sc.collection.objects.link(cam)
+sc.camera = cam
+for f in range(1, N + 1):
+ a = angle_at(f)
+ pos = CENTER + Vector((math.cos(a) * math.cos(ELEV), math.sin(a) * math.cos(ELEV), math.sin(ELEV))) * DIST
+ cam.location = pos
+ cam.rotation_euler = (CENTER - pos).to_track_quat("-Z", "Y").to_euler()
+ cam.keyframe_insert("location", frame=f)
+ cam.keyframe_insert("rotation_euler", frame=f)
+
+
+def eevee():
+ sc.render.engine = "BLENDER_EEVEE"
+ ee = sc.eevee
+ for attr, v in (("taa_render_samples", 32), ("use_shadows", True), ("use_raytracing", True), ("use_fast_gi", True)):
+ if hasattr(ee, attr):
+ setattr(ee, attr, v)
+
+
+def studio_world(color, strength):
+ nt = sc.world.node_tree
+ bg = nt.nodes["Background"]
+ for l in list(bg.inputs["Color"].links):
+ nt.links.remove(l)
+ bg.inputs["Color"].default_value = (*color, 1)
+ bg.inputs["Strength"].default_value = strength
+
+
+def add_sun(energy, rot=(50, 0, 30), size=8):
+ ld = bpy.data.lights.new("bts_sun", "SUN")
+ ld.energy = energy
+ ld.angle = math.radians(size)
+ so = bpy.data.objects.new("bts_sun", ld)
+ sc.collection.objects.link(so)
+ so.rotation_euler = [math.radians(v) for v in rot]
+ return so
+
+
+def clay():
+ m = bpy.data.materials.new("BTS_CLAY")
+ m.use_nodes = True
+ b = m.node_tree.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.62, 0.62, 0.6, 1)
+ b.inputs["Roughness"].default_value = 0.65
+ bpy.context.view_layer.material_override = m
+ hide(LIGHTS | VOLUMES | DECALS | SKY)
+ studio_world((0.7, 0.72, 0.76), 0.45)
+ add_sun(4.5, rot=(48, 0, 120))
+ sc.view_settings.exposure = -0.7 # the scene carries +0.4 EV for the night look: clay washed out without this
+ eevee()
+
+
+def neutral():
+ hide(LIGHTS | VOLUMES | SKY)
+ studio_world((0.8, 0.8, 0.8), 1.1)
+ add_sun(2.5, rot=(50, 0, 140))
+ eevee()
+ # Emissive signage would blow out under flat light: keep only its albedo.
+ for m in bpy.data.materials:
+ if m.node_tree:
+ for n in m.node_tree.nodes:
+ if n.type == "BSDF_PRINCIPLED" and not n.inputs["Emission Strength"].is_linked:
+ n.inputs["Emission Strength"].default_value = min(n.inputs["Emission Strength"].default_value, 0.6)
+ if PASS == "plain":
+ hide(DECALS | {o for o in objs if o.name.startswith(("poster_", "menu_strips"))})
+ for o in objs:
+ o.color = (1, 1, 1, 1) # per-instance grime tint off
+
+
+def clip_a():
+ """The layout: ground, facades, stall frame and shelves; pieces rise into place over the first 2 s."""
+ keep = (SHELL | CAMS) - AWNING - FAR
+ hide([o for o in objs if o not in keep])
+ pieces = [o for o in keep if o.parent is None and o.type in ("MESH", "CURVE", "FONT")
+ and not o.name.startswith(("pavement", "road", "kerb", "harbour", "skyline", "line_", "drain_"))]
+ pieces.sort(key=lambda o: (bbox(o)[0].z, -bbox(o)[0].x))
+ for i, o in enumerate(pieces):
+ s = 4 + int(36 * i / max(1, len(pieces) - 1))
+ z = o.location.z
+ o.location.z = z - 3.5
+ o.keyframe_insert("location", index=2, frame=1)
+ o.keyframe_insert("location", index=2, frame=s)
+ o.location.z = z
+ o.keyframe_insert("location", index=2, frame=s + 10)
+
+
+def clip_b():
+ """Props pop in: furniture, then big props, then clutter (each scales up with a small overshoot)."""
+ hide(SIGNS | DETAIL)
+ props = [o for o in objs if o.parent is None and o.get("placed") and not o.hide_render]
+ def vol(o):
+ lo, hi = bbox(o)
+ return (hi - lo).x * (hi - lo).y * (hi - lo).z
+ props.sort(key=lambda o: (0 if "furniture" in o.users_collection[0].name else 1, -vol(o)))
+ n = len(props)
+ for i, o in enumerate(props):
+ f = 8 + int(188 * (i / max(1, n - 1)) ** 1.4)
+ s = o.scale.copy()
+ o.scale = (0, 0, 0)
+ o.keyframe_insert("scale", frame=1)
+ o.keyframe_insert("scale", frame=f)
+ o.scale = s * 1.12
+ o.keyframe_insert("scale", frame=f + 4)
+ o.scale = s
+ o.keyframe_insert("scale", frame=f + 6)
+ print("BTS props animated", n, flush=True)
+
+
+def _mul_node(nt, sock, key_frames):
+ src = sock.links[0].from_socket if sock.is_linked else None
+ m = nt.nodes.new("ShaderNodeMath")
+ m.operation = "MULTIPLY"
+ if src is not None:
+ nt.links.new(src, m.inputs[0])
+ else:
+ m.inputs[0].default_value = sock.default_value if not hasattr(sock.default_value, "__len__") else 1.0
+ nt.links.new(m.outputs[0], sock)
+ for f, v in key_frames:
+ m.inputs[1].default_value = v
+ m.inputs[1].keyframe_insert("default_value", frame=f)
+ return m
+
+
+def ramp(f0, length=8):
+ return [(1, 0.0), (f0, 0.0), (f0 + length, 1.0)]
+
+
+def clip_d():
+ """Textured scene in the dark: bulbs, wok fire, shade, fluorescent; then neon/lightboxes; street; fills;
+ then steam, haze and drizzle fade in. Lights carry ["order"]/["cat"] from lights.py."""
+ sc.render.engine = "CYCLES"
+ sc.cycles.samples = int(opt("--samples", 16))
+ sc.cycles.use_denoising = True
+ sc.cycles.denoiser = "OPTIX"
+ sc.cycles.use_adaptive_sampling = True
+ sc.render.use_persistent_data = True
+ sc.view_settings.exposure = 0.6 # dollhouse distance: lift the night look a little
+ sc.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.15
+ cat_t = {"practical": (10, 100), "signage": (104, 138), "street": (140, 150), "fill": (154, 160)}
+ by_cat = {}
+ for o in sorted(LIGHTS, key=lambda o: o.get("order", 999)):
+ if o.name.startswith("bts_"):
+ continue
+ by_cat.setdefault(o.get("cat", "fill"), []).append(o)
+ when = {}
+ for cat, lst in by_cat.items():
+ a, b = cat_t.get(cat, (156, 160))
+ for i, o in enumerate(lst):
+ when[o.name] = a + int((b - a) * i / max(1, len(lst) - 1))
+ for o in LIGHTS:
+ if o.name.startswith("bts_"):
+ continue
+ f0 = when.get(o.name, 158)
+ if o.data.animation_data: # flicker drivers would override the keys
+ o.data.animation_data_clear()
+ e = o.data.energy
+ for f, v in ramp(f0, 10):
+ o.data.energy = e * v
+ o.data.keyframe_insert("energy", frame=f)
+ # Emissive materials come on with their category: bulbs/flames with the practicals, neon with the signage.
+ def mat_time(name):
+ if name.startswith(("bulb_glow", "fluoro_glow")):
+ return 14
+ if name.startswith(("neon_", "lightbox_")):
+ return 108
+ if name.startswith(("bldg_", "facemat")) or "facemat" in name:
+ return 146
+ if name == "skyline":
+ return 150
+ return 120
+ done = set()
+ for m in bpy.data.materials:
+ if not m.node_tree or m.name in done:
+ continue
+ for n in m.node_tree.nodes:
+ if n.type == "BSDF_PRINCIPLED":
+ s = n.inputs["Emission Strength"]
+ if s.is_linked or s.default_value > 0:
+ _mul_node(m.node_tree, s, ramp(mat_time(m.name), 10))
+ done.add(m.name)
+ elif n.type == "EMISSION":
+ _mul_node(m.node_tree, n.inputs["Strength"], ramp(mat_time(m.name), 10))
+ done.add(m.name)
+ # Flame volumes come on with the first practicals; steam, haze and drizzle last.
+ vol_time = {"flame_vol": (30, "Emission Strength", 8), "steam_wok": (166, "Density", 24), "steam_pot": (172, "Density", 24),
+ "street_haze": (178, "Density", 26)}
+ for m in bpy.data.materials:
+ if m.name in vol_time and m.node_tree:
+ f0, sock, ln = vol_time[m.name]
+ for n in m.node_tree.nodes:
+ if n.type == "PRINCIPLED_VOLUME":
+ _mul_node(m.node_tree, n.inputs[sock], ramp(f0, ln))
+ rain = bpy.data.materials.get("drizzle")
+ if rain:
+ b = next(n for n in rain.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
+ _mul_node(rain.node_tree, b.inputs["Alpha"], ramp(190, 24))
+ _mul_node(rain.node_tree, b.inputs["Emission Strength"], ramp(190, 24))
+ print("BTS lights", len(LIGHTS), "emissive mats", len(done), flush=True)
+
+
+if CLIP == "a_layout":
+ clay()
+ clip_a()
+elif CLIP == "b_props":
+ clay()
+ clip_b()
+elif CLIP == "c_materials":
+ if PASS == "clay":
+ clay()
+ hide(SIGNS | DETAIL)
+ else:
+ neutral()
+elif CLIP == "d_lighting":
+ clip_d()
+
+a, b = (int(x) for x in opt("--frames", f"1-{N}").split("-"))
+sc.frame_start, sc.frame_end = a, b
+os.makedirs(OUT, exist_ok=True)
+sc.render.filepath = os.path.join(OUT, "")
+if "--still" in argv:
+ f = int(opt("--still"))
+ sc.frame_set(f)
+ sc.render.filepath = os.path.join(OUT, f"still_{f:04d}.png")
+ bpy.ops.render.render(write_still=True)
+else:
+ bpy.ops.render.render(animation=True)
+print("BTS rendered", CLIP, PASS, a, b, flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/bts_clay_redo.sh b/scenes/hk-dai-pai-dong/scripts/bts_clay_redo.sh
new file mode 100644
index 0000000..f856c1f
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/bts_clay_redo.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Re-render the clay passes (a_layout, b_props, c_clay) after the clay exposure fix, then re-encode all clips.
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+SC=scenes/hk-dai-pai-dong
+R=breakdown/hk-dai-pai-dong
+S=$ANYSCENE_ROOT/$SC/scripts
+run() { bash pipeline/gpu_run.sh "$BLENDER" -b "$1" --python $S/gpu_prefs.py --python $S/bts.py -- "${@:2}" 2>&1 | grep -E "BTS rendered|Error:|Traceback"; }
+rm -rf $R/clips/a_layout $R/clips/b_props $R/work/c_clay
+run $SC/hk.blend a_layout
+for r in 1-120 121-240; do run $SC/hk.blend b_props --frames $r; done
+run $SC/hk.blend c_materials --pass clay --frames 1-48 --out $ANYSCENE_ROOT/$R/work/c_clay
+bash $SC/scripts/bts_encode.sh
+echo CLAY_REDO_DONE
diff --git a/scenes/hk-dai-pai-dong/scripts/bts_encode.sh b/scenes/hk-dai-pai-dong/scripts/bts_encode.sh
new file mode 100644
index 0000000..f5b1145
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/bts_encode.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Encode the dollhouse clips (and composite c_materials) from rendered frames. No Blender.
+# bash scenes/hk-dai-pai-dong/scripts/bts_encode.sh
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+R=breakdown/hk-dai-pai-dong
+CL=$R/clips
+WK=$R/work
+mp4() { "$FF" -v error -y -framerate 24 -start_number 1 -i "$CL/$1/%04d.png" -c:v h264_nvenc -preset p7 -rc vbr -cq 16 -b:v 0 -pix_fmt yuv420p "$CL/$1.mp4" && echo "MP4 $1 $(ls $CL/$1 | wc -l) frames"; }
+rm -rf $CL/c_materials $WK/c_seg; mkdir -p $CL/c_materials $WK/c_seg
+"$FF" -v error -y -framerate 24 -start_number 1 -i $WK/c_clay/%04d.png -framerate 24 -start_number 1 -i $WK/c_plain/%04d.png \
+ -filter_complex "[0][1]xfade=transition=wiperight:duration=2:offset=0,format=rgb24" -frames:v 48 -start_number 1 $WK/c_seg/a%04d.png
+"$FF" -v error -y -framerate 24 -start_number 49 -i $WK/c_plain/%04d.png -framerate 24 -start_number 49 -i $WK/c_full/%04d.png \
+ -filter_complex "[0][1]xfade=transition=fade:duration=2:offset=0,format=rgb24" -frames:v 48 -start_number 1 $WK/c_seg/b%04d.png
+i=1
+for f in $WK/c_seg/a*.png $WK/c_seg/b*.png $(for n in $(seq 97 144); do printf "$WK/c_full/%04d.png " $n; done); do
+ cp "$f" $CL/c_materials/$(printf %04d $i).png; i=$((i+1))
+done
+for c in a_layout b_props c_materials d_lighting; do mp4 $c; done
diff --git a/scenes/hk-dai-pai-dong/scripts/build.py b/scenes/hk-dai-pai-dong/scripts/build.py
new file mode 100644
index 0000000..bcded73
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/build.py
@@ -0,0 +1,166 @@
+"""Build the dai pai dong scene from scratch and save hk.blend (the .blend is a build output).
+
+blender -b --factory-startup --python scenes/hk-dai-pai-dong/scripts/build.py -- [--stages shell,dress,validate,light,fx,post]
+ [--save] [--out hk.blend] [--preview street,wok,table,top] [--clay] [--samples 32] [--engine cycles|eevee] [--tag _x]
+Previews go to scenes/hk-dai-pai-dong/out/prev/<cam><tag>.png. Run through pipeline/gpu_run.sh, after gpu_prefs.py.
+"""
+import math
+import os
+import sys
+import time
+
+import bpy
+from mathutils import Vector
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import shell # noqa: E402
+from lib import SCENE_DIR, coll # noqa: E402
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+
+
+def arg(name, default=None):
+ return argv[argv.index(name) + 1] if name in argv else default
+
+
+STAGES = arg("--stages", "shell,dress,validate,grime,light,fx,post").split(",")
+PREVIEW = [p for p in arg("--preview", "").split(",") if p]
+TAG = arg("--tag", "")
+
+# Hero cameras: name -> (pos, aim, lens)
+CAMS = {
+ "street": ((4.6, -9.0, 1.6), (-2.2, 3.0, 1.9), 28),
+ "wok": ((-1.55, 3.7, 1.3), (-2.8, 2.95, 0.68), 28),
+ "table": ((0.45, -1.1, 1.1), (-2.4, 2.4, 0.9), 32),
+ "walk": ((3.2, -5.5, 1.62), (-2.4, 2.6, 1.3), 24),
+ "top": ((9.5, -9.0, 13.0), (-1.5, 2.8, 0.5), 24),
+ "flame": ((-2.05, 2.15, 0.95), (-2.92, 2.55, 0.62), 35),
+ "up": ((2.0, -4.0, 1.4), (-1.5, 6.0, 9.0), 20),
+}
+
+
+def reset():
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ # read_factory_settings also resets user prefs, so select the OptiX device again (else Cycles renders on the CPU).
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ prefs.compute_device_type = "OPTIX"
+ prefs.get_devices()
+ for d in prefs.devices:
+ d.use = d.type == "OPTIX"
+ sc.cycles.device = "GPU"
+ sc.cycles.samples = 48
+ sc.cycles.use_denoising = True
+ sc.cycles.max_bounces = 8
+ sc.cycles.glossy_bounces = 4
+ sc.cycles.transmission_bounces = 6
+ sc.cycles.volume_bounces = 1
+ sc.cycles.caustics_reflective = False
+ sc.cycles.caustics_refractive = False
+ sc.cycles.blur_glossy = 1.0
+ sc.render.resolution_x, sc.render.resolution_y = 1920, 804
+ sc.render.resolution_percentage = 100
+ sc.render.fps = 24
+ sc.frame_start, sc.frame_end = 1, 240
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "AgX - Medium High Contrast"
+ sc.view_settings.exposure = 0.0
+ sc.render.use_motion_blur = True
+ sc.render.motion_blur_shutter = 0.5
+ sc.unit_settings.system = "METRIC"
+ return sc
+
+
+def add_camera(name, pos, aim, lens, c):
+ d = bpy.data.cameras.new(name)
+ d.lens = lens
+ d.sensor_width = 24.89
+ d.clip_start = 0.05
+ d.clip_end = 600
+ o = bpy.data.objects.new(name, d)
+ c.objects.link(o)
+ o.location = pos
+ o.rotation_euler = (Vector(aim) - Vector(pos)).to_track_quat("-Z", "Y").to_euler()
+ return o
+
+
+def clay_override():
+ m = bpy.data.materials.new("clay")
+ m.use_nodes = True
+ b = m.node_tree.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.6, 0.6, 0.6, 1)
+ b.inputs["Roughness"].default_value = 0.7
+ bpy.context.view_layer.material_override = m
+
+
+def preview(names, clay, samples, engine):
+ sc = bpy.context.scene
+ od = os.path.join(SCENE_DIR, "out", "prev")
+ os.makedirs(od, exist_ok=True)
+ if clay:
+ clay_override()
+ # Clay under a soft sky so the layout reads (night lighting hides it).
+ w = sc.world.node_tree.nodes["Background"]
+ for l in list(w.inputs["Color"].links):
+ sc.world.node_tree.links.remove(l)
+ w.inputs["Color"].default_value = (0.55, 0.6, 0.7, 1)
+ w.inputs["Strength"].default_value = 0.6
+ sun = bpy.data.lights.new("clay_sun", "SUN")
+ sun.energy = 2.5
+ so = bpy.data.objects.new("clay_sun", sun)
+ sc.collection.objects.link(so)
+ so.rotation_euler = (math.radians(40), math.radians(15), math.radians(-35))
+ for o in sc.objects: # volumes and rain read as fog in clay
+ if o.name.startswith(("steam", "haze", "rain", "drizzle")):
+ o.hide_render = True
+ sc.cycles.samples = samples
+ sc.render.resolution_percentage = 50
+ sc.render.use_motion_blur = False
+ if engine == "eevee":
+ sc.render.engine = "BLENDER_EEVEE"
+ for n in names:
+ sc.camera = bpy.data.objects["cam_" + n]
+ sc.render.filepath = os.path.join(od, f"{n}{'_clay' if clay else ''}{TAG}.png")
+ t0 = time.time()
+ bpy.ops.render.render(write_still=True)
+ print(f"PREVIEW {n} {time.time() - t0:.1f}s -> {sc.render.filepath}", flush=True)
+
+
+def main():
+ t0 = time.time()
+ sc = reset()
+ shell.build()
+ cams = coll("cameras")
+ for n, (p, a, l) in CAMS.items():
+ add_camera("cam_" + n, p, a, l, cams)
+ sc.camera = bpy.data.objects["cam_street"]
+ if "dress" in STAGES:
+ import dress
+ dress.run()
+ if "validate" in STAGES:
+ import validate
+ validate.resolve(dress.PLACED)
+ validate.run(dress.PLACED, os.path.join(SCENE_DIR, "out", "validate.txt"))
+ if "grime" in STAGES:
+ import grime
+ grime.build()
+ if "light" in STAGES:
+ import lights
+ lights.build()
+ if "fx" in STAGES:
+ import fx
+ fx.build()
+ if "post" in STAGES:
+ import post
+ post.build()
+ print(f"BUILD done in {time.time() - t0:.0f}s", flush=True)
+ if "--save" in argv:
+ out = os.path.join(SCENE_DIR, arg("--out", "hk.blend"))
+ bpy.ops.wm.save_as_mainfile(filepath=out, compress=True)
+ print("SAVED", out, flush=True)
+ if PREVIEW:
+ preview(PREVIEW, "--clay" in argv, int(arg("--samples", 32)), arg("--engine", "cycles"))
+
+
+main()
diff --git a/scenes/hk-dai-pai-dong/scripts/check_path.py b/scenes/hk-dai-pai-dong/scripts/check_path.py
new file mode 100644
index 0000000..0bf3820
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/check_path.py
@@ -0,0 +1,43 @@
+"""Camera-path clearance check for camrig shots: every frame's camera position vs every render-visible mesh (BVH nearest).
+blender -b scenes/hk-dai-pai-dong/hk.blend --python scenes/hk-dai-pai-dong/scripts/check_path.py -- <shots.json> <name,name> [min=0.25]"""
+import json, os, sys
+import bpy
+from mathutils import Vector
+from mathutils.bvhtree import BVHTree
+sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "camera"))
+import camrig # noqa: E402
+a = sys.argv[sys.argv.index("--") + 1:]
+cfg = json.load(open(a[0]))
+names = a[1].split(",")
+lim = float(a[2]) if len(a) > 2 else 0.25
+sc = bpy.context.scene
+dg = bpy.context.evaluated_depsgraph_get()
+skip = ("drizzle", "drip", "awning_drips", "haze", "steam_", "wok_flame", "skyline", "CR_", "clay", "harbour")
+trees = []
+for o in sc.objects:
+ if o.type not in ("MESH", "CURVE") or not o.visible_get() or o.hide_render or o.name.startswith(skip):
+ continue
+ eo = o.evaluated_get(dg)
+ me = eo.to_mesh()
+ if me is None or not len(me.polygons):
+ continue
+ me.transform(o.matrix_world)
+ trees.append((o.name, BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])))
+ eo.to_mesh_clear()
+shots = [camrig.merged(cfg.get("defaults", {}), s) for s in cfg["shots"]]
+for i, s in enumerate(shots):
+ if s["name"] not in names:
+ continue
+ cam = camrig.build(s, seed=i * 7)
+ worst = (9, None, 0)
+ bad = 0
+ for f in range(1, int(s["frames"]) + 1):
+ sc.frame_set(f)
+ p = cam.matrix_world.translation.copy()
+ for n, t in trees:
+ loc, nrm, idx, d = t.find_nearest(p, lim * 2)
+ if loc is not None and d < worst[0]:
+ worst = (d, n, f)
+ if loc is not None and d < lim:
+ bad += 1
+ print(f"PATH {s['name']}: min clearance {worst[0]:.2f} m to {worst[1]} at frame {worst[2]}; {bad} frame-object hits under {lim} m")
diff --git a/scenes/hk-dai-pai-dong/scripts/compare.py b/scenes/hk-dai-pai-dong/scripts/compare.py
new file mode 100644
index 0000000..4853f3e
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/compare.py
@@ -0,0 +1,205 @@
+"""Dai pai dong copy (from the ramen scene) of pipeline/render_compare.py: only tripo-h31 + meshy, filtered by env PROPS, 640 px / 40 spp.
+
+blender -b --factory-startup --python pipeline/render_compare.py -- assets/gen out/compare
+For every assets/gen/<model>/<prop>/model.glb writes out/compare/<model>/<prop>_{beauty,clay}.png + stats.json.
+"""
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+ROOT, OUT = map(os.path.abspath, sys.argv[sys.argv.index("--") + 1:][:2])
+HDRI = os.path.join(bpy.utils.system_resource("DATAFILES"), "studiolights", "world", "studio.exr") # the path= form returns "" in 5.0.1
+RES = 640
+PROBE = bool(os.environ.get("PROBE"))
+# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.
+_yaw_path = os.path.join(OUT, "yaw.json")
+YAW = json.load(open(_yaw_path)) if os.path.exists(_yaw_path) else {}
+
+
+def reset():
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ prefs.compute_device_type = "OPTIX"
+ prefs.get_devices()
+ for d in prefs.devices:
+ d.use = d.type == "OPTIX"
+ sc.cycles.device = "GPU"
+ sc.cycles.samples = 40
+ sc.cycles.use_denoising = True
+ sc.render.resolution_x = sc.render.resolution_y = RES
+ sc.render.film_transparent = False
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "AgX - Medium High Contrast"
+ world = bpy.data.worlds.new("w")
+ sc.world = world
+ world.use_nodes = True
+ nt = world.node_tree
+ env = nt.nodes.new("ShaderNodeTexEnvironment")
+ env.image = bpy.data.images.load(HDRI)
+ bg = nt.nodes["Background"]
+ bg.inputs["Strength"].default_value = 0.6
+ nt.links.new(env.outputs["Color"], bg.inputs["Color"])
+ return sc
+
+
+def add_light(name, loc, energy, size, color=(1, 1, 1)):
+ d = bpy.data.lights.new(name, "AREA")
+ d.energy, d.size, d.color = energy, size, color
+ o = bpy.data.objects.new(name, d)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = loc
+ o.rotation_euler = (-Vector(loc)).to_track_quat("-Z", "Y").to_euler() # area lights shine along -Z
+
+
+def import_glb(path):
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=path)
+ meshes = [o for o in bpy.data.objects if o not in before and o.type == "MESH"]
+ return meshes
+
+
+def bounds(objs):
+ pts = [o.matrix_world @ Vector(c) for o in objs for c in o.bound_box]
+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
+ return lo, hi
+
+
+def stats(objs, real_size):
+ tris = verts = 0
+ images = {}
+ for o in objs:
+ me = o.data
+ me.calc_loop_triangles()
+ tris += len(me.loop_triangles)
+ verts += len(me.vertices)
+ for slot in o.material_slots:
+ if slot.material and slot.material.use_nodes:
+ for n in slot.material.node_tree.nodes:
+ if n.type == "TEX_IMAGE" and n.image:
+ out = [l.to_socket.name for l in n.outputs["Color"].links]
+ images[n.image.name] = {"size": list(n.image.size), "feeds": out}
+ return {"tris": tris, "verts": verts, "objects": len(objs), "images": images, "size_m": [round(v, 3) for v in real_size]}
+
+
+def clay_wire(objs):
+ m = bpy.data.materials.new("clay")
+ m.use_nodes = True
+ nt = m.node_tree
+ bsdf = nt.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (0.55, 0.55, 0.55, 1)
+ bsdf.inputs["Roughness"].default_value = 0.6
+ wire = nt.nodes.new("ShaderNodeWireframe")
+ wire.use_pixel_size = True
+ wire.inputs["Size"].default_value = 0.35
+ mix = nt.nodes.new("ShaderNodeMix")
+ mix.data_type = "RGBA"
+ mix.inputs["A"].default_value = (0.55, 0.55, 0.55, 1)
+ mix.inputs["B"].default_value = (0.08, 0.12, 0.2, 1)
+ nt.links.new(wire.outputs["Fac"], mix.inputs["Factor"])
+ nt.links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])
+ for o in objs:
+ o.data.materials.clear()
+ o.data.materials.append(m)
+
+
+def render_one(glb, out_prefix):
+ sc = reset()
+ objs = import_glb(glb)
+ lo, hi = bounds(objs)
+ real = hi - lo
+ # Normalize: centre on origin, rest on the floor, largest dimension 1 m (framing only; real size goes in stats).
+ s = 1.0 / max(real)
+ root = bpy.data.objects.new("root", None)
+ sc.collection.objects.link(root)
+ for o in [o for o in bpy.data.objects if o.parent is None and o is not root]:
+ o.parent = root
+ c = (lo + hi) / 2
+ root.scale = (s, s, s)
+ root.location = (-c.x * s, -c.y * s, -lo.z * s)
+ bpy.context.view_layer.update()
+ lo, hi = bounds(objs)
+ centre = (lo + hi) / 2
+ radius = (hi - lo).length / 2
+
+ # Shadow catcher-ish floor.
+ bpy.ops.mesh.primitive_plane_add(size=20)
+ floor = bpy.context.object
+ fm = bpy.data.materials.new("floor")
+ fm.use_nodes = True
+ fm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.32, 0.32, 0.33, 1)
+ fm.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.8
+ floor.data.materials.append(fm)
+
+ add_light("key", (2.2, -2.6, 3.0), 260, 1.6)
+ add_light("fill", (-3.0, -1.5, 1.6), 70, 2.5, (0.85, 0.9, 1.0))
+ add_light("rim", (-1.0, 3.0, 2.5), 160, 1.2)
+
+ cam_d = bpy.data.cameras.new("cam")
+ cam_d.lens = 70
+ cam = bpy.data.objects.new("cam", cam_d)
+ sc.collection.objects.link(cam)
+ sc.camera = cam
+ fov = cam_d.angle
+ dist = radius / math.sin(fov / 2) * 1.02
+
+ def shoot(az_deg, el_deg, path):
+ az, el = math.radians(az_deg), math.radians(el_deg)
+ d = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))
+ cam.location = centre + d * dist
+ cam.rotation_euler = (centre - cam.location).to_track_quat("-Z", "Y").to_euler()
+ sc.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+
+ st = stats(objs, real)
+ if PROBE: # four cardinal views to find which way a generator's "front" faces
+ sc.render.resolution_x = sc.render.resolution_y = 360
+ sc.cycles.samples = 16
+ for az in (0, 90, 180, 270):
+ shoot(az, 15, f"{out_prefix}_az{az:03d}.png")
+ return st
+ yaw = YAW.get(os.path.basename(os.path.dirname(out_prefix)), 0)
+ shoot(yaw - 30, 18, out_prefix + "_beauty.png")
+ shoot(yaw + 150, 22, out_prefix + "_back.png")
+ clay_wire(objs)
+ shoot(yaw - 30, 18, out_prefix + "_clay.png")
+ return st
+
+
+def main():
+ allstats = {}
+ keep = set(os.environ["PROPS"].split(",")) if os.environ.get("PROPS") else None
+ for model in [m for m in sorted(os.listdir(ROOT)) if m in ("tripo-h31", "meshy")]:
+ for prop in sorted(os.listdir(os.path.join(ROOT, model))):
+ if keep and prop not in keep:
+ continue
+ glb = os.path.join(ROOT, model, prop, "model.glb")
+ if not os.path.exists(glb):
+ continue
+ od = os.path.join(OUT, model)
+ os.makedirs(od, exist_ok=True)
+ prefix = os.path.join(od, prop)
+ done = prefix + ("_az270.png" if PROBE else "_clay.png")
+ if os.path.exists(done) and os.path.getmtime(done) > os.path.getmtime(glb):
+ print("skip", model, prop)
+ continue
+ print("render", model, prop, flush=True)
+ try:
+ allstats.setdefault(model, {})[prop] = render_one(glb, prefix)
+ except Exception as e: # keep going; a broken GLB is itself a result
+ allstats.setdefault(model, {})[prop] = {"error": repr(e)}
+ print("FAILED", model, prop, e, flush=True)
+ sp = os.path.join(OUT, "stats.json")
+ old = json.load(open(sp)) if os.path.exists(sp) else {}
+ for m, d in allstats.items():
+ old.setdefault(m, {}).update(d)
+ json.dump(old, open(sp, "w"), indent=2)
+
+
+main()
diff --git a/scenes/hk-dai-pai-dong/scripts/compare.sh b/scenes/hk-dai-pai-dong/scripts/compare.sh
new file mode 100644
index 0000000..f1ae0d2
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/compare.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Same-light compare renders (ref | H3.1 | Meshy, front/back/clay) for props whose two GLBs both exist, in GPU-queue
+# chunks of 12 props (each chunk ~5 min), then one review sheet per 8 props in compare/review_<n>.png.
+# bash scenes/hk-dai-pai-dong/scripts/compare.sh [id,id,...] (default: every hk_ prop with both GLBs)
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+SC=scenes/hk-dai-pai-dong
+C=$SC/compare
+mkdir -p $C
+if [ -n "$1" ]; then IFS=, read -ra P <<< "$1"; else
+ P=(); for d in assets/gen/meshy/hk_*; do id=$(basename $d)
+ [ -f assets/gen/meshy/$id/model.glb ] && [ -f assets/gen/tripo-h31/$id/model.glb ] && P+=($id); done
+fi
+echo "compare ${#P[@]} props"
+for ((i = 0; i < ${#P[@]}; i += 12)); do
+ chunk=$(IFS=,; echo "${P[*]:$i:12}")
+ PROPS=$chunk bash pipeline/gpu_run.sh "$BLENDER" -b --factory-startup --python $SC/scripts/compare.py -- "$ANYSCENE_ROOT/assets/gen" "$ANYSCENE_ROOT/$C" 2>&1 | grep -E "^render|FAILED"
+done
+args=()
+n=0
+for id in "${P[@]}"; do
+ args+=("$id=refs/hk-dai-pai-dong/props/${id}_0.png|$C/tripo-h31/${id}_beauty.png|$C/meshy/${id}_beauty.png|$C/tripo-h31/${id}_back.png|$C/meshy/${id}_back.png|$C/tripo-h31/${id}_clay.png|$C/meshy/${id}_clay.png")
+ if [ ${#args[@]} -eq 8 ]; then
+ uv run --no-project --with pillow python -I $SC/scripts/sheet.py $C/review_$n.png 7 300 "${args[@]}" | tail -1; args=(); n=$((n + 1)); fi
+done
+[ ${#args[@]} -gt 0 ] && uv run --no-project --with pillow python -I $SC/scripts/sheet.py $C/review_$n.png 7 300 "${args[@]}" | tail -1
+echo COMPARED
diff --git a/scenes/hk-dai-pai-dong/scripts/dress.py b/scenes/hk-dai-pai-dong/scripts/dress.py
new file mode 100644
index 0000000..5e5d690
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/dress.py
@@ -0,0 +1,494 @@
+"""Dress the street with prepped props (scenes/hk-dai-pai-dong/props/<id>.blend). World coordinates.
+
+Passes big -> small: furniture (cart, range, tables, stools), heroes (woks, pots, teapot, car, lamp), mid props, clutter.
+place(): each prop rests on whatever is under its footprint (raycast drop from start_z, which must be BELOW anything
+overhead: the awning, hanging tools, shelves), or snaps its back to a wall, or hangs at a fixed bottom height.
+Facing: 0 = front toward -Y (the walk-in end), 90 = toward +X (the street), -90 = toward -X, 180 = toward +Y.
+Repeats share mesh data (linked duplicates) and get a per-instance ob.color tint.
+"""
+import json
+import math
+import os
+import random
+
+import bpy
+from mathutils import Vector
+
+import shell as S
+from lib import SCENE_DIR, coll
+
+LIB = os.path.join(SCENE_DIR, "props")
+_loaded = {}
+PLACED = [] # (obj, mode) for the validator
+rng = random.Random(23)
+PICKS = json.load(open(os.path.join(SCENE_DIR, "picks.json"), encoding="utf-8")) if os.path.exists(os.path.join(SCENE_DIR, "picks.json")) else {}
+# Branded originals: only their _nb regeneration may be placed (filled from picks.json "debranded_by").
+NB = {k: v["debranded_by"] for k, v in PICKS.items() if v.get("debranded_by")}
+
+
+def _load(pid):
+ if pid in _loaded:
+ return _loaded[pid]
+ path = os.path.join(LIB, pid + ".blend")
+ if not os.path.exists(path):
+ print("MISSING prop", pid)
+ _loaded[pid] = None
+ return None
+ with bpy.data.libraries.load(path, link=False) as (src, dst):
+ dst.objects = list(src.objects)
+ objs = [o for o in dst.objects if o]
+ root = next(o for o in objs if o.name.split(".")[0] == pid)
+ _loaded[pid] = (root, [o for o in objs if o is not root])
+ return _loaded[pid]
+
+
+def _instance(pid, c):
+ got = _load(pid)
+ if not got:
+ return None
+ root, kids = got
+ # The loaded root stays an unlinked template; every placement is a linked duplicate (shares mesh + materials),
+ # so removing a placement (unplace) never invalidates the cache.
+ o = root.copy()
+ c.objects.link(o)
+ for k in kids:
+ kk = k.copy()
+ c.objects.link(kk)
+ kk.parent = o
+ return o
+
+
+def bounds(o):
+ bpy.context.view_layer.update()
+ pts = [o.matrix_world @ Vector(cc) for cc in o.bound_box]
+ for ch in o.children:
+ pts += [ch.matrix_world @ Vector(cc) for cc in ch.bound_box]
+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
+ return lo, hi
+
+
+def _ray_down(dg, p, skip=()):
+ """Downward scene ray that passes through hanging things (no_support) and the given objects."""
+ for _ in range(64):
+ ok, loc, _n, _idx, hit, _m = bpy.context.scene.ray_cast(dg, p, Vector((0, 0, -1)))
+ if not ok:
+ return None, None
+ if hit.get("no_support") or hit in skip:
+ p = loc - Vector((0, 0, 1e-5)) # a 1 mm step skipped supports closer than that
+ continue
+ return loc.z, hit
+ return None, None
+
+
+def contacts(o, n=40, every=False):
+ """World-space contact candidates: the lowest vertices (feet, legs, base rings), at most n of them
+ (every=True: a spread of all vertices)."""
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ vs = []
+ for ob in [o, *o.children_recursive]:
+ if ob.type != "MESH":
+ continue
+ ev = ob.evaluated_get(dg)
+ me = ev.to_mesh()
+ vs += [ob.matrix_world @ v.co for v in me.vertices]
+ ev.to_mesh_clear()
+ if every:
+ return vs[:: max(1, len(vs) // n)]
+ zmin = min(v.z for v in vs)
+ band = max(0.015, 0.03 * (max(v.z for v in vs) - zmin))
+ feet = [v for v in vs if v.z <= zmin + band]
+ return feet[:: max(1, len(feet) // n)]
+
+
+def contact_gap(o, pts=None):
+ """Smallest drop from the contact points to whatever is below them: > 0 means the prop floats
+ (a footprint drop rests the bbox on the highest thing under it, which may not be under any foot)."""
+ dg = bpy.context.evaluated_depsgraph_get()
+ own = {o, *o.children_recursive}
+ gaps = []
+ for f in pts or contacts(o):
+ z, hit = _ray_down(dg, f + Vector((0, 0, 0.002)), own)
+ if z is not None:
+ gaps.append((f.z - z, hit.name))
+ return min(gaps) if gaps else (None, None)
+
+
+def _drop(o, start_z):
+ """Lower the object onto the highest surface under its footprint (5x5 grid of downward rays from start_z), then
+ settle it until its actual contact points touch something."""
+ lo, hi = bounds(o)
+ dg = bpy.context.evaluated_depsgraph_get()
+ own = {o, *o.children_recursive}
+ top = None
+ for i in range(5):
+ for j in range(5):
+ x = lo.x + (hi.x - lo.x) * (0.1 + 0.8 * i / 4)
+ y = lo.y + (hi.y - lo.y) * (0.1 + 0.8 * j / 4)
+ z, _hit = _ray_down(dg, Vector((x, y, start_z)), own)
+ if z is not None and (top is None or z > top):
+ top = z
+ if top is not None:
+ o.location.z += top - lo.z + 0.0005
+ settle(o)
+
+
+def settle(o):
+ """Move down by the smallest clearance (never up) of the feet and a spread of all vertices, so the first point to
+ touch stops it: by the feet alone, a plate over a table's raised rim sank into the rim."""
+ g, _on = contact_gap(o, contacts(o) + contacts(o, 400, every=True))
+ if g is not None and g > 0.002:
+ o.location.z -= g - 0.0005
+ bpy.context.view_layer.update()
+
+
+def _newspaper(c):
+ """Folded racing paper: a thin slab with the reference photo's printed page on top (both generators turned the
+ printed horses into 3D figurines)."""
+ from lib import m_image
+ ref = os.path.join(SCENE_DIR, "..", "..", "refs", "hk-dai-pai-dong", "props", "hk_newspaper_0.png")
+ w, d, t = 0.31, 0.4, 0.008
+ verts = [(-w / 2, -d / 2, 0), (w / 2, -d / 2, 0), (w / 2, d / 2, 0), (-w / 2, d / 2, 0),
+ (-w / 2, -d / 2, t), (w / 2, -d / 2, t), (w / 2, d / 2, t), (-w / 2, d / 2, t)]
+ faces = [(4, 5, 6, 7), (0, 3, 2, 1), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
+ me = bpy.data.meshes.new("newspaper_direct")
+ me.from_pydata(verts, [], faces)
+ uv = me.uv_layers.new(name="UVMap")
+ # top face gets the page (crop of the ref photo), the edges a sliver of paper
+ crop = [(0.08, 0.1), (0.9, 0.1), (0.9, 0.94), (0.08, 0.94)]
+ for li, poly in enumerate(me.polygons):
+ for k, l in enumerate(poly.loop_indices):
+ uv.data[l].uv = crop[k] if li == 0 else (0.5, 0.05)
+ me.materials.append(m_image("newspaper_page", os.path.abspath(ref), rough=0.8))
+ o = bpy.data.objects.new("hk_newspaper", me)
+ c.objects.link(o)
+ return o
+
+
+DIRECT = {"hk_newspaper": _newspaper}
+
+TINTS = [(1, 1, 1), (0.93, 0.9, 0.86), (1.0, 0.96, 0.9), (0.86, 0.86, 0.88), (0.97, 0.93, 0.92)]
+
+
+def place(pid, x, y, z=None, facing=0.0, jitter=0.0, against=None, gap=0.01, mode="rest", scale=1.0, start_z=1.5,
+ c=None, tint=None, name=None):
+ """mode: rest (drop onto support), hang (z = bottom height). against: 'x-','x+','y-','y+': push the prop's
+ back to that plane (x or y is the wall coordinate)."""
+ pid = NB.get(pid, pid)
+ c = c or coll("props")
+ if PICKS and pid in PICKS and PICKS[pid].get("model") in (None, "retired"):
+ if pid not in DIRECT:
+ return None
+ o = DIRECT[pid](c) # retired generated prop replaced by a direct-modelled one
+ else:
+ o = _instance(pid, c)
+ if o is None:
+ return None
+ if name:
+ o.name = name
+ o.rotation_mode = "XYZ" # glTF-imported props come in quaternion mode
+ o.rotation_euler = (0, 0, math.radians(facing + rng.uniform(-jitter, jitter)))
+ o.scale = (scale, scale, scale)
+ o.location = (x, y, 0 if z is None else z)
+ if against:
+ lo, hi = bounds(o)
+ if against == "x-":
+ o.location.x += (x + gap) - lo.x
+ elif against == "x+":
+ o.location.x += (x - gap) - hi.x
+ elif against == "y+":
+ o.location.y += (y - gap) - hi.y
+ elif against == "y-":
+ o.location.y += (y + gap) - lo.y
+ if mode == "rest":
+ _drop(o, start_z)
+ else:
+ o["no_support"] = True # hanging things (bag, cage, tool rail) are never something to rest on
+ o.color = (*(tint or rng.choice(TINTS)), 1)
+ o["placed"] = True
+ o["prop_id"] = pid
+ o["mode"] = mode
+ o["start_z"] = start_z
+ PLACED.append((o, mode))
+ return o
+
+
+def unplace(o):
+ PLACED[:] = [(q, m) for q, m in PLACED if q is not o]
+ for ch in list(o.children):
+ bpy.data.objects.remove(ch)
+ bpy.data.objects.remove(o)
+
+
+def top_of(o):
+ return bounds(o)[1].z
+
+
+# ---------------------------------------------------------------- layout data (also used by lights/fx/shots)
+
+TABLES = [ # id, x, y, kind
+ ("t1", -0.95, 0.25, "hk_table_round"),
+ ("t2", -0.95, 5.05, "hk_table_square"),
+ ("t3", 1.65, -0.35, "hk_table_round"),
+ ("t4", 1.75, 4.55, "hk_table_round"),
+ ("t5", 3.95, 2.45, "hk_table_round"),
+]
+LANE = ((-2.2, 1.35), (0.6, 3.75)) # (x0, y0), (x1, y1): kept clear for the walk-in (no stools)
+WOKS = [] # (x, y, z) of the burner wells, filled by furniture()
+
+
+def burner_wells(o):
+ """The two wok wells of the picked range: at 25% / 75% of its width, 45% of its depth from the back (read off a
+ top-down ortho render; a lowest-point search found the front gutter instead). Rim height = highest raycast hit in a 16 cm
+ ring around each well centre. Returns [(x, y, z_rim)]."""
+ lo, hi = bounds(o)
+ dg = bpy.context.evaluated_depsgraph_get()
+ wells = []
+ for fy in (0.247, 0.753):
+ cx, cy = lo.x + (hi.x - lo.x) * 0.45, lo.y + (hi.y - lo.y) * fy
+ zs = []
+ for k in range(16):
+ a = k * math.pi / 8
+ ok, loc, _n, _i, hit, _m = bpy.context.scene.ray_cast(dg, Vector((cx + 0.17 * math.cos(a), cy + 0.17 * math.sin(a), hi.z + 0.3)), Vector((0, 0, -1)))
+ if ok and hit is o:
+ zs.append(loc.z)
+ zs.sort()
+ wells.append((cx, cy, zs[len(zs) // 2] if zs else hi.z - 0.1))
+ return wells
+
+
+def seat_wok(o, well):
+ """A round-bottomed wok rests in the well ring: its bowl bottom (mean of the lowest vertices, not the bbox centre,
+ which a long handle drags ~20 cm sideways) goes over the well, 6 cm below the rim (validator: accepted clip)."""
+ bpy.context.view_layer.update()
+ mw = o.matrix_world
+ vs = [mw @ v.co for v in o.data.vertices]
+ zmin = min(v.z for v in vs)
+ low = [v for v in vs if v.z < zmin + 0.025]
+ bx = sum(v.x for v in low) / len(low)
+ by = sum(v.y for v in low) / len(low)
+ o.location.x += well[0] - bx
+ o.location.y += well[1] - by
+ o.location.z += (well[2] - 0.06) - zmin
+
+
+def _in_lane(x, y):
+ (x0, y0), (x1, y1) = LANE
+ return x0 < x < x1 and y0 < y < y1
+
+
+def furniture():
+ k = coll("props_furniture")
+ cart = place("hk_kitchen_cart", -3.55, 1.2, facing=90, against="x-", gap=0.02, c=k, tint=(1, 1, 1), name="kitchen_cart")
+ rng_ = place("hk_wok_range", -3.55, 3.18, facing=90, against="x-", gap=0.02, c=k, tint=(1, 1, 1), name="wok_range")
+ if rng_:
+ WOKS.extend(burner_wells(rng_))
+ print("burner wells", [tuple(round(v, 3) for v in w) for w in WOKS], flush=True)
+ for tid, x, y, kind in TABLES:
+ t = place(kind, x, y, facing=rng.uniform(0, 90), c=k, start_z=2.0, name=f"table_{tid}")
+ if not t:
+ continue
+ r = 0.66 if kind == "hk_table_round" else 0.6
+ n = 0
+ for a in (20, 110, 200, 290) if kind == "hk_table_round" else (0, 90, 180, 270):
+ a = math.radians(a + rng.uniform(-25, 25))
+ sx, sy = x + r * math.cos(a), y + r * math.sin(a)
+ if _in_lane(sx, sy):
+ continue
+ pid = "hk_stool_blue" if rng.random() < 0.12 else "hk_stool_red"
+ # drop from below the table top, measured from the table's own base: road tables stand 15 cm lower,
+ # and a fixed 0.6 m start put their stools on the table top
+ place(pid, sx, sy, facing=rng.uniform(0, 360), c=k, start_z=bounds(t)[0].z + 0.5, name=f"stool_{tid}_{n}")
+ n += 1
+ # Spare stools: a stack by the walk-in pole and two loose ones in the road.
+ place("hk_stool_stack", -0.85, -1.35, facing=20, c=k, start_z=2.0)
+ place("hk_stool_stack", -2.05, 6.55, facing=-30, c=k, start_z=2.0)
+ place("hk_stool_red", 3.4, 7.2, facing=40, c=k, start_z=2.0)
+
+
+def kitchen():
+ k = coll("props_kitchen")
+ cart = bpy.data.objects.get("kitchen_cart")
+ ct = top_of(cart) if cart else 1.0
+ woks = WOKS or [(-3.05, 2.8, 0.85), (-3.05, 3.55, 0.85)]
+ for pid, w, f, nm in (("hk_wok_rice", woks[0], 100, "wok_rice"), ("hk_wok_a", woks[1], 70, "wok_back")):
+ o = place(pid, w[0], w[1], z=w[2], facing=f, mode="hang", c=k, name=nm)
+ if o:
+ seat_wok(o, w)
+ o["mode"] = "seated"
+ place("hk_stockpot", -3.2, 0.55, facing=90, c=k, start_z=1.6, name="stockpot")
+ place("hk_stockpot_small", -3.25, 1.1, facing=60, c=k, start_z=1.6)
+ place("hk_cleaver_block", -2.98, 1.55, facing=90, c=k, start_z=1.6)
+ place("hk_aromatics_bowls", -2.95, 2.0, facing=95, c=k, start_z=1.6)
+ place("hk_wok_tools", -2.85, 0.9, facing=90, c=k, start_z=1.6)
+ place("hk_prawn_tray", -2.95, 4.4, facing=90, c=k, start_z=1.6)
+ place("hk_veg_basket", -3.2, 4.85, facing=80, c=k, start_z=1.6)
+ place("hk_steamer_stack", -3.25, 5.45, facing=90, c=k, start_z=1.6)
+ place("hk_spider_strainer", -2.95, 5.35, facing=10, c=k, start_z=1.6)
+ # Under the prep table.
+ place("hk_rice_sack", -3.15, 5.25, facing=90, c=k, start_z=0.8)
+ place("hk_tub_blue", -3.1, 4.5, facing=90, c=k, start_z=0.8)
+ # Back shelves (x -3.98..-3.58, sections y -0.3..1.6 / 1.7..3.6 / 3.7..5.8, tiers z 1.25 / 1.7 / 2.15).
+ # Packed along y by each prop's real footprint, back to the wall; tall things (>0.4 m) only on the top tier.
+ SECTIONS = [(-0.27, 1.57), (1.73, 3.57), (3.73, 5.77)]
+ TIERS = (1.25, 1.7, 2.15)
+ rows = {
+ (0, 0): ["hk_bowl_stack", "hk_plate_stack", "hk_claypot"],
+ (1, 0): ["hk_sauce_shelf", "hk_jars_preserved"],
+ (2, 0): ["hk_rice_cooker", "hk_plate_stack"],
+ (0, 1): ["hk_thermos", "hk_oil_tin", "hk_takeaway_boxes"],
+ (1, 1): ["hk_claypot", "hk_steamer_stack", "hk_stockpot_small"],
+ (2, 1): ["hk_bowl_stack", "hk_radio"],
+ (0, 2): ["hk_tea_urn", "hk_styrofoam_box"],
+ (1, 2): ["hk_menu_board_b", "hk_cardboard_boxes"],
+ (2, 2): ["hk_fan", "hk_dish_rack"],
+ }
+ for (sec, tier), pids in rows.items():
+ y = SECTIONS[sec][0] + 0.02
+ start = (TIERS[tier + 1] - 0.03) if tier < 2 else 2.95
+ for pid in pids:
+ o = place(pid, S.FX0 + 0.02, y + 0.3, z=TIERS[tier] + 0.3, facing=90 + rng.uniform(-6, 6), against="x-", c=k,
+ mode="hang", start_z=start, name="menu_board_shelf" if pid == "hk_menu_board_b" else None)
+ if not o:
+ continue
+ lo, hi = bounds(o)
+ o.location.y += y - lo.y # pack first, then drop onto the tier
+ _drop(o, start)
+ o["mode"] = "rest"
+ o["no_support"] = False
+ PLACED[:] = [(q, "rest" if q is o else m) for q, m in PLACED]
+ lo, hi = bounds(o)
+ if hi.y > SECTIONS[sec][1] - 0.01: # doesn't fit: drop it rather than clip a post
+ print("SHELF no room for", pid, flush=True)
+ unplace(o)
+ continue
+ y = hi.y + rng.uniform(0.02, 0.06)
+ # Hanging: tool rail over the cart, enamel shade over the woks, fluorescent batten on the wall.
+ place("hk_hanging_utensils", -2.8, 1.25, z=1.72, facing=90, mode="hang", c=k, name="hanging_utensils")
+ place("hk_enamel_shade", woks[0][0] + 0.15, (woks[0][1] + woks[1][1]) / 2, z=2.12, facing=90, mode="hang", c=k, name="wok_shade")
+ place("hk_fluoro_fitting", S.FX0 + 0.08, 2.6, z=2.8, facing=90, mode="hang", against="x-", c=k, name="fluoro")
+ # Both menu boards came back with easel stands: board B stands on the top shelf, A-frame A on the pavement at the
+ # walk-in end with its (mirrored-text) back to the stall.
+ place("hk_menu_board_a", -2.25, -1.2, facing=0, c=k, start_z=1.2, name="menu_board_aframe")
+ # Gas: two cylinders at the walk-in end of the cart, hose to the range.
+ place("hk_lpg_cylinder", -3.25, -0.2, facing=60, c=k, start_z=1.2, name="lpg_a")
+ place("hk_lpg_cylinder", -2.8, -0.55, facing=130, c=k, start_z=1.2, name="lpg_b")
+ # Floor clutter in and behind the stall.
+ place("hk_wash_basin", -2.05, 4.7, facing=0, c=k, start_z=2.0)
+ place("hk_water_bucket", -2.0, 5.35, facing=0, c=k, start_z=2.0)
+ place("hk_crate_stack", -3.3, 6.45, facing=90, c=k, start_z=2.0)
+ place("hk_beer_crate", -2.6, 6.55, facing=20, c=k, start_z=2.0)
+ place("hk_styrofoam_box", -2.5, 6.0, facing=70, c=k, start_z=2.0)
+ place("hk_veg_basket", -2.05, 6.05, facing=10, c=k, start_z=2.0)
+ place("hk_fire_extinguisher", S.FX0, 6.2, facing=90, against="x-", c=k, start_z=2.0)
+ place("hk_mop_bucket", -3.65, 7.1, facing=40, c=k, start_z=2.0)
+ place("hk_bird_cage", -1.2, -0.75, z=1.95, facing=0, mode="hang", c=k, name="bird_cage")
+ place("hk_plastic_bag_hang", -2.3, 5.85, z=1.65, facing=90, mode="hang", c=k)
+ place("hk_umbrella", S.POLE_X - 0.15, 3.05, facing=30, c=k, start_z=1.2)
+
+
+def tables():
+ k = coll("props_table")
+ T = {tid: (x, y) for tid, x, y, _ in TABLES}
+ sets = {
+ # newspapers first: whatever lands on them later rests on the paper
+ "t1": [("hk_newspaper", -0.2, -0.16, 70), ("hk_enamel_teapot", -0.16, 0.19, 200), ("hk_tea_cups", 0.21, 0.02, 0),
+ ("hk_condiment_caddy", 0.0, -0.27, 30), ("hk_chopstick_cup", 0.26, -0.24, 0)], # fried rice: 54 cm platter, no room
+ "t2": [("hk_radio", -0.12, -0.1, -20), ("hk_thermos", 0.22, 0.22, 0), ("hk_milk_tea", 0.2, -0.2, 0),
+ ("hk_ashtray", -0.22, 0.2, 0)],
+ "t3": [("hk_dish_clams", -0.12, 0.08, 0), ("hk_dish_beef_hofun", 0.18, -0.12, 120), ("hk_beer_bottles", 0.05, 0.3, 40),
+ ("hk_soy_bottles", -0.25, -0.18, 0), ("hk_chopstick_cup", 0.28, 0.12, 0), ("hk_lemon_tea", -0.3, 0.2, 0)],
+ "t4": [("hk_dish_greens", 0.1, 0.12, 0), ("hk_dish_salt_squid", -0.18, -0.08, 60), ("hk_bowl_congee", 0.22, -0.2, 0),
+ ("hk_enamel_teapot", -0.25, 0.22, 140), ("hk_toilet_roll", 0.3, 0.25, 0), ("hk_condiment_caddy", -0.05, -0.32, 0)],
+ "t5": [("hk_beer_bottles", 0.0, 0.0, 0), ("hk_ashtray", 0.25, 0.1, 0), ("hk_tea_cups", -0.2, -0.15, 0)],
+ }
+ for tid, items in sets.items():
+ x, y = T[tid]
+ for pid, dx, dy, f in items:
+ nm = {("t1", "hk_enamel_teapot"): "teapot_t1", ("t1", "hk_condiment_caddy"): "caddy_t1",
+ ("t3", "hk_dish_clams"): "clams_t3", ("t4", "hk_enamel_teapot"): "teapot_t4"}.get((tid, pid))
+ place(pid, x + dx, y + dy, facing=f, jitter=12, c=k, start_z=1.6, name=nm)
+
+
+def street():
+ k = coll("props_street")
+ # The lamp mesh is centred on its bbox, so the pole is at one end: find the pole base (mean of the lowest
+ # vertices), pick the facing that puts the arm toward -X (over the road), then move the base onto the far kerb.
+ for f in (90, -90, 180, 0):
+ lamp = place("hk_street_lamp", S.KERB1 + 0.45, 1.8, facing=f, c=k, start_z=2.0, name="street_lamp")
+ bpy.context.view_layer.update()
+ mw = lamp.matrix_world
+ vs = [mw @ v.co for v in lamp.data.vertices]
+ zmin = min(v.z for v in vs)
+ base = [v for v in vs if v.z < zmin + 0.05]
+ bx = sum(v.x for v in base) / len(base)
+ by = sum(v.y for v in base) / len(base)
+ lo, hi = bounds(lamp)
+ if bx > (lo.x + hi.x) / 2 + 0.5: # base on the +X end: arm reaches toward -X
+ lamp.location.x += (S.KERB1 + 0.45) - bx
+ lamp.location.y += 1.8 - by
+ print("street lamp facing", f, "arm reach", round(bx - lo.x, 2), flush=True)
+ break
+ unplace(lamp)
+ for y in (-7.4, -5.35):
+ place("hk_guard_railing", -0.32, y, facing=90, c=k, start_z=2.0)
+ for y in (-3.0, 12.5, 14.55):
+ place("hk_guard_railing", S.KERB1 + 0.32, y, facing=-90, c=k, start_z=2.0)
+ place("hk_water_barrier", 5.05, -0.6, facing=90, c=k, start_z=2.0, name="barrier_a")
+ place("hk_water_barrier", 5.05, 0.75, facing=90, jitter=4, c=k, start_z=2.0, name="barrier_b")
+ place("hk_water_barrier", 5.1, 4.6, facing=90, jitter=4, c=k, start_z=2.0, name="barrier_c")
+ place("hk_traffic_cone", 5.0, 2.6, facing=0, c=k, start_z=2.0)
+ place("hk_traffic_cone", 4.9, 6.4, facing=30, c=k, start_z=2.0)
+ place("hk_parked_car", 6.35, 9.5, facing=180, c=k, start_z=3.0, name="parked_car")
+ place("hk_scooter", 0.75, -3.4, facing=200, c=k, start_z=3.0, name="scooter")
+ place("hk_hand_trolley", -3.55, -1.6, facing=80, c=k, start_z=2.0)
+ place("hk_shrine", S.FX0, -2.15, facing=90, against="x-", c=k, start_z=2.0, name="shrine")
+ place("hk_trash_bin", -3.55, 7.7, facing=90, c=k, start_z=2.0)
+ place("hk_bin_bags", -2.85, 7.85, facing=10, c=k, start_z=2.0)
+ place("hk_bin_bags", S.KERB1 + 0.7, -1.5, facing=200, c=k, start_z=2.0)
+ place("hk_cardboard_boxes", S.KERB1 + 0.8, 5.0, facing=-90, c=k, start_z=2.0)
+ place("hk_electric_box", S.FX0, -3.9, z=1.3, facing=90, mode="hang", against="x-", c=k)
+ place("hk_electric_box", S.FX1, 7.4, z=1.5, facing=-90, mode="hang", against="x+", c=k)
+ # Window air-conditioners up the facades (hang, back to the facade plane).
+ n = 0
+ for side, xf, f, ag in ((-1, S.FX0 + 0.16, 90, "x-"), (1, S.FX1 - 0.16, -90, "x+")):
+ for y in range(-14, 30, 3):
+ for zf in (5.2, 8.1, 11.0, 13.9):
+ if rng.random() < 0.45:
+ continue
+ o = place("hk_aircon_unit", xf, y + rng.uniform(-0.8, 0.8), z=zf + rng.uniform(-0.3, 0.3), facing=f, mode="hang",
+ against=ag, c=k, tint=rng.choice(TINTS))
+ if o and hits_fixed(o):
+ unplace(o)
+ continue
+ n += 1
+ print("aircon units", n)
+
+
+FIXED = ("shell", "stall", "signs", "street_detail")
+
+
+def hits_fixed(o, pad=0.01):
+ """Bounding-box overlap with fixed geometry other than the building mass/face it is mounted on."""
+ lo, hi = bounds(o)
+ for c in FIXED:
+ cc = bpy.data.collections.get(c)
+ for f in (cc.all_objects if cc else []):
+ if f.type not in ("MESH", "FONT", "CURVE") or f.name.endswith(("_mass", "_face")) or f.name.startswith(("cable_", "pavement", "road", "kerb")):
+ continue
+ pts = [f.matrix_world @ Vector(v) for v in f.bound_box]
+ flo = Vector([min(q[i] for q in pts) for i in range(3)])
+ fhi = Vector([max(q[i] for q in pts) for i in range(3)])
+ if all(lo[i] + pad < fhi[i] and flo[i] < hi[i] - pad for i in range(3)):
+ return True
+ return False
+
+
+def run():
+ furniture()
+ kitchen()
+ tables()
+ street()
+ bpy.context.view_layer.update()
+ print("DRESS placed", len(PLACED), flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/emitters.py b/scenes/hk-dai-pai-dong/scripts/emitters.py
new file mode 100644
index 0000000..d56e3e3
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/emitters.py
@@ -0,0 +1,48 @@
+"""Glowing textures on dense generated meshes (ticket machine, fridge, lantern) turned every triangle into a light:
+a 545k-emitter light tree took ~290 s of sync per frame. Their light comes from area/point lights anyway, so
+emissive materials on meshes over 2k triangles stop being sampled as lights (they still glow to the camera)."""
+import bpy
+
+
+def _emissive(m):
+ if not m or not m.node_tree:
+ return False
+ for n in m.node_tree.nodes:
+ if n.type == "EMISSION":
+ return True
+ if n.type == "BSDF_PRINCIPLED":
+ s = n.inputs["Emission Strength"]
+ if s.is_linked or s.default_value > 0:
+ c = n.inputs["Emission Color"]
+ if c.is_linked or any(v > 0 for v in c.default_value[:3]):
+ return True
+ return False
+
+
+def run(min_tris=2000):
+ done = []
+ for o in bpy.data.objects:
+ if o.type != "MESH":
+ continue
+ if sum(len(p.vertices) - 2 for p in o.data.polygons) < min_tris:
+ continue
+ for m in o.data.materials:
+ if _emissive(m) and m.cycles.emission_sampling != "NONE":
+ m.cycles.emission_sampling = "NONE" # lives on m.cycles in 5.0
+ done.append(m.name)
+ print("emitters: sampling off for", done, flush=True)
+ return done
+
+
+if __name__ == "__main__":
+ run()
+ bpy.ops.wm.save_mainfile()
+
+
+def no_volume_blur():
+ """Object motion blur on the Mantaflow domains makes Cycles build velocity motion from the noise grids:
+ ~290 s of sync per frame. Camera blur stays; the steam itself just isn't motion-blurred."""
+ for o in bpy.data.objects:
+ if any(m.type == "FLUID" and m.fluid_type == "DOMAIN" for m in o.modifiers):
+ o.cycles.use_motion_blur = False
+ print("emitters: no motion blur on", o.name, flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/flame_try.py b/scenes/hk-dai-pai-dong/scripts/flame_try.py
new file mode 100644
index 0000000..4835e04
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/flame_try.py
@@ -0,0 +1,48 @@
+"""Flame look-dev without a rebuild: replace the flame (and bulb) materials in an existing build with lights.py's current
+ones and render the wok/flame cameras.
+ bash scenes/hk-dai-pai-dong/scripts/blend.sh scenes/hk-dai-pai-dong/hk_ground.blend --python scenes/hk-dai-pai-dong/scripts/flame_try.py -- --tag _f5 [--frame 40] [--save]
+"""
+import os
+import sys
+
+import bpy
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import lights # noqa: E402
+from lib import SCENE_DIR # noqa: E402
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+TAG = argv[argv.index("--tag") + 1] if "--tag" in argv else "_try"
+sc = bpy.context.scene
+sc.frame_set(int(argv[argv.index("--frame") + 1]) if "--frame" in argv else 40)
+
+old = bpy.data.materials.get("flame_vol")
+if old:
+ old.name = "flame_vol_old"
+m = lights.m_flame("flame_vol")
+ob = bpy.data.materials.get("bulb_glow")
+if ob:
+ ob.name = "bulb_glow_old"
+mb = lights.m_bulb()
+for o in sc.objects:
+ if o.type != "MESH":
+ continue
+ for s in o.material_slots:
+ if s.material is old:
+ s.material = m
+ elif ob and s.material is ob:
+ s.material = mb
+if "--save" in argv:
+ bpy.ops.wm.save_mainfile()
+ print("FLAME saved", bpy.data.filepath, flush=True)
+sc.cycles.samples = 48
+sc.render.resolution_percentage = 50
+sc.render.use_motion_blur = False
+for n in ("flame", "wok", "table"):
+ cam = bpy.data.objects.get("cam_" + n)
+ if not cam:
+ continue
+ sc.camera = cam
+ sc.render.filepath = os.path.join(SCENE_DIR, "out", "prev", f"{n}{TAG}.png")
+ bpy.ops.render.render(write_still=True)
+ print("FLAME", sc.render.filepath, flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/fx.py b/scenes/hk-dai-pai-dong/scripts/fx.py
new file mode 100644
index 0000000..9295ce5
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/fx.py
@@ -0,0 +1,177 @@
+"""Atmosphere: wok/stockpot steam, street haze, drizzle, drips off the awning edge.
+
+Steam is a procedural volume (4D noise advected upward inside a plume-shaped falloff), not Mantaflow: the walkthroughs
+are long uncut takes (500+ frames), and a Mantaflow cache that long would need a bake far past the 10-minute GPU-queue
+budget. Procedural plumes need no cache and no motion-blur special case. They roll out under the awning toward the street.
+"""
+import math
+
+import bpy
+from mathutils import Matrix
+
+import shell as S
+from lib import L, box, coll, cylinder, mathn, new_mat, noise, ramp, texcoord
+
+END = 900 # long enough for the longest take
+
+
+def _vol_box(name, lo, hi, c, mat):
+ o = box(name, lo, hi, c, mat, 0)
+ o.visible_shadow = False
+ o.visible_glossy = False
+ o["no_support"] = True
+ o.cycles.use_motion_blur = False # static volume: no velocity motion (the ramen 290 s/frame trap)
+ return o
+
+
+def m_plume(name, rise=0.05, strength=1.0, lean=0.35):
+ """Plume in a box's generated space: narrow at the bottom (z=0), widening and drifting toward +X (the street) as it
+ rises, flattened under the awning at the top. Density from upward-scrolling 4D noise."""
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ nt.nodes.remove(nt.nodes["Principled BSDF"])
+ gen = texcoord(nt, "Generated")
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ L(nt, gen, sep.inputs[0])
+ z = sep.outputs["Z"]
+ # Plume centre leans toward +X with height (the cook's side is open, air drifts out to the street).
+ cx = mathn(nt, "ADD", 0.3, mathn(nt, "MULTIPLY", mathn(nt, "POWER", z, 1.5), lean))
+ dx = mathn(nt, "SUBTRACT", sep.outputs["X"], cx)
+ dy = mathn(nt, "SUBTRACT", sep.outputs["Y"], 0.5)
+ r = mathn(nt, "SQRT", mathn(nt, "ADD", mathn(nt, "MULTIPLY", dx, dx), mathn(nt, "MULTIPLY", dy, dy)))
+ width = mathn(nt, "ADD", 0.08, mathn(nt, "MULTIPLY", z, 0.42))
+ shape = mathn(nt, "SUBTRACT", 1.0, mathn(nt, "DIVIDE", r, width), clamp=True)
+ shape = mathn(nt, "POWER", shape, 0.8)
+ top = mathn(nt, "SUBTRACT", 1.0, mathn(nt, "POWER", z, 6.0), clamp=True)
+ bottom = mathn(nt, "MINIMUM", mathn(nt, "MULTIPLY", z, 12.0), 1.0)
+ co = texcoord(nt, "Object")
+ mp = nt.nodes.new("ShaderNodeMapping")
+ L(nt, co, mp.inputs["Vector"])
+ mp.inputs["Location"].driver_add("default_value", 2).driver.expression = f"-frame * {rise}"
+ mp.inputs["Location"].driver_add("default_value", 0).driver.expression = f"-frame * {rise * 0.3}"
+ warp = noise(nt, 2.2, 3, 0.5, mp.outputs[0], dim="4D")
+ warp.inputs["W"].driver_add("default_value").driver.expression = "frame * 0.02"
+ mix = nt.nodes.new("ShaderNodeMix")
+ mix.data_type = "VECTOR"
+ mix.inputs["Factor"].default_value = 0.35
+ L(nt, mp.outputs[0], mix.inputs["A"])
+ L(nt, warp.outputs["Color"], mix.inputs["B"])
+ n = noise(nt, 5.5, 6, 0.62, mix.outputs["Result"], dim="4D")
+ n.inputs["W"].driver_add("default_value").driver.expression = "frame * 0.035"
+ wisp = ramp(nt, [(0.5, (0, 0, 0)), (0.78, (1, 1, 1))], n.outputs["Fac"]).outputs["Color"]
+ d = mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", shape, wisp), mathn(nt, "MULTIPLY", top, bottom)), 9.0 * strength)
+ v = nt.nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Color"].default_value = (0.9, 0.9, 0.9, 1)
+ v.inputs["Anisotropy"].default_value = 0.5
+ L(nt, d, v.inputs["Density"])
+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])
+ return m
+
+
+def steam(c):
+ import dress
+ out = []
+ woks = dress.WOKS or [(-3.05, 2.81, 0.85), (-3.05, 3.55, 0.85)]
+ for i, (x, y, z) in enumerate(woks):
+ out.append(_vol_box(f"steam_wok_{i}", (x - 0.35, y - 0.55, z + 0.08), (x + 1.35, y + 0.55, S.AWN["z_wall"] - 0.15), c,
+ m_plume("steam_wok", rise=0.055, strength=0.22)))
+ sp = bpy.data.objects.get("stockpot")
+ if sp:
+ lo, hi = dress.bounds(sp)
+ x, y = (lo.x + hi.x) / 2, (lo.y + hi.y) / 2
+ out.append(_vol_box("steam_stockpot", (x - 0.25, y - 0.4, hi.z - 0.02), (x + 0.95, y + 0.4, S.AWN["z_wall"] - 0.15), c,
+ m_plume("steam_pot", rise=0.03, strength=0.18, lean=0.5)))
+ return out
+
+
+def haze(c):
+ """Low-density haze over the stall and the near street, slightly thicker low down and under the awning."""
+ m, nt = new_mat("street_haze")
+ if nt:
+ nt.nodes.remove(nt.nodes["Principled BSDF"])
+ co = texcoord(nt, "Object")
+ n = noise(nt, 0.35, 3, 0.5, co, dim="4D")
+ n.inputs["W"].driver_add("default_value").driver.expression = "frame * 0.004"
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ L(nt, texcoord(nt, "Generated"), sep.inputs[0])
+ low = mathn(nt, "ADD", 0.6, mathn(nt, "MULTIPLY", mathn(nt, "SUBTRACT", 1.0, sep.outputs["Z"]), 0.8))
+ d = mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", mathn(nt, "ADD", n.outputs["Fac"], 0.3), low), 0.0055)
+ v = nt.nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Color"].default_value = (0.8, 0.82, 0.9, 1)
+ v.inputs["Anisotropy"].default_value = 0.65
+ L(nt, d, v.inputs["Density"])
+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])
+ return _vol_box("haze", (S.FX0 + 0.02, -16, S.ROAD_Z - 0.02), (S.FX1 - 0.02, 24, 9.0), c, m)
+
+
+def _drop_mat():
+ m, nt = new_mat("drizzle")
+ if nt:
+ b = nt.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.8, 0.85, 0.9, 1)
+ b.inputs["Roughness"].default_value = 0.05
+ b.inputs["Emission Color"].default_value = (0.8, 0.86, 1.0, 1)
+ b.inputs["Emission Strength"].default_value = 0.5
+ b.inputs["Alpha"].default_value = 0.35
+ return m
+
+
+def _drop_obj(name, c, length, radius):
+ o = cylinder(name, radius, length, c, None, loc=(0, 0, -60), verts=6)
+ # Particle VEL rotation aligns the instance's +X with velocity: lay the drop's long axis along X.
+ o.data.transform(Matrix.Rotation(math.radians(90), 4, "Y") @ Matrix.Translation((0, 0, -length / 2)))
+ o.data.materials.append(_drop_mat())
+ o["no_support"] = True
+ return o
+
+
+def _emitter(name, c, lo, hi, drop, count, speed, lifetime, gravity=0.0, start=-80):
+ em = box(name, (lo[0], lo[1], hi[2]), (hi[0], hi[1], hi[2] + 0.02), c, None, 0)
+ em["no_support"] = True
+ ps = em.modifiers.new("p", "PARTICLE_SYSTEM").particle_system.settings
+ ps.count = count
+ ps.frame_start = start
+ ps.frame_end = END
+ ps.lifetime = lifetime
+ ps.emit_from = "VOLUME"
+ ps.normal_factor = 0.0
+ ps.object_align_factor = (0.25, 0.1, -speed) # slight wind toward the street end
+ ps.factor_random = 0.15
+ ps.effector_weights.gravity = gravity
+ ps.render_type = "OBJECT"
+ ps.instance_object = drop
+ ps.particle_size = 1.0
+ ps.size_random = 0.5
+ ps.use_rotations = True
+ ps.rotation_mode = "VEL"
+ ps.use_dynamic_rotation = False
+ ps.physics_type = "NEWTON"
+ em.show_instancer_for_render = False
+ em.show_instancer_for_viewport = False
+ return em
+
+
+def drizzle(c):
+ d = _drop_obj("drizzle_drop", c, 0.05, 0.0009)
+ span = END + 80
+ out = []
+ # Near street (where the cameras are), open sky only: from the awning edge out into the road.
+ out.append(_emitter("drizzle_near", c, (-0.1, -12.0, 0), (6.8, 12.0, 6.5), d, int(9000 * span / 40), 5.0, 40))
+ # Beyond the awning to the far side and down the street: sparser.
+ out.append(_emitter("drizzle_far", c, (-3.9, 7.2, 0), (9.5, 30.0, 9.0), d, int(5000 * span / 50), 5.0, 50))
+ out.append(_emitter("drizzle_back", c, (-3.9, -16.0, 0), (-0.2, -1.2, 9.0), d, int(1500 * span / 50), 5.0, 50))
+ # Drips off the awning's front edge: slow, heavier, under gravity.
+ dd = _drop_obj("drip_drop", c, 0.02, 0.0018)
+ a = S.AWN
+ em = _emitter("awning_drips", c, (a["x1"] - 0.03, a["y0"], 0), (a["x1"] + 0.01, a["y1"], a["z_edge"] - 0.02), dd, int(span * 2.5), 0.2, 30, gravity=1.0)
+ out.append(em)
+ return out
+
+
+def build():
+ c = coll("fx")
+ steam(c)
+ haze(c)
+ drizzle(c)
+ print("FX done", flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/gen.mjs b/scenes/hk-dai-pai-dong/scripts/gen.mjs
new file mode 100644
index 0000000..0a2c9ae
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/gen.mjs
@@ -0,0 +1,62 @@
+// Dai pai dong generation: refs (GPT Image 2.5 Sunburst) then Tripo H3.1 + Meshy 7.1 for every prop, plus flat textures.
+// node scenes/hk-dai-pai-dong/scripts/gen.mjs [--only id,id] [--models tripo-h31,meshy] [--stage refs|3d|all] [--pool 12]
+// Skips anything already on disk; re-run to fill gaps. Never run two of these at once (in-flight jobs get double-submitted).
+// Props with "replaces" (the _nb regenerations) are generated like any other prop.
+import { execFile } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+import { promisify } from 'node:util';
+
+const run = promisify(execFile);
+const ROOT = new URL('../../..', import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1');
+const SC = 'hk-dai-pai-dong';
+const M = JSON.parse(readFileSync(`${ROOT}/scenes/${SC}/assets.json`, 'utf8'));
+const args = Object.fromEntries(process.argv.slice(2).reduce((a, v, i, arr) => (v.startsWith('--') ? [...a, [v.slice(2), arr[i + 1]]] : a), []));
+const only = args.only?.split(',');
+const models = (args.models ?? 'tripo-h31,meshy').split(',');
+const stage = args.stage ?? 'all';
+
+const fal = (...a) => run('node', ['generate/fal.mjs', ...a], { cwd: ROOT, maxBuffer: 1 << 24 });
+
+async function pool(tasks, n) {
+ let i = 0;
+ let fails = 0;
+ await Promise.all(Array.from({ length: n }, async () => {
+ while (i < tasks.length) {
+ const t = tasks[i++];
+ try { await t(); } catch (e) { fails++; console.log('FAIL', e.message.split('\n').slice(-3).join(' | ')); }
+ }
+ }));
+ return fails;
+}
+
+const refJson = (id) => `refs/${SC}/props/${id}.json`;
+const props = M.generate.filter((p) => !only || only.includes(p.id));
+
+if (stage !== '3d') {
+ const imgTasks = [
+ ...M.textures.filter((t) => (!only || only.includes(t.id)) && !existsSync(`${ROOT}/refs/${SC}/tex/${t.id}_0.png`)).map((t) => async () => {
+ await fal('image', '--variant', 'sunburst', '--quality', 'high', '--size', t.size, '--out', `refs/${SC}/tex/${t.id}`, '--prompt', t.prompt);
+ console.log('tex', t.id);
+ }),
+ ...props.filter((p) => !existsSync(`${ROOT}/${refJson(p.id)}`)).map((p) => async () => {
+ await fal('image', '--variant', 'sunburst', '--quality', 'high', '--size', 'square_hd', '--out', `refs/${SC}/props/${p.id}`, '--prompt', `${p.prompt} ${M.scan_template}`);
+ console.log('ref', p.id);
+ }),
+ ];
+ console.log('image jobs', imgTasks.length);
+ console.log('image fails', await pool(imgTasks, 10));
+}
+
+if (stage !== 'refs') {
+ // Branded originals (a later "_nb" prop replaces them) are not sent to 3D.
+ const replaced = new Set(M.generate.filter((p) => p.replaces).map((p) => p.replaces));
+ const genTasks = props.filter((p) => !replaced.has(p.id) && existsSync(`${ROOT}/${refJson(p.id)}`)).flatMap((p) =>
+ models.filter((m) => !existsSync(`${ROOT}/assets/gen/${m}/${p.id}/model.glb`)).map((m) => async () => {
+ const t0 = Date.now();
+ await fal('3d', '--model', m, '--ref', refJson(p.id), '--out', `assets/gen/${m}/${p.id}`);
+ console.log('3d', m, p.id, Math.round((Date.now() - t0) / 1000) + 's');
+ }));
+ console.log('3d jobs', genTasks.length);
+ console.log('3d fails', await pool(genTasks, +(args.pool ?? 12)));
+}
+console.log('all done');
diff --git a/scenes/hk-dai-pai-dong/scripts/gpu_prefs.py b/scenes/hk-dai-pai-dong/scripts/gpu_prefs.py
new file mode 100644
index 0000000..855f628
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/gpu_prefs.py
@@ -0,0 +1,12 @@
+"""Run as the first --python: Cycles device prefs live in user preferences, not the .blend, so a plain
+`blender -b scene.blend` renders on the CPU. Select OptiX GPUs and set the scene to GPU."""
+import bpy
+
+prefs = bpy.context.preferences.addons["cycles"].preferences
+prefs.compute_device_type = "OPTIX"
+prefs.get_devices()
+for d in prefs.devices:
+ d.use = d.type == "OPTIX"
+for sc in bpy.data.scenes:
+ sc.cycles.device = "GPU"
+print("gpu_prefs:", [d.name for d in prefs.devices if d.use], flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/grade.sh b/scenes/hk-dai-pai-dong/scripts/grade.sh
new file mode 100644
index 0000000..55d34a6
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/grade.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Grade in ffmpeg (not the Blender compositor): lifted teal shadows, warm highlights, a touch of desaturation,
+# slight chromatic fringe, vignette, temporal grain. Checks the frame count before encoding (a gap = short clip).
+# bash scenes/hk-dai-pai-dong/scripts/grade.sh still <in.png> <out.png>
+# bash scenes/hk-dai-pai-dong/scripts/grade.sh clip <shot_dir> <out.mp4> <expected_frames>
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+FF="$FFMPEG"
+
+GRADE="curves=r='0/0.03 0.25/0.23 0.6/0.635 1/0.985':g='0/0.034 0.25/0.245 0.6/0.615 1/0.965':b='0/0.05 0.25/0.27 0.6/0.6 1/0.93',hue=s=0.88,rgbashift=rh=-1:bh=1:edge=smear,vignette=angle=PI/4.4"
+case "$1" in
+ still) "$FF" -v error -y -i "$2" -vf "$GRADE,noise=alls=5:allf=u" -frames:v 1 "$3" ;;
+ clip)
+ n=$(ls "$2"/frames/*.png 2>/dev/null | wc -l)
+ last=$(printf "%04d" "$4")
+ if [ "$n" -ne "$4" ] || [ ! -f "$2/frames/$last.png" ]; then echo "grade: $2 has $n frames, expected $4 — not encoding"; exit 2; fi
+ "$FF" -v error -y -framerate 24 -start_number 1 -i "$2/frames/%04d.png" -vf "$GRADE,noise=alls=7:allf=t+u,format=yuv420p" \
+ -c:v h264_nvenc -preset p7 -rc vbr -cq 18 -b:v 0 -movflags +faststart "$3"
+ got=$("$FF" -v error -i "$3" -map 0:v:0 -c copy -f null - 2>&1; "$FF" -i "$3" 2>&1 | grep -o "Duration: [0-9:.]*")
+ echo "graded $3 ($n frames) $got" ;;
+ *) echo "usage: grade.sh still|clip ..." ; exit 1 ;;
+esac
diff --git a/scenes/hk-dai-pai-dong/scripts/grime.py b/scenes/hk-dai-pai-dong/scripts/grime.py
new file mode 100644
index 0000000..c30afd1
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/grime.py
@@ -0,0 +1,132 @@
+"""Imperfections pass, adapted from the repair scene's grime_layer for a wet street:
+per-instance tint (Object Info > Color, so linked duplicates don't read as copies), AO crevice dirt, soot/grease
+blotches, and rain-wet up-facing surfaces outside the awning (darker albedo, lower roughness).
+
+The group's global strength lives in the node "grime_master" (a Value node inside the group), so the breakdown's
+materials clip can fade all grime in with one key.
+"""
+import bpy
+
+import shell as S
+
+SKIP = ("glass", "haze", "drizzle", "drip", "skyline", "decal", "fluoro", "bulb", "neon", "lightbox", "clay", "flame",
+ "steam", "water", "posters", "menu_strips", "stall_sign", "paint_", "sign_ink", "cord", "BTS")
+
+
+def _mix(g, fac, a, b, blend="MIX"):
+ m = g.nodes.new("ShaderNodeMix")
+ m.data_type = "RGBA"
+ m.blend_type = blend
+ for sock, val in (("Factor", fac), ("A", a), ("B", b)):
+ if isinstance(val, bpy.types.NodeSocket):
+ g.links.new(val, m.inputs[sock])
+ else:
+ m.inputs[sock].default_value = val if not isinstance(val, tuple) or len(val) == 4 else (*val, 1)
+ return m.outputs["Result"]
+
+
+def _math(g, op, a, b=0.0, clamp=False):
+ m = g.nodes.new("ShaderNodeMath")
+ m.operation = op
+ m.use_clamp = clamp
+ for i, v in enumerate((a, b)):
+ if isinstance(v, bpy.types.NodeSocket):
+ g.links.new(v, m.inputs[i])
+ else:
+ m.inputs[i].default_value = v
+ return m.outputs[0]
+
+
+def group():
+ g = bpy.data.node_groups.get("grime_layer")
+ if g:
+ return g
+ g = bpy.data.node_groups.new("grime_layer", "ShaderNodeTree")
+ g.interface.new_socket("Color", in_out="INPUT", socket_type="NodeSocketColor")
+ g.interface.new_socket("Roughness", in_out="INPUT", socket_type="NodeSocketFloat")
+ g.interface.new_socket("Amount", in_out="INPUT", socket_type="NodeSocketFloat")
+ g.interface.new_socket("Color", in_out="OUTPUT", socket_type="NodeSocketColor")
+ g.interface.new_socket("Roughness", in_out="OUTPUT", socket_type="NodeSocketFloat")
+ n = g.nodes
+ gi, go = n.new("NodeGroupInput"), n.new("NodeGroupOutput")
+ master = n.new("ShaderNodeValue")
+ master.name = master.label = "grime_master"
+ master.outputs[0].default_value = 1.0
+ amt = _math(g, "MULTIPLY", gi.outputs["Amount"], master.outputs[0])
+ oi = n.new("ShaderNodeObjectInfo")
+ tint = _mix(g, master.outputs[0], (1, 1, 1, 1), oi.outputs["Color"])
+ col = _mix(g, 1.0, gi.outputs["Color"], tint, "MULTIPLY")
+ # AO crevice dirt.
+ ao = n.new("ShaderNodeAmbientOcclusion")
+ ao.samples = 8
+ ao.inputs["Distance"].default_value = 0.05
+ crev = _math(g, "SUBTRACT", 1.0, _math(g, "MULTIPLY", _math(g, "SUBTRACT", 1.0, ao.outputs["AO"]), amt), clamp=True)
+ col = _mix(g, 1.0, col, _mix(g, crev, (0.18, 0.15, 0.11, 1), (1, 1, 1, 1)), "MULTIPLY")
+ # Soot / grease blotches.
+ geo = n.new("ShaderNodeNewGeometry")
+ nz = n.new("ShaderNodeTexNoise")
+ nz.inputs["Scale"].default_value = 6.0
+ nz.inputs["Detail"].default_value = 8
+ g.links.new(geo.outputs["Position"], nz.inputs["Vector"])
+ rm = n.new("ShaderNodeMapRange")
+ rm.inputs["From Min"].default_value, rm.inputs["From Max"].default_value = 0.55, 0.8
+ g.links.new(nz.outputs["Fac"], rm.inputs["Value"])
+ blot = _math(g, "MULTIPLY", _math(g, "MULTIPLY", rm.outputs["Result"], amt), 0.45, clamp=True)
+ col = _mix(g, blot, col, (0.05, 0.04, 0.03, 1))
+ # Rain-wet: up-facing surfaces outside the awning (world x > awning edge or y outside it).
+ sep = n.new("ShaderNodeSeparateXYZ")
+ g.links.new(geo.outputs["Normal"], sep.inputs[0])
+ up = n.new("ShaderNodeMapRange")
+ up.inputs["From Min"].default_value, up.inputs["From Max"].default_value = 0.3, 0.8
+ g.links.new(sep.outputs["Z"], up.inputs["Value"])
+ pos = n.new("ShaderNodeSeparateXYZ")
+ g.links.new(geo.outputs["Position"], pos.inputs[0])
+ a = S.AWN
+ out_x = _math(g, "GREATER_THAN", pos.outputs["X"], a["x1"])
+ out_y = _math(g, "MAXIMUM", _math(g, "LESS_THAN", pos.outputs["Y"], a["y0"]), _math(g, "GREATER_THAN", pos.outputs["Y"], a["y1"]))
+ outside = _math(g, "MAXIMUM", out_x, out_y)
+ wet = _math(g, "MULTIPLY", _math(g, "MULTIPLY", up.outputs["Result"], outside), master.outputs[0])
+ col = _mix(g, _math(g, "MULTIPLY", wet, 0.35), col, (0, 0, 0, 1))
+ g.links.new(col, go.inputs["Color"])
+ rough = _math(g, "ADD", gi.outputs["Roughness"], _math(g, "MULTIPLY", blot, 0.25))
+ rough = _math(g, "SUBTRACT", rough, _math(g, "MULTIPLY", wet, 0.55), clamp=True)
+ g.links.new(rough, go.inputs["Roughness"])
+ return g
+
+
+def amount_for(name):
+ n = name.lower()
+ if any(k in n for k in ("stall_", "shelf", "prep", "kitchen", "awn", "hk_wok", "hk_kitchen", "hk_stockpot", "range")):
+ return 1.3
+ if any(k in n for k in ("pavement", "road", "kerb", "bldg", "far_", "fascia")):
+ return 0.6
+ return 0.9
+
+
+def add_grime(m):
+ nt = m.node_tree
+ if nt is None or m.name.startswith(SKIP) or any(k in m.name for k in ("glass", "facemat", "lightbox")):
+ return False
+ if any(nd.type == "GROUP" and nd.node_tree and nd.node_tree.name == "grime_layer" for nd in nt.nodes):
+ return False
+ b = next((nd for nd in nt.nodes if nd.type == "BSDF_PRINCIPLED"), None)
+ if b is None or b.inputs["Emission Strength"].is_linked or b.inputs["Emission Strength"].default_value > 0:
+ return False
+ if b.inputs["Transmission Weight"].default_value > 0.5:
+ return False
+ gn = nt.nodes.new("ShaderNodeGroup")
+ gn.node_tree = group()
+ gn.inputs["Amount"].default_value = amount_for(m.name)
+ for sock, gi, go in (("Base Color", "Color", 0), ("Roughness", "Roughness", 1)):
+ s = b.inputs[sock]
+ if s.is_linked:
+ nt.links.new(s.links[0].from_socket, gn.inputs[gi])
+ else:
+ gn.inputs[gi].default_value = s.default_value
+ nt.links.new(gn.outputs[go], s)
+ return True
+
+
+def build():
+ n = sum(add_grime(m) for m in list(bpy.data.materials))
+ print("GRIME on", n, "materials", flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/ground_stills.py b/scenes/hk-dai-pai-dong/scripts/ground_stills.py
new file mode 100644
index 0000000..3b92d9d
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/ground_stills.py
@@ -0,0 +1,51 @@
+"""Low-angle stills of the tables and stools (knee height) to check every foot is on the ground. Lit, no rain/haze.
+ bash scenes/hk-dai-pai-dong/scripts/blend.sh scenes/hk-dai-pai-dong/hk.blend --python scenes/hk-dai-pai-dong/scripts/ground_stills.py -- [--tag _v2]
+"""
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from lib import SCENE_DIR # noqa: E402
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+TAG = argv[argv.index("--tag") + 1] if "--tag" in argv else ""
+
+# name: (camera pos, aim) - 30-40 cm off the ground, 2-3 m out
+VIEWS = {
+ "t3": ((3.6, -1.6, 0.3), (1.65, -0.35, 0.35)),
+ "t4": ((3.4, 6.4, 0.3), (1.75, 4.55, 0.35)),
+ "t5": ((5.9, 1.2, 0.35), (3.95, 2.45, 0.35)),
+ "t1t2": ((0.9, -1.7, 0.3), (-0.95, 2.4, 0.4)),
+ "kitchen": ((-1.4, 4.6, 1.0), (-3.2, 4.9, 0.9)),
+ "cart": ((-1.6, 1.2, 1.15), (-3.1, 1.5, 0.95)),
+}
+
+
+def add_camera(name, pos, aim, lens, c): # as build.py (importing build would run the build)
+ d = bpy.data.cameras.new(name)
+ d.lens, d.sensor_width, d.clip_start = lens, 24.89, 0.05
+ o = bpy.data.objects.new(name, d)
+ c.objects.link(o)
+ o.location = pos
+ o.rotation_euler = (Vector(aim) - Vector(pos)).to_track_quat("-Z", "Y").to_euler()
+ return o
+
+
+sc = bpy.context.scene
+for o in sc.objects:
+ if o.name.startswith(("haze", "rain", "drizzle", "drip")):
+ o.hide_render = True
+sc.cycles.samples = 24
+sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = 1920, 804, 50
+sc.render.use_motion_blur = False
+sc.view_settings.exposure += 0.8 # knee-height views are in the stools' shadow
+od = os.path.join(SCENE_DIR, "out", "prev")
+os.makedirs(od, exist_ok=True)
+for n, (pos, aim) in VIEWS.items():
+ sc.camera = add_camera("cam_ground_" + n, pos, aim, 28, sc.collection)
+ sc.render.filepath = os.path.join(od, f"ground_{n}{TAG}.png")
+ bpy.ops.render.render(write_still=True)
+ print("GROUND still", sc.render.filepath, flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/lib.py b/scenes/hk-dai-pai-dong/scripts/lib.py
new file mode 100644
index 0000000..5cc580e
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/lib.py
@@ -0,0 +1,439 @@
+"""Ramen scene helpers: geometry primitives and procedural materials (Blender 5.0, Cycles)."""
+import math
+import os
+
+import bpy
+from mathutils import Vector
+
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+SCENE_DIR = os.path.join(ROOT, "scenes", "hk-dai-pai-dong")
+TEX = os.path.join(ROOT, "refs", "hk-dai-pai-dong", "tex")
+
+
+# ---------------------------------------------------------------- collections / objects
+
+def coll(name, parent=None):
+ c = bpy.data.collections.get(name) or bpy.data.collections.new(name)
+ p = parent or bpy.context.scene.collection
+ if c.name not in [x.name for x in p.children]:
+ p.children.link(c)
+ return c
+
+
+def link(obj, c):
+ for uc in list(obj.users_collection):
+ uc.objects.unlink(obj)
+ c.objects.link(obj)
+ return obj
+
+
+def mesh_obj(name, verts, faces, c, mat=None):
+ me = bpy.data.meshes.new(name)
+ me.from_pydata(verts, [], faces)
+ me.update()
+ o = bpy.data.objects.new(name, me)
+ c.objects.link(o)
+ if mat:
+ me.materials.append(mat)
+ return o
+
+
+def box(name, lo, hi, c, mat=None, bevel=0.004, rot_z=0.0):
+ """Axis-aligned box from corner lo to corner hi (world metres), origin at its bottom centre."""
+ lo, hi = Vector(lo), Vector(hi)
+ s = hi - lo
+ hx, hy = s.x / 2, s.y / 2
+ v = [(-hx, -hy, 0), (hx, -hy, 0), (hx, hy, 0), (-hx, hy, 0), (-hx, -hy, s.z), (hx, -hy, s.z), (hx, hy, s.z), (-hx, hy, s.z)]
+ f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
+ o = mesh_obj(name, v, f, c, mat)
+ o.location = ((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z)
+ o.rotation_euler.z = rot_z
+ uv_cube(o)
+ if bevel:
+ m = o.modifiers.new("bevel", "BEVEL")
+ m.width = bevel
+ m.segments = 2
+ m.limit_method = "ANGLE"
+ m.harden_normals = False
+ for p in o.data.polygons:
+ p.use_smooth = False
+ return o
+
+
+def plane(name, w, h, c, mat=None, loc=(0, 0, 0), rot=(0, 0, 0)):
+ """Vertical plane w x h facing -Y in local space (so rot z=0 faces the street side), UV 0-1."""
+ v = [(-w / 2, 0, 0), (w / 2, 0, 0), (w / 2, 0, h), (-w / 2, 0, h)]
+ o = mesh_obj(name, v, [(0, 1, 2, 3)], c, mat)
+ uv = o.data.uv_layers.new(name="UVMap")
+ for i, co in enumerate([(0, 0), (1, 0), (1, 1), (0, 1)]):
+ uv.data[i].uv = co
+ o.location = loc
+ o.rotation_euler = rot
+ return o
+
+
+def cylinder(name, r, h, c, mat=None, loc=(0, 0, 0), verts=32):
+ bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=h, vertices=verts, location=(loc[0], loc[1], loc[2] + h / 2))
+ o = bpy.context.object
+ o.name = name
+ link(o, c)
+ if mat:
+ o.data.materials.append(mat)
+ bpy.ops.object.shade_smooth()
+ return o
+
+
+def uv_cube(o, scale=1.0):
+ """World-size box UVs (1 UV unit = 1 m) so image textures keep real scale."""
+ me = o.data
+ uv = me.uv_layers.get("UVMap") or me.uv_layers.new(name="UVMap")
+ for p in me.polygons:
+ n = p.normal
+ ax = max(range(3), key=lambda i: abs(n[i]))
+ for li in p.loop_indices:
+ co = me.vertices[me.loops[li].vertex_index].co
+ a, b = [(1, 2), (0, 2), (0, 1)][ax]
+ uv.data[li].uv = (co[a] * scale, co[b] * scale)
+
+
+# ---------------------------------------------------------------- material helpers
+
+def new_mat(name):
+ m = bpy.data.materials.get(name)
+ if m:
+ return m, None
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ return m, m.node_tree
+
+
+def bsdf(nt):
+ return nt.nodes["Principled BSDF"]
+
+
+def node(nt, kind, **inputs):
+ n = nt.nodes.new(kind)
+ for k, v in inputs.items():
+ if k in n.inputs:
+ n.inputs[k].default_value = v
+ else:
+ setattr(n, k, v)
+ return n
+
+
+def L(nt, a, b):
+ nt.links.new(a, b)
+
+
+def ramp(nt, stops, src=None):
+ r = nt.nodes.new("ShaderNodeValToRGB")
+ els = r.color_ramp.elements
+ while len(els) > 2:
+ els.remove(els[-1])
+ for i, (pos, col) in enumerate(stops):
+ e = els[i] if i < 2 else els.new(pos)
+ e.position = pos
+ e.color = col if len(col) == 4 else (*col, 1)
+ if src is not None:
+ L(nt, src, r.inputs["Fac"])
+ return r
+
+
+def texcoord(nt, kind="Object"):
+ return nt.nodes.new("ShaderNodeTexCoord").outputs[kind]
+
+
+def noise(nt, scale, detail=6, rough=0.55, coord=None, dim="3D"):
+ n = node(nt, "ShaderNodeTexNoise", Scale=scale, Detail=detail, Roughness=rough)
+ n.noise_dimensions = dim
+ if coord is not None:
+ L(nt, coord, n.inputs["Vector"])
+ return n
+
+
+def bump(nt, height, strength=0.2, distance=0.01, normal=None):
+ b = node(nt, "ShaderNodeBump", Strength=strength, Distance=distance)
+ L(nt, height, b.inputs["Height"])
+ if normal is not None:
+ L(nt, normal, b.inputs["Normal"])
+ return b
+
+
+def mix(nt, fac, a, b, blend="MIX"):
+ m = nt.nodes.new("ShaderNodeMix")
+ m.data_type = "RGBA"
+ m.blend_type = blend
+ for sock, val in (("Factor", fac), ("A", a), ("B", b)):
+ if isinstance(val, bpy.types.NodeSocket):
+ L(nt, val, m.inputs[sock])
+ else:
+ m.inputs[sock].default_value = val
+ return m.outputs["Result"]
+
+
+def mathn(nt, op, a, b=0.0, clamp=False):
+ m = nt.nodes.new("ShaderNodeMath")
+ m.operation = op
+ m.use_clamp = clamp
+ for i, val in enumerate((a, b)):
+ if isinstance(val, bpy.types.NodeSocket):
+ L(nt, val, m.inputs[i])
+ else:
+ m.inputs[i].default_value = val
+ return m.outputs[0]
+
+
+# ---------------------------------------------------------------- materials
+
+def m_plaster(name="plaster", base=(0.62, 0.57, 0.48)):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt)
+ n1 = noise(nt, 3.0, 8, 0.6, co)
+ grime = noise(nt, 0.8, 4, 0.5, co)
+ col = ramp(nt, [(0.35, (base[0] * 0.72, base[1] * 0.68, base[2] * 0.6)), (0.65, base)], n1.outputs["Fac"])
+ # Smoky grime toward the ceiling (object z) mixed with low-frequency blotches.
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ L(nt, texcoord(nt, "Generated"), sep.inputs[0])
+ hgt = mathn(nt, "POWER", sep.outputs["Z"], 3.0)
+ gfac = mathn(nt, "MULTIPLY", mathn(nt, "ADD", hgt, mathn(nt, "MULTIPLY", grime.outputs["Fac"], 0.35)), 0.55, clamp=True)
+ c2 = mix(nt, gfac, col.outputs["Color"], (0.25, 0.2, 0.14, 1), "MULTIPLY")
+ b = bsdf(nt)
+ L(nt, c2, b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.92
+ L(nt, bump(nt, noise(nt, 40, 6, 0.6, co).outputs["Fac"], 0.12, 0.004).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def m_wood(name, dark=(0.06, 0.03, 0.015), light=(0.2, 0.1, 0.045), along="X", scale=1.0, gloss=0.35, wear=True, fine_mix=0.35, bump_k=0.18):
+ """Oiled worn wood: wave-texture grain along an axis, glossy wiped patches, cup rings (voronoi) on top."""
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt)
+ mp = nt.nodes.new("ShaderNodeMapping")
+ L(nt, co, mp.inputs["Vector"])
+ # Stretch the noise along the grain axis.
+ s = {"X": (0.12, 3.0, 3.0), "Y": (3.0, 0.12, 3.0), "Z": (3.0, 3.0, 0.12)}[along]
+ mp.inputs["Scale"].default_value = [v * scale for v in s]
+ wave = node(nt, "ShaderNodeTexWave", Scale=1.6, Distortion=9.0, Detail=6.0)
+ wave.wave_type = "BANDS"
+ wave.bands_direction = {"X": "Y", "Y": "X", "Z": "X"}[along]
+ L(nt, mp.outputs[0], wave.inputs["Vector"])
+ fine = noise(nt, 30, 10, 0.7, mp.outputs[0])
+ g = mix(nt, fine_mix, wave.outputs["Fac"], fine.outputs["Fac"])
+ col = ramp(nt, [(0.2, dark), (0.85, light)], g)
+ b = bsdf(nt)
+ blot = noise(nt, 1.3, 3, 0.5, co)
+ rough = ramp(nt, [(0.35, (gloss * 0.45,) * 3), (0.7, (gloss * 1.9,) * 3)], blot.outputs["Fac"]).outputs["Color"]
+ base = col.outputs["Color"]
+ if wear:
+ # Cup rings: thin bands of voronoi distance, a few per metre.
+ # Two sets: glass rings (~3.5 cm radius) and bowl rings (~6 cm), each on about half the cells.
+ for sc_, band, sel in ((3.0, 0.105, 0.5), (1.7, 0.1, 0.62)):
+ vor = node(nt, "ShaderNodeTexVoronoi", Scale=sc_, Randomness=1.0)
+ L(nt, co, vor.inputs["Vector"])
+ ring = ramp(nt, [(0.0, (0, 0, 0)), (band - 0.008, (0, 0, 0)), (band, (1, 1, 1)), (band + 0.012, (0, 0, 0))], vor.outputs["Distance"])
+ rsel = ramp(nt, [(0.0, (0, 0, 0)), (sel, (0, 0, 0)), (sel + 0.02, (1, 1, 1))], vor.outputs["Color"])
+ rings = mathn(nt, "MULTIPLY", ring.outputs["Color"], rsel.outputs["Color"])
+ base = mix(nt, mathn(nt, "MULTIPLY", rings, 0.7), base, (0.02, 0.01, 0.005, 1))
+ # Worn edges: where the bevelled normal departs from the true normal, the finish is rubbed through.
+ bv = nt.nodes.new("ShaderNodeBevel")
+ bv.inputs["Radius"].default_value = 0.006
+ geo = nt.nodes.new("ShaderNodeNewGeometry")
+ dot = nt.nodes.new("ShaderNodeVectorMath")
+ dot.operation = "DOT_PRODUCT"
+ L(nt, bv.outputs[0], dot.inputs[0])
+ L(nt, geo.outputs["Normal"], dot.inputs[1])
+ edge = ramp(nt, [(0.9, (1, 1, 1)), (0.985, (0, 0, 0))], dot.outputs["Value"])
+ base = mix(nt, mathn(nt, "MULTIPLY", edge.outputs["Color"], 0.8), base, (0.36, 0.22, 0.12, 1))
+ rough = mix(nt, edge.outputs["Color"], rough, (0.75, 0.75, 0.75, 1))
+ # Edge wear lightens high-traffic zones (low-frequency noise).
+ base = mix(nt, mathn(nt, "MULTIPLY", ramp(nt, [(0.55, (0, 0, 0)), (0.8, (1, 1, 1))], noise(nt, 2.0, 4, 0.5, co).outputs["Fac"]).outputs["Color"], 0.35), base, (0.32, 0.2, 0.11, 1))
+ L(nt, base, b.inputs["Base Color"])
+ L(nt, rough, b.inputs["Roughness"])
+ b.inputs["Coat Weight"].default_value = 0.15
+ b.inputs["Coat Roughness"].default_value = 0.25
+ L(nt, bump(nt, g, bump_k, 0.002).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def m_concrete_wet(name="concrete_wet"):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt)
+ n1 = noise(nt, 6, 10, 0.65, co)
+ col = ramp(nt, [(0.3, (0.035, 0.034, 0.032)), (0.7, (0.11, 0.105, 0.095))], n1.outputs["Fac"])
+ puddle = ramp(nt, [(0.48, (0.0,) * 3), (0.56, (1.0,) * 3)], noise(nt, 0.9, 3, 0.5, co).outputs["Fac"])
+ b = bsdf(nt)
+ L(nt, mix(nt, mathn(nt, "MULTIPLY", puddle.outputs["Color"], 0.5), col.outputs["Color"], (0.015, 0.015, 0.014, 1)), b.inputs["Base Color"])
+ rough = mix(nt, puddle.outputs["Color"], (0.7, 0.7, 0.7, 1), (0.08, 0.08, 0.08, 1))
+ L(nt, rough, b.inputs["Roughness"])
+ L(nt, bump(nt, noise(nt, 60, 8, 0.7, co).outputs["Fac"], 0.25, 0.003).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def m_stainless(name="stainless", brushed_axis="X", smudge=0.6, dark=False):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt)
+ mp = nt.nodes.new("ShaderNodeMapping")
+ L(nt, co, mp.inputs["Vector"])
+ mp.inputs["Scale"].default_value = {"X": (1, 400, 400), "Y": (400, 1, 400), "Z": (400, 400, 1)}[brushed_axis]
+ brush = noise(nt, 1.0, 4, 0.5, mp.outputs[0])
+ smear = noise(nt, 2.5, 6, 0.6, co)
+ b = bsdf(nt)
+ b.inputs["Metallic"].default_value = 1.0
+ c = (0.42, 0.42, 0.43, 1) if dark else (0.62, 0.62, 0.63, 1)
+ grease = ramp(nt, [(0.45, (0, 0, 0)), (0.75, (1, 1, 1))], smear.outputs["Fac"])
+ L(nt, mix(nt, mathn(nt, "MULTIPLY", grease.outputs["Color"], 0.5 * smudge), c, (0.25, 0.22, 0.17, 1)), b.inputs["Base Color"])
+ r = ramp(nt, [(0.0, (0.18,) * 3), (1.0, (0.42,) * 3)], mix(nt, 0.5, brush.outputs["Fac"], grease.outputs["Color"]))
+ L(nt, r.outputs["Color"], b.inputs["Roughness"])
+ b.inputs["Anisotropic"].default_value = 0.5
+ return m
+
+
+def m_glass_rain(name="glass_rain", tint=(0.9, 0.95, 0.95)):
+ """Door/window glass with raindrops (voronoi bumps) and a streaky dirty film."""
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt)
+ vor = node(nt, "ShaderNodeTexVoronoi", Scale=45.0, Randomness=1.0)
+ vor.feature = "SMOOTH_F1" if hasattr(vor, "feature") else vor.feature
+ L(nt, co, vor.inputs["Vector"])
+ drop = ramp(nt, [(0.0, (1, 1, 1)), (0.3, (0, 0, 0))], vor.outputs["Distance"])
+ mask = ramp(nt, [(0.55, (0, 0, 0)), (0.6, (1, 1, 1))], vor.outputs["Color"])
+ h = mathn(nt, "MULTIPLY", drop.outputs["Color"], mask.outputs["Color"])
+ b = bsdf(nt)
+ b.inputs["Base Color"].default_value = (*tint, 1)
+ b.inputs["Transmission Weight"].default_value = 1.0
+ b.inputs["IOR"].default_value = 1.45
+ film = noise(nt, 3, 6, 0.6, co)
+ L(nt, ramp(nt, [(0.3, (0.02,) * 3), (0.8, (0.12,) * 3)], film.outputs["Fac"]).outputs["Color"], b.inputs["Roughness"])
+ L(nt, bump(nt, h, 0.6, 0.002).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def m_simple(name, color, rough=0.5, metal=0.0, coat=0.0, trans=0.0, ior=1.45, emission=None, estr=0.0, alpha=1.0):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ b = bsdf(nt)
+ b.inputs["Base Color"].default_value = (*color, 1)
+ b.inputs["Roughness"].default_value = rough
+ b.inputs["Metallic"].default_value = metal
+ b.inputs["Coat Weight"].default_value = coat
+ b.inputs["Transmission Weight"].default_value = trans
+ b.inputs["IOR"].default_value = ior
+ b.inputs["Alpha"].default_value = alpha
+ if emission:
+ b.inputs["Emission Color"].default_value = (*emission, 1)
+ b.inputs["Emission Strength"].default_value = estr
+ return m
+
+
+def m_image(name, path, rough=0.7, emission=0.0, translucent=0.0, alpha_from_image=False, bump_strength=0.0):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ tex = nt.nodes.new("ShaderNodeTexImage")
+ tex.image = bpy.data.images.load(path, check_existing=True)
+ b = bsdf(nt)
+ L(nt, tex.outputs["Color"], b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = rough
+ if emission:
+ L(nt, tex.outputs["Color"], b.inputs["Emission Color"])
+ b.inputs["Emission Strength"].default_value = emission
+ if translucent:
+ b.inputs["Subsurface Weight"].default_value = 0.0
+ tr = nt.nodes.new("ShaderNodeBsdfTranslucent")
+ L(nt, tex.outputs["Color"], tr.inputs["Color"])
+ mx = nt.nodes.new("ShaderNodeMixShader")
+ mx.inputs[0].default_value = translucent
+ out = nt.nodes["Material Output"]
+ L(nt, b.outputs[0], mx.inputs[1])
+ L(nt, tr.outputs[0], mx.inputs[2])
+ L(nt, mx.outputs[0], out.inputs["Surface"])
+ if bump_strength:
+ bw = nt.nodes.new("ShaderNodeRGBToBW")
+ L(nt, tex.outputs["Color"], bw.inputs[0])
+ L(nt, bump(nt, bw.outputs[0], bump_strength, 0.002).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def m_tile(name="tile_white"):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt, "UV") # brick is 2D (ignores Z of object coords), so use the world-scale box UVs
+ br = node(nt, "ShaderNodeTexBrick", Scale=1.0, **{"Mortar Size": 0.012, "Brick Width": 0.1, "Row Height": 0.1})
+ br.offset = 0.0
+ L(nt, co, br.inputs["Vector"])
+ br.inputs["Color1"].default_value = (0.78, 0.77, 0.72, 1)
+ br.inputs["Color2"].default_value = (0.72, 0.71, 0.66, 1)
+ br.inputs["Mortar"].default_value = (0.13, 0.1, 0.06, 1) # stained grout
+ grime = noise(nt, 1.5, 5, 0.55, co)
+ b = bsdf(nt)
+ L(nt, mix(nt, mathn(nt, "MULTIPLY", grime.outputs["Fac"], 0.45), br.outputs["Color"], (0.35, 0.28, 0.17, 1), "MULTIPLY"), b.inputs["Base Color"])
+ L(nt, ramp(nt, [(0.0, (0.08,) * 3), (1.0, (0.6,) * 3)], br.outputs["Fac"]).outputs["Color"], b.inputs["Roughness"])
+ L(nt, bump(nt, mathn(nt, "SUBTRACT", 1.0, br.outputs["Fac"]), 0.4, 0.003).outputs[0], b.inputs["Normal"])
+ return m
+
+
+# ---------------------------------------------------------------- lights
+
+def area(name, c, loc, rot, size, energy, color=(1, 1, 1), shape="RECTANGLE", size_y=None, spread=180):
+ d = bpy.data.lights.new(name, "AREA")
+ d.shape = shape
+ d.size = size
+ if size_y:
+ d.size_y = size_y
+ d.energy = energy
+ d.color = color
+ d.spread = math.radians(spread)
+ o = bpy.data.objects.new(name, d)
+ c.objects.link(o)
+ o.location = loc
+ o.rotation_euler = rot
+ # Fill/glow cards must not show up as white rectangles, directly or refracted through the rough door glass.
+ o.visible_camera = False
+ o.visible_transmission = False
+ return o
+
+
+def point(name, c, loc, energy, color=(1, 0.75, 0.45), radius=0.03):
+ d = bpy.data.lights.new(name, "POINT")
+ d.energy = energy
+ d.color = color
+ d.shadow_soft_size = radius
+ o = bpy.data.objects.new(name, d)
+ c.objects.link(o)
+ o.location = loc
+ return o
+
+
+def spot(name, c, loc, rot, energy, color=(1, 0.75, 0.45), angle=110, blend=0.6, radius=0.02):
+ d = bpy.data.lights.new(name, "SPOT")
+ d.energy = energy
+ d.color = color
+ d.spot_size = math.radians(angle)
+ d.spot_blend = blend
+ d.shadow_soft_size = radius
+ o = bpy.data.objects.new(name, d)
+ c.objects.link(o)
+ o.location = loc
+ o.rotation_euler = rot
+ return o
+
+
+def blackbody(k):
+ """Approximate RGB for a colour temperature (for light colours without nodes)."""
+ t = k / 100.0
+ r = 255 if t <= 66 else 329.7 * (t - 60) ** -0.1332
+ g = 99.47 * math.log(t) - 161.12 if t <= 66 else 288.1 * (t - 60) ** -0.0755
+ b = 255 if t >= 66 else (0 if t <= 19 else 138.5 * math.log(t - 10) - 305.04)
+ return tuple(max(0, min(255, x)) / 255 for x in (r, g, b))
diff --git a/scenes/hk-dai-pai-dong/scripts/lights.py b/scenes/hk-dai-pai-dong/scripts/lights.py
new file mode 100644
index 0000000..a291c89
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/lights.py
@@ -0,0 +1,219 @@
+"""Night lighting: practicals first (bulbs, wok flames, enamel shade, fluorescent), then signage spill, street lamp,
+lit shopfront security tubes, and last a weak sky/bounce fill. Each light gets ["cat"] and ["order"] so the
+breakdown's lighting clip can switch them on in a sensible order.
+
+Gotchas carried over: area lights shine along local -Z; fills are hidden from camera/glossy/transmission;
+emission on dense generated meshes gets emission_sampling NONE (see emitters.run()).
+"""
+import math
+
+import bpy
+from mathutils import Vector
+
+import shell as S
+from lib import L, area, blackbody, bsdf, coll, mathn, new_mat, node, noise, point, ramp, spot, texcoord
+
+ORDER = []
+WARM = blackbody(2500)
+
+
+def tag(o, cat):
+ o["cat"] = cat
+ o["order"] = len(ORDER)
+ ORDER.append(o.name)
+ return o
+
+
+def awning_z(x):
+ a = S.AWN
+ u = (x - a["x0"]) / (a["x1"] - a["x0"])
+ return a["z_wall"] + (a["z_edge"] - a["z_wall"]) * u - 0.05 * math.sin(math.pi * u)
+
+
+def m_bulb():
+ m, nt = new_mat("bulb_glow")
+ if nt:
+ b = bsdf(nt)
+ b.inputs["Base Color"].default_value = (*WARM, 1)
+ b.inputs["Emission Color"].default_value = (*WARM, 1)
+ b.inputs["Emission Strength"].default_value = 18.0 # 60 burnt out to a white disc
+ return m
+
+
+def bulb(name, c, x, y, z_bottom, energy=30.0):
+ """Bare bulb on a black cord from the awning: emissive glass + a point light."""
+ from shell import rod
+ top = awning_z(x) - 0.02
+ cord = rod(name + "_cord", (x, y, top), (x, y, z_bottom + 0.1), 0.004, c, S.m_simple("cord", (0.01, 0.01, 0.01), 0.4))
+ sock = rod(name + "_socket", (x, y, z_bottom + 0.1), (x, y, z_bottom + 0.06), 0.014, c, S.m_simple("socket", (0.03, 0.025, 0.02), 0.5, 0.3))
+ bpy.ops.mesh.primitive_uv_sphere_add(radius=0.03, segments=16, ring_count=10, location=(x, y, z_bottom + 0.03))
+ g = bpy.context.object
+ g.name = name + "_glass"
+ for uc in list(g.users_collection):
+ uc.objects.unlink(g)
+ c.objects.link(g)
+ g.scale.z = 1.25
+ g.data.materials.append(m_bulb())
+ bpy.ops.object.shade_smooth()
+ p = point(name, c, (x, y, z_bottom + 0.035), energy, WARM, radius=0.025)
+ p.data.use_soft_falloff = False
+ return tag(p, "practical"), g
+
+
+def m_flame(name):
+ """Gas jet flame as a volume: blue core near the burner, orange licks up the wok, animated noise."""
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ nt.nodes.remove(bsdf(nt))
+ gen = texcoord(nt, "Generated")
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ L(nt, gen, sep.inputs[0])
+ # Radial distance from the axis in generated space (0..1 box -> centre 0.5).
+ dx = mathn(nt, "SUBTRACT", sep.outputs["X"], 0.5)
+ dy = mathn(nt, "SUBTRACT", sep.outputs["Y"], 0.5)
+ r = mathn(nt, "SQRT", mathn(nt, "ADD", mathn(nt, "MULTIPLY", dx, dx), mathn(nt, "MULTIPLY", dy, dy)))
+ z = sep.outputs["Z"]
+ # Tongues hug the outside of the wok bowl (generated space: box radius 0.36 m, 0.3 m tall; wok bottom at z 0.3,
+ # well rim at 0.5, bowl radius ~0.19 m there and ~0.27 m at z 0.7), half-width ~4 cm. A wider ring stood off the
+ # bowl as an orange curtain around the rim.
+ ring_r = mathn(nt, "ADD", -0.025, mathn(nt, "MULTIPLY", z, 0.56))
+ ring = mathn(nt, "SUBTRACT", 1.0, mathn(nt, "MULTIPLY", mathn(nt, "ABSOLUTE", mathn(nt, "SUBTRACT", r, ring_r)), 18.0), clamp=True)
+ # Animated noise, stretched vertically into tongues, scrolling upward fast.
+ co = texcoord(nt, "Object")
+ mp = nt.nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (1.0, 1.0, 0.12)
+ L(nt, co, mp.inputs["Vector"])
+ mp.inputs["Location"].driver_add("default_value", 2).driver.expression = "-frame * 0.012"
+ n = noise(nt, 34.0, 3, 0.55, mp.outputs[0], dim="4D")
+ n.inputs["W"].driver_add("default_value").driver.expression = "frame * 0.16"
+ lick = ramp(nt, [(0.55, (0, 0, 0)), (0.6, (1, 1, 1))], n.outputs["Fac"]).outputs["Color"]
+ # Full strength under the wok, dying out ~5 cm above the well rim (z 0.68): tongues lick the lower bowl only.
+ t = mathn(nt, "MULTIPLY", mathn(nt, "SUBTRACT", z, 0.42), 3.8, clamp=True)
+ fall = mathn(nt, "POWER", mathn(nt, "SUBTRACT", 1.0, t, clamp=True), 1.5)
+ # Blue jets at the well mouth, broken up by the same noise (a continuous band read as a ring sheet).
+ base = mathn(nt, "SUBTRACT", 1.0, mathn(nt, "MULTIPLY", mathn(nt, "ABSOLUTE", mathn(nt, "SUBTRACT", z, 0.45)), 14.0), clamp=True)
+ jets = ramp(nt, [(0.38, (0, 0, 0)), (0.55, (1, 1, 1))], n.outputs["Fac"]).outputs["Color"]
+ dens = mathn(nt, "MULTIPLY", ring, mathn(nt, "MAXIMUM", mathn(nt, "MULTIPLY", lick, fall),
+ mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", base, jets), 0.6)))
+ v = nt.nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Density"].default_value = 0.0
+ col = ramp(nt, [(0.0, (0.1, 0.25, 1.0)), (0.44, (0.2, 0.35, 1.0)), (0.5, (1.0, 0.42, 0.06)), (1.0, (1.0, 0.22, 0.02))], z).outputs["Color"]
+ L(nt, col, v.inputs["Emission Color"])
+ L(nt, mathn(nt, "MULTIPLY", dens, 210.0), v.inputs["Emission Strength"])
+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])
+ return m
+
+
+def flames(c, woks):
+ out = []
+ for i, (x, y, z) in enumerate(woks):
+ # Volume box around the burner well and the lower wok bowl.
+ bpy.ops.mesh.primitive_cylinder_add(radius=0.36, depth=0.3, vertices=32, location=(x, y, z))
+ f = bpy.context.object
+ f.name = f"wok_flame_{i}"
+ for uc in list(f.users_collection):
+ uc.objects.unlink(f)
+ c.objects.link(f)
+ f.data.materials.append(m_flame("flame_vol"))
+ f.visible_shadow = False
+ f["no_support"] = True
+ # Orange lick light + blue core light, flickering.
+ o = point(f"wok_fire_{i}", c, (x + 0.12, y, z - 0.02), 55, (1.0, 0.48, 0.15), radius=0.1)
+ d = o.data.driver_add("energy").driver
+ d.expression = f"55*(1+0.28*sin(frame*1.9+{i * 2.1})+0.17*sin(frame*5.3+{i})+0.1*sin(frame*11.7))"
+ tag(o, "practical")
+ b = point(f"wok_blue_{i}", c, (x + 0.1, y, z - 0.08), 12, (0.3, 0.45, 1.0), radius=0.08)
+ tag(b, "practical")
+ out += [f, o, b]
+ return out
+
+
+def build():
+ c = coll("lights")
+ import dress
+ woks = dress.WOKS or [(-3.05, 2.81, 0.85), (-3.05, 3.55, 0.85)]
+ # Bare bulbs under the awning (over the cart, the range end, the prep table, and each pavement table).
+ B = [(-2.35, -0.25, 2.1, 28), (-2.35, 1.5, 2.15, 32), (-2.45, 4.6, 2.1, 30), (-1.05, 0.3, 1.95, 34),
+ (-1.05, 2.75, 2.0, 30), (-1.05, 5.1, 1.95, 30), (-1.8, 6.6, 2.05, 22)]
+ for i, (x, y, z, e) in enumerate(B):
+ bulb(f"bulb_{i}", c, x, y, z, e * 1.6)
+ # Enamel shade over the woks: a spot just under the rim and a glowing bulb inside it.
+ shade = bpy.data.objects.get("wok_shade")
+ if shade:
+ lo, hi = dress.bounds(shade)
+ cx, cy = (lo.x + hi.x) / 2, (lo.y + hi.y) / 2
+ s = spot("wok_shade_spot", c, (cx, cy, lo.z - 0.02), (0, 0, 0), 45, WARM, angle=115, blend=0.5, radius=0.05)
+ tag(s, "practical")
+ bpy.ops.mesh.primitive_uv_sphere_add(radius=0.032, segments=16, ring_count=10, location=(cx, cy, lo.z + 0.035))
+ g = bpy.context.object
+ g.name = "wok_shade_bulb"
+ for uc in list(g.users_collection):
+ uc.objects.unlink(g)
+ c.objects.link(g)
+ g.data.materials.append(m_bulb())
+ flames(coll("flames"), woks)
+ # Fluorescent batten on the wall over the back shelves: cool, slightly green.
+ fl = bpy.data.objects.get("fluoro")
+ if fl:
+ lo, hi = dress.bounds(fl)
+ a = area("fluoro_tube", c, ((lo.x + hi.x) / 2 + 0.05, (lo.y + hi.y) / 2, lo.z - 0.01), (0, math.radians(35), 0),
+ 0.06, 45, (0.82, 1.0, 0.86), size_y=1.15)
+ a.visible_camera = False
+ tag(a, "practical")
+ bpy.ops.mesh.primitive_cylinder_add(radius=0.013, depth=1.15, vertices=12, location=((lo.x + hi.x) / 2 + 0.03, (lo.y + hi.y) / 2, lo.z + 0.015),
+ rotation=(math.radians(90), 0, 0))
+ t = bpy.context.object
+ t.name = "fluoro_tube_glow"
+ for uc in list(t.users_collection):
+ uc.objects.unlink(t)
+ c.objects.link(t)
+ t.data.materials.append(S.m_emit("fluoro_glow", (0.85, 1.0, 0.9), 12))
+ # Signage spill: a soft point light just in front of each neon box / lightbox, in its colour.
+ for o in list(bpy.data.objects):
+ if o.name.startswith("neon_box_") or (o.name.startswith("lightbox_") and o.type == "MESH" and o.name.count("_") == 1):
+ lo, hi = dress.bounds(o)
+ ctr = (lo + hi) / 2
+ if o.name.startswith("neon_box_"):
+ k = o.name.split("_")[-1]
+ mat = bpy.data.materials.get(f"neon_{k}")
+ col = tuple(mat.node_tree.nodes["Principled BSDF"].inputs["Emission Color"].default_value[:3]) if mat else (1, 0.2, 0.3)
+ e = 220
+ else:
+ col, e = (1.0, 0.92, 0.8), 90
+ for sy in (-1, 1):
+ p = point(f"spill_{o.name}_{'f' if sy < 0 else 'b'}", c, (ctr.x, ctr.y + sy * 0.45, ctr.z), e, col, radius=0.35)
+ p.visible_glossy = True
+ tag(p, "signage")
+ # Street lamp: spot at the lamp head, cool LED-white, plus a faint glow.
+ lamp = bpy.data.objects.get("street_lamp")
+ if lamp:
+ lo, hi = dress.bounds(lamp)
+ # The head is at the end of the arm: the bbox corner farthest from the pole base, at the top.
+ base = Vector((lamp.location.x, lamp.location.y))
+ cand = [Vector((lo.x, lo.y)), Vector((lo.x, hi.y)), Vector((hi.x, lo.y)), Vector((hi.x, hi.y))]
+ far = max(cand, key=lambda v: (v - base).length)
+ hx, hy = (far.x + base.x * 0.25) / 1.25, (far.y + base.y * 0.25) / 1.25
+ sp = spot("street_lamp_light", c, (hx, hy, hi.z - 0.25), (0, 0, 0), 2200, (0.86, 0.92, 1.0), angle=125, blend=0.6, radius=0.18)
+ tag(sp, "street")
+ # Shopfront security tubes on the far side (closed shops keep one tube on).
+ for i, y in enumerate((-6.0, 4.0, 13.5, 21.0)):
+ x = S.FX1 - 0.35
+ bpy.ops.mesh.primitive_cylinder_add(radius=0.014, depth=1.2, vertices=10, location=(x, y, 2.95), rotation=(math.radians(90), 0, 0))
+ t = bpy.context.object
+ t.name = f"security_tube_{i}"
+ for uc in list(t.users_collection):
+ uc.objects.unlink(t)
+ c.objects.link(t)
+ t.data.materials.append(S.m_emit("fluoro_glow", (0.85, 1.0, 0.9), 12))
+ a = area(f"security_light_{i}", c, (x - 0.05, y, 2.93), (0, math.radians(-30), 0), 0.08, 30, (0.82, 1.0, 0.88), size_y=1.2)
+ tag(a, "street")
+ # Fills last and weak: cool sky bounce over the street, a warm under-awning bounce off the wet ground.
+ f1 = area("fill_sky", c, (2.5, 2.5, 9.0), (0, 0, 0), 12, 160, (0.55, 0.62, 0.9), size_y=24)
+ f1.visible_glossy = False
+ tag(f1, "fill")
+ f2 = area("fill_awning_bounce", c, (-1.6, 2.8, 0.25), (math.radians(180), 0, 0), 3.0, 12, WARM, size_y=7)
+ f2.visible_glossy = False
+ tag(f2, "fill")
+ bpy.context.scene.view_settings.exposure = 0.4
+ print("LIGHTS", len(ORDER), flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/manifest.py b/scenes/hk-dai-pai-dong/scripts/manifest.py
new file mode 100644
index 0000000..7a1611d
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/manifest.py
@@ -0,0 +1,144 @@
+"""Writes assets.json (the prop manifest). Edit here, re-run: python scenes/hk-dai-pai-dong/scripts/manifest.py"""
+import json
+import os
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+# id, h (m), dims [x,y,z] or None, tier, prompt
+P = [
+ # ---- hero: the kitchen
+ ("hk_kitchen_cart", 1.0, [1.9, 0.85, 1.0], "hero", "A battered Hong Kong dai pai dong street-food kitchen cart: a long low steel cabinet painted dark green with peeling chipped paint, rust streaks and dents, hinged side doors with padlock hasps, a stainless-steel counter top with greasy stains and a raised back splash, small wheels."),
+ ("hk_wok_range", 0.85, [1.5, 0.85, 0.85], "hero", "A Chinese commercial two-hole wok range: a stainless-steel cabinet with two deep cast-iron jet burner rings in round wok wells, a swing water faucet and a gutter along the front, gas valves with long lever handles, heavily blackened, grease-streaked and heat-discoloured."),
+ ("hk_wok_a", 0.2, None, "hero", "A large round-bottomed blackened carbon-steel Cantonese wok, about 45 cm across, with two small riveted loop handles, seasoned and charred outside, glossy oily patina inside."),
+ ("hk_wok_rice", 0.22, None, "hero", "A blackened carbon-steel wok with fried rice with egg, green onion and char siu tossed in it and a long-handled steel wok ladle resting inside, glistening with oil."),
+ ("hk_wok_tools", 0.42, None, "mid", "A Cantonese wok ladle and a wok spatula with long steel shafts and wooden grips, plus a bamboo wok brush, lying together, greasy and worn."),
+ ("hk_spider_strainer", 0.45, None, "mid", "A large wire-mesh spider strainer with a long bamboo handle, brass wire basket darkened with oil."),
+ ("hk_stockpot", 0.45, None, "hero", "A large heavily used aluminium stockpot about 45 cm tall with riveted handles, dented sides, soot and heat discolouration, a warped lid half on."),
+ ("hk_stockpot_small", 0.26, None, "mid", "A medium dented aluminium saucepot with a long handle and a battered lid, soot stains."),
+ ("hk_steamer_stack", 0.32, None, "mid", "A stack of three round bamboo dim sum steamer baskets with a lid, darkened and stained from years of use."),
+ ("hk_claypot", 0.16, None, "mid", "A small glazed Chinese claypot with a lid and a wire handle frame, charred black bottom, for claypot rice."),
+ ("hk_rice_cooker", 0.42, None, "mid", "A big commercial electric rice cooker, dented aluminium body with a domed lid and a side lever, no logo, grimy."),
+ ("hk_tea_urn", 0.55, None, "mid", "A stainless-steel hot water urn with a tap at the front and a domed lid, water stains, plain with no logo."),
+ ("hk_cleaver_block", 0.16, None, "mid", "A thick round tree-trunk chopping block, scarred and concave from use, with a Chinese rectangular cleaver lying on it."),
+ ("hk_hanging_utensils", 0.7, [0.9, 0.12, 0.7], "mid", "A greasy steel rod with S-hooks holding hanging kitchen tools: two ladles, a perforated skimmer, a wire spider strainer, a pair of long bamboo chopsticks and a wok brush."),
+ ("hk_sauce_shelf", 0.42, [0.9, 0.25, 0.42], "mid", "A small greasy two-tier steel wall shelf crowded with sauce bottles and jars: soy sauce, oyster sauce, chili oil, Shaoxing wine, sesame oil, tins of salt, all with plain hand-lettered Chinese paper labels, grimy."),
+ ("hk_oil_tin", 0.34, None, "mid", "A large square tin of cooking oil with a pour spout, dented and oily, label in faded red Chinese text of a fictional brand."),
+ ("hk_lpg_cylinder", 0.75, None, "hero", "A tall grey steel LPG gas cylinder with a valve guard collar, a regulator and an orange rubber gas hose, scuffed and rusty at the base, no brand."),
+ ("hk_veg_basket", 0.24, None, "mid", "A red plastic basket heaped with fresh choy sum greens and spring onions, water drops."),
+ ("hk_prawn_tray", 0.07, None, "mid", "A stainless-steel tray of raw grey prawns and sliced squid on ice."),
+ ("hk_aromatics_bowls", 0.1, None, "mid", "Three small stainless bowls of chopped garlic, sliced ginger and red chilli, a wet spoon."),
+ ("hk_bowl_stack", 0.3, None, "mid", "A tall stack of white Chinese melamine rice bowls with a thin blue rim pattern, slightly scratched."),
+ ("hk_plate_stack", 0.22, None, "mid", "A stack of oval white melamine serving plates with a red border pattern, scratched."),
+ ("hk_dish_rack", 0.45, None, "mid", "A stainless wire dish drying rack full of wet white bowls and plates and a cluster of chopsticks."),
+ ("hk_wash_basin", 0.3, None, "mid", "A big round red plastic wash basin full of soapy water and dirty bowls and plates."),
+ ("hk_tub_blue", 0.3, None, "mid", "A large blue plastic storage tub with a loose lid, scuffed."),
+ ("hk_crate_stack", 0.6, None, "mid", "Two stacked worn plastic bread crates, one blue and one red, holding cabbages and bags of bean sprouts."),
+ ("hk_styrofoam_box", 0.3, None, "mid", "A white styrofoam cooler box with a lid, taped with brown tape, dirty and dented, handwritten Chinese marker on the side."),
+ ("hk_rice_sack", 0.55, None, "mid", "A woven white polypropylene 25 kg rice sack, slumped, printed with a fictional red Chinese rice brand and a green field emblem."),
+ ("hk_cardboard_boxes", 0.6, None, "mid", "A stack of three worn wet-cornered cardboard produce boxes printed with fictional Chinese supplier names."),
+ ("hk_jars_preserved", 0.25, None, "mid", "Three big glass jars of preserved vegetables and pickled chillies with red plastic lids."),
+ ("hk_thermos", 0.36, None, "mid", "A vintage Chinese tin thermos flask painted red with a peony flower pattern and a cork stopper, chipped paint."),
+ ("hk_takeaway_boxes", 0.22, None, "clutter", "A stack of white foam takeaway clamshell boxes and a roll of thin red-and-white striped plastic bags."),
+ ("hk_fan", 0.55, None, "mid", "An old oscillating electric table fan with a cream metal cage and grime on the blades, no logo."),
+ ("hk_radio", 0.16, None, "clutter", "A small old transistor radio with a silver telescopic antenna, cracked plastic case, fictional brand name."),
+ ("hk_fire_extinguisher", 0.55, None, "mid", "A red dry-powder fire extinguisher with a black hose and a Chinese instruction label, dusty."),
+ ("hk_menu_board_a", 0.9, [0.6, 0.03, 0.9], "mid", "A weathered wooden menu board painted cream with red and black hand-brushed Chinese dish names and prices in vertical columns, rain-stained."),
+ ("hk_menu_board_b", 0.5, [0.8, 0.03, 0.5], "mid", "A faded yellow plastic menu sign with handwritten red Chinese dish names and prices in marker, curling tape at the corners."),
+ ("hk_enamel_shade", 0.18, None, "mid", "A dark green enamel industrial lamp shade with a bare tungsten bulb and a cloth-covered cord, chipped enamel, rust."),
+ ("hk_fluoro_fitting", 0.08, [1.25, 0.12, 0.08], "mid", "A bare single fluorescent tube light fitting with a white metal batten, dusty and spotted with grease."),
+ # ---- seating & tables
+ ("hk_table_round", 0.74, [0.95, 0.95, 0.74], "hero", "A Hong Kong folding round dining table with a scratched stainless-steel top and a thin rolled rim, folding steel tube legs, worn and wet with raindrops."),
+ ("hk_table_square", 0.72, [0.75, 0.75, 0.72], "mid", "A small square folding table with a green laminated top with chipped edges and folding steel legs, wet."),
+ ("hk_stool_red", 0.45, None, "hero", "A classic red plastic stool with a round seat with a hand hole in the middle and four splayed legs, scuffed and slightly faded, raindrops."),
+ ("hk_stool_stack", 0.95, None, "mid", "A leaning stack of six red plastic stools, scuffed, wet."),
+ ("hk_stool_blue", 0.45, None, "mid", "A blue plastic square stool with a perforated seat, scuffed and faded."),
+ # ---- on the tables
+ ("hk_enamel_teapot", 0.2, None, "hero", "A white enamel teapot with a red peony flower pattern, chipped black edges and a bail handle, tea stains."),
+ ("hk_tea_cups", 0.08, None, "mid", "Four small thick white restaurant tea cups and a plastic bowl of hot water for rinsing chopsticks."),
+ ("hk_condiment_caddy", 0.2, None, "hero", "A small stainless steel condiment caddy holding a soy sauce bottle, a chilli oil jar with a spoon, a white pepper shaker and a toothpick holder, greasy, plain labels."),
+ ("hk_soy_bottles", 0.24, None, "mid", "Two glass sauce dispenser bottles with red plastic caps, one with dark soy sauce, one with red vinegar, smeared."),
+ ("hk_chopstick_cup", 0.24, None, "mid", "A dented stainless-steel cylinder cup full of bamboo chopsticks and a few white plastic soup spoons."),
+ ("hk_toilet_roll", 0.12, None, "clutter", "A roll of pink toilet paper used as napkins sitting in a plastic holder, slightly damp."),
+ ("hk_newspaper", 0.03, None, "mid", "A folded Chinese-language racing newspaper with horse racing tables and photos, creased, a pen lying on it, fictional masthead."),
+ ("hk_dish_fried_rice", 0.08, None, "mid", "An oval white plate of Yangzhou fried rice with shrimp, egg and char siu, half eaten, a porcelain spoon in it."),
+ ("hk_dish_beef_hofun", 0.08, None, "mid", "An oval plate of dry-fried beef ho fun flat rice noodles with bean sprouts and spring onion, glossy dark."),
+ ("hk_dish_clams", 0.08, None, "mid", "A plate of stir-fried clams in black bean and chilli sauce, shells open, glistening."),
+ ("hk_dish_greens", 0.06, None, "mid", "A plate of blanched choy sum greens with oyster sauce drizzled over."),
+ ("hk_dish_salt_squid", 0.08, None, "mid", "A plate of salt and pepper fried squid with fried garlic and red chilli."),
+ ("hk_milk_tea", 0.14, None, "clutter", "A thick white Hong Kong cha chaan teng mug of milk tea, tan colour, on a saucer."),
+ ("hk_lemon_tea", 0.17, None, "clutter", "A tall glass of iced lemon tea with lemon slices, ice and a straw, condensation."),
+ ("hk_beer_bottles", 0.3, None, "mid", "Two large green beer bottles with a fictional label reading 金龍啤酒 and a short glass of beer with foam."),
+ ("hk_beer_crate", 0.32, None, "mid", "A yellow plastic beer crate holding twelve empty green bottles with fictional labels."),
+ ("hk_ashtray", 0.04, None, "clutter", "A crushed tin ashtray with cigarette butts and ash."),
+ ("hk_bowl_congee", 0.1, None, "clutter", "A white melamine bowl of congee with century egg and green onion and a plastic spoon."),
+ # ---- street
+ ("hk_street_lamp", 8.5, None, "hero", "A tall grey steel Hong Kong street lamp post with a long curved outreach arm and a flat rectangular lantern head, rust streaks, small numbered plate."),
+ ("hk_guard_railing", 1.0, [2.0, 0.1, 1.0], "mid", "A section of Hong Kong roadside pedestrian guard railing: grey painted steel tube railing with vertical bars between two posts, chipped paint, rust."),
+ ("hk_water_barrier", 0.8, [1.3, 0.45, 0.8], "mid", "A plastic water-filled road barrier, alternating red and white, dirty, scuffed, rain wet."),
+ ("hk_traffic_cone", 0.7, None, "clutter", "An orange traffic cone with reflective white bands, dirty and scuffed."),
+ ("hk_parked_car", 1.45, [1.75, 4.4, 1.45], "hero", "A generic 1990s boxy four-door saloon car in dark red, rain-wet, no badges, no logos, no number plate text, dirt on the sills."),
+ ("hk_scooter", 1.15, None, "mid", "A small generic delivery motor scooter with a delivery box on the back, no logos, wet, scuffed."),
+ ("hk_hand_trolley", 1.1, None, "mid", "A steel two-wheel hand trolley loaded with flattened cardboard and a crate, straps, worn."),
+ ("hk_trash_bin", 0.95, None, "mid", "A large green plastic wheelie rubbish bin with the lid half open, a black bag poking out, grimy."),
+ ("hk_bin_bags", 0.6, None, "clutter", "Three tied black rubbish bags in a heap, wet and glossy."),
+ ("hk_umbrella", 0.9, None, "clutter", "A closed wet black folding umbrella leaning, slightly crumpled."),
+ ("hk_shrine", 0.5, None, "mid", "A small red Chinese street shrine box for the earth god on the ground with a gold inscription, incense sticks in a pot, oranges and a small cup, burnt candle wax."),
+ ("hk_aircon_unit", 0.4, [0.66, 0.6, 0.4], "mid", "An old window air conditioner unit, beige metal case with rust stains and a grille, dripping water, no logo."),
+ ("hk_electric_box", 0.55, [0.45, 0.2, 0.55], "mid", "A grey steel electrical meter box on a wall with conduits coming out, rusty, a few stickers with Chinese text, no brand."),
+ ("hk_mop_bucket", 0.7, None, "clutter", "A grey mop leaning in a battered red plastic bucket."),
+ ("hk_plastic_bag_hang", 0.4, None, "clutter", "A red-and-white striped thin plastic shopping bag hanging from a hook with something heavy inside."),
+ ("hk_bird_cage", 0.45, None, "clutter", "A round bamboo bird cage with a cloth cover partly lifted, hanging hook on top."),
+ ("hk_water_bucket", 0.32, None, "clutter", "A battered aluminium bucket half full of water."),
+]
+
+TEX = [
+ ("hk_tex_skyline", "landscape_16_9", "Wide night photograph across a harbour toward a dense high-rise city skyline on the far shore, very soft and out of focus as if shot through rain with a long lens, lights reduced to soft blurred bokeh, low clouds glowing orange and magenta from the city lights, misty, no recognisable landmark towers, no readable text."),
+ ("hk_tex_facade_a", "portrait_16_9", "Straight-on orthographic elevation photograph of an old 1960s Hong Kong tenement building facade at night, six floors of windows with rusty metal grilles, a few warm lit windows, laundry poles, air conditioner units, mould stains on grey-green mosaic tiles, flat front view, no perspective, no signs, no text."),
+ ("hk_tex_facade_b", "portrait_16_9", "Straight-on orthographic elevation photograph of an old Hong Kong residential tenement facade at night, cream painted concrete stained with black rain streaks, rows of aluminium windows with security grilles, potted plants on ledges, two lit windows with fluorescent light, flat front view, no perspective, no signs, no text."),
+ ("hk_tex_facade_c", "portrait_16_9", "Straight-on orthographic elevation photograph of a narrow old Hong Kong tenement at night with enclosed balconies with metal cages, faded pink paint, water stains, a few lit windows, hanging laundry, flat front view, no perspective, no signs, no text."),
+ ("hk_tex_shutter_a", "landscape_4_3", "Flat straight-on photo of a closed corrugated steel roller shutter of a Hong Kong shop at night, grey, dented, rust streaks, a small padlock at the bottom, flat lit, fills the frame, no readable shop name."),
+ ("hk_tex_shutter_b", "landscape_4_3", "Flat straight-on photo of a closed green-painted roller shutter of a Hong Kong hardware shop, peeling paint, old paper notices taped on it with handwritten Chinese, rust, fills the frame."),
+ ("hk_tex_stall_sign", "landscape_16_9", "Flat front view of a weathered painted shop sign board for a Hong Kong street-food stall: cream background, large red brush-calligraphy Chinese characters 旺記小炒 on the left and smaller black vertical columns of dish names on the right, rust stains, grease, chipped edges, fills the frame exactly, fictional business."),
+ ("hk_tex_posters", "square_hd", "Flat lay of six weathered torn paper posters and notices on a white background, spaced apart: a Chinese opera performance poster with fictional names, a handwritten room-for-rent notice 吉房出租, a plumbing service sticker with a phone number, a faded movie poster with a fictional title, a missing cat notice, a lucky red paper with gold characters. Fictional text only."),
+ ("hk_tex_menu_strips", "landscape_16_9", "Flat front view of a row of twelve vertical red and yellow paper menu strips with hand-brushed black Chinese dish names and prices like 豉椒炒蜆 $68 and 乾炒牛河 $62, taped side by side on a wall, grease spots, fills the frame."),
+ ("hk_tex_lightbox_a", "portrait_4_3", "Flat front view of a vertical Hong Kong shop lightbox sign, white panel with large red Chinese characters 長發飯店 and a thin green border, slightly dirty, evenly backlit, fills the frame, fictional business, no other text."),
+ ("hk_tex_lightbox_b", "portrait_4_3", "Flat front view of a vertical Hong Kong lightbox sign, yellow panel with large black Chinese characters 和興五金 and a red stripe, dirty, evenly backlit, fills the frame, fictional business."),
+ ("hk_tex_lightbox_c", "portrait_4_3", "Flat front view of a vertical Hong Kong lightbox sign, blue panel with white Chinese characters 美珍冰室 and a painted coffee cup icon, dirty, evenly backlit, fills the frame, fictional business."),
+ ("hk_tex_asphalt", "square_hd", "Top-down seamless texture of wet old asphalt road surface with dark puddles, oil sheen, cracks and patched areas, overcast flat lighting, no markings."),
+ ("hk_tex_pavement", "square_hd", "Top-down seamless texture of Hong Kong pavement made of small square grey and red concrete paving bricks, wet, worn, stained, chewing gum spots, flat lighting."),
+]
+
+
+# De-branded regenerations: the reference of the original showed a brand (checked on the ref sheet).
+NB_REGEN = {
+ "hk_beer_crate": "A yellow plastic beer crate holding twelve empty green beer bottles, the crate moulded with the fictional Chinese brewery name 金龍啤酒 only, no English text, scuffed and dirty.",
+}
+
+NB = "No real-world brand names or logos."
+SCAN = NB + " Product reference photograph for 3D scanning. The entire object fully visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft even diffuse studio lighting, no harsh shadows, no other objects, no hands, realistic used and worn condition, sharp focus, true-to-life materials."
+
+# Lying-flat props: size by their longest dimension ("m"), not their height.
+M_SIZE = {"hk_wok_tools": 0.5, "hk_spider_strainer": 0.55, "hk_umbrella": 0.95}
+gen = []
+for pid, h, dims, tier, prompt in P:
+ e = {"id": pid, "h": h, "tier": tier, "prompt": prompt}
+ if pid in M_SIZE:
+ e.pop("h")
+ e["m"] = M_SIZE[pid]
+ if dims:
+ e["dims"] = dims
+ gen.append(e)
+for pid, prompt in NB_REGEN.items():
+ base = next(e for e in gen if e["id"] == pid)
+ gen.append({**base, "id": pid + "_nb", "replaces": pid, "prompt": prompt})
+out = {
+ "room": {"kind": "street", "width_x": 13.6, "depth_y": 50, "height_z": 22,
+ "note": "Semi-outdoor. Street along +Y. Stall-side facade x=-4, pavement x -4..0 (z 0), kerb x=0, road x 0..7.4 (z -0.15), far pavement to x 9.6, far facade x 9.6. See brief.md."},
+ "scan_template": SCAN,
+ "generate": gen,
+ "textures": [{"id": i, "size": s, "prompt": p + " " + NB} for i, s, p in TEX],
+ "direct": ["street/road/kerb/pavement", "tenement facades, windows, balconies", "awning frame + corrugated tarp", "steel shelves",
+ "bare bulbs + cords", "neon text (msjh.ttc text objects)", "drains, puddles", "wok flames", "cables"],
+}
+if __name__ == "__main__":
+ json.dump(out, open(os.path.join(HERE, "..", "assets.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False)
+ print(len(gen), "props,", len(TEX), "textures")
diff --git a/scenes/hk-dai-pai-dong/scripts/pick.mjs b/scenes/hk-dai-pai-dong/scripts/pick.mjs
new file mode 100644
index 0000000..db6bb58
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/pick.mjs
@@ -0,0 +1,8 @@
+// node scenes/tokyo-ramen-shop/scripts/pick.mjs id model "reason" [id model "reason" ...] -> merges into scenes/hk-dai-pai-dong/picks.json
+import { readFileSync, writeFileSync } from 'node:fs';
+const f = new URL('../picks.json', import.meta.url);
+const p = JSON.parse(readFileSync(f, 'utf8'));
+const a = process.argv.slice(2);
+for (let i = 0; i < a.length; i += 3) p[a[i]] = { model: a[i + 1], reason: a[i + 2] };
+writeFileSync(f, JSON.stringify(p, null, 2));
+console.log(Object.keys(p).length, 'picks');
diff --git a/scenes/hk-dai-pai-dong/scripts/post.py b/scenes/hk-dai-pai-dong/scripts/post.py
new file mode 100644
index 0000000..aa8a025
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/post.py
@@ -0,0 +1,38 @@
+"""Render settings and the light compositor (Glare only; the grade is ffmpeg, see grade.sh).
+Also turns off light-sampling on emissive dense generated meshes."""
+import bpy
+
+import emitters
+
+
+def build():
+ sc = bpy.context.scene
+ sc.cycles.samples = 56
+ sc.cycles.use_denoising = True
+ sc.cycles.denoiser = "OPTIX"
+ sc.cycles.volume_step_rate = 4.0 # haze/steam: coarser steps, fine at 48-64 spp with the denoiser
+ sc.cycles.volume_preview_step_rate = 4.0
+ sc.cycles.volume_max_steps = 256
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "AgX - Medium High Contrast"
+ sc.render.use_motion_blur = True
+ sc.render.motion_blur_shutter = 0.5
+ emitters.run()
+ emitters.no_volume_blur()
+ # Compositor: glare (fog glow) on the bulbs and neon.
+ tree = bpy.data.node_groups.new("hk_comp", "CompositorNodeTree")
+ sc.compositing_node_group = tree
+ rl = tree.nodes.new("CompositorNodeRLayers")
+ gl = tree.nodes.new("CompositorNodeGlare")
+ try:
+ gl.inputs["Type"].default_value = "Fog Glow"
+ except Exception:
+ gl.glare_type = "FOG_GLOW"
+ for k, v in (("Threshold", 1.2), ("Strength", 0.35), ("Size", 0.6)):
+ if k in gl.inputs:
+ gl.inputs[k].default_value = v
+ out = tree.nodes.new("NodeGroupOutput")
+ tree.interface.new_socket("Image", in_out="OUTPUT", socket_type="NodeSocketColor")
+ tree.links.new(rl.outputs["Image"], gl.inputs["Image"])
+ tree.links.new(gl.outputs["Image"], out.inputs[0])
+ print("POST done", flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/prep.py b/scenes/hk-dai-pai-dong/scripts/prep.py
new file mode 100644
index 0000000..181a190
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/prep.py
@@ -0,0 +1,301 @@
+"""Prep the picked generated props into scenes/hk-dai-pai-dong/props/<id>.blend.
+
+Per prop: import GLB -> join -> turn so its front faces -Y (Tripo fronts face +X) -> scale to the manifest size
+-> origin at bottom centre -> decimate to a tri budget -> cap texture size -> material fixes (glass, glow, gloss) -> save.
+
+blender -b --factory-startup --python scenes/hk-dai-pai-dong/scripts/prep.py -- [--only id,id]
+"""
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Matrix, Vector
+
+sys.path.insert(0, os.path.dirname(__file__))
+from lib import L, SCENE_DIR, ROOT # noqa: E402
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+ONLY = argv[argv.index("--only") + 1].split(",") if "--only" in argv else None
+MAN = {p["id"]: p for p in json.load(open(os.path.join(SCENE_DIR, "assets.json"), encoding="utf-8"))["generate"]}
+PICKS = json.load(open(os.path.join(SCENE_DIR, "picks.json"), encoding="utf-8"))
+LIB = os.path.join(SCENE_DIR, "props")
+os.makedirs(LIB, exist_ok=True)
+YAW = {"tripo-h31": -90, "meshy": 0} # degrees about Z that bring each generator's front to -Y
+
+# Tri budgets: props the hero cameras see up close get more.
+HERO = {"hk_kitchen_cart", "hk_wok_range", "hk_wok_a", "hk_wok_rice", "hk_stockpot", "hk_enamel_teapot", "hk_condiment_caddy",
+ "hk_table_round", "hk_stool_red", "hk_parked_car", "hk_street_lamp", "hk_lpg_cylinder", "hk_soy_bottles", "hk_chopstick_cup"}
+TEX_4K = {"hk_kitchen_cart", "hk_wok_range", "hk_parked_car"}
+
+
+# ------------------------------------------------------------------ material fixes
+
+def principled(m):
+ return next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
+
+
+def base_tex(m):
+ b = principled(m)
+ s = b.inputs["Base Color"]
+ return s.links[0].from_node if s.is_linked else None
+
+
+def fx_coat(o, w=0.5, r=0.06):
+ """Glazed ceramic / lacquer: clear coat over the baked albedo."""
+ for m in o.data.materials:
+ b = principled(m)
+ b.inputs["Coat Weight"].default_value = w
+ b.inputs["Coat Roughness"].default_value = r
+
+
+def fx_glassy(o, rough=0.06):
+ """Glass bottles with opaque contents baked into the texture: keep the albedo, add a glossy glass-like coat."""
+ for m in o.data.materials:
+ b = principled(m)
+ b.inputs["Coat Weight"].default_value = 1.0
+ b.inputs["Coat Roughness"].default_value = 0.02
+ b.inputs["Coat IOR"].default_value = 1.5
+ b.inputs["Specular IOR Level"].default_value = 0.7
+ if not b.inputs["Roughness"].is_linked:
+ b.inputs["Roughness"].default_value = rough
+
+
+def fx_clear_glass(o):
+ """Whole object is clear glass (water glass): replace the baked material with real glass + faint tint."""
+ m = bpy.data.materials.new("clear_glass")
+ m.use_nodes = True
+ b = principled(m)
+ b.inputs["Base Color"].default_value = (0.92, 0.96, 0.95, 1)
+ b.inputs["Roughness"].default_value = 0.015
+ b.inputs["Transmission Weight"].default_value = 1.0
+ b.inputs["IOR"].default_value = 1.5
+ o.data.materials.clear()
+ o.data.materials.append(m)
+
+
+def _front_mask(nt, zmin, zmax, facing=0.5):
+ """1 where the surface faces local -Y (the prop's front) and object-space z is within [zmin, zmax]."""
+ geo = nt.nodes.new("ShaderNodeNewGeometry")
+ vt = nt.nodes.new("ShaderNodeVectorTransform")
+ vt.vector_type = "NORMAL"
+ vt.convert_from = "WORLD"
+ vt.convert_to = "OBJECT"
+ L(nt, geo.outputs["Normal"], vt.inputs[0])
+ dot = nt.nodes.new("ShaderNodeVectorMath")
+ dot.operation = "DOT_PRODUCT"
+ dot.inputs[1].default_value = (0, -1, 0)
+ L(nt, vt.outputs[0], dot.inputs[0])
+ gt = nt.nodes.new("ShaderNodeMath")
+ gt.operation = "GREATER_THAN"
+ gt.inputs[1].default_value = facing
+ L(nt, dot.outputs["Value"], gt.inputs[0])
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ L(nt, tc.outputs["Object"], sep.inputs[0])
+ lo = nt.nodes.new("ShaderNodeMath")
+ lo.operation = "GREATER_THAN"
+ lo.inputs[1].default_value = zmin
+ L(nt, sep.outputs["Z"], lo.inputs[0])
+ hi = nt.nodes.new("ShaderNodeMath")
+ hi.operation = "LESS_THAN"
+ hi.inputs[1].default_value = zmax
+ L(nt, sep.outputs["Z"], hi.inputs[0])
+ a = nt.nodes.new("ShaderNodeMath")
+ a.operation = "MULTIPLY"
+ L(nt, lo.outputs[0], a.inputs[0])
+ L(nt, hi.outputs[0], a.inputs[1])
+ b = nt.nodes.new("ShaderNodeMath")
+ b.operation = "MULTIPLY"
+ L(nt, a.outputs[0], b.inputs[0])
+ L(nt, gt.outputs[0], b.inputs[1])
+ return b.outputs[0]
+
+
+def fx_front_glow(o, strength, zmin, zmax, gamma=2.2):
+ """Backlit panel (ticket buttons, fridge interior): emit the albedo, brightest where the texture is light."""
+ for m in o.data.materials:
+ nt = m.node_tree
+ tex = base_tex(m)
+ b = principled(m)
+ if tex is None:
+ continue
+ pw = nt.nodes.new("ShaderNodeMath")
+ pw.operation = "POWER"
+ bw = nt.nodes.new("ShaderNodeRGBToBW")
+ L(nt, tex.outputs["Color"], bw.inputs[0])
+ L(nt, bw.outputs[0], pw.inputs[0])
+ pw.inputs[1].default_value = gamma
+ mask = _front_mask(nt, zmin, zmax)
+ k = nt.nodes.new("ShaderNodeMath")
+ k.operation = "MULTIPLY"
+ L(nt, pw.outputs[0], k.inputs[0])
+ L(nt, mask, k.inputs[1])
+ s = nt.nodes.new("ShaderNodeMath")
+ s.operation = "MULTIPLY"
+ s.inputs[1].default_value = strength
+ L(nt, k.outputs[0], s.inputs[0])
+ L(nt, tex.outputs["Color"], b.inputs["Emission Color"])
+ L(nt, s.outputs[0], b.inputs["Emission Strength"])
+
+
+def fx_lantern(o, strength=2.2):
+ """Paper lantern lit from inside: translucent paper + emission of the albedo (dark kanji stay dark)."""
+ for m in o.data.materials:
+ nt = m.node_tree
+ tex = base_tex(m)
+ b = principled(m)
+ if tex is None:
+ continue
+ L(nt, tex.outputs["Color"], b.inputs["Emission Color"])
+ b.inputs["Emission Strength"].default_value = strength
+ b.inputs["Subsurface Weight"].default_value = 0.3
+
+
+def fx_glass_front(o, zmin, zmax):
+ """Glass-front fridge: add a real glass pane in front of the door so it gets reflections and depth."""
+ lo, hi = bounds([o])
+ w = (hi.x - lo.x) * 0.82
+ me = bpy.data.meshes.new("door_glass")
+ y = lo.y - 0.004
+ me.from_pydata([(-w / 2, y, zmin), (w / 2, y, zmin), (w / 2, y, zmax), (-w / 2, y, zmax)], [], [(0, 1, 2, 3)])
+ g = bpy.data.objects.new(o.name + "_glass", me)
+ bpy.context.scene.collection.objects.link(g)
+ m = bpy.data.materials.new("fridge_glass")
+ m.use_nodes = True
+ b = principled(m)
+ b.inputs["Roughness"].default_value = 0.03
+ b.inputs["Transmission Weight"].default_value = 1.0
+ b.inputs["Base Color"].default_value = (0.95, 0.97, 0.97, 1)
+ me.materials.append(m)
+ g.parent = o
+
+
+FIX = {
+ "hk_soy_bottles": [(fx_glassy, {})],
+ "hk_condiment_caddy": [(fx_glassy, {})],
+ "hk_beer_bottles": [(fx_glassy, {})],
+ "hk_beer_crate": [(fx_glassy, {"rough": 0.1})],
+ "hk_jars_preserved": [(fx_glassy, {})],
+ "hk_lemon_tea": [(fx_glassy, {"rough": 0.03})],
+ "hk_sauce_shelf": [(fx_glassy, {"rough": 0.12})],
+ "hk_enamel_teapot": [(fx_coat, {"w": 0.8, "r": 0.06})],
+ "hk_thermos": [(fx_coat, {"w": 0.5, "r": 0.1})],
+ "hk_tea_cups": [(fx_coat, {"w": 0.7, "r": 0.05})],
+ "hk_milk_tea": [(fx_coat, {"w": 0.7, "r": 0.05})],
+ "hk_bowl_stack": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_plate_stack": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_bowl_congee": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_dish_fried_rice": [(fx_coat, {"w": 0.5, "r": 0.08})],
+ "hk_dish_beef_hofun": [(fx_coat, {"w": 0.7, "r": 0.05})],
+ "hk_dish_clams": [(fx_coat, {"w": 0.7, "r": 0.05})],
+ "hk_dish_greens": [(fx_coat, {"w": 0.7, "r": 0.05})],
+ "hk_dish_salt_squid": [(fx_coat, {"w": 0.4, "r": 0.1})],
+ "hk_wok_rice": [(fx_coat, {"w": 0.5, "r": 0.08})],
+ "hk_wok_a": [(fx_coat, {"w": 0.4, "r": 0.12})],
+ "hk_dish_rack": [(fx_coat, {"w": 0.5, "r": 0.06})],
+ "hk_wash_basin": [(fx_coat, {"w": 0.6, "r": 0.04})],
+ # rain-wet street furniture and seating: a thin clear coat reads as wet
+ "hk_table_round": [(fx_coat, {"w": 0.5, "r": 0.05})],
+ "hk_table_square": [(fx_coat, {"w": 0.5, "r": 0.05})],
+ "hk_stool_red": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_stool_stack": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_stool_blue": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_parked_car": [(fx_coat, {"w": 1.0, "r": 0.03})],
+ "hk_scooter": [(fx_coat, {"w": 0.8, "r": 0.05})],
+ "hk_water_barrier": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_traffic_cone": [(fx_coat, {"w": 0.6, "r": 0.06})],
+ "hk_trash_bin": [(fx_coat, {"w": 0.5, "r": 0.08})],
+ "hk_bin_bags": [(fx_coat, {"w": 0.9, "r": 0.04})],
+ "hk_umbrella": [(fx_coat, {"w": 0.9, "r": 0.04})],
+ "hk_guard_railing": [(fx_coat, {"w": 0.4, "r": 0.1})],
+}
+
+
+# ------------------------------------------------------------------ geometry
+
+def bounds(objs):
+ pts = [o.matrix_world @ Vector(c) for o in objs for c in o.bound_box]
+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
+ return lo, hi
+
+
+def prep(pid, model):
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ glb = os.path.join(ROOT, "assets", "gen", model, pid, "model.glb")
+ bpy.ops.import_scene.gltf(filepath=glb)
+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+ for o in bpy.data.objects:
+ o.select_set(o in meshes)
+ bpy.context.view_layer.objects.active = meshes[0]
+ # Bake parent transforms into the meshes, drop empties, join.
+ bpy.ops.object.parent_clear(type="CLEAR_KEEP_TRANSFORM")
+ for o in [o for o in bpy.data.objects if o.type != "MESH"]:
+ bpy.data.objects.remove(o)
+ if len(meshes) > 1:
+ bpy.ops.object.join()
+ o = bpy.context.view_layer.objects.active
+ o.name = pid
+ o.data.name = pid
+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
+ # glTF imports use quaternion rotation mode, so turn the mesh data itself rather than rotation_euler.
+ o.data.transform(Matrix.Rotation(math.radians(YAW[model]), 4, "Z"))
+ o.data.update()
+ bpy.context.view_layer.update()
+
+ lo, hi = bounds([o])
+ size = hi - lo
+ spec = MAN[pid]
+ s = spec["h"] / size.z if "h" in spec else spec["m"] / max(size)
+ me = o.data
+ centre = Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))
+ if "dims" in spec:
+ # Boxy appliances: generators invent the depth, so fit width/depth/height separately.
+ w, d, h = spec["dims"]
+ S = Matrix.Diagonal((w / size.x, d / size.y, h / size.z, 1))
+ s = h / size.z
+ else:
+ S = Matrix.Scale(s, 4)
+ me.transform(S @ Matrix.Translation(-centre))
+ me.update()
+ o.location = (0, 0, 0)
+
+ me.calc_loop_triangles()
+ tris = len(me.loop_triangles)
+ budget = 220_000 if pid in HERO else (40_000 if max(size) * s < 0.3 else 90_000)
+ if tris > budget * 1.1:
+ d = o.modifiers.new("dec", "DECIMATE")
+ d.ratio = budget / tris
+ d.use_collapse_triangulate = True
+ bpy.ops.object.modifier_apply(modifier="dec")
+ for p in me.polygons:
+ p.use_smooth = True
+
+ cap = 4096 if pid in TEX_4K else 2048
+ for img in bpy.data.images:
+ # glTF images arrive already packed. Re-packing an unmodified one (empty filepath) silently drops
+ # its data, so only resized images get packed again (from their new pixel buffer).
+ if img.source == "FILE" and img.size[0] > cap:
+ img.scale(cap, cap)
+ img.pack()
+
+ for fn, kw in FIX.get(pid, FIX.get(spec.get("replaces", ""), [])): # _nb variants share the original's fixes
+ fn(o, **kw)
+ o["source_model"] = model
+ o["target"] = spec.get("h", spec.get("m"))
+ me.calc_loop_triangles()
+ out = os.path.join(LIB, pid + ".blend")
+ bpy.ops.wm.save_as_mainfile(filepath=out, compress=True)
+ lo, hi = bounds([o])
+ print(f"PREP {pid} {model} tris {tris}->{len(me.loop_triangles)} size {tuple(round(v, 3) for v in (hi - lo))}", flush=True)
+
+
+for pid, pick in PICKS.items():
+ if (ONLY and pid not in ONLY) or pick.get("model") in (None, "retired"):
+ continue
+ try:
+ prep(pid, pick["model"])
+ except Exception as e:
+ print("PREP FAILED", pid, repr(e), flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/reel.sh b/scenes/hk-dai-pai-dong/scripts/reel.sh
new file mode 100644
index 0000000..f251a47
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/reel.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+# Reel of the graded shots (concat, stream copy) + a compressed copy under 30 MB for chat. Checks durations.
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+O=scenes/hk-dai-pai-dong/out/shots
+L=$O/reel_list.txt
+: > $L
+for s in s1_street_crane h1_walk_in_to_wok s2_teapot_wok_rack s3_wok_push h2_walk_tables_neon s4_neon_tilt; do
+ f=$O/${s}_graded.mp4
+ [ -f $f ] || { echo "missing $f"; exit 2; }
+ echo "$s $("$FF" -i $f 2>&1 | grep -o 'Duration: [0-9:.]*')"
+ echo "file '${s}_graded.mp4'" >> $L
+done
+"$FF" -v error -y -f concat -safe 0 -i $L -c copy $O/hk_dai_pai_dong_reel.mp4
+dur=$("$FF" -i $O/hk_dai_pai_dong_reel.mp4 2>&1 | grep -o 'Duration: [0-9:.]*' | cut -d' ' -f2)
+secs=$(echo $dur | awk -F: '{print $1*3600+$2*60+$3}')
+kbps=$(awk -v s=$secs 'BEGIN{printf "%d", 28*8192/s}')
+"$FF" -v error -y -i $O/hk_dai_pai_dong_reel.mp4 -vf scale=1280:-2 -c:v h264_nvenc -preset p7 -b:v ${kbps}k -maxrate ${kbps}k -bufsize $((kbps*2))k -an $O/hk_dai_pai_dong_reel_small.mp4
+ls -la $O/hk_dai_pai_dong_reel*.mp4
+echo "REEL $dur"
diff --git a/scenes/hk-dai-pai-dong/scripts/render_bts.sh b/scenes/hk-dai-pai-dong/scripts/render_bts.sh
new file mode 100644
index 0000000..aa528c0
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/render_bts.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# Dai pai dong dollhouse clips (breakdown/SPEC.md). Every Blender run is its own pipeline/gpu_run.sh call.
+# bash scenes/hk-dai-pai-dong/scripts/render_bts.sh > logs/hk_bts.log 2>&1
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+FF="$FFMPEG"
+SC=scenes/hk-dai-pai-dong
+R=breakdown/hk-dai-pai-dong
+CL=$R/clips
+WK=$R/work
+S=$ANYSCENE_ROOT/$SC/scripts
+run() { local t0=$(date +%s); bash pipeline/gpu_run.sh "$BLENDER" -b "$1" --python $S/gpu_prefs.py --python $S/bts.py -- "${@:2}" 2>&1 | grep -E "BTS rendered|Error:|Traceback|line [0-9]"; echo "GPU $(( $(date +%s)-t0 ))s: ${*:2}"; }
+mp4() { "$FF" -v error -y -framerate 24 -start_number 1 -i "$CL/$1/%04d.png" -c:v h264_nvenc -preset p7 -rc vbr -cq 16 -b:v 0 -pix_fmt yuv420p "$CL/$1.mp4" && echo "MP4 $1 $(ls $CL/$1 | wc -l) frames"; }
+
+# No-grime twin of the scene for c_materials (same build without the grime stage). Saved under breakdown/, never over hk.blend.
+if [ ! -f $R/plain.blend ]; then
+ bash pipeline/gpu_run.sh "$BLENDER" -b --factory-startup --python $S/gpu_prefs.py --python $S/build.py -- \
+ --stages shell,dress,light,fx,post --save --out ../../$R/plain.blend 2>&1 | grep -E "SAVED|Error|Traceback"
+fi
+
+run $SC/hk.blend a_layout && mp4 a_layout
+for r in 1-120 121-240; do run $SC/hk.blend b_props --frames $r; done; mp4 b_props
+
+run $SC/hk.blend c_materials --pass clay --frames 1-48 --out $ANYSCENE_ROOT/$WK/c_clay
+run $R/plain.blend c_materials --pass plain --frames 1-96 --out $ANYSCENE_ROOT/$WK/c_plain
+run $SC/hk.blend c_materials --pass full --frames 49-144 --out $ANYSCENE_ROOT/$WK/c_full
+rm -rf $CL/c_materials $WK/c_seg; mkdir -p $CL/c_materials $WK/c_seg
+"$FF" -v error -y -framerate 24 -start_number 1 -i $WK/c_clay/%04d.png -framerate 24 -start_number 1 -i $WK/c_plain/%04d.png \
+ -filter_complex "[0][1]xfade=transition=wiperight:duration=2:offset=0,format=rgb24" -frames:v 48 -start_number 1 $WK/c_seg/a%04d.png
+"$FF" -v error -y -framerate 24 -start_number 49 -i $WK/c_plain/%04d.png -framerate 24 -start_number 49 -i $WK/c_full/%04d.png \
+ -filter_complex "[0][1]xfade=transition=fade:duration=2:offset=0,format=rgb24" -frames:v 48 -start_number 1 $WK/c_seg/b%04d.png
+i=1
+for f in $WK/c_seg/a*.png $WK/c_seg/b*.png $(for n in $(seq 97 144); do printf "$WK/c_full/%04d.png " $n; done); do
+ cp "$f" $CL/c_materials/$(printf %04d $i).png; i=$((i+1))
+done
+mp4 c_materials
+
+for r in 1-48 49-96 97-144 145-192 193-240; do run $SC/hk.blend d_lighting --frames $r --samples 16; done
+mp4 d_lighting
+echo BTS_DONE
diff --git a/scenes/hk-dai-pai-dong/scripts/render_finals.sh b/scenes/hk-dai-pai-dong/scripts/render_finals.sh
new file mode 100644
index 0000000..18df539
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/render_finals.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+# Final Cycles renders of every shot in 24-frame chunks (each its own GPU-queue call, so the other scene can
+# interleave), then an ffmpeg grade per shot with a frame-count check, then the reel.
+# bash scenes/hk-dai-pai-dong/scripts/render_finals.sh [shot,shot] > logs/hk_finals.log 2>&1
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+SC=scenes/hk-dai-pai-dong
+O=$SC/out/shots
+ORDER=${1:-h1_walk_in_to_wok,h2_walk_tables_neon,s1_street_crane,s2_teapot_wok_rack,s3_wok_push,s4_neon_tilt}
+frames() { uv run --no-project python -I -c "import json;print(next(s['frames'] for s in json.load(open('$SC/shots.json'))['shots'] if s['name']=='$1'))"; }
+IFS=, read -ra SHOTS <<< "$ORDER"
+for s in "${SHOTS[@]}"; do
+ n=$(frames $s)
+ for ((a = 1; a <= n; a += 24)); do
+ b=$((a + 23)); [ $b -gt $n ] && b=$n
+ have=0; for ((f = a; f <= b; f++)); do [ -f $O/$s/frames/$(printf %04d $f).png ] && have=$((have + 1)); done
+ [ $have -eq $((b - a + 1)) ] && continue
+ t0=$(date +%s)
+ bash $SC/scripts/shoot.sh --only $s --frames $a-$b --no-encode 2>&1 | grep -E "camrig: final|Error|Traceback"
+ echo "CHUNK $s $a-$b $(( $(date +%s) - t0 ))s"
+ done
+ bash $SC/scripts/grade.sh clip $O/$s $O/${s}_graded.mp4 $n
+done
+echo FINALS_DONE
diff --git a/scenes/hk-dai-pai-dong/scripts/review.sh b/scenes/hk-dai-pai-dong/scripts/review.sh
new file mode 100644
index 0000000..c1f2a70
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/review.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# Review sheets (ref | H3.1 front/back/clay | Meshy ...) for compared props NOT yet in picks.json, 8 per sheet:
+# bash scenes/hk-dai-pai-dong/scripts/review.sh <tag> -> compare/todo_<tag>_<n>.png
+cd "$(dirname "$0")/../../.."
+SC=scenes/hk-dai-pai-dong
+C=$SC/compare
+P=()
+for f in $C/meshy/hk_*_clay.png; do id=$(basename $f _clay.png)
+ [ -f $C/tripo-h31/${id}_clay.png ] || continue
+ grep -q "\"$id\"" $SC/picks.json && continue
+ P+=($id); done
+echo "to review: ${P[*]}"
+n=0; args=()
+for id in "${P[@]}"; do
+ args+=("$id=refs/hk-dai-pai-dong/props/${id}_0.png|$C/tripo-h31/${id}_beauty.png|$C/meshy/${id}_beauty.png|$C/tripo-h31/${id}_back.png|$C/meshy/${id}_back.png|$C/tripo-h31/${id}_clay.png|$C/meshy/${id}_clay.png")
+ if [ ${#args[@]} -eq 8 ]; then uv run --no-project --with pillow python -I $SC/scripts/sheet.py $C/todo_$1_$n.png 7 300 "${args[@]}" | tail -1; args=(); n=$((n+1)); fi
+done
+[ ${#args[@]} -gt 0 ] && uv run --no-project --with pillow python -I $SC/scripts/sheet.py $C/todo_$1_$n.png 7 300 "${args[@]}" | tail -1
diff --git a/scenes/hk-dai-pai-dong/scripts/sheet.py b/scenes/hk-dai-pai-dong/scripts/sheet.py
new file mode 100644
index 0000000..abb7b69
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/sheet.py
@@ -0,0 +1,39 @@
+"""Contact sheet of labelled images.
+
+uv run --with pillow python -I scenes/hk-dai-pai-dong/scripts/sheet.py OUT.png COLS CELL img1 [img2 ...]
+ an img argument may be "label=path"; a row of several images per prop: "label=a.png|b.png|c.png" (rows mode)
+"""
+import os
+import sys
+
+from PIL import Image, ImageDraw, ImageFont
+
+out, cols, cell = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
+items = []
+for a in sys.argv[4:]:
+ lab, _, p = a.partition("=") if "=" in a else (os.path.basename(a).rsplit(".", 1)[0], "", a)
+ items.append((lab, p.split("|")))
+per = max(len(p) for _, p in items)
+font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", max(12, cell // 16))
+if per > 1: # rows mode: one prop per row
+ W, H = per * cell, len(items) * cell
+ rows, cw = len(items), per
+else:
+ rows = (len(items) + cols - 1) // cols
+ W, H, cw = cols * cell, rows * cell, cols
+sheet = Image.new("RGB", (W, H), (30, 30, 30))
+d = ImageDraw.Draw(sheet)
+for i, (lab, paths) in enumerate(items):
+ for j, p in enumerate(paths):
+ x, y = ((j * cell, i * cell) if per > 1 else ((i % cols) * cell, (i // cols) * cell))
+ if os.path.exists(p):
+ im = Image.open(p).convert("RGB")
+ im.thumbnail((cell, cell))
+ sheet.paste(im, (x + (cell - im.width) // 2, y + (cell - im.height) // 2))
+ else:
+ d.text((x + 10, y + cell // 2), "missing", fill=(200, 60, 60), font=font)
+ if j == 0:
+ d.rectangle((x, y, x + len(lab) * font.size * 0.6 + 8, y + font.size + 6), fill=(0, 0, 0))
+ d.text((x + 4, y + 2), lab, fill=(255, 230, 120), font=font)
+sheet.save(out)
+print("sheet", out, W, H)
diff --git a/scenes/hk-dai-pai-dong/scripts/shell.py b/scenes/hk-dai-pai-dong/scripts/shell.py
new file mode 100644
index 0000000..a56da19
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/shell.py
@@ -0,0 +1,652 @@
+"""Street shell for the dai pai dong (world coordinates, metres, Z up). See brief.md for the layout.
+
+Street along +Y. Stall-side facades at x = FX0 (facing +X), far facades at x = FX1 (facing -X).
+Pavement z 0, road z ROAD_Z. Everything architectural is direct-modelled here; props come from dress.py.
+"""
+import math
+import os
+import random
+
+import bpy
+from mathutils import Matrix, Vector
+
+from lib import (TEX, L, box, bsdf, bump, coll, cylinder, mathn, mesh_obj, mix, new_mat, node, noise, plane, ramp,
+ texcoord, m_simple)
+
+FX0, FX1 = -4.0, 9.6 # facade planes
+KERB0, KERB1 = 0.0, 7.4 # kerb lines (road between)
+ROAD_Z = -0.15
+Y0, Y1 = -22.0, 40.0 # modelled street extent
+STALL = dict(x0=-4.0, x1=-1.6, y0=-0.5, y1=6.0)
+AWN = dict(x0=-4.0, x1=-0.15, y0=-1.0, y1=7.0, z_wall=3.15, z_edge=2.55)
+POLE_X = -0.3
+POLES_Y = (-0.85, 3.0, 6.85)
+FONT = "C:/Windows/Fonts/msjhbd.ttc"
+rng = random.Random(11)
+
+
+def tex(name):
+ p = os.path.join(TEX, name + "_0.png")
+ return p if os.path.exists(p) else None
+
+
+# ---------------------------------------------------------------- materials
+
+def _wet_ground(name, base_path, tile, dark, light, puddle_scale, puddle_cut, rough_dry=0.5, fallback_scale=9.0):
+ """Wet ground: image (or noise) albedo, darkened, with low-roughness puddles and fine rain ripples in them."""
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt, "Object")
+ b = bsdf(nt)
+ if base_path:
+ mp = nt.nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (1 / tile, 1 / tile, 1)
+ L(nt, co, mp.inputs["Vector"])
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(base_path, check_existing=True)
+ t.projection = "FLAT"
+ L(nt, mp.outputs[0], t.inputs["Vector"])
+ base = mix(nt, 0.55, t.outputs["Color"], (0.0, 0.0, 0.0, 1), "MULTIPLY")
+ hgt = t.outputs["Color"]
+ else:
+ n = noise(nt, fallback_scale, 10, 0.65, co)
+ base = ramp(nt, [(0.3, dark), (0.75, light)], n.outputs["Fac"]).outputs["Color"]
+ hgt = n.outputs["Fac"]
+ pn = noise(nt, puddle_scale, 4, 0.55, co)
+ pud = ramp(nt, [(puddle_cut, (0, 0, 0)), (puddle_cut + 0.05, (1, 1, 1))], pn.outputs["Fac"]).outputs["Color"]
+ # Wet everywhere (dark, fairly glossy); puddles are mirror-like and darker still.
+ col = mix(nt, 0.35, base, (0.0, 0.0, 0.0, 1), "MULTIPLY")
+ col = mix(nt, mathn(nt, "MULTIPLY", pud, 0.75), col, (0.004, 0.004, 0.005, 1))
+ L(nt, col, b.inputs["Base Color"])
+ rough = mix(nt, pud, (rough_dry, rough_dry, rough_dry, 1), (0.015, 0.015, 0.015, 1))
+ L(nt, rough, b.inputs["Roughness"])
+ b.inputs["Specular IOR Level"].default_value = 0.6
+ # Rain ripples (voronoi rings) in the puddles, texture relief outside them.
+ rip = node(nt, "ShaderNodeTexVoronoi", Scale=38.0)
+ rip.voronoi_dimensions = "4D"
+ rip.inputs["W"].driver_add("default_value").driver.expression = "frame * 0.06"
+ L(nt, co, rip.inputs["Vector"])
+ ring = ramp(nt, [(0.0, (0, 0, 0)), (0.1, (1, 1, 1)), (0.18, (0, 0, 0))], rip.outputs["Distance"]).outputs["Color"]
+ h = mix(nt, pud, hgt, mathn(nt, "MULTIPLY", ring, 0.3))
+ bm = node(nt, "ShaderNodeBump", Strength=0.25, Distance=0.002)
+ L(nt, h, bm.inputs["Height"])
+ L(nt, bm.outputs[0], b.inputs["Normal"])
+ return m
+
+
+def m_pavement():
+ return _wet_ground("pavement_wet", tex("hk_tex_pavement"), 1.6, (0.05, 0.045, 0.045), (0.16, 0.13, 0.12), 0.9, 0.5, 0.42)
+
+
+def m_road():
+ return _wet_ground("road_wet", tex("hk_tex_asphalt"), 3.0, (0.02, 0.02, 0.022), (0.07, 0.068, 0.065), 0.45, 0.47, 0.38)
+
+
+def m_paint(name, color):
+ m, nt = new_mat(name)
+ if nt:
+ b = bsdf(nt)
+ co = texcoord(nt)
+ worn = ramp(nt, [(0.35, (0, 0, 0)), (0.6, (1, 1, 1))], noise(nt, 6, 6, 0.6, co).outputs["Fac"]).outputs["Color"]
+ L(nt, mix(nt, worn, (0.03, 0.03, 0.03, 1), (*color, 1)), b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.2
+ return m
+
+
+def m_grimy(name, color, rough=0.75, metal=0.0, streak=0.6):
+ """Painted concrete / metal with vertical rain streaks and low grime (generated z from object bounds)."""
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ co = texcoord(nt)
+ mp = nt.nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (6, 6, 0.25)
+ L(nt, co, mp.inputs["Vector"])
+ st = noise(nt, 3.0, 6, 0.6, mp.outputs[0])
+ blot = noise(nt, 1.2, 5, 0.55, co)
+ c = ramp(nt, [(0.3, tuple(v * 0.55 for v in color)), (0.7, color)], blot.outputs["Fac"]).outputs["Color"]
+ sk = ramp(nt, [(0.5, (0, 0, 0)), (0.75, (1, 1, 1))], st.outputs["Fac"]).outputs["Color"]
+ c = mix(nt, mathn(nt, "MULTIPLY", sk, streak), c, (0.03, 0.03, 0.025, 1), "MULTIPLY")
+ b = bsdf(nt)
+ L(nt, c, b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = rough
+ b.inputs["Metallic"].default_value = metal
+ L(nt, bump(nt, noise(nt, 30, 6, 0.6, co).outputs["Fac"], 0.15, 0.004).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def m_facade_img(name, path, lit=4.0, tile_v=1.0):
+ """Facade photo on a front plane: diffuse albedo + emission only where the photo is bright (lit windows)."""
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ uv = texcoord(nt, "UV")
+ mp = nt.nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (1, tile_v, 1)
+ L(nt, uv, mp.inputs["Vector"])
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(path, check_existing=True)
+ L(nt, mp.outputs[0], t.inputs["Vector"])
+ b = bsdf(nt)
+ L(nt, t.outputs["Color"], b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.6
+ bw = nt.nodes.new("ShaderNodeRGBToBW")
+ L(nt, t.outputs["Color"], bw.inputs[0])
+ glow = ramp(nt, [(0.42, (0, 0, 0)), (0.75, (1, 1, 1))], bw.outputs[0]).outputs["Color"]
+ L(nt, t.outputs["Color"], b.inputs["Emission Color"])
+ L(nt, mathn(nt, "MULTIPLY", mathn(nt, "MAXIMUM", glow, 0.0), lit), b.inputs["Emission Strength"])
+ L(nt, bump(nt, bw.outputs[0], 0.3, 0.01).outputs[0], b.inputs["Normal"])
+ m.cycles.emission_sampling = "NONE" # glows to camera; real light comes from lamps
+ return m
+
+
+def m_emit(name, color, strength):
+ m, nt = new_mat(name)
+ if nt:
+ b = bsdf(nt)
+ b.inputs["Base Color"].default_value = (*color, 1)
+ b.inputs["Emission Color"].default_value = (*color, 1)
+ b.inputs["Emission Strength"].default_value = strength
+ return m
+
+
+def m_lightbox(name, path, strength=3.0):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(path, check_existing=True)
+ b = bsdf(nt)
+ L(nt, t.outputs["Color"], b.inputs["Base Color"])
+ L(nt, t.outputs["Color"], b.inputs["Emission Color"])
+ b.inputs["Emission Strength"].default_value = strength
+ b.inputs["Roughness"].default_value = 0.25
+ b.inputs["Coat Weight"].default_value = 0.5
+ return m
+
+
+def m_tarp():
+ """Green corrugated plastic awning: translucent-ish, dirty, with algae streaks and drips."""
+ m, nt = new_mat("tarp_green")
+ if not nt:
+ return m
+ co = texcoord(nt)
+ dirt = noise(nt, 2.0, 6, 0.6, co)
+ c = ramp(nt, [(0.25, (0.04, 0.09, 0.05)), (0.7, (0.12, 0.24, 0.13))], dirt.outputs["Fac"]).outputs["Color"]
+ b = bsdf(nt)
+ L(nt, c, b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.35
+ b.inputs["Coat Weight"].default_value = 0.6 # wet
+ b.inputs["Coat Roughness"].default_value = 0.08
+ b.inputs["Subsurface Weight"].default_value = 0.0
+ b.inputs["Transmission Weight"].default_value = 0.0
+ return m
+
+
+# ---------------------------------------------------------------- pieces
+
+def rod(name, p0, p1, r, c, mat, verts=10):
+ """Cylinder from p0 to p1 (pipes, rafters, cords)."""
+ p0, p1 = Vector(p0), Vector(p1)
+ d = p1 - p0
+ bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=d.length, vertices=verts, location=(p0 + p1) / 2)
+ o = bpy.context.object
+ o.name = name
+ for uc in list(o.users_collection):
+ uc.objects.unlink(o)
+ c.objects.link(o)
+ o.rotation_euler = d.to_track_quat("Z", "Y").to_euler()
+ if mat:
+ o.data.materials.append(mat)
+ return o
+
+
+def text_obj(name, s, c, loc, rot, size, mat, vertical=True, extrude=0.008, bevel=0.003, font=FONT):
+ cu = bpy.data.curves.new(name, "FONT")
+ cu.body = "\n".join(s) if vertical else s
+ cu.font = bpy.data.fonts.load(font, check_existing=True)
+ cu.size = size
+ cu.space_line = 0.9
+ cu.align_x = "CENTER"
+ cu.align_y = "CENTER"
+ cu.extrude = extrude
+ cu.bevel_depth = bevel
+ o = bpy.data.objects.new(name, cu)
+ c.objects.link(o)
+ o.location = loc
+ o.rotation_euler = rot
+ cu.materials.append(mat)
+ return o
+
+
+def ground(c):
+ pav = box("pavement", (FX0 - 0.1, Y0, -0.4), (KERB0 - 0.18, Y1, 0.0), c, m_pavement(), 0)
+ pav2 = box("pavement_far", (KERB1 + 0.18, Y0, -0.4), (FX1 + 0.1, Y1, 0.0), c, m_pavement(), 0)
+ kerb_m = m_grimy("kerb_granite", (0.2, 0.19, 0.18), 0.45, streak=0.2)
+ box("kerb", (KERB0 - 0.18, Y0, -0.4), (KERB0, Y1, 0.0), c, kerb_m, 0.012)
+ box("kerb_far", (KERB1, Y0, -0.4), (KERB1 + 0.18, Y1, 0.0), c, kerb_m, 0.012)
+ road = box("road", (KERB0, Y0, -0.5), (KERB1, Y1 + 60, ROAD_Z), c, m_road(), 0)
+ # Double yellow no-stopping lines along both kerbs, broken white centre line.
+ yel = m_paint("paint_yellow", (0.75, 0.52, 0.06))
+ wht = m_paint("paint_white", (0.7, 0.7, 0.66))
+ for x in (0.28, 0.42, KERB1 - 0.42, KERB1 - 0.28):
+ box(f"line_y_{x:.2f}", (x - 0.05, Y0, ROAD_Z), (x + 0.05, Y1, ROAD_Z + 0.002), c, yel, 0)
+ y = Y0
+ while y < Y1:
+ box(f"line_c_{y:.0f}", (KERB1 / 2 - 0.06, y, ROAD_Z), (KERB1 / 2 + 0.06, y + 2.5, ROAD_Z + 0.002), c, wht, 0)
+ y += 6.0
+ # Gutter drain grates.
+ grate = m_simple("drain_iron", (0.03, 0.03, 0.03), 0.35, 0.8)
+ for gy in (-9.5, -1.8, 9.0, 17.5):
+ for gx in (0.05, KERB1 - 0.45):
+ box(f"drain_{gx:.1f}_{gy:.0f}", (gx, gy, ROAD_Z - 0.005), (gx + 0.4, gy + 0.9, ROAD_Z + 0.004), c, grate, 0.003)
+ # Distant continuation: water and a far harbour-front wall at the end of the street.
+ box("harbour_water", (-80, Y1 + 60, -1.6), (90, Y1 + 400, -1.5), c, m_simple("water", (0.005, 0.006, 0.008), 0.03), 0)
+ return pav, road
+
+
+def _floor_ledges(name, c, xf, sgn, y0, y1, z0, z1, m):
+ z = z0
+ i = 0
+ while z < z1 - 0.5:
+ a, b_ = sorted((xf, xf + sgn * 0.16))
+ box(f"{name}_ledge{i}", (a, y0 + 0.05, z), (b_, y1 - 0.05, z + 0.14), c, m, 0.01)
+ z += 2.9
+ i += 1
+
+
+def tenement(c, name, side, y0, y1, height, tex_id, shutter_id, paint, seed=0):
+ """One building: textured upper facade plane, 3D floor ledges and pilasters, a ground-floor shopfront
+ (two pilasters, a fascia band, a shutter), and a deep mass behind so gaps never show sky."""
+ r = random.Random(seed)
+ xf = FX0 if side < 0 else FX1
+ sgn = 1 if side < 0 else -1 # direction the facade faces (+X for the stall side)
+ back = xf - sgn * 8.0
+ a, b_ = sorted((back, xf))
+ mass = box(f"{name}_mass", (a, y0, 0), (b_, y1, height), c, m_grimy(f"{name}_concrete", paint, 0.85), 0)
+ w = y1 - y0
+ up_z = 3.7
+ # Upper facade photo, tiled so the window size stays roughly real (one tile ~ 9 m tall).
+ path = tex(tex_id)
+ rot_z = math.radians(90 if sgn > 0 else -90) # plane faces -Y locally; turn it to face the street
+ if path:
+ tiles = max(1, round((height - up_z) / 9.5))
+ fp = plane(f"{name}_face", w, height - up_z, c, m_facade_img(f"{name}_facemat", path, tile_v=tiles),
+ loc=(xf + sgn * 0.02, (y0 + y1) / 2, up_z), rot=(0, 0, rot_z))
+ fp["facade"] = True
+ pil = m_grimy(f"{name}_pilaster", tuple(v * 0.85 for v in paint), 0.8)
+ _floor_ledges(name, c, xf, sgn, y0, y1, up_z + 2.75, height, pil)
+ for yy in (y0, y1 - 0.4):
+ a, b_ = sorted((xf, xf + sgn * 0.22))
+ # Inside the stall the ground-floor pilasters would cut through the shelves: start them above the awning.
+ z0 = 3.2 if side < 0 and yy < AWN["y1"] + 0.5 and yy + 0.4 > AWN["y0"] - 0.5 else 0
+ box(f"{name}_pil_{yy:.1f}", (a, yy, z0), (b_, yy + 0.4, height), c, pil, 0.01)
+ # Fascia band for the shop sign and the shutter recess.
+ a, b_ = sorted((xf, xf + sgn * 0.3))
+ box(f"{name}_fascia", (a, y0 + 0.4, 3.05), (b_, y1 - 0.4, 3.7), c, pil, 0.01)
+ sp = tex(shutter_id)
+ if sp:
+ sm, nt = new_mat(f"{name}_shutter")
+ if nt:
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(sp, check_existing=True)
+ L(nt, t.outputs["Color"], bsdf(nt).inputs["Base Color"])
+ bsdf(nt).inputs["Roughness"].default_value = 0.45
+ bsdf(nt).inputs["Metallic"].default_value = 0.5
+ bw = nt.nodes.new("ShaderNodeRGBToBW")
+ L(nt, t.outputs["Color"], bw.inputs[0])
+ L(nt, bump(nt, bw.outputs[0], 0.5, 0.01).outputs[0], bsdf(nt).inputs["Normal"])
+ sh = plane(f"{name}_shutter", w - 0.8, 3.05, c, sm, loc=(xf - sgn * 0.05, (y0 + y1) / 2, 0), rot=(0, 0, rot_z))
+ sh["shutter"] = True
+ return mass
+
+
+def facades(c):
+ """Stall side and far side, ~5-7 m wide buildings, 16-26 m tall."""
+ texs = ["hk_tex_facade_a", "hk_tex_facade_b", "hk_tex_facade_c"]
+ shut = ["hk_tex_shutter_a", "hk_tex_shutter_b"]
+ paints = [(0.36, 0.38, 0.33), (0.45, 0.42, 0.36), (0.42, 0.33, 0.33), (0.33, 0.36, 0.38), (0.4, 0.4, 0.37)]
+ out = []
+ for side in (-1, 1):
+ y = Y0
+ i = 0
+ while y < Y1:
+ w = rng.uniform(4.8, 7.2)
+ h = rng.uniform(16, 27)
+ name = f"bldg_{'L' if side < 0 else 'R'}{i}"
+ out.append(tenement(c, name, side, y, min(y + w, Y1), h, texs[(i + (side > 0)) % 3], shut[i % 2],
+ paints[(i * 2 + (side > 0)) % len(paints)], seed=i * 7 + (side > 0)))
+ y += w
+ i += 1
+ # Distant blocks beyond the modelled street (silhouettes with a few lit windows), fading into haze.
+ far = m_grimy("far_block", (0.12, 0.12, 0.13), 0.9, streak=0.2)
+ for k in range(10):
+ yy = Y1 + 4 + k * 5.5
+ for side in (-1, 1):
+ xf = FX0 if side < 0 else FX1
+ a, b_ = sorted((xf, xf - (1 if side < 0 else -1) * 8))
+ box(f"far_{side}_{k}", (a, yy, 0), (b_, yy + 5, rng.uniform(14, 30)), c, far, 0)
+ return out
+
+
+def sky_card(c):
+ """Soft harbour skyline: an emissive photo card far down the street, sized to fill the gap between facades."""
+ p = tex("hk_tex_skyline")
+ if not p:
+ return None
+ m, nt = new_mat("skyline")
+ if nt:
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(p, check_existing=True)
+ em = nt.nodes.new("ShaderNodeEmission")
+ em.inputs["Strength"].default_value = 0.9
+ L(nt, t.outputs["Color"], em.inputs["Color"])
+ nt.nodes.remove(bsdf(nt))
+ L(nt, em.outputs[0], nt.nodes["Material Output"].inputs["Surface"])
+ o = plane("skyline_card", 190, 107, c, m, loc=(3.0, 210, -14), rot=(0, 0, math.radians(180)))
+ o.visible_shadow = False
+ return o
+
+
+def world():
+ w = bpy.data.worlds.new("night_sky")
+ bpy.context.scene.world = w
+ w.use_nodes = True
+ nt = w.node_tree
+ bg = nt.nodes["Background"]
+ # Low cloud lit orange-magenta from below; darker straight up.
+ geo = nt.nodes.new("ShaderNodeTexCoord")
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ L(nt, geo.outputs["Generated"], sep.inputs[0])
+ r = ramp(nt, [(0.0, (0.05, 0.03, 0.04)), (0.25, (0.03, 0.022, 0.035)), (0.7, (0.008, 0.008, 0.014))], sep.outputs["Z"])
+ L(nt, r.outputs["Color"], bg.inputs["Color"])
+ bg.inputs["Strength"].default_value = 1.0
+ return w
+
+
+# ---------------------------------------------------------------- stall structure
+
+def corrugated(name, c, x0, x1, y0, y1, z0, z1, pitch=0.076, amp=0.009, mat=None, sag=0.05):
+ """Corrugated sheet sloping from (x0, z0) to (x1, z1), ribs running along X (down the slope), slight sag."""
+ nx, ny = 24, int((y1 - y0) / (pitch / 4))
+ verts, faces = [], []
+ for j in range(ny + 1):
+ y = y0 + (y1 - y0) * j / ny
+ wave = amp * math.sin(2 * math.pi * (y - y0) / pitch)
+ for i in range(nx + 1):
+ u = i / nx
+ x = x0 + (x1 - x0) * u
+ z = z0 + (z1 - z0) * u + wave - sag * math.sin(math.pi * u) * (0.6 + 0.4 * math.sin(y * 0.7))
+ verts.append((x, y, z))
+ for j in range(ny):
+ for i in range(nx):
+ a = j * (nx + 1) + i
+ faces.append((a, a + 1, a + nx + 2, a + nx + 1))
+ o = mesh_obj(name, verts, faces, c, mat)
+ sol = o.modifiers.new("thick", "SOLIDIFY")
+ sol.thickness = 0.003
+ for p in o.data.polygons:
+ p.use_smooth = True
+ return o
+
+
+def stall_frame(c):
+ steel = m_grimy("stall_steel", (0.08, 0.1, 0.09), 0.5, 0.7, streak=0.3)
+ green = m_grimy("stall_green", (0.07, 0.17, 0.11), 0.55, 0.2, streak=0.5)
+ a = AWN
+ # Poles at the street edge, a beam along the top, rafters back to the wall bracket.
+ for y in POLES_Y:
+ cylinder(f"awn_pole_{y:.1f}", 0.025, a["z_edge"] + 0.05, c, steel, loc=(POLE_X, y, 0.0), verts=12)
+ beam = box("awn_beam", (POLE_X - 0.025, a["y0"], a["z_edge"]), (POLE_X + 0.025, a["y1"], a["z_edge"] + 0.05), c, steel, 0.004)
+ box("awn_wall_rail", (a["x0"], a["y0"], a["z_wall"] - 0.05), (a["x0"] + 0.06, a["y1"], a["z_wall"] + 0.02), c, steel, 0.004)
+ for k, y in enumerate([a["y0"] + 0.1 + i * (a["y1"] - a["y0"] - 0.2) / 6 for i in range(7)]):
+ rod(f"awn_rafter_{k}", (a["x0"] + 0.06, y, a["z_wall"] - 0.03), (POLE_X, y, a["z_edge"] + 0.04), 0.013, c, steel)
+ tarp = corrugated("awning_tarp", c, a["x0"], a["x1"], a["y0"], a["y1"], a["z_wall"] + 0.03, a["z_edge"] + 0.07, mat=m_tarp())
+ tarp["awning"] = True
+ # Front valance board carrying the stall sign, facing the street (+X).
+ p = tex("hk_tex_stall_sign")
+ sign_m = m_image_sign("stall_sign", p) if p else green
+ # The board sits on the beam, mostly above the awning edge (bottom at ~2.1 m so people walk under it).
+ box("stall_sign_board", (POLE_X - 0.02, 0.2, a["z_edge"] - 0.45), (POLE_X + 0.03, 5.4, a["z_edge"] + 0.19), c, green, 0.006)
+ if p:
+ plane("stall_sign", 5.1, 0.6, c, sign_m, loc=(POLE_X + 0.035, 2.8, a["z_edge"] - 0.43), rot=(0, 0, math.radians(90)))
+ # A second sign on the walk-in end, facing the oncoming walker (-Y).
+ box("stall_sign_end", (-3.9, a["y0"] - 0.05, 2.0), (-1.7, a["y0"], 2.62), c, green, 0.006)
+ if p:
+ plane("stall_sign_end_face", 2.15, 0.58, c, sign_m, loc=(-2.8, a["y0"] - 0.055, 2.02), rot=(0, 0, 0))
+ return tarp
+
+
+def m_image_sign(name, path):
+ m, nt = new_mat(name)
+ if not nt:
+ return m
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(path, check_existing=True)
+ b = bsdf(nt)
+ L(nt, t.outputs["Color"], b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.4
+ b.inputs["Coat Weight"].default_value = 0.4
+ bw = nt.nodes.new("ShaderNodeRGBToBW")
+ L(nt, t.outputs["Color"], bw.inputs[0])
+ L(nt, bump(nt, bw.outputs[0], 0.2, 0.004).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def back_shelves(c):
+ """Steel wire shelving along the facade behind the cart: three tiers, x -4..-3.6."""
+ steel = m_grimy("shelf_steel", (0.35, 0.35, 0.34), 0.35, 0.9, streak=0.4)
+ x0, x1 = FX0 + 0.02, FX0 + 0.42
+ out = []
+ for (y0, y1) in ((-0.3, 1.6), (1.7, 3.6), (3.7, 5.8)):
+ for yy in (y0, y1 - 0.03):
+ for xx in (x0, x1 - 0.03):
+ box(f"shelf_post_{yy:.1f}_{xx:.1f}", (xx, yy, 0), (xx + 0.03, yy + 0.03, 2.3), c, steel, 0.003)
+ for z in (1.25, 1.7, 2.15):
+ s = box(f"shelf_{y0:.1f}_{z:.2f}", (x0, y0, z), (x1, y1, z + 0.025), c, steel, 0.003)
+ s["support"] = True
+ out.append(s)
+ # Steel prep table at the far end of the stall (beyond the wok range).
+ t = box("prep_table", (-3.55, 4.1, 0.86), (-2.7, 5.75, 0.9), c, m_grimy("prep_top", (0.5, 0.5, 0.5), 0.3, 1.0, 0.5), 0.004)
+ t["support"] = True
+ sh = box("prep_table_shelf", (-3.5, 4.15, 0.18), (-2.75, 5.7, 0.2), c, steel, 0.003)
+ sh["support"] = True
+ for yy in (4.12, 5.7):
+ for xx in (-3.53, -2.75):
+ box(f"prep_leg_{yy:.1f}_{xx:.1f}", (xx, yy, 0), (xx + 0.03, yy + 0.03, 0.86), c, steel, 0.003)
+ # Behind the kitchen: old white tiles to 1.5 m, greasy green-painted sheet metal above, menu strips on top.
+ box("kitchen_tiles", (FX0 - 0.01, -0.5, 0.0), (FX0 + 0.015, 6.0, 1.5), c, m_kitchen_tile(), 0)
+ box("kitchen_sheet", (FX0 - 0.01, -0.5, 1.5), (FX0 + 0.012, 6.0, 3.15), c,
+ m_grimy("kitchen_sheet_green", (0.12, 0.2, 0.15), 0.4, 0.3, streak=0.9), 0)
+ p = tex("hk_tex_menu_strips")
+ if p:
+ plane("menu_strips", 2.2, 0.62, c, m_image_sign("menu_strips_mat", p), loc=(FX0 + 0.02, 4.75, 2.42),
+ rot=(0, 0, math.radians(90)))
+ return out
+
+
+def m_kitchen_tile():
+ m, nt = new_mat("tile_kitchen")
+ if not nt:
+ return m
+ co = texcoord(nt, "UV")
+ br = node(nt, "ShaderNodeTexBrick", Scale=1.0, **{"Mortar Size": 0.004, "Brick Width": 0.15, "Row Height": 0.15})
+ br.offset = 0.0
+ L(nt, co, br.inputs["Vector"])
+ br.inputs["Color1"].default_value = (0.62, 0.62, 0.57, 1)
+ br.inputs["Color2"].default_value = (0.58, 0.58, 0.53, 1)
+ br.inputs["Mortar"].default_value = (0.2, 0.18, 0.14, 1)
+ grease = ramp(nt, [(0.3, (1, 1, 1)), (0.75, (0.35, 0.26, 0.14))], noise(nt, 2.0, 6, 0.6, texcoord(nt, "Object")).outputs["Fac"])
+ b = bsdf(nt)
+ L(nt, mix(nt, 1.0, br.outputs["Color"], grease.outputs["Color"], "MULTIPLY"), b.inputs["Base Color"])
+ L(nt, ramp(nt, [(0.0, (0.5,) * 3), (1.0, (0.12,) * 3)], br.outputs["Fac"]).outputs["Color"], b.inputs["Roughness"])
+ L(nt, bump(nt, mathn(nt, "SUBTRACT", 1.0, br.outputs["Fac"]), 0.3, 0.002).outputs[0], b.inputs["Normal"])
+ return m
+
+
+def decal(name, w, h, c, mat, loc, rot, uv=(0, 0, 1, 1)):
+ """Plane facing -Y locally with a UV sub-rectangle (u0, v0, u1, v1) of its image."""
+ o = plane(name, w, h, c, mat, loc=loc, rot=rot)
+ u0, v0, u1, v1 = uv
+ lay = o.data.uv_layers[0]
+ for i, co in enumerate([(u0, v0), (u1, v0), (u1, v1), (u0, v1)]):
+ lay.data[i].uv = co
+ o["decal"] = True
+ return o
+
+
+POSTER_UV = [(0.0, 0.53, 0.33, 0.99), (0.35, 0.56, 0.66, 0.99), (0.68, 0.63, 0.99, 0.97),
+ (0.0, 0.03, 0.33, 0.48), (0.35, 0.05, 0.66, 0.48), (0.69, 0.06, 0.99, 0.45)]
+
+
+def street_detail(c):
+ """Fascia shop boards, posters on pilasters, cables strung across the street."""
+ # Fascia boards (shops closed: unlit, the street light picks them up). All names fictional.
+ names = ["陳記五金", "榮記理髮", "祥興茶行", "德利電器", "金源海味", "聯昌士多", "利源印務", "寶安藥房", "振興車房", "華昌米行",
+ "三和雜貨", "福來茶樓", "東成鐘錶", "新記燒臘"]
+ cols = [(0.55, 0.06, 0.05), (0.05, 0.16, 0.35), (0.65, 0.5, 0.08), (0.08, 0.3, 0.14), (0.75, 0.72, 0.65)]
+ ink = {0: (0.85, 0.75, 0.3), 1: (0.9, 0.9, 0.85), 2: (0.1, 0.05, 0.03), 3: (0.9, 0.85, 0.6), 4: (0.6, 0.05, 0.04)}
+ k = 0
+ for o in [o for o in bpy.data.objects if o.name.endswith("_fascia")]:
+ lo = Vector([min((o.matrix_world @ Vector(v))[i] for v in o.bound_box) for i in range(3)])
+ hi = Vector([max((o.matrix_world @ Vector(v))[i] for v in o.bound_box) for i in range(3)])
+ if lo.y < STALL["y1"] + 1 and hi.y > STALL["y0"] - 1 and lo.x < 0:
+ continue # the stall's own wall has the awning
+ side = -1 if lo.x < 0 else 1
+ xf = hi.x if side < 0 else lo.x
+ w = min(hi.y - lo.y - 0.6, 4.5)
+ yc = (lo.y + hi.y) / 2
+ ci = k % len(cols)
+ bm = m_grimy(f"fascia_board_{ci}", cols[ci], 0.45, streak=0.5)
+ a, b_ = sorted((xf, xf - side * 0.06))
+ box(f"fascia_board_{k}", (a, yc - w / 2, 3.12), (b_, yc + w / 2, 3.64), c, bm, 0.006)
+ rz = math.radians(90 if side < 0 else -90)
+ text_obj(f"fascia_text_{k}", names[k % len(names)], c, (xf - side * 0.065, yc, 3.38), (math.radians(90), 0, rz), 0.36,
+ S_text_mat(ink[ci]), vertical=False, extrude=0.004, bevel=0.001)
+ k += 1
+ # Posters on the ground-floor pilasters (the pilaster faces the street).
+ p = tex("hk_tex_posters")
+ if p:
+ pm = m_image_sign("posters_mat", p)
+ j = 0
+ for o in [o for o in bpy.data.objects if "_pil_" in o.name]:
+ if rng.random() < 0.55:
+ continue
+ lo = Vector([min((o.matrix_world @ Vector(v))[i] for v in o.bound_box) for i in range(3)])
+ hi = Vector([max((o.matrix_world @ Vector(v))[i] for v in o.bound_box) for i in range(3)])
+ side = -1 if lo.x < 0 else 1
+ xf = (hi.x + 0.003) if side < 0 else (lo.x - 0.003)
+ uv = POSTER_UV[j % 6]
+ asp = (uv[3] - uv[1]) / (uv[2] - uv[0])
+ w = 0.34
+ decal(f"poster_{j}", w, w * asp, c, pm, (xf, (lo.y + hi.y) / 2 + rng.uniform(-0.02, 0.02), rng.uniform(1.0, 1.6)),
+ (0, 0, math.radians(90 if side < 0 else -90) + rng.uniform(-0.04, 0.04)), uv)
+ j += 1
+ # Cables across the street (sagging catenaries) and along the facades.
+ cm = m_simple("cable_black", (0.01, 0.01, 0.01), 0.35)
+ for i, (y, z, dy, sag) in enumerate([(-6.5, 7.2, 1.0, 0.7), (2.5, 9.0, -0.6, 0.9), (8.5, 6.4, 0.5, 0.5),
+ (15.0, 8.2, 1.2, 0.8), (22.0, 10.5, -0.8, 1.0), (-11.0, 9.6, 0.4, 0.8)]):
+ cable(f"cable_x{i}", (FX0 + 0.1, y, z), (FX1 - 0.1, y + dy, z + rng.uniform(-0.6, 0.6)), sag, c, cm)
+ for i, (x, y0, y1, z) in enumerate([(FX0 + 0.12, -12, 2, 4.0), (FX0 + 0.12, 7, 20, 4.2), (FX1 - 0.12, -10, 18, 4.1)]):
+ cable(f"cable_f{i}", (x, y0, z), (x, y1, z + 0.2), 0.35, c, cm, r=0.012)
+
+
+def S_text_mat(col):
+ m, nt = new_mat(f"sign_ink_{col[0]:.2f}_{col[1]:.2f}")
+ if nt:
+ b = bsdf(nt)
+ b.inputs["Base Color"].default_value = (*col, 1)
+ b.inputs["Roughness"].default_value = 0.35
+ return m
+
+
+def cable(name, p0, p1, sag, c, mat, r=0.007, n=24):
+ p0, p1 = Vector(p0), Vector(p1)
+ cu = bpy.data.curves.new(name, "CURVE")
+ cu.dimensions = "3D"
+ cu.bevel_depth = r
+ cu.bevel_resolution = 2
+ sp = cu.splines.new("POLY")
+ sp.points.add(n)
+ for i in range(n + 1):
+ t = i / n
+ q = p0.lerp(p1, t)
+ q.z -= sag * 4 * t * (1 - t)
+ sp.points[i].co = (q.x, q.y, q.z, 1)
+ o = bpy.data.objects.new(name, cu)
+ c.objects.link(o)
+ cu.materials.append(mat)
+ return o
+
+
+def neon_signs(c):
+ """Projecting signs on the facades above the street: neon text (tubes = emissive extruded text on a dark box)
+ and backlit lightboxes from the generated textures. Every name is fictional."""
+ frame = m_simple("sign_frame", (0.02, 0.02, 0.022), 0.45, 0.6)
+ signs = []
+ N = [ # text, side, y, z, glyph size, colour, strength
+ ("夜來香", -1, 1.2, 5.6, 0.62, (1.0, 0.08, 0.12), 22),
+ ("金滿樓", -1, 8.6, 6.4, 0.7, (1.0, 0.55, 0.12), 18),
+ ("好運麻雀", -1, 14.8, 5.2, 0.55, (0.15, 0.9, 1.0), 20),
+ ("大德藥行", 1, 4.5, 6.2, 0.6, (0.2, 1.0, 0.45), 16),
+ ("新興旅館", 1, 11.5, 7.6, 0.66, (1.0, 0.25, 0.65), 20),
+ ("福興茶餐廳", 1, 19.0, 5.8, 0.52, (1.0, 0.85, 0.3), 14),
+ ("永昌押", -1, 22.5, 7.0, 0.72, (1.0, 0.12, 0.1), 18),
+ ("美髮", 1, -3.0, 5.0, 0.5, (0.7, 0.3, 1.0), 16),
+ ]
+ for k, (txt, side, y, z, s, col, st) in enumerate(N):
+ xf = FX0 if side < 0 else FX1
+ sgn = 1 if side < 0 else -1
+ w, h = s * 1.45, len(txt) * s * 0.92 + s * 0.4
+ xc = xf + sgn * (0.35 + w / 2)
+ bx = box(f"neon_box_{k}", (xc - w / 2, y - 0.09, z - h / 2), (xc + w / 2, y + 0.09, z + h / 2), c, frame, 0.01)
+ mat = m_emit(f"neon_{k}", col, st)
+ for face, ry in ((-1, 0), (1, 180)):
+ t = text_obj(f"neon_{k}_{'f' if face < 0 else 'b'}", txt, c, (xc, y + face * 0.095, z), (math.radians(90), 0, math.radians(ry)), s, mat)
+ signs.append(t)
+ # Outline tube around the box face.
+ for face in (-1, 1):
+ yy = y + face * 0.1
+ for (p0, p1) in (((xc - w / 2 + 0.04, z - h / 2 + 0.04), (xc + w / 2 - 0.04, z - h / 2 + 0.06)),
+ ((xc - w / 2 + 0.04, z + h / 2 - 0.06), (xc + w / 2 - 0.04, z + h / 2 - 0.04)),
+ ((xc - w / 2 + 0.04, z - h / 2 + 0.04), (xc - w / 2 + 0.06, z + h / 2 - 0.04)),
+ ((xc + w / 2 - 0.06, z - h / 2 + 0.04), (xc + w / 2 - 0.04, z + h / 2 - 0.04))):
+ box(f"neon_{k}_edge", (p0[0], yy - 0.006, p0[1]), (p1[0], yy + 0.006, p1[1]), c, mat, 0)
+ # Bracket to the wall.
+ a, b_ = sorted((xf, xc - sgn * w / 2))
+ box(f"neon_bracket_{k}", (a, y - 0.03, z + h / 2 - 0.1), (b_, y + 0.03, z + h / 2 - 0.04), c, frame, 0.004)
+ bx["sign"] = txt
+ # Lightboxes (generated art) closer to street level.
+ LB = [("hk_tex_lightbox_a", 1, 1.8, 4.3), ("hk_tex_lightbox_b", -1, 11.2, 4.4), ("hk_tex_lightbox_c", 1, 15.8, 4.6)]
+ for k, (tid, side, y, z) in enumerate(LB):
+ p = tex(tid)
+ if not p:
+ continue
+ xf = FX0 if side < 0 else FX1
+ sgn = 1 if side < 0 else -1
+ w, h = 0.95, 1.3
+ xc = xf + sgn * (0.3 + w / 2)
+ box(f"lightbox_{k}", (xc - w / 2, y - 0.12, z - h / 2), (xc + w / 2, y + 0.12, z + h / 2), c, frame, 0.01)
+ m = m_lightbox(f"lightbox_{k}_mat", p)
+ for face, ry in ((-1, 0), (1, 180)):
+ plane(f"lightbox_{k}_{'f' if face < 0 else 'b'}", w - 0.06, h - 0.06, c, m,
+ loc=(xc, y + face * 0.125, z - h / 2 + 0.03), rot=(0, 0, math.radians(ry)))
+ return signs
+
+
+def build():
+ c = coll("shell")
+ st = coll("street")
+ stc = coll("stall")
+ sg = coll("signs")
+ world()
+ ground(st)
+ facades(c)
+ sky_card(c)
+ stall_frame(stc)
+ back_shelves(stc)
+ neon_signs(sg)
+ bpy.context.view_layer.update()
+ street_detail(coll("street_detail"))
+ bpy.context.view_layer.update()
diff --git a/scenes/hk-dai-pai-dong/scripts/shoot.sh b/scenes/hk-dai-pai-dong/scripts/shoot.sh
new file mode 100644
index 0000000..bffa69a
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/shoot.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+# camrig on hk.blend through the GPU queue with OptiX on. bash scenes/hk-dai-pai-dong/scripts/shoot.sh [shoot.py args...]
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+bash pipeline/gpu_run.sh "$BLENDER" -b ${BLEND:-scenes/hk-dai-pai-dong/hk.blend} \
+ --python scenes/hk-dai-pai-dong/scripts/gpu_prefs.py --python camera/shoot.py -- \
+ --shots $ANYSCENE_ROOT/scenes/hk-dai-pai-dong/shots.json --out $ANYSCENE_ROOT/scenes/hk-dai-pai-dong/out/shots "$@"
diff --git a/scenes/hk-dai-pai-dong/scripts/steam.py b/scenes/hk-dai-pai-dong/scripts/steam.py
new file mode 100644
index 0000000..a85cc1c
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/steam.py
@@ -0,0 +1,179 @@
+"""Steam and vapor (design coordinates; build.py mirrors afterwards, the bake runs on the saved .blend).
+
+Mantaflow gas domains:
+ steam_range over the range + noodle boiler, under the hood (hood is a collision effector, open top)
+ steam_bowl a small one over the unfinished bowl on the counter
+Emitters are hidden discs just below each rim; flow density is broken up by an animated clouds texture so the
+plumes come out in wisps instead of a solid column. Bake with scenes/tokyo-ramen-shop/scripts/bake_steam.py (CPU, cache in
+scenes/tokyo-ramen-shop/cache/). The cache starts at PREROLL so plumes are fully developed at frame 1 (shots render 1..N).
+
+Plus kitchen_vapor: a drifting low-density noise volume in the kitchen that the pendants and hood strip pick up."""
+import math
+import os
+
+import bpy
+
+import shell as S
+from lib import L, SCENE_DIR, mathn, new_mat, noise, texcoord
+
+PREROLL = -70
+END = 300 # covers the ~11 s handheld walkthroughs
+CACHE = os.path.join(SCENE_DIR, "cache", "r2") # round 2; round-1 caches stay in cache/
+
+
+def _box_mesh(name, lo, hi, c):
+ bpy.ops.mesh.primitive_cube_add(size=1)
+ o = bpy.context.object
+ o.name = name
+ for uc in list(o.users_collection):
+ uc.objects.unlink(o)
+ c.objects.link(o)
+ o.scale = [hi[i] - lo[i] for i in range(3)]
+ o.location = [(hi[i] + lo[i]) / 2 for i in range(3)]
+ bpy.context.view_layer.objects.active = o
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ return o
+
+
+def steam_material(name="steam_vol", density=8.0):
+ m, nt = new_mat(name)
+ if nt:
+ nt.nodes.remove(nt.nodes["Principled BSDF"])
+ v = nt.nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Color"].default_value = (0.92, 0.92, 0.92, 1)
+ v.inputs["Density"].default_value = density
+ v.inputs["Density Attribute"].default_value = "density"
+ v.inputs["Anisotropy"].default_value = 0.55 # forward scatter: glows when backlit by the hood strip
+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])
+ return m
+
+
+def _domain(name, lo, hi, res, c, noise_scale=2):
+ o = _box_mesh(name, lo, hi, c)
+ mod = o.modifiers.new("Fluid", "FLUID")
+ mod.fluid_type = "DOMAIN"
+ ds = mod.domain_settings
+ ds.domain_type = "GAS"
+ ds.resolution_max = res
+ ds.time_scale = 1.0
+ ds.use_adaptive_timesteps = True
+ ds.cfl_condition = 3.0
+ ds.alpha = -0.15 # density sinks a little (steam is moist), heat carries it up
+ ds.beta = 1.6
+ ds.vorticity = 0.25
+ ds.use_dissolve_smoke = True
+ ds.dissolve_speed = 60
+ ds.use_dissolve_smoke_log = True
+ ds.use_collision_border_top = False
+ ds.use_noise = True
+ ds.noise_scale = noise_scale
+ ds.noise_strength = 1.2
+ ds.noise_pos_scale = 1.6
+ ds.cache_type = "ALL"
+ ds.cache_data_format = "OPENVDB"
+ ds.cache_directory = os.path.join(CACHE, name)
+ ds.cache_frame_start = PREROLL
+ ds.cache_frame_end = END
+ o.data.materials.append(steam_material())
+ o.visible_shadow = False
+ o.display_type = "WIRE"
+ return o
+
+
+def _clouds(name, size=0.06):
+ t = bpy.data.textures.get(name) or bpy.data.textures.new(name, "CLOUDS")
+ t.noise_scale = size
+ t.noise_depth = 3
+ t.contrast = 1.6
+ return t
+
+
+def _emitter(name, x, y, z, r, c, density=0.55, temp=2.0, tex=None, vel=0.25):
+ bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=0.012, vertices=24, location=(x, y, z))
+ o = bpy.context.object
+ o.name = name
+ for uc in list(o.users_collection):
+ uc.objects.unlink(o)
+ c.objects.link(o)
+ mod = o.modifiers.new("Fluid", "FLUID")
+ mod.fluid_type = "FLOW"
+ fs = mod.flow_settings
+ fs.flow_type = "SMOKE"
+ fs.flow_behavior = "INFLOW"
+ fs.flow_source = "MESH"
+ fs.surface_distance = 1.0 # effectively in cells: 0.012 only emitted from discs wide enough to contain cell centres
+ fs.density = density
+ fs.temperature = temp
+ fs.smoke_color = (0.95, 0.95, 0.95)
+ fs.subframes = 1
+ fs.use_initial_velocity = True
+ fs.velocity_normal = vel
+ if tex:
+ fs.use_texture = True
+ fs.noise_texture = tex
+ fs.texture_map_type = "AUTO"
+ fs.texture_size = 1.0
+ # Scroll the texture so the puffs change over time.
+ d = fs.driver_add("texture_offset")
+ d.driver.expression = "frame * 0.018"
+ o.hide_render = True
+ o.display_type = "WIRE"
+ return o
+
+
+def build(c, pots, boiler, bowl):
+ """pots: [(x, y, rim_z, r)], boiler: (x, y, top_z, w, d) or None, bowl: (x, y, rim_z, r) or None."""
+ tex = _clouds("steam_puffs")
+ # Floor well below the pot rims (pots sit in the burner grates, rims ~0.76-0.9 m): emitters must not touch the border cells.
+ dom = _domain("steam_range", (S.W - 0.85, 3.3, 0.6), (S.W - 0.015, 6.15, 2.25), 200, c)
+ # Only pots on the range / back counter inside the domain steam (shelf and floor pots are cold).
+ pots = [p for p in pots if S.W - 0.85 < p[0] and 3.3 < p[1] < 6.15 and p[2] < 1.6]
+ for i, (x, y, z, r) in enumerate(pots):
+ _emitter(f"steam_src_pot{i}", x, y, z - 0.03, r * 0.85, c, density=1.0 - 0.15 * i, temp=2.2, tex=tex)
+ if boiler:
+ x, y, z, w, d = boiler
+ for j, dy in enumerate((-0.12, 0.12)):
+ _emitter(f"steam_src_boiler{j}", x - 0.04, y + dy, z - 0.02, 0.11, c, density=0.8, temp=2.6, tex=tex, vel=0.4)
+ # The hood is a collision object for the range domain (steam pools under it and rolls out the front).
+ hood = bpy.data.objects.get("hood")
+ if hood:
+ m = hood.modifiers.new("Fluid", "FLUID")
+ m.fluid_type = "EFFECTOR"
+ m.effector_settings.effector_type = "COLLISION"
+ if bowl:
+ x, y, z, r = bowl
+ _domain("steam_bowl", (x - 0.24, y - 0.24, z - 0.12), (x + 0.24, y + 0.24, z + 0.6), 110, c)
+ _emitter("steam_src_bowl", x, y, z - 0.035, r * 0.7, c, density=0.6, temp=1.6, tex=_clouds("steam_puffs_bowl", 0.03), vel=0.08)
+ kitchen_vapor(c)
+ return dom
+
+
+def kitchen_vapor(c, density=0.035):
+ """Drifting vapor layer in the kitchen, thicker toward the hood and the ceiling."""
+ m, nt = new_mat("kitchen_vapor")
+ if nt:
+ nt.nodes.remove(nt.nodes["Principled BSDF"])
+ co = texcoord(nt, "Object")
+ mp = nt.nodes.new("ShaderNodeMapping")
+ L(nt, co, mp.inputs["Vector"])
+ mp.inputs["Scale"].default_value = (1.0, 1.0, 1.6)
+ n = noise(nt, 1.8, 4, 0.55, mp.outputs[0], dim="4D")
+ n.inputs["W"].driver_add("default_value").driver.expression = "frame * 0.006"
+ # Slow upward drift of the pattern.
+ mp.inputs["Location"].driver_add("default_value", 2).driver.expression = "-frame * 0.002"
+ wisps = mathn(nt, "MAXIMUM", mathn(nt, "SUBTRACT", n.outputs["Fac"], 0.42), 0.0)
+ gen = nt.nodes.new("ShaderNodeSeparateXYZ")
+ L(nt, texcoord(nt, "Generated"), gen.inputs[0])
+ up = mathn(nt, "POWER", gen.outputs["Z"], 1.5)
+ # Toward the hood wall: +X in design space, but the mirror only moves objects, so it ends up at generated X=0.
+ side = mathn(nt, "POWER", mathn(nt, "SUBTRACT", 1.0, gen.outputs["X"]), 2.0)
+ k = mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", wisps, mathn(nt, "ADD", up, side)), density * 14)
+ v = nt.nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Color"].default_value = (0.9, 0.9, 0.9, 1)
+ v.inputs["Anisotropy"].default_value = 0.5
+ L(nt, mathn(nt, "ADD", k, density * 0.25), v.inputs["Density"])
+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])
+ o = _box_mesh("kitchen_vapor", (S.PASS_X + 0.25, 0.9, 1.0), (S.W - 0.02, S.D - 0.05, S.H - 0.02), c)
+ o.data.materials.append(m)
+ o.visible_shadow = False
+ return o
diff --git a/scenes/hk-dai-pai-dong/scripts/stills.py b/scenes/hk-dai-pai-dong/scripts/stills.py
new file mode 100644
index 0000000..031618a
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/stills.py
@@ -0,0 +1,27 @@
+"""Final hero stills from hk.blend (cameras cam_<name> from build.py): 1920x804, 64 spp, glare on, no motion blur.
+blender -b scenes/hk-dai-pai-dong/hk.blend --python .../gpu_prefs.py --python .../stills.py -- street,wok,table,flame
+"""
+import os
+import sys
+import time
+
+import bpy
+
+names = sys.argv[sys.argv.index("--") + 1].split(",")
+sc = bpy.context.scene
+sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = 1920, 804, 100
+sc.cycles.samples = 64
+sc.render.use_motion_blur = False
+sc.frame_set(60)
+out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "out", "stills")
+os.makedirs(out, exist_ok=True)
+for n in names:
+ cam = bpy.data.objects["cam_" + n]
+ cam.data.dof.use_dof = True
+ cam.data.dof.aperture_fstop = 2.8
+ cam.data.dof.focus_distance = {"street": 9.5, "wok": 1.5, "table": 2.4, "flame": 0.95}.get(n, 3.0)
+ sc.camera = cam
+ sc.render.filepath = os.path.join(out, f"{n}.png")
+ t0 = time.time()
+ bpy.ops.render.render(write_still=True)
+ print(f"STILL {n} {time.time() - t0:.0f}s", flush=True)
diff --git a/scenes/hk-dai-pai-dong/scripts/validate.py b/scenes/hk-dai-pai-dong/scripts/validate.py
new file mode 100644
index 0000000..8c24f27
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/scripts/validate.py
@@ -0,0 +1,163 @@
+"""Placement validator: FLOAT (contact-point gap, as pipeline/grounding.py), CLIP (prop x prop), FURNITURE (prop x fixed structure), SCALE, OUT.
+
+Run after every dressing pass (build.py does). resolve() spiral-searches small clashing/floating props to a clear spot.
+Some reports are legitimate and listed in ACCEPT with the reason (woks sit in the burner wells, etc.).
+"""
+import itertools
+import json
+import math
+import os
+import re
+
+import bpy
+from mathutils import Matrix, Vector
+from mathutils.bvhtree import BVHTree
+
+import shell as S
+from lib import SCENE_DIR
+
+FIXED_COLLS = ("stall", "shell", "street", "signs")
+SKIP_FIXED = ("pavement", "road", "line_", "drain_", "harbour", "kerb", "far_", "skyline") # ground is the support
+GROUND_ONLY = ("hk_stool", "hk_table") # furniture that must stand on the pavement/road, never on another prop
+GROUND = ("pavement", "road", "kerb")
+# (regex on "a x b" or the prop name, reason): reviewed and accepted reports.
+ACCEPT = [
+ (r"wok_(rice|back).* x wok_range", "woks sit down in the burner wells"),
+ (r"wok_range x wok_(rice|back)", "woks sit down in the burner wells"),
+ (r"FLOAT .*hk_umbrella", "leans on the awning pole"),
+ (r"SCALE hk_newspaper", "direct-modelled folded paper (8 mm), manifest h was for the generated one"),
+]
+
+
+def _bb(o):
+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]
+ for ch in o.children:
+ pts += [ch.matrix_world @ Vector(c) for c in ch.bound_box]
+ return (Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))),
+ Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts))))
+
+
+def _tree(o, dg, lift=0.0):
+ ev = o.evaluated_get(dg)
+ me = ev.to_mesh()
+ me.transform(Matrix.Translation((0, 0, lift)) @ o.matrix_world)
+ t = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])
+ ev.to_mesh_clear()
+ return t
+
+
+def _overlap(a, b):
+ (la, ha), (lb, hb) = a, b
+ return not any(ha[i] < lb[i] or hb[i] < la[i] for i in range(3))
+
+
+def check(placed):
+ import dress
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ man = {p["id"]: p for p in json.load(open(os.path.join(SCENE_DIR, "assets.json"), encoding="utf-8"))["generate"]}
+ issues = [] # (kind, obj, text)
+ objs = [o for o, _ in placed if o.name in bpy.data.objects]
+ boxes = {o.name: _bb(o) for o in objs}
+ for o, mode in placed:
+ if o.name not in bpy.data.objects:
+ continue
+ lo, hi = boxes[o.name]
+ if mode == "rest":
+ # contact points (lowest vertices), not the bbox: a stool whose box clipped a table top sat 74 cm up
+ g, on = dress.contact_gap(o)
+ if g is None or g > 0.01:
+ gap = "nothing below" if g is None else f"{g * 100:.1f} cm above {on}"
+ issues.append(("FLOAT", o, f"FLOAT {o.name} ({o['prop_id']}): {gap}"))
+ elif o["prop_id"].startswith(GROUND_ONLY) and not on.startswith(GROUND):
+ issues.append(("FLOAT", o, f"GROUND {o.name} ({o['prop_id']}): stands on {on}, not the ground"))
+ if lo.x < S.FX0 - 0.6 or hi.x > S.FX1 + 0.6 or lo.z < S.ROAD_Z - 0.03:
+ issues.append(("OUT", o, f"OUT {o.name}: x {lo.x:.2f}..{hi.x:.2f} z {lo.z:.2f}"))
+ spec = man.get(o.get("prop_id"))
+ if spec:
+ d = o.dimensions
+ target = spec.get("h") or spec["m"]
+ got = d.z if "h" in spec else max(d)
+ want = target * o.scale.z
+ if abs(got / o.scale.z - target) / target > 0.15:
+ issues.append(("SCALE", o, f"SCALE {o.name}: {got:.2f} m vs {want:.2f} m"))
+ trees = {}
+ for a, b in itertools.combinations(objs, 2):
+ if not _overlap(boxes[a.name], boxes[b.name]):
+ continue
+ ta = trees.get(a.name) or trees.setdefault(a.name, _tree(a, dg))
+ tb = trees.get(b.name) or trees.setdefault(b.name, _tree(b, dg))
+ n = len(ta.overlap(tb))
+ if n > 30:
+ small = a if (boxes[a.name][1] - boxes[a.name][0]).length < (boxes[b.name][1] - boxes[b.name][0]).length else b
+ issues.append(("CLIP", small, f"CLIP {a.name} x {b.name}: {n} tri pairs"))
+ fixed = [o for o in bpy.context.scene.objects if o.type in ("MESH", "FONT") and o.visible_get()
+ and any(c.name in FIXED_COLLS for c in o.users_collection) and not o.name.startswith(SKIP_FIXED)]
+ fb = {f.name: _bb(f) for f in fixed}
+ ft = {}
+ for o in objs:
+ t = None
+ for f in fixed:
+ if not _overlap(boxes[o.name], fb[f.name]):
+ continue
+ t = t or _tree(o, dg, lift=0.003)
+ tf = ft.get(f.name) or ft.setdefault(f.name, _tree(f, dg))
+ n = len(t.overlap(tf))
+ if n > 15:
+ issues.append(("FURNITURE", o, f"FURNITURE {o.name} x {f.name}: {n} tri pairs"))
+ return issues
+
+
+def accepted(text):
+ for pat, why in ACCEPT:
+ if re.search(pat, text):
+ return why
+ return None
+
+
+def resolve(placed, rounds=2):
+ """Spiral-search small props (< 0.6 m) that clash or float to the nearest clear spot on the same support."""
+ import dress
+ moved = 0
+ for _ in range(rounds):
+ bad = {o.name: o for kind, o, t in check(placed) if kind in ("CLIP", "FURNITURE", "FLOAT") and not accepted(t)
+ and o.get("mode") == "rest" and max(o.dimensions) < 0.6}
+ if not bad:
+ break
+ for o in bad.values():
+ x0, y0 = o.location.x, o.location.y
+ best = None
+ for k in range(1, 40):
+ ang = k * 2.4
+ r = 0.03 * math.sqrt(k) * 1.6
+ o.location.x, o.location.y = x0 + r * math.cos(ang), y0 + r * math.sin(ang)
+ dress._drop(o, o.get("start_z", 1.5))
+ bpy.context.view_layer.update()
+ if not [t for kind, oo, t in check([(o, "rest")] + [(p, m) for p, m in placed if p is not o and _overlap(_bb(p), _bb(o))])
+ if oo is o or o.name in t]:
+ best = (o.location.x, o.location.y, o.location.z)
+ break
+ if best:
+ moved += 1
+ else:
+ o.location.x, o.location.y = x0, y0
+ dress._drop(o, o.get("start_z", 1.5))
+ print("RESOLVE moved", moved, flush=True)
+ return moved
+
+
+def run(placed, report_path):
+ issues = check(placed)
+ lines = []
+ for kind, o, t in issues:
+ why = accepted(t)
+ lines.append(f"{t} [accepted: {why}]" if why else t)
+ open_ = [l for l in lines if "[accepted" not in l]
+ os.makedirs(os.path.dirname(report_path), exist_ok=True)
+ with open(report_path, "w", encoding="utf-8") as f:
+ f.write("\n".join(lines) or "OK")
+ f.write(f"\n\nVALIDATE {len(open_)} open, {len(lines) - len(open_)} accepted, {len(placed)} props\n")
+ print(f"VALIDATE {len(open_)} open, {len(lines) - len(open_)} accepted over {len(placed)} props -> {report_path}", flush=True)
+ for l in open_:
+ print(" ", l)
+ return open_
diff --git a/scenes/hk-dai-pai-dong/shots.json b/scenes/hk-dai-pai-dong/shots.json
new file mode 100644
index 0000000..1b0df1c
--- /dev/null
+++ b/scenes/hk-dai-pai-dong/shots.json
@@ -0,0 +1,392 @@
+{
+ "defaults": {
+ "fps": 24,
+ "res": [
+ 1920,
+ 804
+ ],
+ "aspect": "2.39",
+ "samples": 48,
+ "shutter": 180,
+ "sensor": "s35",
+ "fstop": 2.8,
+ "ease": "inout",
+ "handheld": 0.15,
+ "blades": 0,
+ "ratio": 1.3,
+ "lens_fx": {
+ "distortion": 0.01,
+ "dispersion": 0.01,
+ "glare": "fog",
+ "glare_threshold": 1.4,
+ "glare_strength": 0.12
+ }
+ },
+ "shots": [
+ {
+ "name": "s1_street_crane",
+ "frames": 120,
+ "move": "crane",
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 5.6,
+ -11.0,
+ 3.4
+ ],
+ "aim": [
+ -1.6,
+ 3.4,
+ 2.6
+ ],
+ "lens": 32
+ },
+ {
+ "t": 1,
+ "pos": [
+ 4.3,
+ -7.4,
+ 1.48
+ ],
+ "aim": [
+ -1.8,
+ 2.8,
+ 1.45
+ ],
+ "lens": 32
+ }
+ ],
+ "focus": {
+ "mode": "point",
+ "pos": [
+ -1.3,
+ 1.0,
+ 1.4
+ ]
+ },
+ "fstop": 4.0,
+ "handheld": 0.12
+ },
+ {
+ "name": "s2_teapot_wok_rack",
+ "frames": 144,
+ "move": "dolly",
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 0.38,
+ -1.42,
+ 1.3
+ ],
+ "aim": [
+ -1.9,
+ 1.6,
+ 0.8
+ ],
+ "lens": 75
+ },
+ {
+ "t": 1,
+ "pos": [
+ 0.27,
+ -1.28,
+ 1.27
+ ],
+ "aim": [
+ -1.9,
+ 1.6,
+ 0.8
+ ],
+ "lens": 75
+ }
+ ],
+ "focus": {
+ "mode": "rack",
+ "keys": [
+ {
+ "t": 0,
+ "obj": "teapot_t1"
+ },
+ {
+ "t": 0.35,
+ "obj": "teapot_t1"
+ },
+ {
+ "t": 0.7,
+ "obj": "wok_rice"
+ }
+ ]
+ },
+ "fstop": 2.0,
+ "handheld": 0.3
+ },
+ {
+ "name": "s3_wok_push",
+ "frames": 96,
+ "move": "push_in",
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ -1.3,
+ 3.55,
+ 1.12
+ ],
+ "aim": [
+ -3.0,
+ 2.9,
+ 0.68
+ ],
+ "lens": 35
+ },
+ {
+ "t": 1,
+ "pos": [
+ -1.92,
+ 3.17,
+ 0.98
+ ],
+ "aim": [
+ -3.0,
+ 2.9,
+ 0.68
+ ],
+ "lens": 35
+ }
+ ],
+ "focus": {
+ "mode": "track",
+ "obj": "wok_rice"
+ },
+ "fstop": 2.0,
+ "handheld": 0.25
+ },
+ {
+ "name": "s4_neon_tilt",
+ "frames": 120,
+ "move": "tilt",
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 1.8,
+ -2.2,
+ 1.35
+ ],
+ "aim": [
+ -2.6,
+ 7.5,
+ 9.0
+ ],
+ "lens": 28
+ },
+ {
+ "t": 1,
+ "pos": [
+ 1.8,
+ -2.2,
+ 1.35
+ ],
+ "aim": [
+ -2.0,
+ 2.4,
+ 1.3
+ ],
+ "lens": 28
+ }
+ ],
+ "focus": {
+ "mode": "rack",
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ -3.0,
+ 8.6,
+ 6.4
+ ]
+ },
+ {
+ "t": 0.3,
+ "pos": [
+ -3.0,
+ 8.6,
+ 6.4
+ ]
+ },
+ {
+ "t": 0.9,
+ "pos": [
+ -1.6,
+ 1.8,
+ 1.4
+ ]
+ }
+ ]
+ },
+ "fstop": 2.8,
+ "handheld": 0.2
+ },
+ {
+ "name": "h1_walk_in_to_wok",
+ "frames": 480,
+ "move": "path",
+ "ease": "inout",
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 3.9,
+ -5.6,
+ 1.47
+ ],
+ "aim": [
+ -1.8,
+ 3.2,
+ 1.65
+ ],
+ "lens": 24
+ },
+ {
+ "t": 0.25,
+ "pos": [
+ 3.1,
+ -2.6,
+ 1.48
+ ],
+ "aim": [
+ -2.0,
+ 3.0,
+ 1.4
+ ]
+ },
+ {
+ "t": 0.5,
+ "pos": [
+ 2.35,
+ 1.35,
+ 1.5
+ ],
+ "aim": [
+ -2.4,
+ 3.0,
+ 1.2
+ ]
+ },
+ {
+ "t": 0.74,
+ "pos": [
+ 0.35,
+ 2.0,
+ 1.58
+ ],
+ "aim": [
+ -2.8,
+ 2.9,
+ 0.9
+ ]
+ },
+ {
+ "t": 1,
+ "pos": [
+ -1.8,
+ 3.2,
+ 1.4
+ ],
+ "aim": [
+ -3.0,
+ 2.9,
+ 0.68
+ ],
+ "lens": 26
+ }
+ ],
+ "fstop": 2.8,
+ "handheld": {
+ "profile": "walk",
+ "amount": 1.0
+ }
+ },
+ {
+ "name": "h2_walk_tables_neon",
+ "frames": 408,
+ "move": "path",
+ "ease": "inout",
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 2.9,
+ 9.8,
+ 1.47
+ ],
+ "aim": [
+ -1.0,
+ 3.0,
+ 1.3
+ ],
+ "lens": 24
+ },
+ {
+ "t": 0.3,
+ "pos": [
+ 2.75,
+ 6.4,
+ 1.47
+ ],
+ "aim": [
+ -2.5,
+ 4.4,
+ 1.2
+ ]
+ },
+ {
+ "t": 0.55,
+ "pos": [
+ 2.85,
+ 3.3,
+ 1.47
+ ],
+ "aim": [
+ -3.0,
+ 3.2,
+ 1.0
+ ]
+ },
+ {
+ "t": 0.78,
+ "pos": [
+ 1.7,
+ 1.75,
+ 1.47
+ ],
+ "aim": [
+ -2.6,
+ 2.4,
+ 1.6
+ ]
+ },
+ {
+ "t": 1,
+ "pos": [
+ 1.2,
+ 1.5,
+ 1.45
+ ],
+ "aim": [
+ -2.6,
+ 9.0,
+ 6.0
+ ]
+ }
+ ],
+ "fstop": 2.8,
+ "handheld": {
+ "profile": "walk",
+ "amount": 1.0
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/scenes/mission-control-1970s/NOTES.md b/scenes/mission-control-1970s/NOTES.md
new file mode 100644
index 0000000..2a939db
--- /dev/null
+++ b/scenes/mission-control-1970s/NOTES.md
@@ -0,0 +1,105 @@
+# Mission control 1970s — notes
+
+Brief and decisions: `brief.md`. Fictional agency *Aurora Flight Directorate*, mission PERSEUS 7; all screen text and
+labels are invented (screens.py, placards in dress.py).
+
+## Pipeline (run from the repo root, every Blender call through `pipeline/gpu_run.sh`)
+
+1. `node scenes/mission-control-1970s/scripts/refs.mjs` — Sunburst refs for `assets.json` (props + textures + detail concept).
+ Brand check: `scripts/refsheet.sh`. Rejected refs are kept in `refs/mission-control-1970s/props_rejected/`.
+2. `node scenes/mission-control-1970s/scripts/gen3d.mjs [ids]` — Tripo H3.1 + Meshy 7.1 per prop, 12 at a time.
+3. `scripts/compare_batch.sh` (same-light renders, 10-prop GPU chunks) + `scripts/sheet.sh` → `picks.json`.
+4. `scripts/prep.py` → `props/<id>.blend` (+ `props/<id>.json` sidecar), then `scripts/fixes.py` (CRT face patches).
+5. `scripts/screens.py` → `refs/mission-control-1970s/tex/screens/*.png` (CRT pages + wall display, Eevee + numpy bloom).
+6. `scripts/build.py` → `mc.blend`: shell → dress (+ validate with spiral resolve) → screens → grime → lights → haze → post.
+7. Shots: `shots.json`; `scripts/shoot.sh` (GPU prefs + camrig), `scripts/check_path.py`, `scripts/render_finals.sh`
+ (24-frame chunks, grade, frame-count check).
+8. Breakdown: `scripts/bts.py` + `scripts/bts_render.sh` → `breakdown/mission-control-1970s/clips/`.
+
+## Gotchas
+
+- `bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")` returns `""` in 5.0.1; the shared
+ `pipeline/render_compare.py` (and the repair copy) fail every render with "Cannot read ''". Join the path yourself.
+- `render_compare.py` renders every prop of every scene in `assets/gen` (no id filter) and points the Tripo camera at the
+ side (yaw.json lookup). The scene copy `scripts/compare.py` takes ids and fixes Tripo's +X front with yaw 90.
+- Prep skip-by-mtime against `picks.json` re-prepped every prop on every pick edit, which silently dropped the CRT
+ patches from fixes.py. Now a sidecar `props/<id>.json` records model/yaw/lay; any re-prep must be followed by fixes.py.
+- The generated consoles' own writing shelf is ~20 cm deep at 0.57 m; clutter had nowhere to go. A scripted laminate desk
+ run (0.46 m) sits in front of each row, ending 6 mm short of the console fronts so the validator stays clean.
+- Drop rays must start below the console's upper housing; a ray starting at desk+0.95 m began *inside* the housing and hit
+ its inner faces. Props with overhangs (desk lamps, chairs) are dropped by their lowest vertices, not their bbox.
+- Validator: furniture collections must exclude placed props (each placed prop otherwise "intersects" itself) and the
+ placards (they sit on console tops on purpose). Wall props need ~3.5 cm off the right/back walls (acoustic panels).
+- Screen detection (fixes.py): green-or-dark texels facing -Y in the upper 45 % of the front; the b/w ceiling TV needed a
+ grey-glass mask instead. Round radar tubes bulge ~2 cm past the bezel plane: a 6 mm dome left a hole in the middle.
+- Glass ashtray: both generators bake opaque grey glass. Transmission comes from an HSV mask on the albedo (low saturation,
+ light) so the butts stay opaque. Don't use that mask on cream enamel (the water cooler would turn to glass).
+- Lamp glow on console buttons is texture emission with `emission_sampling = NONE`; CRT patches keep sampling (192 faces
+ each) so they light the desks.
+- Blender ray_cast hits volume boxes (haze) and decals: run all drops before haze/grime.
+- Eevee framing renders show the windows black; check window views in Cycles.
+- camrig handheld walk: keep 0.45 m from every mesh; the window aisle is 1.95 m wide, so the path hugs x ≈ 1.0–1.4.
+- Render cost (1920×804, 48 spp, OptiX denoise): a `--still` is ~15 s but frames in final (animation) mode were
+ ~24–34 s. Bisected with 4-frame chunks: no haze ~4 s/frame; room haze alone ~7; smoke curls alone ~7; both ~21 —
+ the curls sit inside the room volume and overlapping volumes are what cost. Motion blur, lens FX, the frame-driven
+ noise drift and heterogeneous vs homogeneous room haze made little difference; persistent data made it *slower*
+ (29 vs 24 s). Fix: homogeneous room layers, and every shot except the push-in renders with the curls hidden
+ (`NOCURL` → `scripts/nocurl.py` in shoot.sh). Time chunks, not stills, before estimating a render budget.
+- Stopping a background task (the harness's TaskStop) killed only the outer shell: `render_finals.sh` and
+ `bts_render.sh` kept running, kept queueing chunks, and rendered frames from two different builds. Kill the loop
+ scripts by pid (`ps -ef | grep render_finals`), then their waiting `gpu_run.sh` children, before restarting.
+- A GUI Blender (not this scene's) was open on the box holding ~2 GB and some GPU time; GPU memory sat at 14.5/16 GB
+ during finals. Left alone (not ours).
+- Grounding (v2): the validator's bbox FLOAT check (1 cm) missed contact-point gaps. `drop()` takes the *highest* hit
+ under a prop's base, so anything whose feet overhang the desk's 2 mm metal edge lip hung ~2.5 mm over the laminate,
+ and the CRT terminal, dropped after the hard hat at the same spot, landed on the hat (2 cm up once resolve moved it).
+ validate.py now has GROUND (rays from the lowest vertices, as `pipeline/grounding.py`, 2 mm tolerance) and
+ `settle()` after resolve; placards settle with their consoles. `pipeline/grounding.py --all` leaves only wall-hung
+ and bracket-hung shell parts. Low-angle check stills: `scripts/lowcams.py` → out/sheets/ground_lowangle.png.
+- Backdrop through the windows: a 96 m card at 45 m read as a wall-sized photo. 24 m reads as ~3 km away, but its
+ edges show; the final card is 72 m with the image mapped to the middle third and EXTEND, so sky and marsh run on.
+
+## Results
+
+- 76 generated props (Tripo 30 / Meshy 46 picks, every pick with a reason in picks.json), 146 placed instances,
+ validator 0 issues. fal spend for this scene ≈ $133 (84 images, 76 Tripo, 83 Meshy calls incl. failed retries).
+- Shots (1920×804, 48 spp, OptiX denoise, ffmpeg grade): orbital_push 5 s, fd_wide 6 s, display_rack 5 s,
+ printer_crane 5 s, walk_windows 20 s, walk_rows 17 s (both handheld walk profile). out/graded/*.mp4, reel
+ out/mc_reel.mp4 (58 s), chat copy out/mc_reel_chat.mp4 (25 MB). Hero stills: out/stills/.
+- **Farm frames:** 1,212 of the 1,392 final frames (fd_wide 61–144, display_rack, printer_crane, both walks) were
+ rendered elsewhere (PNG metadata: /data/anyscene-farm/bundles/d45a7c39d1bb879a/scene.blend, 48 spp, ~3 s/frame)
+ and copied into out/shots/*/frames at 16:50–16:53 — not by this session. Audited: complete sequences, the right
+ CR_<shot>_cam cameras, 48 spp, no visible seam against the local frames (fd_wide 60→61). Kept as they are.
+- v2 (grounded rebuild, mc.blend 22:05): all 1,392 frames re-rendered on the farm (v1 frames deleted in a disk
+ clean-up), regraded 22:27; graded mp4s and reel replaced, same durations, reel 1,392 frames.
+- Breakdown: breakdown/mission-control-1970s/clips/{a_layout 144, b_props 240, c_materials 144, d_lighting 240}.mp4
+ + `*_contact.png`. d_lighting is the slow one (~5–22 min per 40-frame chunk, with another scene sharing the GPU).
+
+## SKILL.md: steps that were wrong, missing or unclear (first real test)
+
+1. **Step 5 / `pipeline/render_compare.py` is broken on Blender 5.0.1** (empty HDRI path, every render fails), has no
+ prop-id filter (renders every scene's GLBs), and reads `yaw.json` from the output folder, which nothing writes — so
+ Tripo's "front" render shows the prop's side. The skill tells you to use it as-is.
+2. **Step 3 size keys are underspecified.** It says `h` + optional `dims`, but flat props (open binders, glasses,
+ printouts) need "largest dimension", and the example scenes use `fit`/`size` (repair) or `h`/`dims`/`m` (ramen).
+ Pick one schema and document it; this scene uses `h` | `dims` | `max`.
+3. **Step 6 doesn't say re-prepping wipes script fixes (step 9).** Prep and the CRT/glass fixes edit the same
+ `props/<id>.blend`; any re-prep (pick change) must be followed by the fixes. Order and idempotency need stating.
+4. **Steps 8/9 assume generated furniture has usable surfaces.** Generated consoles' desk shelves were ~20 cm deep;
+ the fix was a scripted desk. Worth a line: check the support surfaces of generated furniture before planning clutter.
+5. **Step 9 "fix glass by script" has no recipe** for glass inside a textured prop (ashtray with butts). An HSV-masked
+ transmission on the albedo works; say so.
+6. **Step 11 says "Volumetric haze: cheap and worth it."** Not here: overlapping volumes tripled the frame cost.
+ Add: one volume, no overlaps; time a 4-frame chunk in final mode, not a `--still`.
+7. **Step 12/13 budget numbers** ("4–12 s per frame") came from stills; final-mode frames here were 2× a still.
+ The budget step should say to measure with `--frames a-b`.
+8. **"Gate: the user agrees on the look"** has no instruction for side sessions where the concept is pre-approved;
+ I treated the given concept as the gate.
+9. **Runaway background jobs.** "Killing a waiting shell does not kill its child processes" is in the GPU section,
+ but the concrete failure (stopping a harness background task leaves the loop running) needs a how-to: kill
+ the loop script's pid, then its `gpu_run.sh` children.
+10. **Step 2** says to run the detail concept too, but the brief arrived with an approved wide concept; unclear
+ whether the detail is still required (I generated one: `refs/mission-control-1970s/concept_detail_0.png`).
+11. **No guidance on Meshy failures that repeat.** Three references failed three times with fal 500
+ `downstream_service_error`; the skill says "re-run the same ids". Say when to stop and go single-model.
+12. **Step 15 + `breakdown/SPEC.md`** say "repair, ramen" only; a third scene has to guess the camera rules apply as-is.
diff --git a/scenes/mission-control-1970s/assets.json b/scenes/mission-control-1970s/assets.json
new file mode 100644
index 0000000..ab3d39a
--- /dev/null
+++ b/scenes/mission-control-1970s/assets.json
@@ -0,0 +1,591 @@
+{
+ "room": {
+ "w": 11,
+ "d": 13,
+ "h": 3.6,
+ "tiers": [
+ [
+ 0,
+ 7.5,
+ 13
+ ],
+ [
+ 0.35,
+ 4.5,
+ 7.5
+ ],
+ [
+ 0.7,
+ 0,
+ 4.5
+ ]
+ ],
+ "note": "x across (window wall x=0), y from back door (y=0) to wall display (y=13), z up. tiers = [floor z, y0, y1]. Size keys per prop: h = real height; dims = [x width, y depth, z height] for boxy things (fit per axis); max = largest dimension for things lying flat."
+ },
+ "style": {
+ "console": "Warm beige and light grey painted steel with dark charcoal trim and brushed aluminium edge strips, 1970s aerospace ground-control equipment, worn paint where hands rest, small fictional engraved labels only."
+ },
+ "generate": [
+ {
+ "id": "mc_console_crt",
+ "tier": "hero",
+ "dims": [
+ 1.25,
+ 1,
+ 1.35
+ ],
+ "prompt": "A single 1970s space mission control console bay seen from the operator side: a steel desk-height console with a flat writing shelf at the front, a sloped panel of toggle switches and square illuminated push-buttons, and an upright upper panel holding one large rectangular green-phosphor CRT monitor with a thick dark bezel, small round meters beside it. {console}"
+ },
+ {
+ "id": "mc_console_twin",
+ "tier": "hero",
+ "dims": [
+ 1.25,
+ 1,
+ 1.35
+ ],
+ "prompt": "A single 1970s space mission control console bay seen from the operator side: a steel desk-height console with a flat writing shelf, a sloped keyboard and switch panel, and an upright upper panel with two medium green-phosphor CRT monitors side by side, rows of small amber indicator lamps between them. {console}"
+ },
+ {
+ "id": "mc_console_scope",
+ "tier": "hero",
+ "dims": [
+ 1.25,
+ 1,
+ 1.35
+ ],
+ "prompt": "A single 1970s space mission control console bay seen from the operator side: a steel desk-height console with a flat writing shelf, a sloped panel of rotary knobs and toggle switches, and an upright upper panel holding a large round green radar-style CRT scope with a graticule bezel, two analog needle meters and a row of lit push-buttons. {console}"
+ },
+ {
+ "id": "mc_console_lamps",
+ "tier": "hero",
+ "dims": [
+ 1.25,
+ 1,
+ 1.35
+ ],
+ "prompt": "A single 1970s space mission control status console bay seen from the operator side: a steel desk-height console with a flat writing shelf, a sloped panel of guarded toggle switches, and an upright upper panel covered in a grid of square illuminated indicator buttons in amber, white, green and red, three analog meters and a small red numeric digital readout. {console}"
+ },
+ {
+ "id": "mc_console_comms",
+ "tier": "hero",
+ "dims": [
+ 1.25,
+ 1,
+ 1.35
+ ],
+ "prompt": "A single 1970s space mission control communications console bay seen from the operator side: a steel desk-height console with a flat writing shelf, a sloped panel with long rows of square push-to-talk loop keys with tiny lit labels, an upright upper panel with a small green CRT, a perforated speaker grille, volume knobs and headset jacks. {console}"
+ },
+ {
+ "id": "mc_console_end",
+ "tier": "hero",
+ "dims": [
+ 0.45,
+ 1,
+ 1.35
+ ],
+ "prompt": "A narrow end cabinet that caps a row of 1970s mission control consoles: a slim steel desk-height module with a sloped panel of four small analog meters and a few toggle switches, an upright upper panel with a vertical strip of lit indicator lamps, a small drawer at the front. {console}"
+ },
+ {
+ "id": "mc_tape_drive",
+ "tier": "hero",
+ "dims": [
+ 0.75,
+ 0.7,
+ 1.8
+ ],
+ "prompt": "A 1970s mainframe computer magnetic tape drive cabinet: a tall free-standing steel cabinet painted light grey and pale blue, a smoked glass door showing two large tape reels at the top, vacuum column windows below, a strip of lit operator buttons, scuffed paint."
+ },
+ {
+ "id": "mc_mainframe_rack",
+ "tier": "hero",
+ "dims": [
+ 0.8,
+ 0.7,
+ 1.9
+ ],
+ "prompt": "A tall 1970s mainframe computer processor cabinet: a free-standing steel cabinet in beige and charcoal with an operator panel of many small lit lamps in rows, toggle switches, a key lock and a ventilation grille at the bottom, worn paint and fingerprints."
+ },
+ {
+ "id": "mc_equipment_rack",
+ "tier": "hero",
+ "dims": [
+ 0.6,
+ 0.6,
+ 1.9
+ ],
+ "prompt": "A tall 1970s 19-inch electronics equipment rack in grey steel: stacked rack units with analog needle meters, a patch panel with dangling patch cords, a small oscilloscope unit with a round green screen, rows of knobs and toggle switches, a perforated vent panel, worn and dusty."
+ },
+ {
+ "id": "mc_line_printer",
+ "tier": "hero",
+ "dims": [
+ 1.2,
+ 0.75,
+ 1.15
+ ],
+ "prompt": "A 1970s mainframe line printer: a large boxy beige and grey steel cabinet with a sloped acoustic lid, a small operator panel of lit buttons, continuous green-bar fanfold computer paper feeding out of the top and folding into a pile in a wire basket at the back."
+ },
+ {
+ "id": "mc_teleprinter",
+ "tier": "hero",
+ "dims": [
+ 0.95,
+ 0.6,
+ 1
+ ],
+ "prompt": "A 1970s teleprinter terminal on its own steel pedestal stand: a beige teletype machine with a mechanical keyboard and a round-cornered hood, a roll of yellowish paper printed with typed lines curling out of the top, a punched paper tape unit on the side, worn and dusty."
+ },
+ {
+ "id": "mc_strip_recorder",
+ "tier": "hero",
+ "dims": [
+ 0.5,
+ 0.4,
+ 0.35
+ ],
+ "prompt": "A 1970s multi-channel strip chart recorder: a grey metal desktop instrument with a glass front window showing eight pens drawing wavy ink traces on a moving paper chart, paper spilling out of the front slot, knobs along the bottom."
+ },
+ {
+ "id": "mc_tv_ceiling",
+ "tier": "hero",
+ "h": 0.7,
+ "prompt": "A 1970s black-and-white CRT television monitor in a dark grey steel cabinet hanging from a ceiling-mount bracket and pole, slightly tilted down, curved grey screen, a row of small knobs under the screen."
+ },
+ {
+ "id": "mc_wall_clock",
+ "tier": "mid",
+ "dims": [
+ 0.36,
+ 0.07,
+ 0.36
+ ],
+ "prompt": "A 1970s institutional round wall clock, white face with plain black numerals and hands, a red sweep second hand, thin aluminium rim, slightly yellowed face, no text on the dial."
+ },
+ {
+ "id": "mc_met_clock",
+ "tier": "hero",
+ "dims": [
+ 0.9,
+ 0.16,
+ 0.26
+ ],
+ "prompt": "A 1970s wall-mounted digital timer box: a long black steel enclosure with a row of glowing red-orange nixie-tube digits behind a smoked glass window showing a time with colons, a small screwed name plate, mounting brackets."
+ },
+ {
+ "id": "mc_chair_a",
+ "tier": "hero",
+ "h": 1.05,
+ "prompt": "A 1970s high-back office swivel chair with tufted black vinyl upholstery, padded armrests on chrome supports, a five-star chrome base with casters, the vinyl cracked and worn on the seat edge."
+ },
+ {
+ "id": "mc_chair_b",
+ "tier": "hero",
+ "h": 0.95,
+ "prompt": "A 1970s mid-back office swivel chair upholstered in brown tweed fabric with dark brown vinyl armrest pads, black five-star base on casters, seat cushion compressed and stained."
+ },
+ {
+ "id": "mc_chair_c",
+ "tier": "hero",
+ "h": 0.93,
+ "prompt": "A 1970s mid-back office swivel chair in burnt orange vinyl with a chrome tubular frame and black plastic armrests, five-star base on casters, faded and scuffed."
+ },
+ {
+ "id": "mc_filing_cabinet",
+ "tier": "mid",
+ "dims": [
+ 0.47,
+ 0.65,
+ 1.35
+ ],
+ "prompt": "A 1970s four-drawer steel office filing cabinet painted grey-green, chrome drawer pulls with paper label holders, dented and scratched, a few papers sticking out of the top drawer."
+ },
+ {
+ "id": "mc_water_cooler",
+ "tier": "mid",
+ "h": 1.15,
+ "prompt": "A 1970s office water cooler: a beige enamel cabinet with an upturned large glass water bottle on top, a chrome push tap and drip tray, a paper cone cup dispenser on the side."
+ },
+ {
+ "id": "mc_coffee_urn",
+ "tier": "mid",
+ "h": 0.48,
+ "prompt": "A large 1970s stainless steel coffee urn percolator for an office, with a black plastic tap at the bottom, a glass sight tube on the side, two black handles, coffee drips and water stains."
+ },
+ {
+ "id": "mc_coffee_maker",
+ "tier": "mid",
+ "h": 0.36,
+ "prompt": "A 1970s drip coffee maker in harvest gold and brown plastic with a glass carafe half full of dark coffee on the warming plate, a small red lit power switch, coffee stains."
+ },
+ {
+ "id": "mc_coat_rack",
+ "tier": "mid",
+ "h": 1.8,
+ "prompt": "A free-standing bentwood coat rack with a tan trench coat and a grey felt hat hanging on its hooks."
+ },
+ {
+ "id": "mc_fire_extinguisher",
+ "tier": "mid",
+ "h": 0.6,
+ "prompt": "A 1970s red steel fire extinguisher with a chrome valve, black hose and a plain instruction label without logos, scuffed paint."
+ },
+ {
+ "id": "mc_wastebasket",
+ "tier": "mid",
+ "h": 0.38,
+ "prompt": "A grey steel office waste basket overflowing with crumpled paper, torn computer printout and empty crushed cigarette packs."
+ },
+ {
+ "id": "mc_floor_ashtray",
+ "tier": "mid",
+ "h": 0.62,
+ "prompt": "A 1970s chrome pedestal floor-standing ashtray with a weighted round base and a bowl at the top filled with cigarette butts and grey ash."
+ },
+ {
+ "id": "mc_rolling_cart",
+ "tier": "mid",
+ "h": 0.9,
+ "prompt": "A grey steel two-shelf utility cart on casters holding a 1970s grey analog oscilloscope with a small round green CRT and rows of knobs on top, and a stack of thick technical manuals and coiled cables on the lower shelf."
+ },
+ {
+ "id": "mc_typewriter",
+ "tier": "mid",
+ "max": 0.5,
+ "prompt": "A 1970s electric office typewriter in pale blue with a golf-ball type element, a sheet of typed paper in the platen, black keys."
+ },
+ {
+ "id": "mc_overhead_projector",
+ "tier": "mid",
+ "h": 0.62,
+ "prompt": "A 1970s overhead projector: a boxy grey metal base with a glass stage and a folding arm holding the projection head with a mirror, power cable coiled."
+ },
+ {
+ "id": "mc_desk_fan",
+ "tier": "mid",
+ "h": 0.4,
+ "prompt": "A 1970s metal oscillating desk fan with a chrome wire cage and grey enamel base, dusty blades."
+ },
+ {
+ "id": "mc_speaker_wall",
+ "tier": "mid",
+ "dims": [
+ 0.36,
+ 0.2,
+ 0.46
+ ],
+ "prompt": "A 1970s wall-mounted public address loudspeaker box in walnut-finish wood with a brown fabric grille and a small volume knob on the side."
+ },
+ {
+ "id": "mc_briefcase",
+ "tier": "mid",
+ "max": 0.46,
+ "prompt": "A worn brown leather 1970s hard briefcase with brass latches and a handle, scuffed corners."
+ },
+ {
+ "id": "mc_paper_box",
+ "tier": "mid",
+ "dims": [
+ 0.45,
+ 0.36,
+ 0.3
+ ],
+ "prompt": "An open plain brown cardboard carton of continuous green-bar fanfold computer paper, the top fold of paper hanging over the edge, no printing on the box."
+ },
+ {
+ "id": "mc_lamp_goose",
+ "tier": "mid",
+ "h": 0.55,
+ "prompt": "A 1970s gooseneck desk lamp with a dark green enamel cone shade, a flexible chrome gooseneck and a heavy round black base with a toggle switch."
+ },
+ {
+ "id": "mc_lamp_arm",
+ "tier": "mid",
+ "h": 0.62,
+ "prompt": "A 1970s spring-balanced articulated desk lamp in cream-painted metal with a rounded shade, arm bent so the shade points down, on a heavy square weighted base."
+ },
+ {
+ "id": "mc_headset",
+ "tier": "mid",
+ "max": 0.3,
+ "prompt": "A 1970s communications operator headset lying on a desk: a single padded black earpiece on a thin metal headband with a boom microphone, a coiled grey cord ending in a large jack plug."
+ },
+ {
+ "id": "mc_desk_phone",
+ "tier": "mid",
+ "max": 0.3,
+ "prompt": "A 1970s beige multi-line office key telephone with a rotary dial and a row of clear plastic line-select push buttons along the front, coiled handset cord, yellowed plastic."
+ },
+ {
+ "id": "mc_rotary_phone",
+ "tier": "mid",
+ "max": 0.24,
+ "prompt": "A 1970s red rotary dial desk telephone with no dial numbers card, a coiled cord to the handset, glossy plastic slightly scratched."
+ },
+ {
+ "id": "mc_desk_mic",
+ "tier": "mid",
+ "h": 0.42,
+ "prompt": "A 1970s gooseneck desk microphone on a heavy black cast base with a chrome push-to-talk bar, a slim microphone capsule at the end of the gooseneck."
+ },
+ {
+ "id": "mc_intercom",
+ "tier": "mid",
+ "max": 0.26,
+ "prompt": "A 1970s desktop intercom box in beige and woodgrain with a perforated speaker grille, a row of small lever keys and a volume wheel."
+ },
+ {
+ "id": "mc_calculator",
+ "tier": "mid",
+ "max": 0.32,
+ "prompt": "A 1970s desktop printing calculator in grey and beige with chunky keys, a green vacuum fluorescent numeric display and a roll of paper tape curling out of the top."
+ },
+ {
+ "id": "mc_reel_recorder",
+ "tier": "mid",
+ "max": 0.42,
+ "prompt": "A 1970s portable reel-to-reel tape recorder in brushed aluminium and black with two tape reels, VU meters and piano-key controls."
+ },
+ {
+ "id": "mc_crt_terminal",
+ "tier": "hero",
+ "dims": [
+ 0.45,
+ 0.6,
+ 0.42
+ ],
+ "prompt": "A 1970s computer video terminal with a boxy beige case, a curved green-phosphor CRT screen and an attached sloped keyboard with chunky grey keys, slightly yellowed plastic."
+ },
+ {
+ "id": "mc_card_tray",
+ "tier": "mid",
+ "max": 0.4,
+ "prompt": "A long grey steel tray full of cream computer punch cards standing on edge, a few cards sticking up out of the deck, with a rubber band around one stack."
+ },
+ {
+ "id": "mc_tape_reel",
+ "tier": "mid",
+ "max": 0.27,
+ "prompt": "A 1970s half-inch computer magnetic tape reel with brown tape wound on a clear blue plastic reel, a white plastic seal ring around it, a blank paper label."
+ },
+ {
+ "id": "mc_ashtray_glass",
+ "tier": "clutter",
+ "max": 0.15,
+ "prompt": "A heavy thick clear glass ashtray overflowing with many cigarette butts and grey ash, a few burnt matches."
+ },
+ {
+ "id": "mc_ashtray_tin",
+ "tier": "clutter",
+ "max": 0.11,
+ "prompt": "A small round dented tin ashtray full of cigarette butts and ash, one butt still resting in the notch."
+ },
+ {
+ "id": "mc_ashtray_square",
+ "tier": "clutter",
+ "max": 0.13,
+ "prompt": "A square brown glazed ceramic ashtray with four cigarette rests, heaped with cigarette butts and ash."
+ },
+ {
+ "id": "mc_mug_white",
+ "tier": "clutter",
+ "h": 0.095,
+ "prompt": "A plain white ceramic coffee mug with brown coffee stains running down the side and a ring of dried coffee inside, half full of black coffee."
+ },
+ {
+ "id": "mc_mug_brown",
+ "tier": "clutter",
+ "h": 0.1,
+ "prompt": "A brown glazed stoneware coffee mug with a speckled finish, half full of black coffee, a chip on the rim."
+ },
+ {
+ "id": "mc_mug_green",
+ "tier": "clutter",
+ "h": 0.09,
+ "prompt": "An olive green melamine coffee mug, scratched, with cold coffee in it and a spoon leaning on the rim."
+ },
+ {
+ "id": "mc_paper_cup",
+ "tier": "clutter",
+ "h": 0.095,
+ "prompt": "A white styrofoam coffee cup half full of coffee, slightly crushed rim, coffee drip on the side."
+ },
+ {
+ "id": "mc_thermos",
+ "tier": "clutter",
+ "h": 0.32,
+ "prompt": "A 1970s tartan-pattern metal vacuum flask with a red plastic cup lid, dented and scuffed."
+ },
+ {
+ "id": "mc_binder_open",
+ "tier": "clutter",
+ "max": 0.55,
+ "prompt": "A thick open three-ring binder lying flat, its pages of typed procedures with checklists and tabbed dividers, a blue cloth-covered cover, dog-eared pages."
+ },
+ {
+ "id": "mc_binder_closed",
+ "tier": "clutter",
+ "max": 0.32,
+ "prompt": "A closed thick black vinyl three-ring binder lying flat with a white blank spine label, worn corners, papers poking out."
+ },
+ {
+ "id": "mc_binder_stack",
+ "tier": "clutter",
+ "max": 0.34,
+ "prompt": "A messy stack of four thick ring binders lying flat in different colours, dark blue, black, maroon and grey, with coloured tabs and loose paper between them."
+ },
+ {
+ "id": "mc_binders_row",
+ "tier": "clutter",
+ "max": 0.5,
+ "prompt": "A row of eight thick ring binders standing upright between two steel bookends, mixed blue, black and grey spines with blank white labels."
+ },
+ {
+ "id": "mc_printout_stack",
+ "tier": "clutter",
+ "max": 0.4,
+ "prompt": "A stack of continuous fanfold green-bar computer printout paper with tractor-feed holes along the edges, printed with columns of numbers, slightly messy."
+ },
+ {
+ "id": "mc_printout_spill",
+ "tier": "clutter",
+ "max": 0.65,
+ "prompt": "A long strip of continuous fanfold green-bar computer printout paper unfolding off a stack into a loose cascading pile on the floor, printed columns of numbers, tractor-feed holes."
+ },
+ {
+ "id": "mc_clipboard",
+ "tier": "clutter",
+ "max": 0.33,
+ "prompt": "A brown masonite clipboard with a steel clip holding a typed checklist with handwritten ticks in pencil, a pencil clipped on top."
+ },
+ {
+ "id": "mc_logbook",
+ "tier": "clutter",
+ "max": 0.45,
+ "prompt": "An open hardcover green cloth log book with ruled pages full of handwritten entries in blue ink and times, a ballpoint pen lying in the gutter."
+ },
+ {
+ "id": "mc_manuals_stack",
+ "tier": "clutter",
+ "max": 0.3,
+ "prompt": "A stack of five thick technical manuals with plain grey and blue covers and blank labels, some paper bookmarks sticking out."
+ },
+ {
+ "id": "mc_pencil_cup",
+ "tier": "clutter",
+ "h": 0.17,
+ "prompt": "A metal mesh desk pencil cup full of yellow pencils, red grease pencils, a ruler and ballpoint pens."
+ },
+ {
+ "id": "mc_slide_rule",
+ "tier": "clutter",
+ "max": 0.3,
+ "prompt": "A 1970s bamboo and plastic slide rule with a clear cursor, printed scales, lying flat."
+ },
+ {
+ "id": "mc_cigarette_pack",
+ "tier": "clutter",
+ "max": 0.09,
+ "prompt": "An open crushed soft pack of cigarettes in a navy blue and cream design with a small line drawing of a sailing ship and the fictional brand name 'CORSAIR' in thin serif type, two cigarettes sticking out."
+ },
+ {
+ "id": "mc_lighter",
+ "tier": "clutter",
+ "max": 0.06,
+ "prompt": "A brushed steel flip-top petrol lighter with the lid open, scratched, no engraving."
+ },
+ {
+ "id": "mc_donut_box",
+ "tier": "clutter",
+ "max": 0.32,
+ "prompt": "An open plain white cardboard pastry box with grease spots holding three leftover glazed and chocolate doughnuts on wax paper."
+ },
+ {
+ "id": "mc_sandwich",
+ "tier": "clutter",
+ "max": 0.2,
+ "prompt": "A half-eaten sandwich on white bread on crumpled wax paper."
+ },
+ {
+ "id": "mc_soda_can",
+ "tier": "clutter",
+ "h": 0.122,
+ "prompt": "A 1970s steel soda can with a pull-ring tab, orange and white design with a fictional brand called 'ZEPHYR' in plain type, slightly dented."
+ },
+ {
+ "id": "mc_reading_glasses",
+ "tier": "clutter",
+ "max": 0.14,
+ "prompt": "A pair of 1970s thick black plastic framed glasses lying folded."
+ },
+ {
+ "id": "mc_paper_crumpled",
+ "tier": "clutter",
+ "max": 0.08,
+ "prompt": "A crumpled ball of white typing paper with typed lines visible on it."
+ },
+ {
+ "id": "mc_stapler",
+ "tier": "clutter",
+ "max": 0.2,
+ "prompt": "A heavy 1970s chrome and black desk stapler, scratched."
+ },
+ {
+ "id": "mc_desk_tray",
+ "tier": "clutter",
+ "max": 0.36,
+ "prompt": "A two-level grey steel desk letter tray stacked with typed memos, carbon copies and folded printouts."
+ },
+ {
+ "id": "mc_rolodex",
+ "tier": "clutter",
+ "max": 0.2,
+ "prompt": "A rotary card file with a black metal frame and knobs, full of slightly yellowed index cards with handwriting."
+ },
+ {
+ "id": "mc_flashlight",
+ "tier": "clutter",
+ "max": 0.26,
+ "prompt": "A 1970s black rubber and chrome flashlight lying on its side, scuffed."
+ },
+ {
+ "id": "mc_hard_hat",
+ "tier": "clutter",
+ "max": 0.3,
+ "prompt": "A scuffed white fibreglass hard hat with a plain stripe and no logos."
+ }
+ ],
+ "textures": [
+ {
+ "id": "launch_pad",
+ "size": "landscape_16_9",
+ "prompt": "Night photograph across a flat dark coastal marsh toward a distant floodlit rocket launch pad about three kilometres away: a tall white multi-stage rocket beside a red steel service tower lit by bright xenon floodlights, sodium-orange site lights, beams in thin haze, low lights of a distant causeway, dark sky with a few stars, no people, no text, no logos, no flags, realistic long-lens film still."
+ },
+ {
+ "id": "world_map",
+ "size": "landscape_16_9",
+ "prompt": "A flat equirectangular world map drawn as clean thin glowing cyan-green outline coastlines only on a pure black background, like a 1970s vector display, latitude and longitude grid lines every 15 degrees in dim green, no text, no labels, no country borders, no logos, the whole world edge to edge, high contrast."
+ },
+ {
+ "id": "poster_motto",
+ "size": "portrait_4_3",
+ "prompt": "A 1970s framed institutional wall poster: a dramatic photograph of a crescent moon over the curve of the earth in space, bold condensed white type reading 'FURTHER HIGHER SAFER' and small type 'AURORA FLIGHT DIRECTORATE', muted printed colours, slight fading, front view, flat, no other logos."
+ },
+ {
+ "id": "decal_coffee",
+ "size": "square_hd",
+ "prompt": "Several overlapping brown coffee mug ring stains and drips on a pure white background, top-down, flat, high detail, no other objects."
+ },
+ {
+ "id": "decal_burns",
+ "size": "square_hd",
+ "prompt": "Several small black and brown cigarette burn marks and scattered grey ash smudges on a pure white background, top-down, flat, high detail, no other objects."
+ },
+ {
+ "id": "concept_detail",
+ "size": "landscape_16_9",
+ "variant": "sunburst",
+ "prompt": "Close-up of a 1970s space mission control console at night during a long shift: a glowing green CRT with columns of telemetry numbers, a sloped panel of toggle switches and amber lit push-buttons, an overflowing glass ashtray with a cigarette still smouldering and a thin curl of smoke, a white coffee mug with stains, an open three-ring procedures binder, a headset with boom mic, fanfold green-bar printout, a gooseneck desk lamp throwing a warm pool, the big wall display softly out of focus behind. Photoreal cinematic film still, 50mm lens, natural film grain, practical lighting only, no people, no real-world brand names or logos, all labels fictional."
+ }
+ ]
+}
\ No newline at end of file
diff --git a/scenes/mission-control-1970s/brief.md b/scenes/mission-control-1970s/brief.md
new file mode 100644
index 0000000..5083d93
--- /dev/null
+++ b/scenes/mission-control-1970s/brief.md
@@ -0,0 +1,52 @@
+# Mission control, 1970s — brief
+
+**Brief.** A 1970s space mission control room at night during a long shift. Tiered rows of beige and grey consoles with
+glowing green CRTs, switches and lit buttons; a big wall display with an orbital ground track and telemetry; binders,
+printout spools, coffee cups, overflowing ashtrays and cigarette haze; fluorescent ceiling panels partly off; windows onto
+a night launch pad. No people.
+
+**Fiction.** The agency is the *Aurora Flight Directorate* (AFD). The mission is **PERSEUS 7**, an orbital flight on
+revolution 112. Ground stations are birds: KESTREL, OSPREY, HARRIER, MERLIN. Console positions use plain job words
+(TRAJECTORY, GUIDANCE, TELEMETRY, COMMS, LIFE SUPPORT, POWER, PROPULSION, RECOVERY, NETWORK, FLIGHT DIRECTOR,
+ORBITAL ANALYSIS). No real agency names, logos, patches or brands anywhere; every label is invented and set in real
+font text objects or generated screen textures.
+
+**Time and weather.** About 03:40, dry, clear night. The launch pad 3 km away is floodlit (cold xenon + sodium).
+
+**Mood.** Tired, smoky, humming, institutional, quietly tense.
+
+**Look.** Concept `refs/mission-control-1970s/concept_wide_0.png` (approved). Green phosphor everywhere, warm desk-lamp
+pools, a cold cyan-green wall display, most overhead troffers off. Anamorphic 2.39:1, 35 mm-ish lenses, film grain.
+
+## Room
+
+Metres; x across (0 = window wall), y from the back door (y = 0) to the wall display (y = 13), z up. Ceiling 3.6 m above
+the lowest tier.
+
+| Zone | Where |
+|---|---|
+| Back aisle + door | y 0–1.5, on tier 2 (z 0.70). Coffee station, coat rack, filing cabinets, water cooler. |
+| Row C (flight director) | tier 2, consoles y ≈ 3.2–4.1, x 3.0–8.2 (4 bays), chairs at y ≈ 2.6 |
+| Row B | tier 1 (z 0.35, y 4.5–7.5), consoles y ≈ 6.2–7.1, x 2.4–9.2 (5 bays), chairs y ≈ 5.6 |
+| Row A | tier 0 (z 0, y 7.5–13), consoles y ≈ 9.4–10.3, x 1.8–9.6 (6 bays), chairs y ≈ 8.8 |
+| Window aisle | x 0–1.8, steps down the tiers along the windows; walkthrough 1 lives here |
+| Right wall | x ≈ 10.4–11: tape drives, equipment racks, line printer, teleprinter |
+| Wall display | y = 13, x 1.5–9.5, z 1.1–3.3: left telemetry panel, centre ground-track map, right station panel |
+| Windows | left wall x = 0, y 1.5–9.5, z 1.0–3.0, mullions every ~1.6 m, launch-pad backdrop outside |
+
+## Hero spots
+
+1. Row A centre console (ORBITAL ANALYSIS): ashtray, binders, coffee, the CRT and the wall display behind.
+2. The wall display seen down the console rows from row C (flight director's view).
+3. The right-wall printer / teleprinter corner with the paper spool spilling.
+
+## Practicals
+
+- every CRT (green P1 phosphor, a few amber), console lamp buttons and event-light strips;
+- the wall display (cyan-green map + amber/green text) — the biggest light in the room;
+- 4–5 gooseneck/arm desk lamps (warm 2700 K);
+- 3 of 18 ceiling troffers on (cool white, one flickering-looking dim);
+- the launch-pad floodlight spill through the windows (cold, low);
+- an exit sign over the door (red), the coffee maker's warmer light.
+
+Haze: a uniform low-density volume in the room (cigarette smoke), denser near the ceiling.
diff --git a/scenes/mission-control-1970s/picks.json b/scenes/mission-control-1970s/picks.json
new file mode 100644
index 0000000..4e0d135
--- /dev/null
+++ b/scenes/mission-control-1970s/picks.json
@@ -0,0 +1,308 @@
+{
+ "_note": "Per prop: chosen model + one-line why. Provisional entries are marked and get revisited on the full compare sheets.",
+ "mc_console_crt": {
+ "model": "tripo-h31",
+ "why": "keeps the beige/charcoal paint and the meter/bezel geometry; Meshy washes the paint near-white"
+ },
+ "mc_console_twin": {
+ "model": "tripo-h31",
+ "why": "twin CRT bezels and keyboard are real geometry, colour matches the other bays"
+ },
+ "mc_console_scope": {
+ "model": "tripo-h31",
+ "why": "round scope bezel is modelled; Meshy has better proportions but its white paint breaks the row"
+ },
+ "mc_console_end": {
+ "model": "tripo-h31",
+ "why": "clean slim cabinet, same paint as the bays; Meshy adds a dark side that reads as a different unit"
+ },
+ "mc_console_lamps": {
+ "model": "tripo-h31",
+ "why": "lamp grid and meters crisp, matching beige; Meshy back panel is a grille mess"
+ },
+ "mc_console_comms": {
+ "model": "tripo-h31",
+ "why": "loop keys and speaker grille as geometry, colour consistent with the row"
+ },
+ "mc_equipment_rack": {
+ "model": "meshy",
+ "why": "sharper meters, patch cords and the little scope; Tripo flattens the rack units"
+ },
+ "mc_mainframe_rack": {
+ "model": "meshy",
+ "why": "lamp rows and switches are crisp; Tripo puts the panel on the wrong face and blurs it"
+ },
+ "mc_tape_drive": {
+ "model": "meshy",
+ "why": "reels, vacuum columns and lit buttons are detailed geometry; Tripo is softer"
+ },
+ "mc_line_printer": {
+ "model": "tripo-h31",
+ "why": "Meshy mangles the cabinet and basket into a heap; Tripo keeps a clean printer with paper"
+ },
+ "mc_teleprinter": {
+ "model": "meshy",
+ "why": "keyboard and paper roll sharper, pedestal proportions right"
+ },
+ "mc_filing_cabinet": {
+ "model": "meshy",
+ "why": "drawers are real recesses in the clay with the open top drawer; Tripo is a box"
+ },
+ "mc_chair_a": {
+ "model": "meshy",
+ "why": "crisp tufting and chrome base; Tripo is smaller and softer"
+ },
+ "mc_met_clock": {
+ "model": "meshy",
+ "why": "nixie digits read clearly (14:27:36 swapped in the scene) and the case is cleaner"
+ },
+ "mc_tv_ceiling": {
+ "model": "meshy",
+ "why": "curved screen and mount are geometry; Tripo screen is flat"
+ },
+ "mc_wall_clock": {
+ "model": "meshy",
+ "why": "clean dial and hands; back is a mirrored face but it hangs on the wall"
+ },
+ "mc_chair_b": {
+ "model": "meshy",
+ "why": "tweed weave and seat stains read; Tripo is a flat tan"
+ },
+ "mc_chair_c": {
+ "model": "meshy",
+ "why": "vinyl channels and chrome frame crisper, colour matches the ref"
+ },
+ "mc_coat_rack": {
+ "model": "tripo-h31",
+ "why": "coat folds and hat are cleaner geometry; both close"
+ },
+ "mc_coffee_maker": {
+ "model": "meshy",
+ "why": "carafe with dark coffee and the stained top; Tripo carafe reads empty"
+ },
+ "mc_coffee_urn": {
+ "model": "meshy",
+ "why": "dents, rust and the sight tube; Tripo is cleaner than the ref"
+ },
+ "mc_fire_extinguisher": {
+ "model": "meshy",
+ "why": "label and hose crisper; label is a generic instruction card, no logos"
+ },
+ "mc_floor_ashtray": {
+ "model": "tripo-h31",
+ "why": "bowl actually holds butts and ash; Meshy bowl is empty"
+ },
+ "mc_strip_recorder": {
+ "model": "meshy",
+ "why": "coloured pens and traced chart visible; Tripo chart is mush"
+ },
+ "mc_water_cooler": {
+ "model": "tripo-h31",
+ "why": "tray, tap and cream enamel closer to the ref; Meshy darker cabinet"
+ },
+ "mc_briefcase": {
+ "model": "meshy",
+ "why": "scuffed leather and latches crisper"
+ },
+ "mc_desk_fan": {
+ "model": "tripo-h31",
+ "why": "base and blade shape match the ref; Meshy turned the base into a chrome bulb"
+ },
+ "mc_desk_mic": {
+ "model": "meshy",
+ "why": "gooseneck smooth, PTT bar on the base reads"
+ },
+ "mc_headset": {
+ "model": "tripo-h31",
+ "why": "coiled cord and boom mic readable; Meshy close but the headband is thinner"
+ },
+ "mc_lamp_arm": {
+ "model": "meshy",
+ "why": "larger shade and springs as geometry, matches the ref"
+ },
+ "mc_lamp_goose": {
+ "model": "meshy",
+ "why": "open shade with a white interior (spot sits under the rim); Tripo shade smaller"
+ },
+ "mc_overhead_projector": {
+ "model": "meshy",
+ "why": "glass stage and folding head crisper"
+ },
+ "mc_paper_box": {
+ "model": "meshy",
+ "why": "fanfold paper with tractor holes over the edge; Tripo paper is a flat card"
+ },
+ "mc_rolling_cart": {
+ "model": "meshy",
+ "why": "scope screen and knobs sharper, manuals stacked"
+ },
+ "mc_rotary_phone": {
+ "model": "meshy",
+ "why": "coiled cord and dial are geometry; Tripo smaller"
+ },
+ "mc_speaker_wall": {
+ "model": "tripo-h31",
+ "why": "proportions and bracket match; Meshy too deep"
+ },
+ "mc_typewriter": {
+ "model": "meshy",
+ "why": "keys and type element crisp"
+ },
+ "mc_wastebasket": {
+ "model": "tripo-h31",
+ "why": "mesh basket shows the paper inside; Meshy reads as a solid can"
+ },
+ "mc_calculator": {
+ "model": "tripo-h31",
+ "why": "green VFD digits and paper roll read; Meshy display is white"
+ },
+ "mc_card_tray": {
+ "model": "meshy",
+ "why": "card deck edges and drawer pull sharper"
+ },
+ "mc_crt_terminal": {
+ "model": "meshy",
+ "why": "curved green screen as geometry (screen fix finds it) and crisp keys"
+ },
+ "mc_desk_phone": {
+ "model": "meshy",
+ "why": "line buttons and dial crisp; Tripo softer"
+ },
+ "mc_intercom": {
+ "model": "tripo-h31",
+ "why": "woodgrain panel like the ref; Meshy turned it grey"
+ },
+ "mc_reel_recorder": {
+ "model": "meshy",
+ "why": "reels, VU meters and piano keys sharper"
+ },
+ "mc_tape_reel": {
+ "model": "meshy",
+ "why": "clean reel spokes and seal ring"
+ },
+ "mc_ashtray_glass": {
+ "model": "meshy",
+ "why": "butts and ash crisper; both made the glass opaque grey, fixed by script (texture-masked transmission)"
+ },
+ "mc_ashtray_square": {
+ "model": "meshy",
+ "why": "glaze speckle and heaped butts sharper"
+ },
+ "mc_mug_brown": {
+ "model": "meshy",
+ "why": "speckled glaze and the chip read"
+ },
+ "mc_mug_green": {
+ "model": "meshy",
+ "why": "scratches and spoon crisper"
+ },
+ "mc_mug_white": {
+ "model": "tripo-h31",
+ "why": "clean drips; Meshy has a black notch artifact in the rim"
+ },
+ "mc_ashtray_tin": {
+ "model": "meshy",
+ "why": "rust, dent and the resting butt sharper"
+ },
+ "mc_clipboard": {
+ "model": "meshy",
+ "why": "checklist ticks and clip crisper (clipboard text is an invented checklist)"
+ },
+ "mc_paper_cup": {
+ "model": "tripo-h31",
+ "why": "crushed rim and drip; both lost the coffee inside"
+ },
+ "mc_thermos": {
+ "model": "meshy",
+ "why": "tartan and chipped red cup crisper"
+ },
+ "mc_binder_open": {
+ "model": "meshy",
+ "why": "coloured tabs and typed pages read; Tripo pages blur"
+ },
+ "mc_binders_row": {
+ "model": "tripo-h31",
+ "why": "mixed blue/black/grey spines like the ref; Meshy made them all blue"
+ },
+ "mc_lighter": {
+ "model": "tripo-h31",
+ "why": "worn brushed steel and wheel; near tie"
+ },
+ "mc_logbook": {
+ "model": "meshy",
+ "why": "lies open and flat with the pen; Tripo stands the book upright on its edge"
+ },
+ "mc_printout_spill": {
+ "model": "meshy",
+ "why": "tractor holes and the cascade fold are geometry; Tripo spill is a crumpled rag"
+ },
+ "mc_slide_rule": {
+ "model": "meshy",
+ "why": "cursor and scales crisp; both stand it on edge, so prep lays it face up",
+ "lay": true
+ },
+ "mc_cigarette_pack": {
+ "model": "meshy",
+ "why": "fictional CORSAIR label legible, foil crisp (regenerated ref: the first had real-brand-like trade dress)"
+ },
+ "mc_donut_box": {
+ "model": "meshy",
+ "why": "grease spots and glaze crisp"
+ },
+ "mc_manuals_stack": {
+ "model": "meshy",
+ "why": "page edges and bookmarks real geometry"
+ },
+ "mc_sandwich": {
+ "model": "tripo-h31",
+ "why": "bite mark and wax paper crumple read; Meshy is a lump"
+ },
+ "mc_soda_can": {
+ "model": "meshy",
+ "why": "fictional ZEPHYR reads cleanly; Tripo mangled it to ZLPHYR"
+ },
+ "mc_stapler": {
+ "model": "meshy",
+ "why": "chrome and base crisper"
+ },
+ "mc_pencil_cup": {
+ "model": "meshy",
+ "why": "mesh cup and pencils sharper, colours match"
+ },
+ "mc_reading_glasses": {
+ "model": "meshy",
+ "why": "thick black frames like the ref; Tripo greyed them"
+ },
+ "mc_paper_crumpled": {
+ "model": "tripo-h31",
+ "why": "typed lines visible on the paper; Meshy is blank"
+ },
+ "mc_rolodex": {
+ "model": "tripo-h31",
+ "why": "handwritten cards read on the front; Meshy cards are blank"
+ },
+ "mc_flashlight": {
+ "model": "meshy",
+ "why": "ribbed body and lens crisper"
+ },
+ "mc_hard_hat": {
+ "model": "meshy",
+ "why": "scuffs and reflective band crisper; plain, no logos"
+ },
+ "mc_binder_closed": {
+ "model": "meshy",
+ "why": "papers poking out and worn corners; Tripo is a clean slab"
+ },
+ "mc_binder_stack": {
+ "model": "tripo-h31",
+ "why": "Meshy failed three times (fal 500 downstream_service_error); Tripo stack is good: colours, tabs, rings"
+ },
+ "mc_printout_stack": {
+ "model": "tripo-h31",
+ "why": "Meshy failed three times (fal 500 downstream_service_error); Tripo has tractor holes and green bars"
+ },
+ "mc_desk_tray": {
+ "model": "tripo-h31",
+ "why": "Meshy failed three times (fal 500 downstream_service_error); Tripo tray and memos read fine"
+ }
+}
\ No newline at end of file
diff --git a/scenes/mission-control-1970s/scripts/bts.py b/scenes/mission-control-1970s/scripts/bts.py
new file mode 100644
index 0000000..1fd1f23
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/bts.py
@@ -0,0 +1,334 @@
+"""Behind-the-scenes "dollhouse" clips (breakdown/SPEC.md), adapted from the repair scene's bts.py.
+
+ blender -b scenes/mission-control-1970s/mc.blend --python .../bts.py -- setup
+ -> breakdown/mission-control-1970s/bts.blend (copy + bts camera); never saves over a scene file
+ blender -b breakdown/mission-control-1970s/bts.blend --python .../bts.py -- <a_layout|b_props|c_materials|d_lighting> [first last] [clay]
+ -> breakdown/mission-control-1970s/clips/<clip>/####.png (existing frames skipped). Each run goes through gpu_run.sh.
+
+One continuous 120° orbit around the room, A 0-30°, B 30-60°, C 60-90°, D 90-120° (ease in on A, out on D). The
+camera stays on the back/left side so the wall display faces it the whole way; ceiling and the walls nearest the
+camera are hidden per frame.
+"""
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+OUT = os.path.join(ROOT, "breakdown", "mission-control-1970s")
+W, D, H = 11.0, 13.0, 3.6
+CENTRE = Vector((5.6, 6.9, 0.6))
+AZ0 = -165.0
+ELEV, DIST, LENS = 40.0, 19.0, 30.0
+CLIPS = {"a_layout": (144, 0, 30, "in"), "b_props": (240, 30, 60, None),
+ "c_materials": (144, 60, 90, None), "d_lighting": (240, 90, 120, "out")}
+args = sys.argv[sys.argv.index("--") + 1:]
+sc = bpy.context.scene
+
+SHELL_COLLS = ("shell", "display", "furniture")
+PROP_COLLS = ("consoles", "chairs", "furniture", "wall_items", "desk_props", "placards")
+WALLS = {
+ (-1, 0): ("wall_left", "sill", "mullion_", "transom", "window_glass", "blind", "poster_"),
+ (1, 0): ("wall_right", "acoustic_right", "base_right"),
+ (0, -1): ("wall_back", "door_", "exit_", "acoustic_back"),
+ (0, 1): ("wall_front", "base_front"),
+}
+
+
+def coll_objs(names):
+ out = []
+ for n in names:
+ c = bpy.data.collections.get(n)
+ if c:
+ out += list(c.all_objects)
+ return out
+
+
+def azimuth(clip, f):
+ n, a0, a1, ease = CLIPS[clip]
+ u = (f - 1) / (n - 1)
+ if ease == "in":
+ u = 2 * u * u - u ** 3
+ elif ease == "out":
+ u = u + u * u - u ** 3
+ return AZ0 + a0 + (a1 - a0) * u
+
+
+def cam_pose(az):
+ a, e = math.radians(az), math.radians(ELEV)
+ p = CENTRE + Vector((math.cos(a) * math.cos(e), math.sin(a) * math.cos(e), math.sin(e))) * DIST
+ return p, (CENTRE - p).to_track_quat("-Z", "Y").to_euler()
+
+
+if args[0] == "setup":
+ cd = bpy.data.cameras.new("bts_cam")
+ cd.lens, cd.sensor_width, cd.sensor_fit = LENS, 36.0, "HORIZONTAL"
+ cd.shift_y = -0.1 # room sits a little high: the bottom 140 px stay clear for captions
+ cd.dof.use_dof = False
+ cd.clip_end = 200
+ cam = bpy.data.objects.new("bts_cam", cd)
+ sc.collection.objects.link(cam)
+ os.makedirs(OUT, exist_ok=True)
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "bts.blend"), copy=True)
+ print("BTS setup saved")
+ sys.exit(0)
+
+clip = args[0]
+n = CLIPS[clip][0]
+first, last = (int(args[1]), int(args[2])) if len(args) > 2 else (1, n)
+CLAY_PLATE = len(args) > 3 and args[3] == "clay"
+cam = bpy.data.objects["bts_cam"]
+sc.camera = cam
+sc.frame_start, sc.frame_end = 1, n
+r = sc.render
+r.resolution_x, r.resolution_y, r.resolution_percentage = 1920, 1080, 100
+r.fps = 24
+r.use_motion_blur = False
+r.use_compositing = False
+r.image_settings.file_format = "PNG"
+r.image_settings.color_mode = "RGB"
+r.image_settings.color_depth = "8"
+r.film_transparent = False
+for f in range(1, n + 1):
+ p, rot = cam_pose(azimuth(clip, f))
+ cam.location, cam.rotation_euler = p, rot
+ cam.keyframe_insert("location", frame=f)
+ cam.keyframe_insert("rotation_euler", frame=f)
+
+props = {o for o in coll_objs(PROP_COLLS) if o.get("placed") or o.parent is None and o.name.startswith(("placard", "poster", "exit_text"))}
+props = {o for o in props if not o.name.startswith(("coffee_table",))}
+shell = set(coll_objs(SHELL_COLLS)) - props
+ceiling = set(coll_objs(("ceiling_fixtures",))) | {sc.objects["ceiling"]}
+outside = set(coll_objs(("outside",)))
+haze = [o for o in coll_objs(("haze",))]
+lights = [o for o in sc.objects if o.type == "LIGHT"]
+decals = set(coll_objs(("decals",)))
+for o in sc.objects:
+ if o.type in ("MESH", "CURVE", "FONT", "LIGHT"):
+ o.hide_render = False
+for o in ceiling | outside:
+ o.hide_render = True
+
+
+def wall_objs(normal):
+ pre = WALLS[normal]
+ objs = [o for o in sc.objects if o.name.startswith(pre)]
+ nx, ny = normal
+ for o in props: # wall-hung props go with their wall
+ if not o.get("wall"):
+ continue
+ x, y = o.matrix_world.translation.x, o.matrix_world.translation.y
+ if (nx < 0 and x < 0.5) or (nx > 0 and x > W - 0.5) or (ny < 0 and y < 0.5) or (ny > 0 and y > D - 0.5):
+ objs.append(o)
+ return objs
+
+
+cut = {k: wall_objs(k) for k in WALLS}
+for f in range(1, n + 1):
+ a = math.radians(azimuth(clip, f))
+ d = (math.cos(a), math.sin(a))
+ for (nx, ny), objs in cut.items():
+ hide = d[0] * nx + d[1] * ny > 0.25
+ for o in objs:
+ o.hide_render = hide
+ o.keyframe_insert("hide_render", frame=f)
+for o in {o for objs in cut.values() for o in objs}:
+ if o.animation_data and o.animation_data.action:
+ act = o.animation_data.action
+ for fc in act.layers[0].strips[0].channelbag(act.slots[0]).fcurves:
+ for kp in fc.keyframe_points:
+ kp.interpolation = "CONSTANT"
+
+
+def studio(clay):
+ for o in lights:
+ o.hide_render = True
+ for o in haze:
+ o.hide_render = True
+ w = sc.world
+ bg = w.node_tree.nodes["Background"]
+ bg.inputs["Color"].default_value = (0.75, 0.77, 0.8, 1)
+ bg.inputs["Strength"].default_value = 0.5 if clay else 0.45
+ ld = bpy.data.lights.new("bts_sun", "SUN")
+ ld.energy, ld.angle = (1.6 if clay else 2.0), math.radians(12)
+ s = bpy.data.objects.new("bts_sun", ld)
+ sc.collection.objects.link(s)
+ s.rotation_euler = (math.radians(38), math.radians(8), math.radians(-30))
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "None"
+ sc.view_settings.exposure = 0.0
+ r.engine = "BLENDER_EEVEE"
+ ev = sc.eevee
+ ev.taa_render_samples = 32
+ ev.use_raytracing = True
+ ev.use_shadows = True
+
+
+def clay_override():
+ m = bpy.data.materials.get("bts_clay") or bpy.data.materials.new("bts_clay")
+ b = m.node_tree.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.62, 0.62, 0.6, 1)
+ b.inputs["Roughness"].default_value = 0.7
+ sc.view_layers[0].material_override = m
+
+
+def emission_off_in_studio():
+ """Screens and lamp glow would read as lit in the 'flat' materials pass; mute them (keyed multiplier = 0)."""
+ for m in bpy.data.materials:
+ if not m.node_tree:
+ continue
+ b = next((nd for nd in m.node_tree.nodes if nd.type == "BSDF_PRINCIPLED"), None)
+ if b is None:
+ continue
+ es = b.inputs["Emission Strength"]
+ if es.is_linked:
+ nt = m.node_tree
+ mul = nt.nodes.new("ShaderNodeMath")
+ mul.operation = "MULTIPLY"
+ nt.links.new(es.links[0].from_socket, mul.inputs[0])
+ mul.inputs[1].default_value = 0.15
+ nt.links.new(mul.outputs[0], es)
+ else:
+ es.default_value *= 0.15
+
+
+if clip == "a_layout":
+ studio(True)
+ clay_override()
+ for o in props | decals:
+ o.hide_render = True
+ risers = [o for o in shell if o.parent is None and o.name.startswith(("floor_t1", "floor_t2", "step", "nosing", "display", "coffee_table"))]
+ risers.sort(key=lambda o: -o.location.y)
+ for i, o in enumerate(risers):
+ f0 = 1 + int(30 * i / max(1, len(risers) - 1))
+ o.delta_location = (0, 0, -3.0)
+ o.keyframe_insert("delta_location", index=2, frame=f0)
+ o.delta_location = (0, 0, 0.12)
+ o.keyframe_insert("delta_location", index=2, frame=f0 + 12)
+ o.delta_location = (0, 0, 0)
+ o.keyframe_insert("delta_location", index=2, frame=f0 + 18)
+
+elif clip == "b_props":
+ studio(True)
+ clay_override()
+ for o in decals:
+ o.hide_render = True
+ order = sorted(props, key=lambda o: (o.get("order", 10 ** 6) if o.get("placed") else 10 ** 5 + len(o.name)))
+ # big furniture first is already the dressing order (consoles, chairs, room furniture, wall items, desks)
+ span = 194
+ for i, o in enumerate(order):
+ f0 = 1 + int(span * (i / max(1, len(order) - 1)) ** 1.25)
+ for fr, s in ((f0, 0.0), (f0 + 4, 1.12), (f0 + 6, 0.97), (f0 + 8, 1.0)):
+ o.delta_scale = (s, s, s)
+ o.keyframe_insert("delta_scale", frame=fr)
+
+elif clip == "c_materials" and CLAY_PLATE:
+ studio(True)
+ clay_override()
+ for o in decals:
+ o.hide_render = True
+
+elif clip == "c_materials":
+ studio(False)
+ emission_off_in_studio()
+ for m in bpy.data.materials:
+ if not m.node_tree:
+ continue
+ for nd in m.node_tree.nodes:
+ if nd.type == "GROUP" and nd.node_tree and nd.node_tree.name == "grime_layer":
+ s = nd.inputs["Factor"]
+ v = s.default_value
+ s.default_value = 0.0
+ s.keyframe_insert("default_value", frame=48)
+ s.default_value = v
+ s.keyframe_insert("default_value", frame=96)
+ for m in bpy.data.materials:
+ if m.name.startswith(("decal_",)) and m.node_tree:
+ a = m.node_tree.nodes.get("decal_alpha")
+ if a:
+ v = a.inputs[1].default_value
+ a.inputs[1].default_value = 0.0
+ a.inputs[1].keyframe_insert("default_value", frame=48)
+ a.inputs[1].default_value = v
+ a.inputs[1].keyframe_insert("default_value", frame=96)
+
+elif clip == "d_lighting":
+ r.engine = "CYCLES"
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ prefs.compute_device_type = "OPTIX"
+ prefs.get_devices()
+ for dv in prefs.devices:
+ dv.use = dv.type == "OPTIX"
+ c = sc.cycles
+ c.device = "GPU"
+ c.samples = 16
+ c.use_adaptive_sampling = True
+ c.adaptive_threshold = 0.05
+ c.use_denoising = True
+ c.denoiser = "OPTIX"
+ c.max_bounces = 4
+ c.diffuse_bounces, c.glossy_bounces, c.transmission_bounces = 2, 2, 4
+ c.volume_step_rate = 8.0
+ r.use_persistent_data = True
+ sc.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.3
+ RAMP = 10
+ # light_order groups (lights.py): 1 lamps, 2 troffers, 3 display spill, 4 pad spill, 5 accents, 6 fills
+ START = {1: 10, 2: 88, 3: 66, 4: 112, 5: 100, 6: 140}
+ for o in lights:
+ g = int(o.get("light_order", 600)) // 100
+ f0 = START.get(g, 150) + (int(o.get("light_order", 0)) % 100) % 6 * 3 if g == 1 else START.get(g, 150)
+ e = o.data.energy
+ o.data.energy = 0.0
+ o.data.keyframe_insert("energy", frame=f0)
+ o.data.energy = e
+ o.data.keyframe_insert("energy", frame=f0 + RAMP)
+ # emissive materials: CRTs + console lamps with the screens stage, wall display after, troffer lenses with the
+ # tubes, exit + backdrop with accents/outside
+ EMIT = (("CRT_SLOT", 44), ("wall_wall", 66), ("troffer_", 88), ("exit_", 100), ("backdrop", 112))
+ for m in bpy.data.materials:
+ if not m.node_tree:
+ continue
+ b = next((nd for nd in m.node_tree.nodes if nd.type == "BSDF_PRINCIPLED"), None)
+ if b is None:
+ continue
+ es = b.inputs["Emission Strength"]
+ if not es.is_linked and es.default_value <= 0:
+ continue
+ f0 = next((v for k, v in EMIT if m.name.startswith(k)), 44)
+ nt = m.node_tree
+ mul = nt.nodes.new("ShaderNodeMath")
+ mul.operation = "MULTIPLY"
+ if es.is_linked:
+ nt.links.new(es.links[0].from_socket, mul.inputs[0])
+ else:
+ mul.inputs[0].default_value = es.default_value
+ nt.links.new(mul.outputs[0], es)
+ mul.inputs[1].default_value = 0.0
+ mul.inputs[1].keyframe_insert("default_value", frame=f0)
+ mul.inputs[1].default_value = 1.0
+ mul.inputs[1].keyframe_insert("default_value", frame=f0 + RAMP)
+ # image-emission materials (backdrop) use an Emission Strength default > 0 handled above
+ for o in haze:
+ o.hide_render = False
+ mt = o.active_material
+ k = next((nd for nd in mt.node_tree.nodes if nd.type == "MATH" and nd.outputs[0].links
+ and nd.outputs[0].links[0].to_socket.name == "Density"), None)
+ if k:
+ d = k.inputs[1].default_value
+ k.inputs[1].default_value = 0.0
+ k.inputs[1].keyframe_insert("default_value", frame=176)
+ k.inputs[1].default_value = d
+ k.inputs[1].keyframe_insert("default_value", frame=212)
+
+out = os.path.join(OUT, "clips", clip + ("_clayplate" if CLAY_PLATE else ""))
+os.makedirs(out, exist_ok=True)
+for f in range(first, last + 1):
+ path = os.path.join(out, f"{f:04d}.png")
+ if os.path.exists(path):
+ continue
+ sc.frame_set(f)
+ r.filepath = path
+ bpy.ops.render.render(write_still=True)
+ print("BTS", clip, f, flush=True)
diff --git a/scenes/mission-control-1970s/scripts/bts_render.sh b/scenes/mission-control-1970s/scripts/bts_render.sh
new file mode 100644
index 0000000..6143e5e
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/bts_render.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# Render the four BTS dollhouse clips in short GPU-queue chunks, build the C wipe, encode mp4s and contact sheets.
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+
+C=breakdown/mission-control-1970s/clips
+run() { # clip first last [clay]
+ local t0=$(date +%s)
+ bash pipeline/gpu_run.sh "$B" -b breakdown/mission-control-1970s/bts.blend --python scenes/mission-control-1970s/scripts/bts.py -- "$@" 2>&1 | grep -E "Traceback|Error:" | grep -v HIPEW
+ echo "$* : $(( $(date +%s) - t0 )) s"
+}
+for r in "1 72" "73 144"; do run a_layout $r; done
+for r in "1 80" "81 160" "161 240"; do run b_props $r; done
+run c_materials 1 48 clay
+for r in "1 72" "73 144"; do run c_materials $r; done
+for r in "1 40" "41 80" "81 120" "121 160" "161 200" "201 240"; do run d_lighting $r; done
+# C: soft diagonal wipe clay -> materials over frames 1-48 (frame files are the source of truth; mp4 is made from them)
+mkdir -p $C/c_tmp
+"$FF" -v error -y -framerate 24 -i $C/c_materials_clayplate/%04d.png -framerate 24 -i $C/c_materials/%04d.png -frames:v 48 \
+ -filter_complex "[0:v][1:v]blend=all_expr='A*(1-clip((N/47*1.25-(X/W*0.8+Y/H*0.2))/0.25,0,1))+B*clip((N/47*1.25-(X/W*0.8+Y/H*0.2))/0.25,0,1)'" \
+ -start_number 1 $C/c_tmp/%04d.png
+for f in $C/c_tmp/*.png; do mv -f "$f" $C/c_materials/; done
+rmdir $C/c_tmp
+for c in a_layout b_props c_materials d_lighting; do
+ "$FF" -v error -y -framerate 24 -i $C/$c/%04d.png -c:v h264_nvenc -preset p7 -rc vbr -cq 16 -b:v 0 -pix_fmt yuv420p -movflags +faststart $C/$c.mp4
+ n=$(ls $C/$c | wc -l)
+ "$FF" -v error -y -i $C/$c.mp4 -vf "select='not(mod(n\,$(( n / 8 ))))',scale=480:-1,tile=4x2" -frames:v 1 $C/${c}_contact.png
+ echo "$c: $n frames"
+done
+echo BTS DONE
diff --git a/scenes/mission-control-1970s/scripts/build.py b/scenes/mission-control-1970s/scripts/build.py
new file mode 100644
index 0000000..2c66a39
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/build.py
@@ -0,0 +1,54 @@
+"""Mission control 1970s: the whole scene build, in stages.
+
+blender -b --factory-startup --python scenes/mission-control-1970s/scripts/build.py -- \
+ [--stages shell,dress,screens,lights,haze,post] [--save scenes/mission-control-1970s/mc.blend] [--clay]
+Coordinates: x across (0 = window wall), y from the back door (0) to the wall display (13), z up. Metres.
+Every stage is a function in a module next to this file; the .blend is a build output, never hand-edited.
+"""
+import argparse
+import os
+import sys
+
+import bpy
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import lib # noqa: E402
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+ap = argparse.ArgumentParser()
+ap.add_argument("--stages", default="shell,dress,screens,grime,lights,haze,post")
+ap.add_argument("--save", default=os.path.join(lib.ROOT, "scenes", "mission-control-1970s", "mc.blend"))
+ap.add_argument("--clay", action="store_true")
+ap.add_argument("--dress-passes", default="furniture,heroes,mid,clutter")
+args = ap.parse_args(argv)
+stages = args.stages.split(",")
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+sc = bpy.context.scene
+sc.unit_settings.system = "METRIC"
+
+import shell # noqa: E402
+
+shell.build()
+if "dress" in stages:
+ import dress # noqa: E402
+ dress.build(args.dress_passes.split(","))
+ import validate # noqa: E402
+ validate.check(resolve=True)
+if "screens" in stages:
+ import fixscreens # noqa: E402
+ fixscreens.build()
+if "grime" in stages:
+ import grime # noqa: E402
+ grime.build()
+if "lights" in stages:
+ import lights # noqa: E402
+ lights.build()
+if "haze" in stages:
+ import haze # noqa: E402
+ haze.build()
+import post # noqa: E402
+post.build(clay=args.clay)
+bpy.context.view_layer.update()
+bpy.ops.wm.save_as_mainfile(filepath=os.path.abspath(args.save))
+print("SAVED", args.save, flush=True)
diff --git a/scenes/mission-control-1970s/scripts/check_path.py b/scenes/mission-control-1970s/scripts/check_path.py
new file mode 100644
index 0000000..1250454
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/check_path.py
@@ -0,0 +1,43 @@
+"""Camera-path clearance check for camrig shots: every frame's camera position vs every render-visible mesh (BVH nearest).
+blender -b scenes/mission-control-1970s/mc.blend --python scenes/mission-control-1970s/scripts/check_path.py -- <shots.json> <name,name> [min=0.25]"""
+import json, os, sys
+import bpy
+from mathutils import Vector
+from mathutils.bvhtree import BVHTree
+sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "camera"))
+import camrig # noqa: E402
+a = sys.argv[sys.argv.index("--") + 1:]
+cfg = json.load(open(a[0]))
+names = a[1].split(",")
+lim = float(a[2]) if len(a) > 2 else 0.25
+sc = bpy.context.scene
+dg = bpy.context.evaluated_depsgraph_get()
+skip = ("haze", "smoke_curl", "backdrop", "outside_", "CR_", "decal", "window_glass", "troffer_lens")
+trees = []
+for o in sc.objects:
+ if o.type not in ("MESH", "CURVE") or not o.visible_get() or o.hide_render or o.name.startswith(skip):
+ continue
+ eo = o.evaluated_get(dg)
+ me = eo.to_mesh()
+ if me is None or not len(me.polygons):
+ continue
+ me.transform(o.matrix_world)
+ trees.append((o.name, BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])))
+ eo.to_mesh_clear()
+shots = [camrig.merged(cfg.get("defaults", {}), s) for s in cfg["shots"]]
+for i, s in enumerate(shots):
+ if s["name"] not in names:
+ continue
+ cam = camrig.build(s, seed=i * 7)
+ worst = (9, None, 0)
+ bad = 0
+ for f in range(1, int(s["frames"]) + 1):
+ sc.frame_set(f)
+ p = cam.matrix_world.translation.copy()
+ for n, t in trees:
+ loc, nrm, idx, d = t.find_nearest(p, lim * 2)
+ if loc is not None and d < worst[0]:
+ worst = (d, n, f)
+ if loc is not None and d < lim:
+ bad += 1
+ print(f"PATH {s['name']}: min clearance {worst[0]:.2f} m to {worst[1]} at frame {worst[2]}; {bad} frame-object hits under {lim} m")
diff --git a/scenes/mission-control-1970s/scripts/compare.py b/scenes/mission-control-1970s/scripts/compare.py
new file mode 100644
index 0000000..8b91487
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/compare.py
@@ -0,0 +1,207 @@
+"""Head-to-head renders of generated props: same studio light and camera fit for every model.
+
+blender -b --factory-startup --python scenes/mission-control-1970s/scripts/compare.py -- assets/gen scenes/mission-control-1970s/compare mc_a,mc_b
+For every assets/gen/<model>/<prop>/model.glb writes out/compare/<model>/<prop>_{beauty,clay}.png + stats.json.
+"""
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+ARGS = sys.argv[sys.argv.index("--") + 1:]
+ROOT, OUT = map(os.path.abspath, ARGS[:2])
+IDS = set(ARGS[2].split(",")) if len(ARGS) > 2 else None
+# 5.0: system_resource(..., path=...) returns "" here, so join the path ourselves
+HDRI = os.path.join(bpy.utils.system_resource("DATAFILES"), "studiolights", "world", "studio.exr")
+RES = 640
+PROBE = bool(os.environ.get("PROBE"))
+# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.
+# Tripo H3.1 fronts face +X, Meshy -Y: turn the camera so "front" shows the side the reference image shows.
+YAW = {"tripo-h31": 90, "meshy": 0}
+
+
+def reset():
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ prefs.compute_device_type = "OPTIX"
+ prefs.get_devices()
+ for d in prefs.devices:
+ d.use = d.type == "OPTIX"
+ sc.cycles.device = "GPU"
+ sc.cycles.samples = 48
+ sc.cycles.use_denoising = True
+ sc.render.resolution_x = sc.render.resolution_y = RES
+ sc.render.film_transparent = False
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "AgX - Medium High Contrast"
+ world = bpy.data.worlds.new("w")
+ sc.world = world
+ world.use_nodes = True
+ nt = world.node_tree
+ env = nt.nodes.new("ShaderNodeTexEnvironment")
+ env.image = bpy.data.images.load(HDRI)
+ bg = nt.nodes["Background"]
+ bg.inputs["Strength"].default_value = 0.6
+ nt.links.new(env.outputs["Color"], bg.inputs["Color"])
+ return sc
+
+
+def add_light(name, loc, energy, size, color=(1, 1, 1)):
+ d = bpy.data.lights.new(name, "AREA")
+ d.energy, d.size, d.color = energy, size, color
+ o = bpy.data.objects.new(name, d)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = loc
+ o.rotation_euler = (-Vector(loc)).to_track_quat("-Z", "Y").to_euler() # area lights shine along -Z
+
+
+def import_glb(path):
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=path)
+ meshes = [o for o in bpy.data.objects if o not in before and o.type == "MESH"]
+ return meshes
+
+
+def bounds(objs):
+ pts = [o.matrix_world @ Vector(c) for o in objs for c in o.bound_box]
+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
+ return lo, hi
+
+
+def stats(objs, real_size):
+ tris = verts = 0
+ images = {}
+ for o in objs:
+ me = o.data
+ me.calc_loop_triangles()
+ tris += len(me.loop_triangles)
+ verts += len(me.vertices)
+ for slot in o.material_slots:
+ if slot.material and slot.material.use_nodes:
+ for n in slot.material.node_tree.nodes:
+ if n.type == "TEX_IMAGE" and n.image:
+ out = [l.to_socket.name for l in n.outputs["Color"].links]
+ images[n.image.name] = {"size": list(n.image.size), "feeds": out}
+ return {"tris": tris, "verts": verts, "objects": len(objs), "images": images, "size_m": [round(v, 3) for v in real_size]}
+
+
+def clay_wire(objs):
+ m = bpy.data.materials.new("clay")
+ m.use_nodes = True
+ nt = m.node_tree
+ bsdf = nt.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (0.55, 0.55, 0.55, 1)
+ bsdf.inputs["Roughness"].default_value = 0.6
+ wire = nt.nodes.new("ShaderNodeWireframe")
+ wire.use_pixel_size = True
+ wire.inputs["Size"].default_value = 0.35
+ mix = nt.nodes.new("ShaderNodeMix")
+ mix.data_type = "RGBA"
+ mix.inputs["A"].default_value = (0.55, 0.55, 0.55, 1)
+ mix.inputs["B"].default_value = (0.08, 0.12, 0.2, 1)
+ nt.links.new(wire.outputs["Fac"], mix.inputs["Factor"])
+ nt.links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])
+ for o in objs:
+ o.data.materials.clear()
+ o.data.materials.append(m)
+
+
+def render_one(glb, out_prefix):
+ sc = reset()
+ objs = import_glb(glb)
+ lo, hi = bounds(objs)
+ real = hi - lo
+ # Normalize: centre on origin, rest on the floor, largest dimension 1 m (framing only; real size goes in stats).
+ s = 1.0 / max(real)
+ root = bpy.data.objects.new("root", None)
+ sc.collection.objects.link(root)
+ for o in [o for o in bpy.data.objects if o.parent is None and o is not root]:
+ o.parent = root
+ c = (lo + hi) / 2
+ root.scale = (s, s, s)
+ root.location = (-c.x * s, -c.y * s, -lo.z * s)
+ bpy.context.view_layer.update()
+ lo, hi = bounds(objs)
+ centre = (lo + hi) / 2
+ radius = (hi - lo).length / 2
+
+ # Shadow catcher-ish floor.
+ bpy.ops.mesh.primitive_plane_add(size=20)
+ floor = bpy.context.object
+ fm = bpy.data.materials.new("floor")
+ fm.use_nodes = True
+ fm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.32, 0.32, 0.33, 1)
+ fm.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.8
+ floor.data.materials.append(fm)
+
+ add_light("key", (2.2, -2.6, 3.0), 260, 1.6)
+ add_light("fill", (-3.0, -1.5, 1.6), 70, 2.5, (0.85, 0.9, 1.0))
+ add_light("rim", (-1.0, 3.0, 2.5), 160, 1.2)
+
+ cam_d = bpy.data.cameras.new("cam")
+ cam_d.lens = 70
+ cam = bpy.data.objects.new("cam", cam_d)
+ sc.collection.objects.link(cam)
+ sc.camera = cam
+ fov = cam_d.angle
+ dist = radius / math.sin(fov / 2) * 1.02
+
+ def shoot(az_deg, el_deg, path):
+ az, el = math.radians(az_deg), math.radians(el_deg)
+ d = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))
+ cam.location = centre + d * dist
+ cam.rotation_euler = (centre - cam.location).to_track_quat("-Z", "Y").to_euler()
+ sc.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+
+ st = stats(objs, real)
+ if PROBE: # four cardinal views to find which way a generator's "front" faces
+ sc.render.resolution_x = sc.render.resolution_y = 360
+ sc.cycles.samples = 16
+ for az in (0, 90, 180, 270):
+ shoot(az, 15, f"{out_prefix}_az{az:03d}.png")
+ return st
+ yaw = YAW.get(os.path.basename(os.path.dirname(out_prefix)), 0)
+ shoot(yaw - 30, 18, out_prefix + "_beauty.png")
+ shoot(yaw + 150, 22, out_prefix + "_back.png")
+ clay_wire(objs)
+ shoot(yaw - 30, 18, out_prefix + "_clay.png")
+ return st
+
+
+def main():
+ allstats = {}
+ for model in ("tripo-h31", "meshy"):
+ for prop in sorted(os.listdir(os.path.join(ROOT, model))):
+ glb = os.path.join(ROOT, model, prop, "model.glb")
+ if IDS and prop not in IDS:
+ continue
+ if not os.path.exists(glb):
+ continue
+ od = os.path.join(OUT, model)
+ os.makedirs(od, exist_ok=True)
+ prefix = os.path.join(od, prop)
+ done = prefix + ("_az270.png" if PROBE else "_clay.png")
+ if os.path.exists(done) and os.path.getmtime(done) > os.path.getmtime(glb):
+ print("skip", model, prop)
+ continue
+ print("render", model, prop, flush=True)
+ try:
+ allstats.setdefault(model, {})[prop] = render_one(glb, prefix)
+ except Exception as e: # keep going; a broken GLB is itself a result
+ allstats.setdefault(model, {})[prop] = {"error": repr(e)}
+ print("FAILED", model, prop, e, flush=True)
+ sp = os.path.join(OUT, "stats.json")
+ old = json.load(open(sp)) if os.path.exists(sp) else {}
+ for m, d in allstats.items():
+ old.setdefault(m, {}).update(d)
+ json.dump(old, open(sp, "w"), indent=2)
+
+
+main()
diff --git a/scenes/mission-control-1970s/scripts/compare_batch.sh b/scenes/mission-control-1970s/scripts/compare_batch.sh
new file mode 100644
index 0000000..ad2e363
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/compare_batch.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Same-light compare renders (ref | Tripo | Meshy, front/back/clay) for mc_* props that have GLBs, in GPU-queue chunks
+# of N props (default 10, ~5 min each) so no single gpu_run call holds the card for long.
+# scenes/mission-control-1970s/scripts/compare_batch.sh [N]
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+N=${1:-10}
+S=scenes/mission-control-1970s
+todo=()
+for d in assets/gen/tripo-h31/mc_* assets/gen/meshy/mc_*; do
+ [ -f "$d/model.glb" ] || continue
+ m=$(basename "$(dirname "$d")"); id=$(basename "$d")
+ c="$S/compare/$m/${id}_clay.png"
+ [ -f "$c" ] && [ "$c" -nt "$d/model.glb" ] && continue
+ todo+=("$id")
+done
+ids=($(printf '%s\n' "${todo[@]}" | sort -u))
+echo "compare: ${#ids[@]} props to render"
+for ((i = 0; i < ${#ids[@]}; i += N)); do
+ chunk=$(IFS=,; echo "${ids[*]:i:N}")
+ bash pipeline/gpu_run.sh "$B" -b --factory-startup --python $S/scripts/compare.py -- "$ROOT_ABS/assets/gen" "$ROOT_ABS/$S/compare" "$chunk" 2>&1 | grep -E "^render|FAILED"
+done
diff --git a/scenes/mission-control-1970s/scripts/dress.py b/scenes/mission-control-1970s/scripts/dress.py
new file mode 100644
index 0000000..cfdac12
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/dress.py
@@ -0,0 +1,434 @@
+"""Dressing passes, big -> small: furniture (consoles, racks, chairs, back aisle), heroes, mid props, clutter.
+
+Props come from props/<id>.blend (prep.py + fixes.py output) as linked duplicates. Everything placed gets
+ob["placed"] = True and ob["prop_id"], which the validator and the breakdown read. Instances are tinted through ob.color
+(multiplied into albedo by grime.py) so repeats don't read as copies.
+"""
+import math
+import os
+import random
+
+import bpy
+from mathutils import Vector
+
+import layout as L
+import lib
+from lib import box, collection
+
+PROPS = os.path.join(lib.ROOT, "scenes", "mission-control-1970s", "props")
+TEX = os.path.join(lib.ROOT, "refs", "mission-control-1970s", "tex")
+rng = random.Random(1974)
+_loaded = {}
+PLACED = []
+ORDER = 0
+
+
+def have(pid):
+ return os.path.exists(os.path.join(PROPS, pid + ".blend"))
+
+
+def _load(pid):
+ if pid in _loaded:
+ return _loaded[pid]
+ path = os.path.join(PROPS, pid + ".blend")
+ if not os.path.exists(path):
+ print("MISSING prop", pid)
+ _loaded[pid] = None
+ return None
+ with bpy.data.libraries.load(path, link=False) as (src, dst):
+ dst.objects = [n for n in src.objects if n == pid]
+ _loaded[pid] = dst.objects[0]
+ return _loaded[pid]
+
+
+def instance(pid, coll):
+ src = _load(pid)
+ if src is None:
+ return None
+ if src.users_collection:
+ o = src.copy() # linked duplicate: shares mesh + materials
+ else:
+ o = src
+ coll.objects.link(o)
+ o.rotation_mode = "XYZ"
+ return o
+
+
+def bbox(o):
+ bpy.context.view_layer.update()
+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]
+ return (Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))),
+ Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts))))
+
+
+def drop(o, start_z, n=5):
+ """Lower o so its lowest vertices rest on whatever is under them (rays from those vertices' xy). Lamps and chairs
+ have big overhangs; a bounding-box footprint would land them on the console instead of the desk."""
+ bpy.context.view_layer.update()
+ mw = o.matrix_world
+ if o.type == "MESH" and len(o.data.vertices):
+ vs = [mw @ v.co for v in o.data.vertices]
+ zmin = min(v.z for v in vs)
+ base = [v for v in vs if v.z < zmin + 0.015]
+ if len(base) > 4:
+ step = max(1, len(base) // 40)
+ o.hide_set(True)
+ dg = bpy.context.evaluated_depsgraph_get()
+ top = None
+ for v in base[::step]:
+ ok, loc, nrm, _i, hit, _m = bpy.context.scene.ray_cast(dg, Vector((v.x, v.y, start_z)), Vector((0, 0, -1)))
+ if ok and (top is None or loc.z > top):
+ top = loc.z
+ o.hide_set(False)
+ if top is not None:
+ o.location.z += top - zmin + 0.0005
+ return top
+ return drop_bbox(o, start_z, n)
+
+
+def drop_bbox(o, start_z, n=5):
+ """Lower o onto the highest surface under its footprint. Rays start at start_z, which must be below anything
+ overhead (shelves above, console upper panels) or the prop lands on top of it."""
+ lo, hi = bbox(o)
+ o.hide_set(True)
+ dg = bpy.context.evaluated_depsgraph_get()
+ top = None
+ for i in range(n):
+ for j in range(n):
+ x = lo.x + (hi.x - lo.x) * (0.12 + 0.76 * i / (n - 1))
+ y = lo.y + (hi.y - lo.y) * (0.12 + 0.76 * j / (n - 1))
+ ok, loc, nrm, _i, hit, _m = bpy.context.scene.ray_cast(dg, Vector((x, y, start_z)), Vector((0, 0, -1)))
+ if ok and (top is None or loc.z > top):
+ top = loc.z
+ o.hide_set(False)
+ if top is not None:
+ o.location.z += top - lo.z + 0.0005
+ return top
+
+
+def place(pid, coll, x, y, yaw=0.0, z=None, start_z=None, against=None, gap=0.005, tint=None, jitter=0.0, label=None):
+ """Put a prop with its bottom-centre at (x, y). yaw in degrees (0 = front faces -Y, 90 = front faces +X... see
+ rotation: front -Y rotated by yaw counter-clockwise). against: 'x+'/'x-'/'y+'/'y-' pushes its back to that wall
+ coordinate (taken from x or y). z fixes the bottom height; otherwise it is dropped from start_z."""
+ global ORDER
+ o = instance(pid, coll)
+ if o is None:
+ return None
+ o.rotation_euler = (0, 0, math.radians(yaw + rng.uniform(-jitter, jitter)))
+ o.location = (x, y, z if z is not None else L.tier_z(y))
+ if against:
+ lo, hi = bbox(o)
+ if against == "x+":
+ o.location.x += (x - gap) - hi.x
+ elif against == "x-":
+ o.location.x += (x + gap) - lo.x
+ elif against == "y+":
+ o.location.y += (y - gap) - hi.y
+ elif against == "y-":
+ o.location.y += (y + gap) - lo.y
+ if z is None:
+ drop(o, start_z if start_z is not None else L.tier_z(o.location.y) + 0.3)
+ o["placed"] = True
+ o["prop_id"] = pid
+ o["order"] = ORDER
+ ORDER += 1
+ if tint:
+ o.color = (*tint, 1)
+ if label:
+ o.name = label
+ PLACED.append(o)
+ return o
+
+
+def tint(spread=0.08, warm=0.0):
+ k = 1 + rng.uniform(-spread, spread)
+ return (k * (1 + warm), k, k * (1 - warm))
+
+
+# ---------------------------------------------------------------- furniture
+
+DESK_D, DESK_H = 0.46, 0.70 # writing desk in front of each console row (the generated consoles' own shelf is ~20 cm)
+
+
+def desks():
+ top = lib.grimy("desk_formica", (0.16, 0.17, 0.165), (0.07, 0.065, 0.06), rough=(0.35, 0.6), amount=0.3, scale=4)
+ edge = lib.grimy("desk_edge", (0.55, 0.56, 0.57), (0.2, 0.19, 0.17), rough=(0.25, 0.45), metal=1.0, amount=0.2, bump=0.05)
+ dark = lib.principled("desk_under", (0.05, 0.05, 0.05), 0.7)
+ C = collection("furniture")
+ for row in L.ROWS:
+ name, z, yf = row[0], row[1], row[2]
+ b = list(L.bays(row))
+ x0, x1 = b[0][3], b[-1][4]
+ box(f"desk_{name}", (x0, yf - DESK_D, z + DESK_H - 0.035), (x1, yf - 0.006, z + DESK_H), top, C, bevel=0.004)
+ box(f"desk_edge_{name}", (x0, yf - DESK_D - 0.008, z + DESK_H - 0.04), (x1, yf - DESK_D + 0.002, z + DESK_H + 0.002), edge, C, bevel=0.002)
+ box(f"desk_apron_{name}", (x0 + 0.02, yf - DESK_D + 0.03, z + DESK_H - 0.12), (x1 - 0.02, yf - DESK_D + 0.05, z + DESK_H - 0.035), dark, C, bevel=0.002)
+ for i, bb in enumerate(b): # a bracket under every bay joint
+ xb = min(max(bb[3], x0 + 0.03), x1 - 0.03)
+ box(f"desk_bracket_{name}{i}", (xb - 0.012, yf - DESK_D + 0.06, z + DESK_H - 0.25), (xb + 0.012, yf - 0.01, z + DESK_H - 0.035), dark, C, bevel=0.002)
+
+
+def consoles():
+ C = collection("consoles")
+ bays = []
+ desks()
+ for row in L.ROWS:
+ name, z, yf = row[0], row[1], row[2]
+ for i, (pid, lab, xc, x0, x1) in enumerate(L.bays(row)):
+ o = place(pid, C, xc, yf + L.CONSOLE_D / 2, z=z, tint=tint(0.05, rng.uniform(-0.02, 0.04)), label=f"console_{name}{i}")
+ if o is None:
+ continue
+ o["bay"] = f"{name}{i}"
+ o["screen_idx"] = rng.randrange(8)
+ bays.append((o, pid, lab, xc, x0, x1, z, yf, name))
+ # the hero bay: row A ORBITAL ANALYSIS shows the ground track, its neighbours the telemetry pages
+ for o, pid, lab, *_ in bays:
+ if lab == "ORBITAL ANALYSIS":
+ o["screen_idx"] = 6
+ elif lab == "TELEMETRY":
+ o["screen_idx"] = 0
+ elif lab == "FLIGHT DIRECTOR":
+ o["screen_idx"] = 2
+ return bays
+
+
+def placards(bays):
+ C = collection("placards")
+ font = bpy.data.fonts.load("C:/Windows/Fonts/arialbd.ttf", check_existing=True)
+ m_box = lib.principled("placard_black", (0.012, 0.012, 0.012), 0.35)
+ m_txt = lib.principled("placard_text", (0.8, 0.8, 0.76), 0.5)
+ for o, pid, lab, xc, x0, x1, z, yf, row in bays:
+ if not lab:
+ continue
+ lo, hi = bbox(o)
+ w = min(0.8, 0.042 * len(lab) + 0.1)
+ # sit on the highest point of the console top (the upper housing), probed along the bay centre line
+ dg = bpy.context.evaluated_depsgraph_get()
+ best = None
+ for k in range(24):
+ y = lo.y + (hi.y - lo.y) * (k + 0.5) / 24
+ ok, loc, nrm, _i, ob, _m = bpy.context.scene.ray_cast(dg, Vector((xc, y, hi.z + 0.5)), Vector((0, 0, -1)))
+ if ok and (best is None or loc.z > best[1] + 0.005):
+ best = (y, loc.z)
+ y0, zt = (best[0] - 0.025, best[1]) if best else (lo.y + 0.5, hi.z)
+ b = box(f"placard_{row}_{lab.lower().replace(' ', '_')}", (xc - w / 2, y0, zt), (xc + w / 2, y0 + 0.04, zt + 0.075), m_box, C, bevel=0.004)
+ cu = bpy.data.curves.new("placard_text", "FONT")
+ cu.body = lab
+ cu.font = font
+ cu.size = 0.04
+ cu.align_x = "CENTER"
+ cu.align_y = "CENTER"
+ cu.extrude = 0.0008
+ cu.materials.append(m_txt)
+ t = bpy.data.objects.new(f"placard_text_{row}_{lab.lower().replace(' ', '_')}", cu)
+ t.location = (xc, y0 - 0.001, zt + 0.0375)
+ t.rotation_euler = (math.radians(90), 0, 0)
+ C.objects.link(t)
+ b["settle"] = True # validate.settle() lowers it with its console; the text rides along
+ t["follows"] = b.name
+
+
+def chairs(bays):
+ C = collection("chairs")
+ kinds = ["mc_chair_a", "mc_chair_b", "mc_chair_c", "mc_chair_b", "mc_chair_a"]
+ for k, (o, pid, lab, xc, x0, x1, z, yf, row) in enumerate(bays):
+ if pid == "mc_console_end":
+ continue
+ back = DESK_D + (rng.uniform(0.42, 0.62) if k % 5 else 0.95) # one in five pushed well back
+ yaw = 180 + rng.uniform(-30, 30) + (rng.choice([-1, 1]) * 50 if k % 7 == 3 else 0)
+ dx = rng.uniform(-0.2, 0.2)
+ if lab == "ORBITAL ANALYSIS": # the push-in passes through here: chair swung out to the left
+ dx, back, yaw = -1.0, DESK_D + 0.9, 235
+ place(rng.choice(kinds), C, xc + dx, yf - back, yaw=yaw, z=z, tint=tint(0.06))
+
+
+def table(name, x0, y0, x1, y1, z0, h=0.74, coll=None):
+ """Grey steel folding table with a wood-grain laminate top."""
+ top = lib.wood("laminate_top", light=(0.42, 0.33, 0.24), dark=(0.3, 0.22, 0.15), worn=0.4)
+ leg = lib.grimy("table_steel", (0.3, 0.31, 0.3), (0.12, 0.11, 0.1), metal=0.6, amount=0.3)
+ coll = coll or collection("furniture")
+ box(f"{name}_top", (x0, y0, z0 + h - 0.03), (x1, y1, z0 + h), top, coll, bevel=0.003)
+ box(f"{name}_apron", (x0 + 0.03, y0 + 0.03, z0 + h - 0.1), (x1 - 0.03, y1 - 0.03, z0 + h - 0.03), leg, coll, bevel=0.002)
+ for i, (x, y) in enumerate(((x0 + 0.05, y0 + 0.05), (x1 - 0.05, y0 + 0.05), (x0 + 0.05, y1 - 0.05), (x1 - 0.05, y1 - 0.05))):
+ box(f"{name}_leg{i}", (x - 0.018, y - 0.018, z0), (x + 0.018, y + 0.018, z0 + h - 0.1), leg, coll, bevel=0.002)
+
+
+def room_furniture():
+ C = collection("furniture")
+ W, D = L.W, L.D
+ # right wall machines, fronts facing -X (yaw -90)
+ right = [("mc_line_printer", 1.75), ("mc_teleprinter", 2.95), ("mc_tape_drive", 3.95),
+ ("mc_mainframe_rack", 5.1), ("mc_tape_drive", 6.0), ("mc_equipment_rack", 6.85),
+ ("mc_mainframe_rack", 8.2), ("mc_equipment_rack", 9.0), ("mc_tape_drive", 9.75), ("mc_filing_cabinet", 11.6),
+ ("mc_filing_cabinet", 12.1)]
+ for pid, y in right:
+ o = place(pid, C, W, y, yaw=-90, against="x+", gap=0.04 if pid != "mc_teleprinter" else 0.12, tint=tint(0.05))
+ if o and pid in ("mc_teleprinter", "mc_line_printer"):
+ o.name = pid[3:]
+ # back aisle (tier 2): coffee table back-left, filing cabinets, water cooler, coat rack
+ z2 = L.TIERS[2][0]
+ table("coffee_table", 0.35, 0.25, 2.15, 0.95, z2)
+ for i, x in enumerate((2.55, 3.05, 3.55)):
+ place("mc_filing_cabinet", C, x, 0.0, yaw=180, against="y-", gap=0.03, tint=tint(0.06))
+ place("mc_water_cooler", C, 6.75, 0.0, yaw=180, against="y-", gap=0.04)
+ place("mc_coat_rack", C, 7.5, 0.45, yaw=160)
+ place("mc_paper_box", C, 9.2, 0.0, yaw=175, against="y-", gap=0.05)
+ place("mc_paper_box", C, 9.25, 0.42, yaw=190)
+ place("mc_rolling_cart", C, 0.55, 11.2, yaw=95, tint=tint(0.05))
+ place("mc_overhead_projector", C, 0.55, 12.3, yaw=80)
+ place("mc_paper_box", C, 0.42, 10.1, yaw=80)
+ # floor ashtrays and waste baskets at row ends and in the lanes
+ for x, y in ((1.65, 9.2), (9.3, 6.2), (2.45, 3.3)):
+ place("mc_floor_ashtray", C, x, y)
+ for x, y in ((1.7, 8.85), (8.75, 7.1), (3.0, 4.3), (9.45, 10.4), (8.2, 3.95)):
+ place("mc_wastebasket", C, x, y, yaw=rng.uniform(0, 360), tint=tint(0.06))
+
+
+def wall_items():
+ C = collection("wall_items")
+ W, D, H = L.W, L.D, L.H
+ place("mc_met_clock", C, 5.75, D - 0.16, z=L.DISP_Z1 + 0.15, against="y+", gap=0.0)
+ place("mc_wall_clock", C, W - 0.03, 11.4, yaw=-90, z=2.55, against="x+", gap=0.002)
+ place("mc_fire_extinguisher", C, 0.0, 10.15, yaw=90, z=0.55, against="x-", gap=0.0)
+ place("mc_fire_extinguisher", C, 8.0, 0.03, yaw=180, z=0.7 + 0.5, against="y-", gap=0.002)
+ for x, y, yaw, ag in ((W - 0.03, 2.0, -90, "x+"), (W - 0.03, 10.4, -90, "x+"), (0.0, 12.4, 90, "x-")):
+ place("mc_speaker_wall", C, x, y, yaw=yaw, z=2.85, against=ag, gap=0.0)
+ for x in (2.2, 9.0): # ceiling TVs over the tier-1 aisle, screens toward the back rows
+ place("mc_tv_ceiling", C, x, 5.2, yaw=0, z=H - 0.706)
+ # motto poster between the last window and the front wall, exit sign text
+ pm = os.path.join(TEX, "poster_motto_0.png")
+ if os.path.exists(pm):
+ mat = lib.image_mat("poster_motto", pm, rough=0.35)
+ p = lib.plane("poster_motto", (0.012, 11.3, 2.05), 0.9, 1.2, "X", mat, C)
+ frame = lib.principled("poster_frame", (0.05, 0.045, 0.04), 0.4, Metallic=0.6)
+ box("poster_frame", (0.0, 11.3 - 0.47, 2.05 - 0.62), (0.01, 11.3 + 0.47, 2.05 + 0.62), frame, C, bevel=0.002)
+ cu = bpy.data.curves.new("exit_text", "FONT")
+ cu.body = "EXIT"
+ cu.font = bpy.data.fonts.load("C:/Windows/Fonts/arialbd.ttf", check_existing=True)
+ cu.size = 0.12
+ cu.align_x = "CENTER"
+ cu.align_y = "CENTER"
+ cu.materials.append(lib.emissive("exit_red", (1.0, 0.08, 0.04), 12.0))
+ t = bpy.data.objects.new("exit_text", cu)
+ t.location = (5.5, 0.092, L.DOOR_Z1 + 0.22)
+ t.rotation_euler = (math.radians(90), 0, 0)
+ C.objects.link(t)
+ for o in C.objects:
+ o["wall"] = True
+
+
+# ---------------------------------------------------------------- desk dressing
+
+DESK_SETS = {
+ # bay label -> extra props that bay must have (the hero bays are composed, the rest random)
+ "ORBITAL ANALYSIS": ["mc_ashtray_glass", "mc_mug_white", "mc_binder_open", "mc_printout_stack", "mc_headset", "mc_cigarette_pack", "mc_lighter"],
+ "TELEMETRY": ["mc_ashtray_square", "mc_paper_cup", "mc_logbook", "mc_desk_phone", "mc_pencil_cup"],
+ "FLIGHT DIRECTOR": ["mc_ashtray_glass", "mc_mug_brown", "mc_clipboard", "mc_rotary_phone", "mc_binder_stack", "mc_reading_glasses"],
+ "TRAJECTORY": ["mc_ashtray_tin", "mc_mug_green", "mc_slide_rule", "mc_printout_stack", "mc_calculator"],
+ "COMMS": ["mc_ashtray_tin", "mc_desk_mic", "mc_headset", "mc_intercom", "mc_paper_cup"],
+ "GUIDANCE": ["mc_ashtray_square", "mc_binder_open", "mc_mug_white", "mc_thermos"],
+}
+SMALL_POOL = ["mc_mug_white", "mc_mug_brown", "mc_paper_cup", "mc_binder_closed", "mc_printout_stack", "mc_clipboard",
+ "mc_pencil_cup", "mc_headset", "mc_ashtray_tin", "mc_ashtray_square", "mc_soda_can", "mc_paper_crumpled",
+ "mc_stapler", "mc_desk_tray", "mc_rolodex", "mc_manuals_stack", "mc_flashlight", "mc_sandwich", "mc_card_tray"]
+LAMP_BAYS = {"ORBITAL ANALYSIS": "mc_lamp_goose", "FLIGHT DIRECTOR": "mc_lamp_arm", "LIFE SUPPORT": "mc_lamp_goose",
+ "NETWORK": "mc_lamp_arm", "GUIDANCE": "mc_lamp_goose"}
+
+
+def shelf_band(o):
+ """Find the console's front writing shelf: probe down the bay centre line from the front edge back, keep the run of
+ hits that are flat and at desk height. Returns (y0, y1, z) in world space or None."""
+ lo, hi = bbox(o)
+ xc = (lo.x + hi.x) / 2
+ o_hide = []
+ dg = bpy.context.evaluated_depsgraph_get()
+ hits = []
+ for k in range(40):
+ y = lo.y + (hi.y - lo.y) * k / 39
+ ok, loc, nrm, _i, ob, _m = bpy.context.scene.ray_cast(dg, Vector((xc, y, lo.z + 0.95)), Vector((0, 0, -1)))
+ if ok and ob is o and nrm.z > 0.93 and 0.6 < loc.z - lo.z < 0.9:
+ hits.append((y, loc.z))
+ elif hits:
+ break
+ if len(hits) < 3:
+ return None
+ return hits[0][0], hits[-1][0], sum(z for _, z in hits) / len(hits)
+
+
+def dress_desks(bays, tiers=("hero", "mid", "clutter")):
+ C = collection("desk_props")
+ placed_xy = []
+
+ def free(x, y, r):
+ return all((x - a) ** 2 + (y - b) ** 2 > (r + c) ** 2 for a, b, c in placed_xy)
+
+ def put(pid, x0, x1, y0, y1, zs, yaw=None, tries=30):
+ a = _load(pid)
+ if a is None:
+ return None
+ r = max(a.dimensions.x, a.dimensions.y) * 0.5
+ for _ in range(tries):
+ x = rng.uniform(x0 + r, x1 - r) if x1 - x0 > 2 * r else (x0 + x1) / 2
+ y = rng.uniform(y0 + r * 0.8, y1 - r * 0.8) if y1 - y0 > 1.6 * r else (y0 + y1) / 2
+ if free(x, y, r * 0.85):
+ o = place(pid, C, x, y, yaw=rng.uniform(150, 210) if yaw is None else yaw, start_z=zs, tint=tint(0.07))
+ placed_xy.append((x, y, r * 0.85))
+ return o
+ print("NO ROOM", pid)
+ return None
+
+ for o, pid, lab, xc, x0, x1, z, yf, row in bays:
+ sy0, sy1, sz = yf - DESK_D + 0.03, yf - 0.02, z + DESK_H
+ zs = sz + 0.45 # nothing overhead at the desk except lamp shades
+ items = list(DESK_SETS.get(lab, []))
+ if pid != "mc_console_end" and not items:
+ items = [rng.choice(["mc_ashtray_tin", "mc_ashtray_square", "mc_ashtray_glass"])] + rng.sample(SMALL_POOL, rng.randint(2, 4))
+ elif pid == "mc_console_end":
+ items = rng.sample(["mc_mug_white", "mc_binder_closed", "mc_manuals_stack", "mc_paper_cup", "mc_printout_stack"], rng.randint(0, 2))
+ if lab in LAMP_BAYS:
+ if lab == "ORBITAL ANALYSIS": # right corner: the left of this desk belongs to the hero ashtray
+ lamp = put(LAMP_BAYS[lab], x1 - 0.3, x1 - 0.06, sy0 + 0.15, sy1, zs, yaw=rng.uniform(-70, -50))
+ else: # bay corner, shade toward the operator
+ lamp = put(LAMP_BAYS[lab], x0 + 0.06, x0 + 0.3, sy0 + 0.15, sy1, zs, yaw=rng.uniform(15, 40))
+ if lamp:
+ lamp["desk_lamp"] = True
+ for it in items:
+ if lab == "ORBITAL ANALYSIS" and it == "mc_ashtray_glass": # hero ashtray: front centre-left, in the push-in
+ a = put(it, xc - 0.42, xc - 0.12, sy0 + 0.01, sy0 + 0.22, zs)
+ if a:
+ a.name = "hero_ashtray"
+ continue
+ put(it, x0 + 0.04, x1 - 0.04, sy0 + 0.01, sy1 - 0.01, zs)
+ # back-aisle coffee table and console tops
+ z2 = L.TIERS[2][0] + 0.75
+ for pid in ("mc_coffee_urn", "mc_coffee_maker", "mc_donut_box", "mc_paper_cup", "mc_mug_brown", "mc_thermos"):
+ put(pid, 0.4, 2.1, 0.3, 0.9, z2 + 0.4)
+ tops = [b for b in bays if b[1] != "mc_console_end"]
+ for o, *_ in rng.sample(tops, 4):
+ lo, hi = bbox(o)
+ put(rng.choice(["mc_binders_row", "mc_manuals_stack", "mc_binder_stack"]), lo.x + 0.1, hi.x - 0.1, lo.y + 0.05, lo.y + 0.45, hi.z + 0.5)
+ # floor spill by the line printer and the teleprinter, a briefcase by a chair, a hard hat on the filing cabinet
+ place("mc_printout_spill", C, L.W - 1.25, 1.6, yaw=-60, tint=tint(0.03))
+ place("mc_printout_spill", C, L.W - 1.05, 3.05, yaw=-110, tint=tint(0.03))
+ place("mc_briefcase", C, 4.3, 2.75, yaw=200)
+ place("mc_strip_recorder", C, L.W - 0.45, 9.0, yaw=-90, start_z=2.5)
+ place("mc_reel_recorder", C, L.W - 0.42, 8.2, yaw=-90, start_z=2.5)
+ place("mc_desk_fan", C, 3.55, 0.35, yaw=200, start_z=2.5)
+ place("mc_typewriter", C, 3.05, 0.35, yaw=180, start_z=2.5)
+ # terminal before the hat: dropped after it, the terminal landed on the hat's crown (2 cm up once resolve moved the hat)
+ place("mc_crt_terminal", C, 2.55, 0.4, yaw=185, start_z=2.6)
+ place("mc_hard_hat", C, 2.55, 0.35, yaw=30, start_z=2.5)
+ place("mc_tape_reel", C, L.W - 0.4, 6.0, yaw=-80, start_z=2.5)
+ place("mc_card_tray", C, L.W - 0.45, 5.1, yaw=-95, start_z=2.5)
+
+
+def build(passes):
+ bays = consoles()
+ if "furniture" in passes:
+ placards(bays)
+ chairs(bays)
+ room_furniture()
+ wall_items()
+ if any(p in passes for p in ("heroes", "mid", "clutter")):
+ dress_desks(bays)
+ bpy.context.view_layer.update()
+ print(f"DRESS placed {len(PLACED)} props", flush=True)
diff --git a/scenes/mission-control-1970s/scripts/fixes.py b/scenes/mission-control-1970s/scripts/fixes.py
new file mode 100644
index 0000000..9ab2241
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/fixes.py
@@ -0,0 +1,214 @@
+"""Script repairs on prepped props: CRT faces. Generators bake screens into opaque albedo; this finds each screen on the
+front of the prop and lays a thin domed patch over it carrying a placeholder material CRT_SLOT_<k> that the scene's
+fixscreens.py swaps for the emissive phosphor shader (so every console instance can show a different page).
+
+blender -b --factory-startup --python scenes/mission-control-1970s/scripts/fixes.py -- [id ...]
+Edits props/<id>.blend in place (after prep.py; skipped when already fixed unless FORCE=1).
+Detection (after the repair scene's oscilloscope fix): ray-cast a grid at the prop from -Y, read the albedo at each hit's UV,
+mark screen-like texels (dark glass or phosphor green), take the largest connected regions in the upper part of the
+front, fit a plane through their hits and build the patch on that plane. `screens_override.json` can pin a rect by hand.
+"""
+import json
+import math
+import os
+import sys
+
+import bpy
+import numpy as np
+from mathutils import Vector
+from mathutils.bvhtree import BVHTree
+
+ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+SCN = os.path.join(ROOT, "scenes", "mission-control-1970s")
+PROPS = os.path.join(SCN, "props")
+OVR = os.path.join(SCN, "screens_override.json")
+only = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+
+# id -> number of screens, shape, lowest z (fraction of height) a screen can start at, min area (m^2)
+CFG = {
+ "mc_console_crt": dict(n=1, zmin=0.55),
+ "mc_console_twin": dict(n=2, zmin=0.55),
+ "mc_console_scope": dict(n=1, zmin=0.55, round=True),
+ "mc_console_comms": dict(n=1, zmin=0.55),
+ "mc_crt_terminal": dict(n=1, zmin=0.3, amin=0.01),
+ "mc_tv_ceiling": dict(n=1, zmin=0.0, amin=0.01, grey=True), # b/w set: light grey glass
+}
+
+
+def albedo_image(ob):
+ for slot in ob.material_slots:
+ if not slot.material:
+ continue
+ for n in slot.material.node_tree.nodes:
+ if n.type == "TEX_IMAGE" and any(l.to_socket.name == "Base Color" for l in n.outputs["Color"].links):
+ return n.image
+ for slot in ob.material_slots: # fall back to any image
+ for n in slot.material.node_tree.nodes if slot.material else []:
+ if n.type == "TEX_IMAGE" and n.image:
+ return n.image
+ return None
+
+
+def front_grid(ob, step):
+ me = ob.data
+ me.calc_loop_triangles()
+ verts = [v.co.copy() for v in me.vertices]
+ bvh = BVHTree.FromPolygons(verts, [tuple(t.vertices) for t in me.loop_triangles])
+ uvl = me.uv_layers.active.data
+ img = albedo_image(ob)
+ w, h = img.size
+ px = np.empty(w * h * 4, dtype=np.float32)
+ img.pixels.foreach_get(px)
+ px = px.reshape(h, w, 4)
+ d = ob.dimensions
+ xs = np.arange(-d.x / 2, d.x / 2, step)
+ zs = np.arange(0.002, d.z, step)
+ col = np.zeros((len(zs), len(xs), 3), np.float32)
+ hy = np.full((len(zs), len(xs)), np.nan, np.float32)
+ ny = np.zeros((len(zs), len(xs)), np.float32)
+ for j, z in enumerate(zs):
+ for i, x in enumerate(xs):
+ loc, nrm, idx, dist = bvh.ray_cast(Vector((x, -5.0, z)), Vector((0, 1, 0)))
+ if loc is None:
+ continue
+ t = me.loop_triangles[idx]
+ a, b, c = (verts[k] for k in t.vertices)
+ v0, v1, v2 = b - a, c - a, loc - a
+ d00, d01, d11, d20, d21 = v0.dot(v0), v0.dot(v1), v1.dot(v1), v2.dot(v0), v2.dot(v1)
+ den = d00 * d11 - d01 * d01 or 1e-12
+ bv = (d11 * d20 - d01 * d21) / den
+ bw = (d00 * d21 - d01 * d20) / den
+ uv = uvl[t.loops[0]].uv * (1 - bv - bw) + uvl[t.loops[1]].uv * bv + uvl[t.loops[2]].uv * bw
+ col[j, i] = px[int((uv.y % 1) * (h - 1)), int((uv.x % 1) * (w - 1)), :3]
+ hy[j, i] = loc.y
+ ny[j, i] = nrm.y
+ return xs, zs, col, hy, ny
+
+
+def components(mask):
+ lab = np.zeros(mask.shape, np.int32)
+ n = 0
+ for j0, i0 in zip(*np.nonzero(mask)):
+ if lab[j0, i0]:
+ continue
+ n += 1
+ st = [(j0, i0)]
+ lab[j0, i0] = n
+ while st:
+ j, i = st.pop()
+ for dj, di in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ a, b = j + dj, i + di
+ if 0 <= a < mask.shape[0] and 0 <= b < mask.shape[1] and mask[a, b] and not lab[a, b]:
+ lab[a, b] = n
+ st.append((a, b))
+ return lab, n
+
+
+def find_screens(ob, cfg):
+ step = 0.006 if ob.dimensions.x > 0.6 else 0.003
+ xs, zs, col, hy, ny = front_grid(ob, step)
+ r, g, b = col[..., 0], col[..., 1], col[..., 2]
+ v = col.max(axis=2)
+ greenish = (g > r * 1.08) & (g >= b * 0.95)
+ screenish = (greenish & (v < 0.75)) | ((v < 0.12) & (g >= r * 0.9))
+ if cfg.get("grey"):
+ screenish = (col.max(axis=2) - col.min(axis=2) < 0.08) & (v > 0.3)
+ screenish &= ~np.isnan(hy) & (ny < -0.3) # facing the operator
+ zz = np.broadcast_to(zs[:, None], hy.shape)
+ screenish &= zz > cfg["zmin"] * ob.dimensions.z
+ # close small holes (text on the screen) with a 3x3 majority pass
+ m = screenish.astype(np.float32)
+ k = np.pad(m, 1)
+ s = sum(k[1 + dj:1 + dj + m.shape[0], 1 + di:1 + di + m.shape[1]] for dj in (-1, 0, 1) for di in (-1, 0, 1))
+ screenish = (s >= 5)
+ lab, n = components(screenish)
+ amin = cfg.get("amin", 0.03)
+ regs = []
+ for k in range(1, n + 1):
+ sel = lab == k
+ area = sel.sum() * step * step
+ if area < amin:
+ continue
+ jj, ii = np.nonzero(sel)
+ x0, x1 = np.percentile(xs[ii], 4), np.percentile(xs[ii], 96)
+ z0, z1 = np.percentile(zs[jj], 4), np.percentile(zs[jj], 96)
+ fill = area / max((x1 - x0) * (z1 - z0), 1e-6)
+ if (x1 - x0) / max(z1 - z0, 1e-6) > 3 or (z1 - z0) / max(x1 - x0, 1e-6) > 3:
+ continue # strips (lamp rows, trim) are not screens
+ # plane through the hits: y = a x + b z + c
+ A = np.c_[xs[ii], zs[jj], np.ones(len(ii))]
+ coef, *_ = np.linalg.lstsq(A, hy[jj, ii], rcond=None)
+ regs.append(dict(area=area, rect=(float(x0), float(z0), float(x1), float(z1)), plane=[float(c) for c in coef], fill=float(fill)))
+ regs.sort(key=lambda r: -r["area"])
+ return sorted(regs[:cfg["n"]], key=lambda r: r["rect"][0])
+
+
+def patch(ob, reg, k, round_=False, bulge=0.006):
+ x0, z0, x1, z1 = reg["rect"]
+ a, b, c = reg["plane"]
+ # most-forward point of the screen face on this plane, so the patch sits proud of the bezel glass
+ me = bpy.data.meshes.new(f"screen_{k}")
+ nx, nz = 16, 12
+ vs, fs = [], []
+ for j in range(nz + 1):
+ for i in range(nx + 1):
+ u, v = i / nx, j / nz
+ if round_: # disc: squash the square grid into a circle
+ cu, cv = 2 * u - 1, 2 * v - 1
+ cu, cv = cu * math.sqrt(1 - cv * cv / 2), cv * math.sqrt(1 - cu * cu / 2)
+ u, v = (cu + 1) / 2, (cv + 1) / 2
+ x, z = x0 + (x1 - x0) * u, z0 + (z1 - z0) * v
+ dome = bulge * max(0.0, 1 - (2 * u - 1) ** 2) * max(0.0, 1 - (2 * v - 1) ** 2)
+ vs.append((x, a * x + b * z + c - 0.003 - dome, z))
+ for j in range(nz):
+ for i in range(nx):
+ q = j * (nx + 1) + i
+ fs.append((q, q + 1, q + nx + 2, q + nx + 1))
+ me.from_pydata(vs, [], fs)
+ uv = me.uv_layers.new(name=ob.data.uv_layers.active.name)
+ for li, l in enumerate(me.loops):
+ vi = l.vertex_index
+ uv.data[li].uv = ((vi % (nx + 1)) / nx, (vi // (nx + 1)) / nz)
+ for p in me.polygons:
+ p.use_smooth = True
+ mat = bpy.data.materials.get(f"CRT_SLOT_{k}") or bpy.data.materials.new(f"CRT_SLOT_{k}")
+ mat.diffuse_color = (0.2, 1, 0.4, 1)
+ me.materials.append(mat)
+ p = bpy.data.objects.new(f"screen_{k}", me)
+ ob.users_collection[0].objects.link(p)
+ bpy.ops.object.select_all(action="DESELECT")
+ p.select_set(True)
+ ob.select_set(True)
+ bpy.context.view_layer.objects.active = ob
+ bpy.ops.object.join()
+
+
+ovr = json.load(open(OVR)) if os.path.exists(OVR) else {}
+report = {}
+for pid, cfg in CFG.items():
+ if only and pid not in only:
+ continue
+ path = os.path.join(PROPS, f"{pid}.blend")
+ if not os.path.exists(path):
+ print("FIX skip (not prepped)", pid)
+ continue
+ bpy.ops.wm.open_mainfile(filepath=path)
+ ob = bpy.data.objects[pid]
+ if ob.get("fixed") and not os.environ.get("FORCE"):
+ print("FIX already", pid)
+ continue
+ regs = ovr.get(pid) or find_screens(ob, cfg)
+ for k, reg in enumerate(regs):
+ rnd = cfg.get("round", False) or reg.get("round", False)
+ patch(ob, reg, k, rnd, bulge=0.022 if rnd else 0.006) # radar tubes bulge well past the bezel plane
+ ob = bpy.data.objects[pid]
+ ob["fixed"] = True
+ ob["screens"] = len(regs)
+ report[pid] = regs
+ bpy.ops.wm.save_as_mainfile(filepath=path)
+ print(f"FIXED {pid}: {len(regs)} screens " + "; ".join(f"x {r['rect'][0]:.3f}..{r['rect'][2]:.3f} z {r['rect'][1]:.3f}..{r['rect'][3]:.3f} fill {r.get('fill', 1):.2f}" for r in regs), flush=True)
+rp = os.path.join(SCN, "out", "screens_found.json")
+old = json.load(open(rp)) if os.path.exists(rp) else {}
+old.update(report)
+os.makedirs(os.path.dirname(rp), exist_ok=True)
+json.dump(old, open(rp, "w"), indent=1)
diff --git a/scenes/mission-control-1970s/scripts/fixscreens.py b/scenes/mission-control-1970s/scripts/fixscreens.py
new file mode 100644
index 0000000..d1f523c
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/fixscreens.py
@@ -0,0 +1,143 @@
+"""Screens: CRT phosphor shader on every CRT_SLOT_* patch (from fixes.py), the ceiling TVs' b/w pad feed, and the
+three emissive wall-display panels. Pages come from screens.py (refs/mission-control-1970s/tex/screens/).
+
+CRT page per instance = (ob["screen_idx"] + 3 * slot) mod 8, read through an OBJECT attribute, so linked duplicates of
+one console mesh still show different pages. Scanlines, a soft edge falloff and a faint phosphor floor are procedural.
+"""
+import os
+
+import bpy
+
+import layout as L
+import lib
+from lib import sock
+
+SCR = os.path.join(lib.ROOT, "refs", "mission-control-1970s", "tex", "screens")
+PAGES = ["crt_telemetry", "crt_trajectory", "crt_events", "crt_guidance", "crt_power", "crt_comms", "crt_orbit", "crt_amber_status"]
+CRT_STRENGTH = 3.0
+WALL_STRENGTH = 2.2
+
+
+def _math(nt, op, a, b=None, c=None):
+ n = nt.nodes.new("ShaderNodeMath")
+ n.operation = op
+ for i, v in enumerate((a, b, c)):
+ if v is None:
+ continue
+ if isinstance(v, (int, float)):
+ n.inputs[i].default_value = v
+ else:
+ nt.links.new(v, n.inputs[i])
+ return n.outputs[0]
+
+
+def _edge(nt, uvsep, power=8.0):
+ """1 in the middle, falling off at the edges of the 0..1 UV square (a CRT's darker corners)."""
+ out = None
+ for ax in ("X", "Y"):
+ c = _math(nt, "MULTIPLY_ADD", uvsep.outputs[ax], 2.0, -1.0)
+ p = _math(nt, "POWER", _math(nt, "ABSOLUTE", c), power)
+ e = _math(nt, "SUBTRACT", 1.0, p)
+ out = e if out is None else _math(nt, "MULTIPLY", out, e)
+ return _math(nt, "MAXIMUM", out, 0.0)
+
+
+def crt_material(name, slot=0, tv=False, strength=CRT_STRENGTH):
+ m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
+ nt = m.node_tree
+ nt.nodes.clear()
+ out = nt.nodes.new("ShaderNodeOutputMaterial")
+ b = nt.nodes.new("ShaderNodeBsdfPrincipled")
+ nt.links.new(b.outputs[0], out.inputs[0])
+ b.inputs["Base Color"].default_value = (0.012, 0.016, 0.014, 1)
+ b.inputs["Roughness"].default_value = 0.3
+ b.inputs["Coat Weight"].default_value = 1.0
+ b.inputs["Coat Roughness"].default_value = 0.06
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ nt.links.new(tc.outputs["UV"], sep.inputs["Vector"])
+ if tv: # black-and-white pad camera feed: the launch-pad backdrop, desaturated and blue-ish
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(os.path.join(lib.ROOT, "refs", "mission-control-1970s", "tex", "launch_pad_0.png"), check_existing=True)
+ mp = nt.nodes.new("ShaderNodeMapping")
+ mp.inputs["Location"].default_value = (0.3, 0.1, 0)
+ mp.inputs["Scale"].default_value = (0.4, 0.75, 1)
+ nt.links.new(tc.outputs["UV"], mp.inputs["Vector"])
+ nt.links.new(mp.outputs[0], t.inputs["Vector"])
+ hsv = nt.nodes.new("ShaderNodeHueSaturation")
+ hsv.inputs["Saturation"].default_value = 0.0
+ hsv.inputs["Value"].default_value = 2.2
+ nt.links.new(t.outputs["Color"], hsv.inputs["Color"])
+ col = lib._mix(nt, 1.0, hsv.outputs["Color"], (0.75, 0.85, 1.0), "MULTIPLY")
+ col = lib._mix(nt, 1.0, col, (0.03, 0.035, 0.04), "ADD")
+ else:
+ at = nt.nodes.new("ShaderNodeAttribute")
+ at.attribute_type = "OBJECT"
+ at.attribute_name = "screen_idx"
+ idx = _math(nt, "FLOORED_MODULO", _math(nt, "ADD", at.outputs["Fac"], 3 * slot), len(PAGES))
+ col = None
+ for i, page in enumerate(PAGES):
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(os.path.join(SCR, page + ".png"), check_existing=True)
+ t.extension = "EXTEND"
+ nt.links.new(tc.outputs["UV"], t.inputs["Vector"])
+ if col is None:
+ col = t.outputs["Color"]
+ continue
+ hit = _math(nt, "COMPARE", idx, float(i), 0.5)
+ col = lib._mix(nt, hit, col, t.outputs["Color"])
+ col = lib._mix(nt, 1.0, col, (0.006, 0.03, 0.012), "ADD") # phosphor never quite black
+ # scanlines (~240 visible lines) and the darker edges of the tube
+ sl = _math(nt, "SINE", _math(nt, "MULTIPLY", sep.outputs["Y"], 2 * 3.14159 * 240))
+ sl = _math(nt, "MULTIPLY_ADD", sl, 0.14, 0.86)
+ k = _math(nt, "MULTIPLY", _math(nt, "MULTIPLY", sl, _edge(nt, sep, 6.0)), strength)
+ nt.links.new(col, b.inputs["Emission Color"])
+ nt.links.new(k, b.inputs["Emission Strength"])
+ return m
+
+
+def wall_material(name, page, strength=WALL_STRENGTH):
+ """Rear-projection panel: the page, a slight hotspot falloff, a matte dark screen surface."""
+ m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
+ nt = m.node_tree
+ nt.nodes.clear()
+ out = nt.nodes.new("ShaderNodeOutputMaterial")
+ b = nt.nodes.new("ShaderNodeBsdfPrincipled")
+ nt.links.new(b.outputs[0], out.inputs[0])
+ b.inputs["Base Color"].default_value = (0.02, 0.022, 0.024, 1)
+ b.inputs["Roughness"].default_value = 0.55
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ nt.links.new(tc.outputs["UV"], sep.inputs["Vector"])
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(os.path.join(SCR, page + ".png"), check_existing=True)
+ t.extension = "EXTEND"
+ nt.links.new(tc.outputs["UV"], t.inputs["Vector"])
+ col = lib._mix(nt, 1.0, t.outputs["Color"], (0.004, 0.012, 0.01), "ADD")
+ k = _math(nt, "MULTIPLY", _math(nt, "MULTIPLY_ADD", _edge(nt, sep, 2.0), 0.25, 0.75), strength)
+ nt.links.new(col, b.inputs["Emission Color"])
+ nt.links.new(k, b.inputs["Emission Strength"])
+ return m
+
+
+def build():
+ done = {}
+ for o in bpy.context.scene.objects:
+ if o.type != "MESH":
+ continue
+ pid = o.get("prop_id", "")
+ for s in o.material_slots:
+ mt = s.material
+ if not mt or not mt.name.startswith("CRT_SLOT_"):
+ continue
+ if mt.name in done:
+ continue
+ slot = int(mt.name.split(".")[0].rsplit("_", 1)[1])
+ crt_material(mt.name, slot, tv=pid == "mc_tv_ceiling", strength=1.6 if pid == "mc_tv_ceiling" else CRT_STRENGTH)
+ done[mt.name] = pid
+ for name, *_ in L.DISP_PANELS:
+ p = bpy.data.objects.get(f"disp_{name}")
+ if p:
+ p.data.materials.clear()
+ p.data.materials.append(wall_material(f"wall_{name}", name))
+ print("SCREENS", len(done), "CRT materials:", done, flush=True)
diff --git a/scenes/mission-control-1970s/scripts/gen3d.mjs b/scenes/mission-control-1970s/scripts/gen3d.mjs
new file mode 100644
index 0000000..2eb1504
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/gen3d.mjs
@@ -0,0 +1,23 @@
+// Every mission-control prop through Tripo H3.1 and Meshy 7.1, 12 at a time. Skips props that already have model.glb.
+// node scenes/mission-control-1970s/scripts/gen3d.mjs [id ...] (ids limit the run). Never run two of these at once.
+import { execFile } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+const S = 'scenes/mission-control-1970s';
+const man = JSON.parse(readFileSync(`${S}/assets.json`, 'utf8'));
+const only = process.argv.slice(2);
+mkdirSync(`${S}/logs`, { recursive: true });
+const jobs = [];
+for (const a of man.generate) {
+ if (only.length && !only.includes(a.id)) continue;
+ const ref = a.ref ?? `refs/mission-control-1970s/props/${a.id}.json`;
+ if (!existsSync(ref)) { console.log(`no ref ${a.id}`); continue; }
+ for (const m of (a.models ?? ['tripo-h31', 'meshy'])) if (!existsSync(`assets/gen/${m}/${a.id}/model.glb`)) jobs.push([m, a.id, ref]);
+}
+console.log(`${jobs.length} jobs`);
+const run = ([m, id, ref]) => new Promise((res) => execFile('node', ['generate/fal.mjs', '3d', '--model', m, '--ref', ref, '--out', `assets/gen/${m}/${id}`], { maxBuffer: 1e7, timeout: 40 * 60_000 }, (err, out, errout) => {
+ writeFileSync(`${S}/logs/gen_${m}_${id}.log`, out + errout);
+ console.log(`${err ? 'FAIL' : 'ok '} ${m} ${id}${err ? ' ' + errout.slice(-200).replace(/\s+/g, ' ') : ''}`);
+ res();
+}));
+let i = 0;
+await Promise.all(Array.from({ length: +(process.env.POOL ?? 12) }, async () => { while (i < jobs.length) await run(jobs[i++]); }));
diff --git a/scenes/mission-control-1970s/scripts/gpu_prefs.py b/scenes/mission-control-1970s/scripts/gpu_prefs.py
new file mode 100644
index 0000000..806545e
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/gpu_prefs.py
@@ -0,0 +1,10 @@
+"""Enable OptiX for this Blender session; chain before another script: --python gpu_prefs.py --python shoot.py -- ..."""
+import bpy
+prefs = bpy.context.preferences.addons["cycles"].preferences
+prefs.compute_device_type = "OPTIX"
+prefs.get_devices()
+for d in prefs.devices:
+ d.use = d.type == "OPTIX"
+for sc in bpy.data.scenes:
+ sc.cycles.device = "GPU"
+print("gpu_prefs: OPTIX on", [d.name for d in prefs.devices if d.use])
diff --git a/scenes/mission-control-1970s/scripts/grade.sh b/scenes/mission-control-1970s/scripts/grade.sh
new file mode 100644
index 0000000..97b3bcb
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/grade.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Final look in post (deterministic, no re-render): lifted teal-green shadows, warm lamp highlights, slightly
+# desaturated, a touch of chromatic aberration, vignette, temporal grain.
+# scenes/mission-control-1970s/scripts/grade.sh still <in.png> <out.png>
+# scenes/mission-control-1970s/scripts/grade.sh clip <frames_dir> <out.mp4> (frames_dir/####.png)
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+GRADE="curves=r='0/0.028 0.25/0.22 0.6/0.62 1/0.98':g='0/0.034 0.25/0.245 0.6/0.61 1/0.96':b='0/0.045 0.25/0.255 0.6/0.58 1/0.9',hue=s=0.86,rgbashift=rh=-1:bh=1:edge=smear,vignette=angle=PI/4.4"
+case "$1" in
+ still) "$FF" -v error -y -i "$2" -vf "$GRADE,noise=alls=5:allf=u" -frames:v 1 "$3" ;;
+ clip) "$FF" -v error -y -framerate 24 -start_number 1 -i "$2/%04d.png" -vf "$GRADE,noise=alls=7:allf=t+u,format=yuv420p" \
+ -c:v h264_nvenc -preset p7 -rc vbr -cq 18 -b:v 0 -movflags +faststart "$3" ;;
+ *) echo "usage: grade.sh still|clip ..." ; exit 1 ;;
+esac
diff --git a/scenes/mission-control-1970s/scripts/grime.py b/scenes/mission-control-1970s/scripts/grime.py
new file mode 100644
index 0000000..a4da73f
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/grime.py
@@ -0,0 +1,262 @@
+"""Material pass on generated props: per-instance tint, a shared grime layer (AO crevice dirt + top dust + nicotine film),
+lamp glow on console/equipment indicator lamps, decals (coffee rings, cigarette burns).
+
+grime_layer group: (Color, Factor) -> Color. Factor is 1 in the scene; the breakdown fades it 0 -> 1.
+Lamp glow: emission = albedo where the albedo is a saturated bright lamp colour (HSV mask), switched per lamp by a
+noise keyed on the object's random value, so linked duplicates don't light identical buttons. Dense generated meshes get
+emission_sampling = NONE (texture emission would make every triangle a light).
+"""
+import os
+import random
+
+import bpy
+from mathutils import Vector
+
+import lib
+
+TEX = os.path.join(lib.ROOT, "refs", "mission-control-1970s", "tex")
+GLOW = {"mc_console_crt", "mc_console_twin", "mc_console_scope", "mc_console_lamps", "mc_console_comms", "mc_console_end",
+ "mc_mainframe_rack", "mc_tape_drive", "mc_equipment_rack", "mc_line_printer", "mc_met_clock", "mc_calculator",
+ "mc_desk_phone", "mc_strip_recorder", "mc_reel_recorder", "mc_coffee_maker", "mc_intercom"}
+GLOW_K = {"mc_met_clock": 18.0, "mc_calculator": 6.0, "mc_coffee_maker": 4.0}
+rng = random.Random(3)
+
+
+def grime_group():
+ g = bpy.data.node_groups.get("grime_layer")
+ if g:
+ return g
+ g = bpy.data.node_groups.new("grime_layer", "ShaderNodeTree")
+ g.interface.new_socket("Color", in_out="INPUT", socket_type="NodeSocketColor")
+ g.interface.new_socket("Factor", in_out="INPUT", socket_type="NodeSocketFloat")
+ g.interface.new_socket("Color", in_out="OUTPUT", socket_type="NodeSocketColor")
+ nt = g
+ gi = nt.nodes.new("NodeGroupInput")
+ go = nt.nodes.new("NodeGroupOutput")
+ tint = nt.nodes.new("ShaderNodeObjectInfo")
+ c = lib._mix(nt, 1.0, gi.outputs[0], tint.outputs["Color"], "MULTIPLY")
+ ao = nt.nodes.new("ShaderNodeAmbientOcclusion")
+ ao.samples = 8
+ ao.inputs["Distance"].default_value = 0.04
+ crev = lib._ramp(nt, ao.outputs["AO"], [(0.35, (1, 1, 1)), (0.9, (0, 0, 0))])
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ nz = lib._noise(nt, 18.0, 6, tc.outputs["Object"])
+ nzr = lib._ramp(nt, nz.outputs["Fac"], [(0.35, (0.3, 0.3, 0.3)), (0.7, (1, 1, 1))])
+ dirt = lib._mix(nt, 1.0, crev.outputs["Color"], nzr.outputs["Color"], "MULTIPLY")
+ geo = nt.nodes.new("ShaderNodeNewGeometry")
+ sz = nt.nodes.new("ShaderNodeSeparateXYZ")
+ nt.links.new(geo.outputs["Normal"], sz.inputs["Vector"])
+ top = lib._ramp(nt, sz.outputs["Z"], [(0.6, (0, 0, 0)), (0.95, (1, 1, 1))])
+ dust = lib._mix(nt, 1.0, top.outputs["Color"], nzr.outputs["Color"], "MULTIPLY")
+ f1 = nt.nodes.new("ShaderNodeMath")
+ f1.operation = "MULTIPLY"
+ nt.links.new(gi.outputs[1], f1.inputs[0])
+ f1.inputs[1].default_value = 0.55
+ sepd = nt.nodes.new("ShaderNodeSeparateColor")
+ nt.links.new(dirt, sepd.inputs["Color"])
+ fd = nt.nodes.new("ShaderNodeMath")
+ fd.operation = "MULTIPLY"
+ nt.links.new(sepd.outputs[0], fd.inputs[0])
+ nt.links.new(f1.outputs[0], fd.inputs[1])
+ c2 = lib._mix(nt, fd.outputs[0], c, (0.06, 0.05, 0.035))
+ seps = nt.nodes.new("ShaderNodeSeparateColor")
+ nt.links.new(dust, seps.inputs["Color"])
+ fs = nt.nodes.new("ShaderNodeMath")
+ fs.operation = "MULTIPLY"
+ nt.links.new(seps.outputs[0], fs.inputs[0])
+ fs2 = nt.nodes.new("ShaderNodeMath")
+ fs2.operation = "MULTIPLY"
+ nt.links.new(gi.outputs[1], fs2.inputs[0])
+ fs2.inputs[1].default_value = 0.22
+ fs3 = nt.nodes.new("ShaderNodeMath")
+ fs3.operation = "MULTIPLY"
+ nt.links.new(fs.outputs[0], fs3.inputs[0])
+ nt.links.new(fs2.outputs[0], fs3.inputs[1])
+ c3 = lib._mix(nt, fs3.outputs[0], c2, (0.42, 0.4, 0.36))
+ # nicotine film: everything a touch warmer and darker
+ fn = nt.nodes.new("ShaderNodeMath")
+ fn.operation = "MULTIPLY"
+ nt.links.new(gi.outputs[1], fn.inputs[0])
+ fn.inputs[1].default_value = 0.12
+ c4 = lib._mix(nt, fn.outputs[0], c3, (0.55, 0.45, 0.28), "MULTIPLY")
+ nt.links.new(c4, go.inputs[0])
+ return g
+
+
+def base_color_source(m):
+ b = next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
+ if b is None:
+ return None, None
+ s = b.inputs["Base Color"]
+ return b, (s.links[0].from_socket if s.links else None)
+
+
+def add_grime(m, factor=1.0):
+ if m.get("grimed"):
+ return
+ b, src = base_color_source(m)
+ if b is None:
+ return
+ nt = m.node_tree
+ g = nt.nodes.new("ShaderNodeGroup")
+ g.node_tree = grime_group()
+ g.name = g.label = "grime"
+ if src is not None:
+ nt.links.new(src, g.inputs["Color"])
+ else:
+ g.inputs["Color"].default_value = b.inputs["Base Color"].default_value
+ g.inputs["Factor"].default_value = factor
+ nt.links.new(g.outputs[0], b.inputs["Base Color"])
+ m["grimed"] = True
+
+
+def add_glow(m, k=3.0):
+ if m.get("glow"):
+ return
+ b, src = base_color_source(m)
+ if b is None or src is None:
+ return
+ nt = m.node_tree
+ hsv = nt.nodes.new("ShaderNodeSeparateColor")
+ hsv.mode = "HSV"
+ nt.links.new(src, hsv.inputs["Color"])
+ sm = lib._ramp(nt, hsv.outputs[1], [(0.42, (0, 0, 0)), (0.62, (1, 1, 1))])
+ vm = lib._ramp(nt, hsv.outputs[2], [(0.5, (0, 0, 0)), (0.75, (1, 1, 1))])
+ mask = lib._mix(nt, 1.0, sm.outputs["Color"], vm.outputs["Color"], "MULTIPLY")
+ # per-lamp on/off: cellular noise in UV space, offset by the object's random value
+ oi = nt.nodes.new("ShaderNodeObjectInfo")
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ add = nt.nodes.new("ShaderNodeVectorMath")
+ add.operation = "ADD"
+ nt.links.new(tc.outputs["UV"], add.inputs[0])
+ comb = nt.nodes.new("ShaderNodeCombineXYZ")
+ mul = nt.nodes.new("ShaderNodeMath")
+ mul.operation = "MULTIPLY"
+ mul.inputs[1].default_value = 97.0
+ nt.links.new(oi.outputs["Random"], mul.inputs[0])
+ nt.links.new(mul.outputs[0], comb.inputs["X"])
+ nt.links.new(comb.outputs[0], add.inputs[1])
+ vo = nt.nodes.new("ShaderNodeTexVoronoi")
+ vo.inputs["Scale"].default_value = 140.0
+ vo.feature = "F1"
+ nt.links.new(add.outputs[0], vo.inputs["Vector"])
+ sw = lib._ramp(nt, vo.outputs["Color"], [(0.3, (0.08, 0.08, 0.08)), (0.32, (1, 1, 1))])
+ mask = lib._mix(nt, 1.0, mask, sw.outputs["Color"], "MULTIPLY")
+ em = lib._mix(nt, 1.0, src, mask, "MULTIPLY")
+ nt.links.new(em, b.inputs["Emission Color"])
+ b.inputs["Emission Strength"].default_value = k
+ m.cycles.emission_sampling = "NONE"
+ m["glow"] = True
+
+
+GLASS_MASK = {"mc_ashtray_glass"} # generators bake glass as opaque grey (not the cooler: its cream enamel would match too)
+
+
+def add_glass(m):
+ """Glass from an opaque generated texture: low-saturation light texels (the glass body) become transmissive, the
+ butts/ash/metal (saturated or dark) stay opaque."""
+ if m.get("glass"):
+ return
+ b, src = base_color_source(m)
+ if b is None or src is None:
+ return
+ nt = m.node_tree
+ hsv = nt.nodes.new("ShaderNodeSeparateColor")
+ hsv.mode = "HSV"
+ nt.links.new(src, hsv.inputs["Color"])
+ s = lib._ramp(nt, hsv.outputs[1], [(0.12, (1, 1, 1)), (0.22, (0, 0, 0))])
+ v = lib._ramp(nt, hsv.outputs[2], [(0.4, (0, 0, 0)), (0.55, (1, 1, 1))])
+ mask = lib._mix(nt, 1.0, s.outputs["Color"], v.outputs["Color"], "MULTIPLY")
+ sep = nt.nodes.new("ShaderNodeSeparateColor")
+ nt.links.new(mask, sep.inputs["Color"])
+ nt.links.new(sep.outputs[0], b.inputs["Transmission Weight"])
+ rr = nt.nodes.new("ShaderNodeMapRange")
+ rr.inputs["To Min"].default_value = 0.5
+ rr.inputs["To Max"].default_value = 0.06
+ nt.links.new(sep.outputs[0], rr.inputs["Value"])
+ nt.links.new(rr.outputs["Result"], b.inputs["Roughness"])
+ b.inputs["IOR"].default_value = 1.5
+ m["glass"] = True
+
+
+def decal_material(name, path):
+ """White-background stain image: colour from the image, alpha = 1 - luminance."""
+ m, nt = lib._new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(path, check_existing=True)
+ t.extension = "CLIP"
+ nt.links.new(t.outputs["Color"], b.inputs["Base Color"])
+ inv = nt.nodes.new("ShaderNodeInvert")
+ bw = nt.nodes.new("ShaderNodeRGBToBW")
+ nt.links.new(t.outputs["Color"], bw.inputs["Color"])
+ nt.links.new(bw.outputs[0], inv.inputs["Color"])
+ r = lib._ramp(nt, inv.outputs["Color"], [(0.05, (0, 0, 0)), (0.5, (1, 1, 1))])
+ a = nt.nodes.new("ShaderNodeMath")
+ a.operation = "MULTIPLY"
+ nt.links.new(r.outputs["Color"], a.inputs[0])
+ a.inputs[1].default_value = 0.85
+ a.name = "decal_alpha"
+ nt.links.new(a.outputs[0], b.inputs["Alpha"])
+ b.inputs["Roughness"].default_value = 0.6
+ m.surface_render_method = "DITHERED"
+ return m
+
+
+def decals():
+ C = lib.collection("decals")
+ mats = [decal_material("decal_coffee", os.path.join(TEX, "decal_coffee_0.png")),
+ decal_material("decal_burns", os.path.join(TEX, "decal_burns_0.png"))]
+ dg = bpy.context.evaluated_depsgraph_get()
+ targets = [o for o in bpy.context.scene.objects if o.get("prop_id", "").startswith("mc_console") and o.get("bay")]
+ n = 0
+ for o in targets:
+ lo = Vector(o.bound_box[0])
+ mw = o.matrix_world
+ bb = [mw @ Vector(c) for c in o.bound_box]
+ x0, x1 = min(p.x for p in bb), max(p.x for p in bb)
+ y0 = min(p.y for p in bb)
+ for k in range(rng.randint(1, 3)):
+ x, y = rng.uniform(x0 + 0.15, x1 - 0.15), y0 + rng.uniform(0.05, 0.3)
+ ok, loc, nrm, _i, hit, _m = bpy.context.scene.ray_cast(dg, Vector((x, y, min(p.z for p in bb) + 0.95)), Vector((0, 0, -1)))
+ if not ok or hit is not o or nrm.z < 0.9:
+ continue
+ s = rng.uniform(0.12, 0.22)
+ p = lib.plane(f"decal_{n}", (x, y, loc.z + 0.0006), s, s, "Z", rng.choice(mats), C)
+ p.rotation_euler = (0, 0, rng.uniform(0, 6.28))
+ p.visible_shadow = False
+ n += 1
+ # cigarette burns on the carpet near the chairs
+ for k in range(10):
+ x, y = rng.uniform(1.8, 9.3), rng.choice([8.9, 6.0, 3.0]) + rng.uniform(-0.6, 0.4)
+ ok, loc, nrm, _i, hit, _m = bpy.context.scene.ray_cast(dg, Vector((x, y, 1.0)), Vector((0, 0, -1)))
+ if ok and hit.name.startswith("floor_t"):
+ s = rng.uniform(0.25, 0.4)
+ p = lib.plane(f"decal_floor_{k}", (x, y, loc.z + 0.0008), s, s, "Z", mats[1], C)
+ p.rotation_euler = (0, 0, rng.uniform(0, 6.28))
+ p.visible_shadow = False
+ print("DECALS", n, flush=True)
+
+
+def build(factor=1.0):
+ seen = set()
+ for o in bpy.context.scene.objects:
+ pid = o.get("prop_id")
+ if not pid or o.type != "MESH":
+ continue
+ for s in o.material_slots:
+ m = s.material
+ if not m or m.name in seen or m.name.startswith("CRT_SLOT_") or m.name.startswith("crt_"):
+ continue
+ seen.add(m.name)
+ add_grime(m, factor)
+ if pid in GLASS_MASK:
+ add_glass(m)
+ if pid in GLOW:
+ add_glow(m, GLOW_K.get(pid, 3.0))
+ elif len(o.data.polygons) > 20000:
+ m.cycles.emission_sampling = "NONE"
+ decals()
+ print("GRIME", len(seen), "materials", flush=True)
diff --git a/scenes/mission-control-1970s/scripts/haze.py b/scenes/mission-control-1970s/scripts/haze.py
new file mode 100644
index 0000000..70042ff
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/haze.py
@@ -0,0 +1,99 @@
+"""Cigarette haze: two homogeneous room layers, thin up to head height and denser under the ceiling (smoke pools there),
+plus thin rising smoke curls above the hero ashtrays, animated by drifting their noise.
+
+A noise-driven room volume made Cycles ray-march the whole 11 x 13 m box: ~22 s/frame against ~4 s without haze.
+Homogeneous volumes are sampled analytically, so the room layers carry no texture; only the small curls are
+heterogeneous.
+
+Object motion blur is off on every volume object (a moving or deforming volume domain makes Cycles rebuild velocity
+per frame; on the ramen scene's Mantaflow domain that cost ~290 s/frame). These are static objects with animated
+textures, so there is nothing to blur anyway.
+"""
+import bpy
+from mathutils import Vector
+
+import layout as L
+import lib
+
+DENSITY = 0.014
+CEILING_DENSITY = 0.032
+LAYER_Z = 2.35
+
+
+def flat_material(name, density):
+ m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
+ nt = m.node_tree
+ nt.nodes.clear()
+ out = nt.nodes.new("ShaderNodeOutputMaterial")
+ v = nt.nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Color"].default_value = (0.82, 0.8, 0.76, 1)
+ v.inputs["Anisotropy"].default_value = 0.35
+ k = nt.nodes.new("ShaderNodeMath") # a plain multiply so the breakdown can key the density in
+ k.operation = "MULTIPLY"
+ k.inputs[0].default_value = 1.0
+ k.inputs[1].default_value = density
+ nt.links.new(k.outputs[0], v.inputs["Density"])
+ nt.links.new(v.outputs[0], out.inputs["Volume"])
+ return m
+
+
+def haze_material(name, density, height_lo, height_hi, scale=0.35, curl=False):
+ m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
+ nt = m.node_tree
+ nt.nodes.clear()
+ out = nt.nodes.new("ShaderNodeOutputMaterial")
+ v = nt.nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Color"].default_value = (0.82, 0.8, 0.76, 1)
+ v.inputs["Anisotropy"].default_value = 0.35
+ nt.links.new(v.outputs[0], out.inputs["Volume"])
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ mp = nt.nodes.new("ShaderNodeMapping")
+ nt.links.new(tc.outputs["Object" if curl else "Generated"], mp.inputs["Vector"])
+ # drift with time (driver on the mapping's location)
+ fc = mp.inputs["Location"].driver_add("default_value", 2 if curl else 0)
+ fc.driver.expression = ("frame * -0.012" if curl else "frame * 0.0006")
+ nz = nt.nodes.new("ShaderNodeTexNoise")
+ nz.inputs["Scale"].default_value = scale
+ nz.inputs["Detail"].default_value = 4.0
+ nz.inputs["Distortion"].default_value = 0.6 if not curl else 2.5
+ nt.links.new(mp.outputs[0], nz.inputs["Vector"])
+ r = lib._ramp(nt, nz.outputs["Fac"], [(0.38, (0.25, 0.25, 0.25)), (0.7, (1, 1, 1))] if not curl
+ else [(0.52, (0, 0, 0)), (0.56, (1, 1, 1))])
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ nt.links.new(tc.outputs["Generated"], sep.inputs["Vector"])
+ hr = lib._ramp(nt, sep.outputs["Z"], [(height_lo, (0.35, 0.35, 0.35)), (height_hi, (1, 1, 1))] if not curl
+ else [(0.0, (1, 1, 1)), (1.0, (0, 0, 0))])
+ f = lib._mix(nt, 1.0, r.outputs["Color"], hr.outputs["Color"], "MULTIPLY")
+ k = nt.nodes.new("ShaderNodeMath")
+ k.operation = "MULTIPLY"
+ k.inputs[1].default_value = density
+ sp = nt.nodes.new("ShaderNodeSeparateColor")
+ nt.links.new(f, sp.inputs["Color"])
+ nt.links.new(sp.outputs[0], k.inputs[0])
+ nt.links.new(k.outputs[0], v.inputs["Density"])
+ return m
+
+
+def build(density=DENSITY):
+ C = lib.collection("haze")
+ for name, z0, z1, dn in (("haze_room", 0.0, LAYER_Z, density), ("haze_ceiling", LAYER_Z, L.H - 0.06, CEILING_DENSITY)):
+ hz = lib.box(name, (0.02, 0.02, z0), (L.W - 0.02, L.D - 0.02, z1), flat_material(name, dn), C, bevel=0)
+ hz.visible_shadow = False
+ hz.cycles.use_motion_blur = False
+ # smoke curls over the ashtrays of the composed bays
+ n = 0
+ for o in bpy.context.scene.objects:
+ if o.get("prop_id") not in ("mc_ashtray_glass",) or n >= 3:
+ continue
+ lo = o.matrix_world @ Vector(o.bound_box[0])
+ hi = o.matrix_world @ Vector(o.bound_box[6])
+ c = (lo + hi) / 2
+ b = lib.box(f"smoke_curl_{n}", (c.x - 0.09, c.y - 0.09, hi.z), (c.x + 0.09, c.y + 0.09, hi.z + 0.75),
+ haze_material(f"smoke_curl_{n}", 6.0, 0, 1, scale=9.0, curl=True), C, bevel=0)
+ b.visible_shadow = False
+ b.cycles.use_motion_blur = False
+ n += 1
+ sc = bpy.context.scene
+ sc.cycles.volume_step_rate = 4.0
+ sc.cycles.volume_max_steps = 256
+ print("HAZE", density, "curls", n, flush=True)
diff --git a/scenes/mission-control-1970s/scripts/layout.py b/scenes/mission-control-1970s/scripts/layout.py
new file mode 100644
index 0000000..7f9ea4c
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/layout.py
@@ -0,0 +1,46 @@
+"""Shared layout constants for the mission-control room (metres; x across, y back door -> wall display, z up)."""
+W, D, H = 11.0, 13.0, 3.6
+T = 0.2 # wall thickness
+# tiers: (floor z, y0, y1); tier 0 is the front (display end)
+TIERS = [(0.0, 7.5, D), (0.35, 4.5, 7.5), (0.7, 0.0, 4.5)]
+WIN_Y0, WIN_Y1, WIN_Z0, WIN_Z1 = 1.2, 9.6, 1.3, 3.1 # left-wall window band
+DOOR_X0, DOOR_X1, DOOR_Z1 = 4.9, 6.1, 2.85
+AISLE_L = (0.3, 1.7) # step x-range, window aisle
+AISLE_R = (9.35, 10.2) # step x-range, right aisle
+
+# console rows: name, floor z, front (operator-side) y of the consoles, x start, bay list (left -> right)
+# bays: console prop ids; placard text per bay (None = no placard)
+ROWS = [
+ ("A", 0.0, 9.6, 1.95, ["mc_console_end", "mc_console_crt", "mc_console_twin", "mc_console_scope", "mc_console_crt",
+ "mc_console_comms", "mc_console_end"],
+ [None, "GUIDANCE", "TRAJECTORY", "ORBITAL ANALYSIS", "TELEMETRY", "COMMS", None]),
+ ("B", 0.35, 6.5, 2.6, ["mc_console_end", "mc_console_lamps", "mc_console_twin", "mc_console_crt", "mc_console_comms",
+ "mc_console_end"],
+ [None, "POWER", "LIFE SUPPORT", "PROPULSION", "NETWORK", None]),
+ ("C", 0.7, 3.5, 3.25, ["mc_console_end", "mc_console_crt", "mc_console_lamps", "mc_console_twin", "mc_console_end"],
+ [None, "RECOVERY", "FLIGHT DIRECTOR", "MISSION OPS", None]),
+]
+BAY_W = {"mc_console_end": 0.45}
+DEFAULT_BAY_W = 1.25
+CONSOLE_D = 1.0
+
+
+def tier_z(y):
+ for z, y0, y1 in TIERS:
+ if y0 <= y <= y1:
+ return z
+ return 0.0
+
+
+def bays(row):
+ """Yield (prop id, placard, x centre, x0, x1) for a row."""
+ name, z, y, x, ids, labels = row
+ for pid, lab in zip(ids, labels):
+ w = BAY_W.get(pid, DEFAULT_BAY_W)
+ yield pid, lab, x + w / 2, x, x + w
+ x += w
+
+
+# wall display on the front wall (y = D): panels (name, x0, x1), shared z range
+DISP_Z0, DISP_Z1 = 1.05, 3.15
+DISP_PANELS = [("wall_left", 1.3, 3.4), ("wall_map", 3.65, 7.85), ("wall_right", 8.1, 10.2)]
diff --git a/scenes/mission-control-1970s/scripts/lib.py b/scenes/mission-control-1970s/scripts/lib.py
new file mode 100644
index 0000000..38b6bd8
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/lib.py
@@ -0,0 +1,365 @@
+"""Small direct-modelling + material library for the repair shop scene (Blender 5.0)."""
+import math
+import os
+import random
+
+import bpy
+import bmesh
+from mathutils import Vector
+
+ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+
+
+def sock(node, name, kind=None):
+ """Enabled input socket by name (Mix nodes have several sockets per name)."""
+ for s in node.inputs:
+ if s.name == name and s.enabled and (kind is None or s.type == kind):
+ return s
+ raise KeyError(name)
+
+
+def collection(name, parent=None):
+ c = bpy.data.collections.get(name) or bpy.data.collections.new(name)
+ p = parent or bpy.context.scene.collection
+ if c.name not in [x.name for x in p.children]:
+ p.children.link(c)
+ return c
+
+
+def link(obj, coll):
+ for c in obj.users_collection:
+ c.objects.unlink(obj)
+ coll.objects.link(obj)
+ return obj
+
+
+def box(name, lo, hi, mat=None, coll=None, bevel=0.002, uv_scale=1.0):
+ """Axis-aligned box from world-space corners, real geometry (no object scale), box-projected UVs in metres."""
+ lo, hi = Vector(lo), Vector(hi)
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ size = hi - lo
+ for v in bm.verts:
+ v.co = Vector((v.co.x * size.x, v.co.y * size.y, v.co.z * size.z))
+ uv = bm.loops.layers.uv.new("UVMap")
+ for f in bm.faces:
+ n = f.normal
+ for l in f.loops:
+ co = l.vert.co + (lo + hi) / 2
+ if abs(n.z) > 0.5:
+ l[uv].uv = (co.x * uv_scale, co.y * uv_scale)
+ elif abs(n.x) > 0.5:
+ l[uv].uv = (co.y * uv_scale, co.z * uv_scale)
+ else:
+ l[uv].uv = (co.x * uv_scale, co.z * uv_scale)
+ bm.to_mesh(me)
+ bm.free()
+ ob = bpy.data.objects.new(name, me)
+ ob.location = (lo + hi) / 2
+ (coll or bpy.context.scene.collection).objects.link(ob)
+ if mat:
+ me.materials.append(mat)
+ if bevel > 0 and min(size) > bevel * 3:
+ m = ob.modifiers.new("bevel", "BEVEL")
+ m.width = bevel
+ m.segments = 2
+ m.limit_method = "ANGLE"
+ m.harden_normals = True
+ for p in me.polygons: # smooth only with a bevel + hardened normals; a smooth unbevelled slab refracts like a lens
+ p.use_smooth = True
+ return ob
+
+
+def cylinder(name, centre, r, h, mat=None, coll=None, axis="Z", verts=24):
+ bpy.ops.mesh.primitive_cylinder_add(vertices=verts, radius=r, depth=h, location=centre)
+ ob = bpy.context.object
+ ob.name = name
+ if axis == "X":
+ ob.rotation_euler = (0, math.pi / 2, 0)
+ elif axis == "Y":
+ ob.rotation_euler = (math.pi / 2, 0, 0)
+ if mat:
+ ob.data.materials.append(mat)
+ if coll:
+ link(ob, coll)
+ return ob
+
+
+def plane(name, centre, w, h, normal="-Y", mat=None, coll=None):
+ """Upright (or flat with normal Z) textured plane, UV 0..1."""
+ me = bpy.data.meshes.new(name)
+ hw, hh = w / 2, h / 2
+ if normal in ("-Y", "Y"):
+ vs = [(-hw, 0, -hh), (hw, 0, -hh), (hw, 0, hh), (-hw, 0, hh)]
+ elif normal in ("-X", "X"):
+ vs = [(0, hw, -hh), (0, -hw, -hh), (0, -hw, hh), (0, hw, hh)]
+ else:
+ vs = [(-hw, -hh, 0), (hw, -hh, 0), (hw, hh, 0), (-hw, hh, 0)]
+ if normal in ("Y", "X"):
+ vs = [vs[1], vs[0], vs[3], vs[2]]
+ me.from_pydata(vs, [], [(0, 1, 2, 3)])
+ uv = me.uv_layers.new(name="UVMap")
+ for i, l in enumerate(me.loops):
+ uv.data[i].uv = [(0, 0), (1, 0), (1, 1), (0, 1)][l.vertex_index]
+ ob = bpy.data.objects.new(name, me)
+ ob.location = centre
+ (coll or bpy.context.scene.collection).objects.link(ob)
+ if mat:
+ me.materials.append(mat)
+ return ob
+
+
+def set_uv_rect(ob, u0, v0, u1, v1):
+ uv = ob.data.uv_layers[0]
+ for i, l in enumerate(ob.data.loops):
+ c = [(u0, v0), (u1, v0), (u1, v1), (u0, v1)][l.vertex_index]
+ uv.data[i].uv = c
+
+
+# ---------------------------------------------------------------- materials
+
+def _new(name):
+ m = bpy.data.materials.get(name)
+ if m:
+ return m, None
+ m = bpy.data.materials.new(name)
+ nt = m.node_tree
+ return m, nt
+
+
+def principled(name, color, rough=0.5, metal=0.0, **kw):
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (*color, 1)
+ b.inputs["Roughness"].default_value = rough
+ b.inputs["Metallic"].default_value = metal
+ for k, v in kw.items():
+ b.inputs[k].default_value = v
+ return m
+
+
+def _noise(nt, scale, detail=6, coord=None):
+ n = nt.nodes.new("ShaderNodeTexNoise")
+ n.inputs["Scale"].default_value = scale
+ n.inputs["Detail"].default_value = detail
+ if coord is not None:
+ nt.links.new(coord, n.inputs["Vector"])
+ return n
+
+
+def _ramp(nt, src, stops):
+ r = nt.nodes.new("ShaderNodeValToRGB")
+ nt.links.new(src, r.inputs["Fac"])
+ els = r.color_ramp.elements
+ for i, (pos, col) in enumerate(stops):
+ e = els[i] if i < len(els) else els.new(pos)
+ e.position = pos
+ e.color = (*col, 1) if len(col) == 3 else col
+ return r
+
+
+def _mix(nt, fac, a, b, blend="MIX"):
+ m = nt.nodes.new("ShaderNodeMix")
+ m.data_type = "RGBA"
+ m.blend_type = blend
+ if isinstance(fac, float):
+ sock(m, "Factor", "VALUE").default_value = fac
+ else:
+ nt.links.new(fac, sock(m, "Factor", "VALUE"))
+ for s, v in (("A", a), ("B", b)):
+ if isinstance(v, tuple):
+ sock(m, s, "RGBA").default_value = (*v, 1) if len(v) == 3 else v
+ else:
+ nt.links.new(v, sock(m, s, "RGBA"))
+ return m.outputs["Result"]
+
+
+def _bump(nt, height, strength, dist=0.002):
+ b = nt.nodes.new("ShaderNodeBump")
+ b.inputs["Strength"].default_value = strength
+ b.inputs["Distance"].default_value = dist
+ nt.links.new(height, b.inputs["Height"])
+ return b.outputs["Normal"]
+
+
+def grimy(name, base, grime=(0.18, 0.16, 0.13), rough=(0.45, 0.75), metal=0.0, scale=3.0, amount=0.35, bump=0.15):
+ """Generic worn surface: base colour broken up by large-scale grime and fine speckle, roughness follows grime."""
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ n1 = _noise(nt, scale, 8, tc.outputs["Object"])
+ n2 = _noise(nt, scale * 40, 4, tc.outputs["Object"])
+ r1 = _ramp(nt, n1.outputs["Fac"], [(0.45, (0, 0, 0)), (0.75, (1, 1, 1))])
+ fac = _mix(nt, 0.5, r1.outputs["Color"], n2.outputs["Color"], "MULTIPLY")
+ f2 = nt.nodes.new("ShaderNodeMath")
+ f2.operation = "MULTIPLY"
+ f2.inputs[1].default_value = amount * 2
+ nt.links.new(fac, f2.inputs[0])
+ col = _mix(nt, f2.outputs[0], base, grime)
+ nt.links.new(col, b.inputs["Base Color"])
+ mr = nt.nodes.new("ShaderNodeMapRange")
+ mr.inputs["To Min"].default_value = rough[0]
+ mr.inputs["To Max"].default_value = rough[1]
+ nt.links.new(f2.outputs[0], mr.inputs["Value"])
+ nt.links.new(mr.outputs["Result"], b.inputs["Roughness"])
+ b.inputs["Metallic"].default_value = metal
+ nt.links.new(_bump(nt, n2.outputs["Fac"], bump), b.inputs["Normal"])
+ return m
+
+
+def wood(name, light=(0.42, 0.27, 0.15), dark=(0.2, 0.11, 0.05), scale=2.0, worn=0.3):
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ mp = nt.nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (scale * 6, scale * 0.15, scale * 6) # long streaks along Y (bench/shelf length)
+ nt.links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ nz = _noise(nt, 4.0, 8, mp.outputs["Vector"])
+ w = nt.nodes.new("ShaderNodeTexWave") # kept for the bump only
+ w.wave_type = "BANDS"
+ w.bands_direction = "X"
+ w.inputs["Scale"].default_value = 40.0
+ w.inputs["Distortion"].default_value = 1.5
+ nt.links.new(mp.outputs["Vector"], w.inputs["Vector"])
+ r = _ramp(nt, nz.outputs["Fac"], [(0.3, dark), (0.7, light)])
+ grime = _noise(nt, 1.5, 6, tc.outputs["Object"])
+ gr = _ramp(nt, grime.outputs["Fac"], [(0.5, (0, 0, 0)), (0.8, (1, 1, 1))])
+ f = nt.nodes.new("ShaderNodeMath")
+ f.operation = "MULTIPLY"
+ f.inputs[1].default_value = worn
+ nt.links.new(gr.outputs["Color"], f.inputs[0])
+ col = _mix(nt, f.outputs[0], r.outputs["Color"], (0.06, 0.04, 0.025))
+ nt.links.new(col, b.inputs["Base Color"])
+ mr = nt.nodes.new("ShaderNodeMapRange")
+ mr.inputs["To Min"].default_value = 0.35
+ mr.inputs["To Max"].default_value = 0.7
+ nt.links.new(nz.outputs["Fac"], mr.inputs["Value"])
+ nt.links.new(mr.outputs["Result"], b.inputs["Roughness"])
+ nt.links.new(_bump(nt, w.outputs["Fac"], 0.08), b.inputs["Normal"])
+ return m
+
+
+def floor_tiles(name, tile=0.3, a=(0.55, 0.53, 0.47), b2=(0.33, 0.33, 0.31)):
+ """Old checker vinyl floor tiles with grout, scuffs and traffic grime."""
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ br = nt.nodes.new("ShaderNodeTexBrick")
+ br.offset = 0.0
+ br.inputs["Scale"].default_value = 1.0
+ br.inputs["Brick Width"].default_value = tile
+ br.inputs["Row Height"].default_value = tile
+ br.inputs["Mortar Size"].default_value = 0.002
+ br.inputs["Color1"].default_value = (*a, 1)
+ br.inputs["Color2"].default_value = (*b2, 1)
+ br.inputs["Mortar"].default_value = (0.08, 0.075, 0.07, 1)
+ nt.links.new(tc.outputs["Object"], br.inputs["Vector"])
+ ch = nt.nodes.new("ShaderNodeTexChecker")
+ ch.inputs["Scale"].default_value = 1 / tile / 2 * 2
+ ch.inputs["Color1"].default_value = (*a, 1)
+ ch.inputs["Color2"].default_value = (*b2, 1)
+ nt.links.new(tc.outputs["Object"], ch.inputs["Vector"])
+ base = _mix(nt, br.outputs["Fac"], ch.outputs["Color"], (0.08, 0.075, 0.07))
+ n1 = _noise(nt, 0.8, 8, tc.outputs["Object"])
+ g = _ramp(nt, n1.outputs["Fac"], [(0.4, (0, 0, 0)), (0.75, (1, 1, 1))])
+ n2 = _noise(nt, 60, 3, tc.outputs["Object"])
+ col = _mix(nt, g.outputs["Color"], base, (0.12, 0.1, 0.08), "MULTIPLY")
+ col = _mix(nt, 0.15, col, n2.outputs["Color"], "OVERLAY")
+ nt.links.new(col, b.inputs["Base Color"])
+ mr = nt.nodes.new("ShaderNodeMapRange")
+ mr.inputs["To Min"].default_value = 0.25
+ mr.inputs["To Max"].default_value = 0.65
+ nt.links.new(n1.outputs["Fac"], mr.inputs["Value"])
+ nt.links.new(mr.outputs["Result"], b.inputs["Roughness"])
+ nt.links.new(_bump(nt, br.outputs["Fac"], 0.3), b.inputs["Normal"])
+ return m
+
+
+def wall_paint(name, base=(0.62, 0.6, 0.55)):
+ """Painted plaster: low-frequency blotches, darker grime band towards the floor."""
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ n1 = _noise(nt, 1.2, 8, tc.outputs["Object"])
+ n2 = _noise(nt, 25, 6, tc.outputs["Object"])
+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")
+ nt.links.new(tc.outputs["Generated"], sep.inputs["Vector"])
+ band = _ramp(nt, sep.outputs["Z"], [(0.0, (1, 1, 1)), (0.25, (0, 0, 0))])
+ blot = _ramp(nt, n1.outputs["Fac"], [(0.45, (0, 0, 0)), (0.8, (0.6, 0.6, 0.6))])
+ fac = _mix(nt, 1.0, band.outputs["Color"], blot.outputs["Color"], "LIGHTEN")
+ col = _mix(nt, fac, base, (0.3, 0.27, 0.22))
+ col = _mix(nt, 0.08, col, n2.outputs["Color"], "OVERLAY")
+ nt.links.new(col, b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.85
+ nt.links.new(_bump(nt, n2.outputs["Fac"], 0.05), b.inputs["Normal"])
+ return m
+
+
+def rain_glass(name):
+ """Storefront glass with beaded drops and vertical run streaks (normal-only, transmission glass)."""
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.9, 0.95, 0.95, 1)
+ b.inputs["Roughness"].default_value = 0.03
+ b.inputs["Transmission Weight"].default_value = 1.0
+ b.inputs["IOR"].default_value = 1.5
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ vo = nt.nodes.new("ShaderNodeTexVoronoi")
+ vo.feature = "SMOOTH_F1"
+ vo.inputs["Scale"].default_value = 55
+ vo.inputs["Randomness"].default_value = 1.0
+ nt.links.new(tc.outputs["Object"], vo.inputs["Vector"])
+ drops = _ramp(nt, vo.outputs["Distance"], [(0.0, (1, 1, 1)), (0.18, (0, 0, 0))])
+ mp = nt.nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (60, 60, 1.2)
+ nt.links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ st = _noise(nt, 1.0, 2, mp.outputs["Vector"])
+ streak = _ramp(nt, st.outputs["Fac"], [(0.66, (0, 0, 0)), (0.7, (0.4, 0.4, 0.4))])
+ mask = _noise(nt, 3, 2, tc.outputs["Object"])
+ mk = _ramp(nt, mask.outputs["Fac"], [(0.4, (0, 0, 0)), (0.6, (1, 1, 1))])
+ h = _mix(nt, 1.0, drops.outputs["Color"], streak.outputs["Color"], "LIGHTEN")
+ h = _mix(nt, mk.outputs["Color"], (0.0, 0.0, 0.0), h)
+ nt.links.new(_bump(nt, h, 0.5, 0.002), b.inputs["Normal"])
+ return m
+
+
+def image_mat(name, path, rough=0.7, emission=0.0, alpha=False, extend="REPEAT"):
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(path, check_existing=True)
+ t.extension = extend
+ nt.links.new(t.outputs["Color"], b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = rough
+ if emission:
+ nt.links.new(t.outputs["Color"], b.inputs["Emission Color"])
+ b.inputs["Emission Strength"].default_value = emission
+ if alpha:
+ nt.links.new(t.outputs["Color"], b.inputs["Alpha"]) # white-on-black decals: luminance as alpha
+ return m
+
+
+def emissive(name, color, strength):
+ m, nt = _new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (*color, 1)
+ b.inputs["Emission Color"].default_value = (*color, 1)
+ b.inputs["Emission Strength"].default_value = strength
+ return m
diff --git a/scenes/mission-control-1970s/scripts/lights.py b/scenes/mission-control-1970s/scripts/lights.py
new file mode 100644
index 0000000..4b9cf8f
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/lights.py
@@ -0,0 +1,105 @@
+"""Night lighting: practicals first (CRT faces and the wall display are emissive already), then desk lamps, the few
+troffers that are on, the display spill, the launch-pad spill through the windows, small accents; weak fills last.
+
+Every light lives in collection "lights" with ob["light_order"] (the breakdown's switch-on order) and
+ob["base_energy"]. Area lights shine along local -Z. Fills are hidden from camera, glossy and transmission rays so
+they never show through the window glass as bright discs.
+"""
+import math
+
+import bpy
+from mathutils import Vector
+
+import layout as L
+import lib
+
+EXPOSURE = -0.35 # the haze lifts the blacks
+WARM = (1.0, 0.68, 0.38)
+COOL_TUBE = (0.82, 0.93, 1.0)
+PHOSPHOR = (0.35, 1.0, 0.55)
+_order = [0]
+
+
+def light(name, kind, loc, energy, color, size=0.1, aim=None, rot=None, spot=None, fill=False, order_group=0):
+ d = bpy.data.lights.new(name, kind)
+ d.energy = energy
+ d.color = color
+ if kind == "AREA":
+ if isinstance(size, tuple):
+ d.shape = "RECTANGLE"
+ d.size, d.size_y = size
+ else:
+ d.size = size
+ elif kind in ("POINT", "SPOT"):
+ d.shadow_soft_size = size
+ if spot:
+ d.spot_size, d.spot_blend = math.radians(spot[0]), spot[1]
+ o = bpy.data.objects.new(name, d)
+ lib.collection("lights").objects.link(o)
+ o.location = loc
+ if aim is not None:
+ o.rotation_euler = (Vector(aim) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
+ elif rot is not None:
+ o.rotation_euler = rot
+ if fill:
+ o.visible_camera = False
+ o.visible_glossy = False
+ o.visible_transmission = False
+ o["light_order"] = order_group * 100 + _order[0]
+ o["base_energy"] = energy
+ _order[0] += 1
+ return o
+
+
+def lamp_head(o):
+ """World-space centre of a desk lamp's shade: the mean of the highest 25 % of vertices, pushed to the shade's rim."""
+ mw = o.matrix_world
+ vs = [mw @ v.co for v in o.data.vertices]
+ zmax = max(v.z for v in vs)
+ zmin = min(v.z for v in vs)
+ top = [v for v in vs if v.z > zmin + 0.72 * (zmax - zmin)]
+ c = sum(top, Vector()) / len(top)
+ low = min(v.z for v in top)
+ return Vector((c.x, c.y, low - 0.01))
+
+
+def build():
+ sc = bpy.context.scene
+ sc.view_settings.exposure = EXPOSURE
+ # group 1: desk lamps (warm pools)
+ for o in [o for o in sc.objects if o.get("desk_lamp")]:
+ h = lamp_head(o)
+ light(f"lamp_{o.name}", "SPOT", h, 28.0, WARM, size=0.025, aim=h + Vector((0, 0.15, -1)), spot=(105, 0.55), order_group=1)
+ light(f"lampglow_{o.name}", "POINT", h + Vector((0, 0, 0.03)), 1.2, WARM, size=0.02, order_group=1)
+ # group 2: troffers that are on (area light just under each lit lens)
+ for o in sc.objects:
+ st = o.get("state")
+ if st in ("tr_on", "tr_dim"):
+ lo = o.matrix_world @ Vector(o.bound_box[0])
+ hi = o.matrix_world @ Vector(o.bound_box[6])
+ c = (lo + hi) / 2
+ e = 70.0 if st == "tr_on" else 14.0
+ lt = light(f"tube_{o.name}", "AREA", (c.x, c.y, lo.z - 0.005), e, COOL_TUBE, size=(0.54, 1.12), rot=(0, 0, 0), order_group=2)
+ lt.visible_camera = False
+ # group 3: the wall display spill (the panels are emissive; these add the soft directional throw into the room)
+ for name, x0, x1 in L.DISP_PANELS:
+ col = (0.35, 1.0, 0.85) if name == "wall_map" else (0.45, 1.0, 0.6)
+ light(f"disp_{name}", "AREA", ((x0 + x1) / 2, L.D - 0.3, (L.DISP_Z0 + L.DISP_Z1) / 2), 60.0 if name == "wall_map" else 25.0, col,
+ size=(x1 - x0, L.DISP_Z1 - L.DISP_Z0), rot=(math.radians(-90), 0, 0), fill=True, order_group=3)
+ # group 4: launch-pad spill through the windows (cold xenon from high up, a little sodium low)
+ light("pad_spill", "AREA", (-2.5, 5.4, 3.4), 140.0, (0.72, 0.82, 1.0), size=(1.8, 8.4), aim=(3.5, 5.4, 0.0), fill=True, order_group=4)
+ light("pad_sodium", "AREA", (-2.5, 5.4, 1.6), 30.0, (1.0, 0.6, 0.25), size=(1.0, 8.4), aim=(3.0, 5.4, 1.0), fill=True, order_group=4)
+ # group 5: accents (exit sign glow, the coffee maker's warmer, CRT bounce for the hero console)
+ light("exit_glow", "POINT", (5.5, 0.25, L.DOOR_Z1 + 0.2), 3.0, (1.0, 0.1, 0.05), size=0.05, order_group=5)
+ cm = next((o for o in sc.objects if o.get("prop_id") == "mc_coffee_maker"), None)
+ if cm:
+ lo = cm.matrix_world @ Vector(cm.bound_box[0])
+ hi = cm.matrix_world @ Vector(cm.bound_box[6])
+ light("warmer_glow", "POINT", ((lo.x + hi.x) / 2, lo.y - 0.05, lo.z + 0.06), 0.6, (1.0, 0.2, 0.05), size=0.02, order_group=5)
+ # group 6: weak fills last: a cool bounce from the display end over the rows, a whisper of warm from the back
+ light("fill_rows", "AREA", (5.6, 9.0, 3.4), 18.0, (0.6, 0.9, 0.85), size=(6.0, 3.0), rot=(0, 0, 0), fill=True, order_group=6)
+ light("fill_back", "AREA", (5.5, 1.6, 3.4), 6.0, (1.0, 0.8, 0.6), size=(6.0, 2.0), rot=(0, 0, 0), fill=True, order_group=6)
+ w = sc.world
+ if w and w.use_nodes:
+ w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.003, 0.004, 0.007, 1)
+ print("LIGHTS", len(lib.collection("lights").objects), flush=True)
diff --git a/scenes/mission-control-1970s/scripts/lowcams.py b/scenes/mission-control-1970s/scripts/lowcams.py
new file mode 100644
index 0000000..9337e26
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/lowcams.py
@@ -0,0 +1,29 @@
+"""Low-angle check cameras for contact/grounding review (desk tops at eye level, chair feet, floor spill, back cabinets).
+
+blender -b mc.blend --python gpu_prefs.py --python lowcams.py --python preview.py -- --cams low_desk_a,... --exposure 1.5
+Adds cameras only; nothing is saved.
+"""
+import bpy
+from mathutils import Vector
+
+CAMS = { # name: (position, aim, lens)
+ "low_desk_a": ((2.6, 8.55, 0.80), (4.6, 9.4, 0.70), 28),
+ "low_desk_b": ((6.8, 5.55, 1.15), (5.0, 6.3, 1.05), 28),
+ "low_desk_c": ((3.4, 2.55, 1.50), (5.2, 3.3, 1.40), 28),
+ "low_chairs_a": ((2.2, 7.7, 0.12), (4.5, 8.6, 0.25), 24),
+ "low_chairs_b": ((8.0, 4.8, 0.47), (5.5, 5.6, 0.6), 24),
+ "low_back_cabinets": ((3.0, 1.7, 2.1), (2.7, 0.35, 1.85), 28),
+ "low_spill": ((8.6, 2.2, 0.85), (9.8, 2.3, 0.72), 28),
+}
+
+for name, (pos, aim, lens) in CAMS.items():
+ cd = bpy.data.cameras.new(name)
+ cd.lens = lens
+ cd.clip_start = 0.02
+ o = bpy.data.objects.new(name, cd)
+ bpy.context.scene.collection.objects.link(o)
+ o.location = pos
+ d = Vector(aim) - Vector(pos)
+ o.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()
+bpy.context.scene.render.resolution_x, bpy.context.scene.render.resolution_y = 1920, 1080
+print("LOWCAMS", ",".join(CAMS), flush=True)
diff --git a/scenes/mission-control-1970s/scripts/nocurl.py b/scenes/mission-control-1970s/scripts/nocurl.py
new file mode 100644
index 0000000..ad50327
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/nocurl.py
@@ -0,0 +1,7 @@
+"""Hide the ashtray smoke curls (run before camera/shoot.py). The curls sit inside the room haze; overlapping volumes
+cost ~21 s/frame against ~7 s with either alone, and only the push-in onto the hero ashtray needs them."""
+import bpy
+
+for o in bpy.data.objects:
+ if o.name.startswith("smoke_curl"):
+ o.hide_render = True
diff --git a/scenes/mission-control-1970s/scripts/post.py b/scenes/mission-control-1970s/scripts/post.py
new file mode 100644
index 0000000..f9fae59
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/post.py
@@ -0,0 +1,71 @@
+"""Render settings, hero cameras and the optional clay override."""
+import math
+
+import bpy
+from mathutils import Vector
+
+import lib
+
+# hero cameras: name -> (position, aim, lens)
+CAMS = {
+ "cam_back_wide": ((8.6, 1.2, 2.25), (4.6, 12.5, 1.7), 24), # from the back aisle, down the rows to the display
+ "cam_row_a": ((5.3, 8.2, 1.45), (5.2, 10.0, 1.15), 32), # behind the ORBITAL ANALYSIS chair
+ "cam_windows": ((1.0, 11.6, 1.6), (4.0, 2.0, 1.5), 24), # front-left corner looking back up the tiers
+ "cam_printer": ((8.2, 3.0, 1.9), (10.6, 0.8, 1.0), 30), # the right-wall printer corner
+ "cam_display": ((5.6, 4.2, 2.1), (5.8, 13.0, 2.1), 35), # flight director's view
+}
+
+
+def camera(name, pos, aim, lens):
+ cam = bpy.data.objects.get(name)
+ if cam is None:
+ cam = bpy.data.objects.new(name, bpy.data.cameras.new(name))
+ lib.collection("cameras").objects.link(cam)
+ cam.location = pos
+ cam.rotation_euler = (Vector(aim) - Vector(pos)).to_track_quat("-Z", "Y").to_euler()
+ cam.data.lens = lens
+ cam.data.sensor_width = 24.89
+ cam.data.clip_start = 0.05
+ cam.data.clip_end = 200
+ return cam
+
+
+def make_clay():
+ m = lib.principled("clay", (0.6, 0.6, 0.6), 0.6)
+ for o in bpy.context.scene.objects:
+ if o.type in ("MESH", "CURVE", "FONT") and not o.name.startswith(("backdrop", "outside")):
+ o.data.materials.clear()
+ o.data.materials.append(m)
+ for s in o.material_slots:
+ s.link = "OBJECT"
+ s.material = m
+
+
+def build(clay=False):
+ sc = bpy.context.scene
+ for n, (p, a, l) in CAMS.items():
+ camera(n, p, a, l)
+ sc.camera = bpy.data.objects["cam_back_wide"]
+ sc.render.engine = "CYCLES"
+ sc.cycles.samples = 48
+ sc.cycles.use_denoising = True
+ sc.cycles.denoiser = "OPTIX" # ~2 s/frame faster than OIDN here
+ sc.render.use_persistent_data = False # measured slower here (29 vs 24 s/frame)
+ sc.cycles.max_bounces = 6
+ sc.cycles.volume_bounces = 1
+ sc.cycles.transparent_max_bounces = 8
+ sc.cycles.light_sampling_threshold = 0.01
+ sc.render.resolution_x, sc.render.resolution_y = 1920, 804
+ sc.render.resolution_percentage = 100
+ sc.render.fps = 24
+ sc.view_settings.view_transform = "AgX"
+ sc.view_settings.look = "AgX - Medium High Contrast"
+ sc.view_settings.exposure = 0.0
+ if bpy.context.scene.world is None:
+ w = bpy.data.worlds.new("night")
+ w.use_nodes = True
+ w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.004, 0.005, 0.008, 1)
+ w.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.0
+ sc.world = w
+ if clay:
+ make_clay()
diff --git a/scenes/mission-control-1970s/scripts/prep.py b/scenes/mission-control-1970s/scripts/prep.py
new file mode 100644
index 0000000..767681d
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/prep.py
@@ -0,0 +1,119 @@
+"""Prep picked generated props into per-prop library .blend files.
+
+blender -b --factory-startup --python scenes/mission-control-1970s/scripts/prep.py -- [id ...]
+Reads assets.json + picks.json. For each pick: import the GLB, join, turn so the front faces -Y (rotating mesh data),
+scale to the manifest size (h = height, dims = per-axis [x, y, z], max = largest dimension), bottom-centre origin,
+decimate to the tier budget, textures <= 2K, save props/<id>.blend (one collection named after the id).
+Already-prepped props are skipped unless the pick changed model/yaw or the GLB is newer (or FORCE=1); a re-prep
+drops fixes.py patches, so run fixes.py after every prep.
+"""
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Matrix, Vector
+
+ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+SCN = os.path.join(ROOT, "scenes", "mission-control-1970s")
+FRONT_YAW = {"tripo-h31": 90, "meshy": 0} # where each generator's front points, degrees from -Y (counter-clockwise)
+MAX_TEX = 2048
+BUDGET = {"hero": 150_000, "mid": 80_000, "clutter": 40_000}
+
+man = {a["id"]: a for a in json.load(open(os.path.join(SCN, "assets.json")))["generate"]}
+picks_path = os.path.join(SCN, "picks.json")
+picks = {k: v for k, v in json.load(open(picks_path)).items() if not k.startswith("_")}
+only = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+
+
+def prep(pid):
+ a, pick = man[pid], picks[pid]
+ model = pick["model"]
+ glb = os.path.join(ROOT, "assets", "gen", model, pid, "model.glb")
+ out = os.path.join(SCN, "props", f"{pid}.blend")
+ side = os.path.join(SCN, "props", f"{pid}.json") # sidecar: which model the .blend was prepped from
+ if not os.environ.get("FORCE") and os.path.exists(out) and os.path.exists(side) and os.path.getmtime(out) > os.path.getmtime(glb) and json.load(open(side)).get("model") == model and json.load(open(side)).get("yaw", 0) == pick.get("yaw", 0) and json.load(open(side)).get("lay", False) == pick.get("lay", False):
+ print("PREP skip", pid)
+ return
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=glb)
+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+ for o in bpy.data.objects:
+ o.select_set(o.type == "MESH")
+ bpy.context.view_layer.objects.active = meshes[0]
+ if len(meshes) > 1:
+ bpy.ops.object.join()
+ ob = bpy.context.view_layer.objects.active
+ mw = ob.matrix_world.copy()
+ ob.parent = None
+ ob.rotation_mode = "XYZ" # glTF imports are QUATERNION; rotation_euler is ignored otherwise
+ ob.matrix_world = mw
+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
+ for o in [o for o in bpy.data.objects if o is not ob]:
+ bpy.data.objects.remove(o)
+ yaw = -math.radians(FRONT_YAW[model] + pick.get("yaw", 0))
+ ob.data.transform(Matrix.Rotation(yaw, 4, "Z"))
+ if pick.get("lay"): # generator stood a flat object on its edge: lay it front face up
+ ob.data.transform(Matrix.Rotation(math.radians(-90), 4, "X"))
+ vs = [v.co for v in ob.data.vertices]
+ lo = Vector((min(v.x for v in vs), min(v.y for v in vs), min(v.z for v in vs)))
+ hi = Vector((max(v.x for v in vs), max(v.y for v in vs), max(v.z for v in vs)))
+ dims = hi - lo
+ ob.data.transform(Matrix.Translation(-Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))))
+ if "dims" in a:
+ sx, sy, sz = (t / max(d, 1e-6) for t, d in zip(a["dims"], dims))
+ ob.data.transform(Matrix.Diagonal((sx, sy, sz, 1)))
+ else:
+ s = a["h"] / dims.z if "h" in a else a["max"] / max(dims)
+ ob.data.transform(Matrix.Scale(s, 4))
+ ob.location = (0, 0, 0)
+ tris = sum(len(p.vertices) - 2 for p in ob.data.polygons)
+ budget = BUDGET[a.get("tier", "mid")]
+ if tris > budget:
+ m = ob.modifiers.new("dec", "DECIMATE")
+ m.ratio = budget / tris
+ bpy.ops.object.modifier_apply(modifier="dec")
+ for p in ob.data.polygons:
+ p.use_smooth = True
+ texdir = os.path.join(SCN, "props", "tex")
+ os.makedirs(texdir, exist_ok=True)
+ for i, img in enumerate(bpy.data.images):
+ if img.size[0] == 0:
+ continue
+ if max(img.size) > MAX_TEX:
+ f = MAX_TEX / max(img.size)
+ img.scale(int(img.size[0] * f), int(img.size[1] * f))
+ path = os.path.join(texdir, f"{pid}_{i}.png")
+ img.filepath_raw = path
+ img.file_format = "PNG"
+ img.save()
+ img.filepath = path
+ ob.name = pid
+ ob.data.name = pid
+ for i, slot in enumerate(ob.material_slots):
+ if slot.material:
+ slot.material.name = f"{pid}_mat{i}"
+ coll = bpy.data.collections.new(pid)
+ bpy.context.scene.collection.children.link(coll)
+ for c in ob.users_collection:
+ c.objects.unlink(ob)
+ coll.objects.link(ob)
+ ob["source_model"] = model
+ ob["prop_id"] = pid
+ ob["tris"] = sum(len(p.vertices) - 2 for p in ob.data.polygons)
+ bpy.ops.wm.save_as_mainfile(filepath=out)
+ json.dump({"model": model, "yaw": pick.get("yaw", 0), "lay": pick.get("lay", False)}, open(side, "w"))
+ d = ob.dimensions
+ print(f"PREP {pid} {model} tris {tris}->{ob['tris']} dims {d.x:.2f}x{d.y:.2f}x{d.z:.2f}", flush=True)
+
+
+for pid in picks:
+ if only and pid not in only:
+ continue
+ if picks[pid].get("retired"):
+ continue
+ try:
+ prep(pid)
+ except Exception as e:
+ print("PREP FAILED", pid, repr(e), flush=True)
diff --git a/scenes/mission-control-1970s/scripts/preview.py b/scenes/mission-control-1970s/scripts/preview.py
new file mode 100644
index 0000000..08f1bcb
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/preview.py
@@ -0,0 +1,44 @@
+"""Stills from the hero cameras of a built .blend (run with gpu_prefs.py first for Cycles).
+
+blender -b mc.blend --python gpu_prefs.py --python preview.py -- --cams cam_a,cam_b [--engine cycles|eevee|workbench]
+ [--samples 32] [--pct 50] [--tag x] [--exposure 0]
+-> scenes/mission-control-1970s/out/prev/<tag>_<cam>.png
+"""
+import argparse
+import os
+import sys
+
+import bpy
+
+ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+OUT = os.path.join(ROOT, "scenes", "mission-control-1970s", "out", "prev")
+ap = argparse.ArgumentParser()
+ap.add_argument("--cams", default="cam_back_wide,cam_row_a,cam_windows,cam_printer,cam_display")
+ap.add_argument("--engine", default="cycles")
+ap.add_argument("--samples", type=int, default=32)
+ap.add_argument("--pct", type=int, default=50)
+ap.add_argument("--tag", default="p")
+ap.add_argument("--exposure", type=float, default=None)
+a = ap.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
+sc = bpy.context.scene
+sc.render.resolution_percentage = a.pct
+if a.exposure is not None:
+ sc.view_settings.exposure = a.exposure
+if a.engine == "eevee":
+ sc.render.engine = "BLENDER_EEVEE"
+ sc.eevee.taa_render_samples = a.samples
+elif a.engine == "workbench":
+ sc.render.engine = "BLENDER_WORKBENCH"
+ sc.display.shading.light = "STUDIO"
+ sc.display.shading.color_type = "MATERIAL"
+ sc.display.shading.show_cavity = True
+ sc.display.shading.show_shadows = True
+ sc.view_settings.view_transform = "Standard"
+else:
+ sc.cycles.samples = a.samples
+os.makedirs(OUT, exist_ok=True)
+for c in a.cams.split(","):
+ sc.camera = bpy.data.objects[c]
+ sc.render.filepath = os.path.join(OUT, f"{a.tag}_{c}.png")
+ bpy.ops.render.render(write_still=True)
+ print("PREVIEW", sc.render.filepath, flush=True)
diff --git a/scenes/mission-control-1970s/scripts/prevsheet.sh b/scenes/mission-control-1970s/scripts/prevsheet.sh
new file mode 100644
index 0000000..333e009
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/prevsheet.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# 2-column sheet of preview stills: prevsheet.sh <tag> [cams] -> out/prev/<tag>_sheet.png
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+P=scenes/mission-control-1970s/out/prev
+cams=${2:-cam_back_wide,cam_row_a,cam_windows,cam_printer,cam_display}
+IFS=, read -ra cs <<< "$cams"
+args=(); f=""; n=0
+for c in "${cs[@]}"; do args+=(-i "$P/${1}_$c.png"); f+="[$n]scale=960:402[s$n];"; n=$((n+1)); done
+if [ $((n % 2)) -eq 1 ]; then args+=(-f lavfi -i color=c=black:s=960x402:d=1); f+="[$n]null[s$n];"; n=$((n+1)); fi
+rows=""
+for ((i = 0; i < n; i += 2)); do f+="[s$i][s$((i+1))]hstack=2[r$i];"; rows+="[r$i]"; done
+f+="${rows}vstack=$((n / 2))"
+"$FF" -v error -y "${args[@]}" -filter_complex "$f" -frames:v 1 "$P/${1}_sheet.png"
+echo "$P/${1}_sheet.png"
diff --git a/scenes/mission-control-1970s/scripts/refs.mjs b/scenes/mission-control-1970s/scripts/refs.mjs
new file mode 100644
index 0000000..e6f66f8
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/refs.mjs
@@ -0,0 +1,26 @@
+// GPT Image 2.5 Sunburst references for the mission-control manifest (props + textures), 10 at a time; skips existing.
+// node scenes/mission-control-1970s/scripts/refs.mjs [id ...]
+import { execFile } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+const S = 'scenes/mission-control-1970s', R = 'refs/mission-control-1970s';
+const REF = 'No real-world brand names or logos. Product reference photograph for 3D scanning. The entire object fully visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft even diffuse studio lighting, no harsh shadows, no other objects, no hands, realistic used and worn condition, sharp focus, true-to-life materials.';
+const man = JSON.parse(readFileSync(`${S}/assets.json`, 'utf8'));
+const only = process.argv.slice(2);
+const want = (id) => !only.length || only.includes(id);
+const jobs = [];
+for (const a of man.generate) {
+ const out = `${R}/props/${a.id}`;
+ if (!want(a.id) || a.ref || existsSync(`${out}.json`)) continue;
+ jobs.push(['--variant', 'sunburst', '--quality', 'high', '--size', 'square_hd', '--out', out, '--prompt', `${a.prompt.replace('{console}', man.style.console)} ${REF}`]);
+}
+for (const t of man.textures ?? []) {
+ const out = t.id.startsWith('concept') ? `${R}/${t.id}` : `${R}/tex/${t.id}`;
+ if (!want(t.id) || existsSync(`${out}.json`)) continue;
+ jobs.push(['--variant', t.variant ?? 'sunburst', '--quality', 'high', '--size', t.size, '--out', out, '--prompt', t.prompt]);
+}
+console.log(`${jobs.length} image jobs`);
+const run = (args) => new Promise((res) => execFile('node', ['generate/fal.mjs', 'image', ...args], { maxBuffer: 1e7 }, (err, out, errout) => {
+ console.log(err ? `FAIL ${args[args.indexOf('--out') + 1]} ${errout.slice(-300)}` : out.trim().split('\n').at(-1)); res();
+}));
+let i = 0;
+await Promise.all(Array.from({ length: 10 }, async () => { while (i < jobs.length) await run(jobs[i++]); }));
diff --git a/scenes/mission-control-1970s/scripts/refsheet.sh b/scenes/mission-control-1970s/scripts/refsheet.sh
new file mode 100644
index 0000000..c03837f
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/refsheet.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Grid of reference images (brand check gate): refsheet.sh <out.png> <id> [id ...] -> 6 per row, 256 px, id order.
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+out=$1; shift
+args=(); f=""; n=0; rows=""; r=0; row=""; k=0
+for id in "$@"; do
+ args+=(-i "refs/mission-control-1970s/props/${id}_0.png"); f+="[$n]scale=256:256[s$n];"; row+="[s$n]"; n=$((n+1)); k=$((k+1))
+ if [ $k -eq 6 ]; then f+="${row}hstack=6[r$r];"; rows+="[r$r]"; r=$((r+1)); row=""; k=0; fi
+done
+while [ $k -gt 0 ] && [ $k -lt 6 ]; do args+=(-f lavfi -i color=c=black:s=256x256:d=1); f+="[$n]null[s$n];"; row+="[s$n]"; n=$((n+1)); k=$((k+1)); done
+[ -n "$row" ] && { f+="${row}hstack=6[r$r];"; rows+="[r$r]"; r=$((r+1)); }
+if [ $r -gt 1 ]; then f+="${rows}vstack=$r"; else f="${f%;}"; f="${f%\[r0\]}"; fi
+"$FF" -v error -y "${args[@]}" -filter_complex "$f" -frames:v 1 "$out"
diff --git a/scenes/mission-control-1970s/scripts/render_finals.sh b/scenes/mission-control-1970s/scripts/render_finals.sh
new file mode 100644
index 0000000..e434153
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/render_finals.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+# Every shot in 24-frame chunks through the GPU queue (existing frames skipped, so this resumes), then a graded mp4
+# per shot with a frame-count check, then the reel and a <30 MB chat copy.
+# scenes/mission-control-1970s/scripts/render_finals.sh [shot ...]
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+S=scenes/mission-control-1970s
+O=$S/out/shots
+CHUNK=${CHUNK:-24}
+shots=${*:-$(node -e "console.log(require('./$S/shots.json').shots.map(s=>s.name).join(' '))")}
+for s in $shots; do
+ n=$(node -e "console.log(require('./$S/shots.json').shots.find(x=>x.name=='$s').frames)")
+ for ((a = 1; a <= n; a += CHUNK)); do
+ b=$((a + CHUNK - 1)); [ $b -gt $n ] && b=$n
+ have=$(ls $O/$s/frames 2>/dev/null | awk -v a=$a -v b=$b '{f=$0+0} f>=a && f<=b' | wc -l)
+ [ "$have" -eq $((b - a + 1)) ] && continue
+ t0=$(date +%s)
+ if [ "$s" = orbital_push ]; then nc=; else nc=1; fi # smoke curls only in the push-in (see nocurl.py)
+ NOCURL=$nc bash $S/scripts/shoot.sh --only $s --frames $a-$b --no-encode > $S/logs/final_${s}_$a.log 2>&1
+ echo "$s $a-$b: $(( $(date +%s) - t0 )) s"
+ done
+ got=$(ls $O/$s/frames | wc -l)
+ if [ "$got" -ne "$n" ]; then echo "SHORT $s: $got/$n frames"; continue; fi
+ bash $S/scripts/grade.sh clip $O/$s/frames $S/out/graded/$s.mp4
+ echo "graded $s: $("$FF" -i $S/out/graded/$s.mp4 2>&1 | grep -o 'Duration: [0-9:.]*')"
+done
diff --git a/scenes/mission-control-1970s/scripts/screens.py b/scenes/mission-control-1970s/scripts/screens.py
new file mode 100644
index 0000000..214ac2e
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/screens.py
@@ -0,0 +1,370 @@
+"""Screen content textures: green-phosphor CRT pages and the three wall-display panels, all invented text.
+
+blender -b --factory-startup --python scenes/mission-control-1970s/scripts/screens.py -- [name ...]
+Each screen is a little 2D scene (real font text objects, polyline curves, the generated world map for the big display)
+rendered with Eevee through an ortho camera, then given a phosphor bloom in numpy. Output:
+refs/mission-control-1970s/tex/screens/<name>.png. Coordinates below are in screen units: x 0..aspect, y 0..1 (top = 1).
+"""
+import math
+import os
+import random
+import sys
+
+import bpy
+import numpy as np
+
+ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+OUT = os.path.join(ROOT, "refs", "mission-control-1970s", "tex", "screens")
+MAP = os.path.join(ROOT, "refs", "mission-control-1970s", "tex", "world_map_0.png")
+MONO = "C:/Windows/Fonts/lucon.ttf"
+BOLD = "C:/Windows/Fonts/arialbd.ttf"
+GREEN = (0.35, 1.0, 0.45)
+DIM = (0.1, 0.38, 0.14)
+AMBER = (1.0, 0.62, 0.12)
+CYAN = (0.4, 1.0, 0.85)
+WHITE = (0.85, 1.0, 0.9)
+only = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+os.makedirs(OUT, exist_ok=True)
+
+
+class Page:
+ def __init__(self, name, px=(1024, 768), tint=GREEN):
+ self.name, self.px, self.tint = name, px, tint
+ self.aspect = px[0] / px[1]
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ sc = self.sc = bpy.context.scene
+ sc.render.engine = "BLENDER_EEVEE"
+ sc.render.resolution_x, sc.render.resolution_y = px
+ sc.render.resolution_percentage = 100
+ sc.view_settings.view_transform = "Standard"
+ sc.eevee.taa_render_samples = 16
+ w = bpy.data.worlds.new("w")
+ w.use_nodes = True
+ w.node_tree.nodes["Background"].inputs["Color"].default_value = (0, 0, 0, 1)
+ sc.world = w
+ cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam"))
+ cam.data.type = "ORTHO"
+ cam.data.ortho_scale = self.aspect
+ cam.location = (self.aspect / 2, 0.5, 5)
+ sc.collection.objects.link(cam)
+ sc.camera = cam
+ self.mats = {}
+ self.fonts = {}
+
+ def mat(self, col, k=1.0):
+ key = (tuple(round(c, 3) for c in col), k)
+ if key not in self.mats:
+ m = bpy.data.materials.new("e")
+ nt = m.node_tree
+ nt.nodes.clear()
+ em = nt.nodes.new("ShaderNodeEmission")
+ em.inputs["Color"].default_value = (*col, 1)
+ em.inputs["Strength"].default_value = k
+ o = nt.nodes.new("ShaderNodeOutputMaterial")
+ nt.links.new(em.outputs[0], o.inputs[0])
+ self.mats[key] = m
+ return self.mats[key]
+
+ def text(self, s, x, y, size=0.04, col=None, font=MONO, align="LEFT", k=1.0):
+ if font not in self.fonts:
+ self.fonts[font] = bpy.data.fonts.load(font)
+ cu = bpy.data.curves.new("t", "FONT")
+ cu.body = s
+ cu.font = self.fonts[font]
+ cu.size = size
+ cu.align_x = align
+ cu.align_y = "TOP"
+ cu.materials.append(self.mat(col or self.tint, k))
+ ob = bpy.data.objects.new("t", cu)
+ ob.location = (x, y, 0)
+ self.sc.collection.objects.link(ob)
+ return ob
+
+ def lines(self, rows, x, y, size=0.04, lead=1.35, col=None, k=1.0):
+ for i, r in enumerate(rows):
+ if r:
+ self.text(r, x, y - i * size * lead, size, col, k=k)
+
+ def poly(self, pts, width=0.003, col=None, closed=False, k=1.0):
+ cu = bpy.data.curves.new("p", "CURVE")
+ cu.dimensions = "3D"
+ cu.extrude = 0
+ sp = cu.splines.new("POLY")
+ sp.points.add(len(pts) - 1)
+ for p, (px, py) in zip(sp.points, pts):
+ p.co = (px, py, 0, 1)
+ sp.use_cyclic_u = closed
+ cu.bevel_mode = "ROUND"
+ cu.dimensions = "3D"
+ cu.bevel_depth = width / 2
+ cu.materials.append(self.mat(col or self.tint, k))
+ ob = bpy.data.objects.new("p", cu)
+ self.sc.collection.objects.link(ob)
+ return ob
+
+ def rect(self, x0, y0, x1, y1, **kw):
+ return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], closed=True, **kw)
+
+ def fill(self, x0, y0, x1, y1, col, k=1.0):
+ me = bpy.data.meshes.new("f")
+ me.from_pydata([(x0, y0, -0.01), (x1, y0, -0.01), (x1, y1, -0.01), (x0, y1, -0.01)], [], [(0, 1, 2, 3)])
+ me.materials.append(self.mat(col, k))
+ ob = bpy.data.objects.new("f", me)
+ self.sc.collection.objects.link(ob)
+
+ def circle(self, cx, cy, r, n=64, **kw):
+ return self.poly([(cx + r * math.cos(2 * math.pi * i / n), cy + r * math.sin(2 * math.pi * i / n)) for i in range(n)], closed=True, **kw)
+
+ def image(self, path, x0, y0, x1, y1, k=1.0):
+ me = bpy.data.meshes.new("img")
+ me.from_pydata([(x0, y0, -0.02), (x1, y0, -0.02), (x1, y1, -0.02), (x0, y1, -0.02)], [], [(0, 1, 2, 3)])
+ uv = me.uv_layers.new()
+ for i, l in enumerate(me.loops):
+ uv.data[i].uv = [(0, 0), (1, 0), (1, 1), (0, 1)][l.vertex_index]
+ m = bpy.data.materials.new("img")
+ nt = m.node_tree
+ nt.nodes.clear()
+ t = nt.nodes.new("ShaderNodeTexImage")
+ t.image = bpy.data.images.load(path)
+ em = nt.nodes.new("ShaderNodeEmission")
+ em.inputs["Strength"].default_value = k
+ o = nt.nodes.new("ShaderNodeOutputMaterial")
+ nt.links.new(t.outputs["Color"], em.inputs["Color"])
+ nt.links.new(em.outputs[0], o.inputs[0])
+ me.materials.append(m)
+ ob = bpy.data.objects.new("img", me)
+ self.sc.collection.objects.link(ob)
+
+ def render(self, bloom=0.55, raster=True):
+ path = os.path.join(OUT, f"{self.name}.png")
+ self.sc.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+ img = bpy.data.images.load(path)
+ w, h = img.size
+ a = np.empty(w * h * 4, np.float32)
+ img.pixels.foreach_get(a)
+ a = a.reshape(h, w, 4)[..., :3]
+ glow = a.copy()
+ for r in (3, 7, 15): # three box-blur passes per radius ~ a soft phosphor halo
+ g = a.copy()
+ for _ in range(3):
+ g = box(g, r)
+ glow = glow + g * (bloom / 3)
+ out = glow
+ if raster: # faint raster lines baked in (the scene shader adds the real scanlines)
+ rows = (np.arange(h) % 3 == 0)[:, None, None]
+ out = np.where(rows, out * 0.82, out)
+ out = np.clip(out, 0, 1)
+ rgba = np.concatenate([out, np.ones((h, w, 1), np.float32)], axis=2)
+ img.pixels.foreach_set(rgba.ravel())
+ img.filepath_raw = path
+ img.file_format = "PNG"
+ img.save()
+ print("SCREEN", self.name, w, h, flush=True)
+
+
+def box(a, r):
+ c = np.cumsum(np.pad(a, ((r + 1, r), (0, 0), (0, 0)), mode="edge"), axis=0)
+ a = (c[2 * r + 1:] - c[:-2 * r - 1]) / (2 * r + 1)
+ c = np.cumsum(np.pad(a, ((0, 0), (r + 1, r), (0, 0)), mode="edge"), axis=1)
+ return (c[:, 2 * r + 1:] - c[:, :-2 * r - 1]) / (2 * r + 1)
+
+
+R = random.Random(7)
+
+
+def num(lo, hi, d=2):
+ return f"{R.uniform(lo, hi):.{d}f}"
+
+
+def header(p, title, sub="PERSEUS 7 REV 112"):
+ p.text(title, 0.05, 0.96, 0.045)
+ p.text(sub, p.aspect - 0.05, 0.96, 0.045, align="RIGHT")
+ p.text(f"GMT 303:03:{R.randint(36, 44):02d}:{R.randint(0, 59):02d}", 0.05, 0.9, 0.034, DIM)
+ p.text(f"MET 007:14:{R.randint(10, 50):02d}:{R.randint(0, 59):02d}", p.aspect - 0.05, 0.9, 0.034, DIM, align="RIGHT")
+ p.poly([(0.05, 0.85), (p.aspect - 0.05, 0.85)], 0.003, DIM)
+
+
+def crt_telemetry(name="crt_telemetry", tint=GREEN):
+ p = Page(name, tint=tint)
+ header(p, "TLM ENVIRONMENTAL")
+ rows = [("CABIN PRESS", num(4.9, 5.1), "PSIA"), ("CABIN TEMP", num(68, 74, 1), "DEG F"), ("O2 FLOW", num(0.2, 0.4), "LB/HR"),
+ ("CO2 PART PR", num(1.2, 2.4, 1), "MMHG"), ("SUIT LOOP DP", num(0.2, 0.5), "IN H2O"), ("H2O ACCUM", num(10, 40, 0), "PCT"),
+ ("GLYCOL IN", num(44, 49, 1), "DEG F"), ("GLYCOL OUT", num(52, 58, 1), "DEG F"), ("RAD OUT TEMP", num(30, 45, 1), "DEG F"),
+ ("SURGE TK PR", num(880, 900, 0), "PSIA"), ("O2 TK 1 QTY", num(71, 74, 1), "PCT"), ("O2 TK 2 QTY", num(70, 73, 1), "PCT")]
+ for i, (k, v, u) in enumerate(rows):
+ y = 0.8 - i * 0.058
+ p.text(f"{i + 101:03d}", 0.05, y, 0.038, DIM)
+ p.text(k, 0.17, y, 0.038)
+ p.text(v.rjust(7), 0.72, y, 0.038, WHITE if i == 3 else None)
+ p.text(u, 0.98, y, 0.038, DIM)
+ p.text("OK" if i != 3 else "WTCH", 1.2, y, 0.038, None if i != 3 else WHITE)
+ p.text("> _", 0.05, 0.07, 0.04)
+ p.render()
+
+
+def crt_trajectory(name="crt_trajectory", tint=GREEN):
+ p = Page(name, tint=tint)
+ header(p, "TRAJ ALT / RANGE")
+ x0, x1, y0, y1 = 0.16, 1.25, 0.14, 0.78
+ p.rect(x0, y0, x1, y1, width=0.003, col=DIM)
+ for i in range(1, 6):
+ p.poly([(x0 + (x1 - x0) * i / 6, y0), (x0 + (x1 - x0) * i / 6, y1)], 0.0015, DIM)
+ p.poly([(x0, y0 + (y1 - y0) * i / 6), (x1, y0 + (y1 - y0) * i / 6)], 0.0015, DIM)
+ pts = [(x0 + (x1 - x0) * t, y0 + (y1 - y0) * (0.5 + 0.38 * math.sin(2 * math.pi * (t * 1.1 + 0.1)) * (1 - 0.15 * t))) for t in np.linspace(0, 1, 120)]
+ p.poly(pts[:84], 0.006)
+ for x, y in pts[84::4]:
+ p.poly([(x - 0.002, y), (x + 0.002, y)], 0.005, DIM)
+ p.text("+", pts[83][0] - 0.012, pts[83][1] + 0.022, 0.05, WHITE)
+ for i, v in enumerate(("160", "140", "120", "100")):
+ p.text(v, 0.05, y1 - i * (y1 - y0) / 3 + 0.015, 0.03, DIM)
+ p.text("NM", 0.05, y0 - 0.02, 0.03, DIM)
+ p.text(f"HA {num(158, 162, 1)} HP {num(141, 145, 1)} INC {num(32, 33, 2)}", 0.16, 0.08, 0.036)
+ p.render()
+
+
+def crt_events(name="crt_events", tint=GREEN):
+ p = Page(name, tint=tint)
+ header(p, "EVENT LOG")
+ evs = ["AOS KESTREL", "TLM LOCK KESTREL", "CMD UPLINK 4471 VERIFIED", "LOS KESTREL", "AOS OSPREY", "S-BAND HI GAIN",
+ "PTC ROLL INITIATED", "LOS OSPREY", "AOS HARRIER", "STATE VECTOR UPDATE", "FUEL CELL 2 PURGE", "LOS HARRIER",
+ "AOS MERLIN", "CREW STATUS NOMINAL"]
+ t = 3 * 3600 + 2 * 60
+ for i, e in enumerate(evs):
+ t += R.randint(90, 260)
+ y = 0.8 - i * 0.052
+ p.text(f"{t // 3600:02d}:{t // 60 % 60:02d}:{t % 60:02d}", 0.05, y, 0.036, DIM)
+ p.text(e, 0.36, y, 0.036, WHITE if i == len(evs) - 1 else None)
+ p.text("\u2588", 0.05, 0.07, 0.04)
+ p.render()
+
+
+def crt_guidance(name="crt_guidance", tint=GREEN):
+ p = Page(name, tint=tint)
+ header(p, "GNC STATE VECTOR")
+ p.lines([" X Y Z",
+ f"R {num(-4e6, 4e6, 0):>11} {num(-4e6, 4e6, 0):>12} {num(-4e6, 4e6, 0):>12}",
+ f"V {num(-7e3, 7e3, 1):>11} {num(-7e3, 7e3, 1):>12} {num(-7e3, 7e3, 1):>12}", "",
+ "ATTITUDE ROLL PITCH YAW",
+ f" CMD {num(0, 360, 1):>7} {num(0, 360, 1):>8} {num(0, 360, 1):>8}",
+ f" ACT {num(0, 360, 1):>7} {num(0, 360, 1):>8} {num(0, 360, 1):>8}",
+ f" ERR {num(-1, 1, 2):>7} {num(-1, 1, 2):>8} {num(-1, 1, 2):>8}", "",
+ f"GDC ALIGN {num(0, 1, 3)} IMU TEMP {num(125, 127, 1)}",
+ f"PIPA BIAS {num(-0.01, 0.01, 4)} DRIFT {num(-0.02, 0.02, 4)}", "",
+ "NEXT BURN TIG 008:02:14:30 DV 12.4"], 0.05, 0.8, 0.036)
+ p.render()
+
+
+def crt_power(name="crt_power", tint=GREEN):
+ p = Page(name, tint=tint)
+ header(p, "EPS BUS STATUS")
+ labels = ["MAIN A", "MAIN B", "BAT C", "FC 1", "FC 2", "FC 3", "AC 1", "AC 2"]
+ for i, l in enumerate(labels):
+ y = 0.78 - i * 0.082
+ v = R.uniform(0.55, 0.92)
+ p.text(l, 0.05, y, 0.036)
+ p.rect(0.33, y - 0.045, 1.05, y - 0.005, width=0.002, col=DIM)
+ p.fill(0.335, y - 0.04, 0.335 + 0.71 * v, y - 0.01, p.tint, 0.85 if i != 4 else 1.0)
+ p.text(f"{26 + v * 6:.1f} V", 1.08, y, 0.036, WHITE if i == 4 else None)
+ p.render()
+
+
+def crt_comms(name="crt_comms", tint=GREEN):
+ p = Page(name, tint=tint)
+ header(p, "NETWORK STATIONS")
+ p.text("STA STATUS AOS LOS EL", 0.05, 0.8, 0.036, DIM)
+ rows = [("MERLIN", "TRACK", "03:40:42", "03:48:57", "55.9"), ("OSPREY", "READY", "04:01:52", "04:10:31", "41.0"),
+ ("HARRIER", "STBY", "04:39:05", "04:46:12", "22.7"), ("KESTREL", "READY", "05:12:44", "05:21:30", "68.3"),
+ ("FALCON", "MAINT", "--:--:--", "--:--:--", " --"), ("CONDOR", "READY", "05:58:10", "06:04:02", "17.2")]
+ for i, r in enumerate(rows):
+ p.text(f"{r[0]:<9} {r[1]:<8} {r[2]} {r[3]} {r[4]}", 0.05, 0.72 - i * 0.07, 0.036, WHITE if i == 0 else None)
+ p.text("UPLINK 2287.5 MHZ DNLINK 2106.4 MHZ", 0.05, 0.24, 0.034, DIM)
+ p.text("VOICE LOOP FD NET 1 NET 2 CREW", 0.05, 0.17, 0.034, DIM)
+ p.render()
+
+
+def crt_orbit(name="crt_orbit", tint=GREEN):
+ p = Page(name, tint=tint)
+ header(p, "GROUND TRACK PREDICT")
+ x0, x1, y0, y1 = 0.06, 1.27, 0.08, 0.8
+ p.rect(x0, y0, x1, y1, width=0.003, col=DIM)
+ for i in range(1, 12):
+ p.poly([(x0 + (x1 - x0) * i / 12, y0), (x0 + (x1 - x0) * i / 12, y1)], 0.0012, DIM)
+ for i in range(1, 6):
+ p.poly([(x0, y0 + (y1 - y0) * i / 6), (x1, y0 + (y1 - y0) * i / 6)], 0.0012, DIM)
+ for k, ph in enumerate((0.0, 0.26, 0.52)):
+ pts = [(x0 + (x1 - x0) * t, (y0 + y1) / 2 + (y1 - y0) * 0.36 * math.sin(2 * math.pi * (t - ph))) for t in np.linspace(0, 1, 160)]
+ p.poly(pts, 0.005 if k == 1 else 0.003, None if k == 1 else DIM)
+ p.circle(x0 + (x1 - x0) * 0.47, (y0 + y1) / 2 + (y1 - y0) * 0.36 * math.sin(2 * math.pi * (0.47 - 0.26)), 0.018, col=WHITE, width=0.005)
+ p.render()
+
+
+def crt_amber(name="crt_amber_status"):
+ p = Page(name, tint=AMBER)
+ p.text("PROP RCS QUADS", 0.05, 0.96, 0.045)
+ p.text("PERSEUS 7", p.aspect - 0.05, 0.96, 0.045, align="RIGHT")
+ p.poly([(0.05, 0.88), (p.aspect - 0.05, 0.88)], 0.003, (0.45, 0.25, 0.04))
+ for q, (cx, cy) in enumerate(((0.35, 0.62), (0.98, 0.62), (0.35, 0.27), (0.98, 0.27))):
+ p.rect(cx - 0.27, cy - 0.15, cx + 0.27, cy + 0.17, width=0.003)
+ p.text(f"QUAD {'ABCD'[q]}", cx - 0.24, cy + 0.14, 0.036)
+ p.lines([f"HE {num(4000, 4200, 0)}", f"PRP {num(150, 180, 0)} PCT {num(60, 90, 0)}", f"PKG T {num(120, 140, 0)} F"],
+ cx - 0.24, cy + 0.07, 0.034)
+ p.render()
+
+
+def wall_left():
+ p = Page("wall_left", px=(1024, 1024), tint=GREEN)
+ p.text("PERSEUS 7", 0.06, 0.95, 0.075, WHITE, BOLD)
+ p.text("ORBITAL ELEMENTS", 0.06, 0.85, 0.045, DIM)
+ rows = [("REV", "112"), ("APOGEE", "312 KM"), ("PERIGEE", "298 KM"), ("INCLINATION", "51.6\u00b0"), ("PERIOD", "90.2 MIN"),
+ ("VELOCITY", "7.72 KM/S"), ("BETA ANGLE", "-14.8\u00b0"), ("NEXT AOS", "04:01:52"), ("NEXT LOS", "04:10:31")]
+ for i, (k, v) in enumerate(rows):
+ y = 0.75 - i * 0.075
+ p.text(k, 0.06, y, 0.048)
+ p.text(v, 0.94, y, 0.048, WHITE, align="RIGHT")
+ p.poly([(0.06, 0.07), (0.94, 0.07)], 0.004, DIM)
+ p.render(bloom=0.7, raster=False)
+
+
+def wall_right():
+ p = Page("wall_right", px=(1024, 1024), tint=GREEN)
+ p.text("AOS 03:40:42", 0.06, 0.95, 0.06, WHITE)
+ p.text("LOS 03:48:57", 0.06, 0.87, 0.06, WHITE)
+ p.text("MAX EL 55.9\u00b0", 0.06, 0.79, 0.06)
+ p.poly([(0.06, 0.71), (0.94, 0.71)], 0.004, DIM)
+ p.text("NETWORK", 0.06, 0.66, 0.045, DIM)
+ for i, (s, st) in enumerate((("KESTREL", "ONLINE"), ("OSPREY", "ONLINE"), ("HARRIER", "STANDBY"), ("MERLIN", "TRACK"),
+ ("FALCON", "MAINT"), ("CONDOR", "ONLINE"))):
+ y = 0.58 - i * 0.075
+ p.text(s, 0.06, y, 0.05)
+ p.text(st, 0.94, y, 0.05, AMBER if st in ("STANDBY", "MAINT") else WHITE, align="RIGHT")
+ p.render(bloom=0.7, raster=False)
+
+
+def wall_map():
+ p = Page("wall_map", px=(2048, 1024), tint=CYAN)
+ a = p.aspect
+ p.image(MAP, 0.0, 0.0, a, 1.0, k=0.75)
+ # three revolutions of ground track (sinusoid drifting west), the current one bright
+ for k, ph in enumerate((0.0, 0.25, 0.5)):
+ pts = [(a * t, 0.5 + 0.31 * math.sin(2 * math.pi * (t - ph))) for t in np.linspace(0, 1, 300)]
+ p.poly(pts, 0.006 if k == 1 else 0.0035, WHITE if k == 1 else (0.25, 0.75, 0.6), k=1.0)
+ t = 0.8
+ x, y = a * t, 0.5 + 0.31 * math.sin(2 * math.pi * (t - 0.25))
+ p.circle(x, y, 0.016, col=WHITE, width=0.007, k=1.6)
+ p.circle(x, y, 0.08, col=(0.4, 1, 0.8), width=0.003, n=96) # acquisition circle
+ for (sx, sy, n) in ((0.32, 0.67, "KESTREL"), (0.62, 0.35, "OSPREY"), (1.05, 0.72, "HARRIER"), (1.62, 0.3, "MERLIN"), (1.38, 0.62, "CONDOR")):
+ p.circle(sx, sy, 0.1, col=(0.2, 0.55, 0.45), width=0.0025, n=96)
+ p.poly([(sx - 0.01, sy), (sx + 0.01, sy)], 0.004, AMBER)
+ p.poly([(sx, sy - 0.01), (sx, sy + 0.01)], 0.004, AMBER)
+ p.text(n, sx + 0.02, sy - 0.02, 0.03, AMBER)
+ p.text("REV 112", 0.03, 0.06, 0.03, WHITE)
+ p.render(bloom=0.6, raster=False)
+
+
+ALL = {"crt_telemetry": crt_telemetry, "crt_trajectory": crt_trajectory, "crt_events": crt_events, "crt_guidance": crt_guidance,
+ "crt_power": crt_power, "crt_comms": crt_comms, "crt_orbit": crt_orbit, "crt_amber_status": crt_amber,
+ "wall_left": wall_left, "wall_right": wall_right, "wall_map": wall_map}
+for k, fn in ALL.items():
+ if not only or k in only:
+ fn()
diff --git a/scenes/mission-control-1970s/scripts/sheet.sh b/scenes/mission-control-1970s/scripts/sheet.sh
new file mode 100644
index 0000000..2ec52d1
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/sheet.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+# Review sheet: one row per prop = ref | H3.1 front | Meshy front | H3.1 back | Meshy back | H3.1 clay | Meshy clay.
+# scenes/mission-control-1970s/scripts/sheet.sh <out.png> <id> [id ...] (up to ~5 ids)
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+S=scenes/mission-control-1970s
+out=$1; shift
+img() { local f="$S/compare/$1/$2_$3.png"; [ -f "$f" ] || f="$S/compare/missing.png"; echo "$f"; }
+mkdir -p "$S/compare"
+[ -f $S/compare/missing.png ] || "$FF" -v error -f lavfi -i color=c=black:s=300x300 -frames:v 1 $S/compare/missing.png
+args=(); f=""; rows=""; n=0; r=0
+for id in "$@"; do
+ ref="refs/mission-control-1970s/props/${id}_0.png"
+ tiles=("$ref" "$(img tripo-h31 $id beauty)" "$(img meshy $id beauty)" "$(img tripo-h31 $id back)" "$(img meshy $id back)" "$(img tripo-h31 $id clay)" "$(img meshy $id clay)")
+ row=""
+ for t in "${tiles[@]}"; do args+=(-i "$t"); f+="[$n]scale=300:300[s$n];"; row+="[s$n]"; n=$((n+1)); done
+ f+="${row}hstack=7[r$r];"; rows+="[r$r]"; r=$((r+1))
+done
+if [ $r -gt 1 ]; then f+="${rows}vstack=$r"; else f="${f%;}"; f="${f%\[r0\]}"; fi
+"$FF" -v error -y "${args[@]}" -filter_complex "$f" "$out"
diff --git a/scenes/mission-control-1970s/scripts/shell.py b/scenes/mission-control-1970s/scripts/shell.py
new file mode 100644
index 0000000..e0b3530
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/shell.py
@@ -0,0 +1,212 @@
+"""Room shell: tiered floor, walls with the window band, back door, ceiling grid with troffers, wall-display frame,
+outside launch-pad backdrop. Object names here are referenced by lights, shots and the validator."""
+import math
+import os
+
+import bpy
+
+import layout as L
+import lib
+from lib import box, collection, plane
+
+TEX = os.path.join(lib.ROOT, "refs", "mission-control-1970s", "tex")
+M = {}
+
+
+def carpet(name, base=(0.075, 0.085, 0.1), tile=0.6):
+ """Low-pile carpet tiles: fibre noise, slight per-tile tone shift, traffic wear in the lanes."""
+ m, nt = lib._new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ fib = lib._noise(nt, 900, 2, tc.outputs["Object"])
+ ch = nt.nodes.new("ShaderNodeTexChecker")
+ ch.inputs["Scale"].default_value = 1 / tile
+ ch.inputs["Color1"].default_value = (1, 1, 1, 1)
+ ch.inputs["Color2"].default_value = (0.86, 0.86, 0.86, 1)
+ nt.links.new(tc.outputs["Object"], ch.inputs["Vector"])
+ wear = lib._noise(nt, 0.7, 6, tc.outputs["Object"])
+ wr = lib._ramp(nt, wear.outputs["Fac"], [(0.35, (0.75, 0.75, 0.75)), (0.7, (1.15, 1.12, 1.08))])
+ col = lib._mix(nt, 1.0, base, ch.outputs["Color"], "MULTIPLY")
+ col = lib._mix(nt, 1.0, col, wr.outputs["Color"], "MULTIPLY")
+ col = lib._mix(nt, 0.25, col, fib.outputs["Color"], "OVERLAY")
+ nt.links.new(col, b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.95
+ b.inputs["Sheen Weight"].default_value = 0.4
+ nt.links.new(lib._bump(nt, fib.outputs["Fac"], 0.35, 0.001), b.inputs["Normal"])
+ return m
+
+
+def ceiling_tiles(name):
+ """Acoustic 2x4 ft lay-in tiles in a white T-bar grid, pinhole fissure speckle, nicotine yellowing."""
+ m, nt = lib._new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ br = nt.nodes.new("ShaderNodeTexBrick")
+ br.offset = 0.0
+ br.squash = 1.0
+ br.inputs["Scale"].default_value = 1.0
+ br.inputs["Brick Width"].default_value = 1.2
+ br.inputs["Row Height"].default_value = 0.6
+ br.inputs["Mortar Size"].default_value = 0.012
+ br.inputs["Color1"].default_value = (0.62, 0.6, 0.53, 1)
+ br.inputs["Color2"].default_value = (0.58, 0.56, 0.49, 1)
+ br.inputs["Mortar"].default_value = (0.7, 0.7, 0.68, 1)
+ nt.links.new(tc.outputs["Object"], br.inputs["Vector"])
+ pin = lib._noise(nt, 300, 2, tc.outputs["Object"])
+ pr = lib._ramp(nt, pin.outputs["Fac"], [(0.62, (1, 1, 1)), (0.7, (0.55, 0.55, 0.55))])
+ stain = lib._noise(nt, 0.6, 6, tc.outputs["Object"])
+ sr = lib._ramp(nt, stain.outputs["Fac"], [(0.5, (1, 1, 1)), (0.75, (0.72, 0.62, 0.42))])
+ col = lib._mix(nt, 1.0, br.outputs["Color"], pr.outputs["Color"], "MULTIPLY")
+ col = lib._mix(nt, 1.0, col, sr.outputs["Color"], "MULTIPLY")
+ nt.links.new(col, b.inputs["Base Color"])
+ b.inputs["Roughness"].default_value = 0.92
+ nt.links.new(lib._bump(nt, br.outputs["Fac"], 0.4, 0.004), b.inputs["Normal"])
+ return m
+
+
+def troffer_lens(name, on):
+ """Prismatic acrylic diffuser: a fine square-pyramid bump; emissive when on (strength set by lights.py)."""
+ m, nt = lib._new(name)
+ if nt is None:
+ return m
+ b = nt.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (0.78, 0.8, 0.78, 1)
+ b.inputs["Roughness"].default_value = 0.35
+ b.inputs["Transmission Weight"].default_value = 0.0
+ tc = nt.nodes.new("ShaderNodeTexCoord")
+ ch = nt.nodes.new("ShaderNodeTexWave")
+ ch.inputs["Scale"].default_value = 120
+ nt.links.new(tc.outputs["Object"], ch.inputs["Vector"])
+ nt.links.new(lib._bump(nt, ch.outputs["Fac"], 0.2, 0.001), b.inputs["Normal"])
+ if on:
+ b.inputs["Emission Color"].default_value = (0.92, 0.97, 1.0, 1)
+ b.inputs["Emission Strength"].default_value = 6.0
+ return m
+
+
+def materials():
+ M["carpet"] = carpet("carpet_tiles")
+ M["vinyl"] = lib.floor_tiles("vinyl_tiles", tile=0.3, a=(0.42, 0.41, 0.37), b2=(0.36, 0.35, 0.32))
+ M["wall"] = lib.wall_paint("wall_paint", base=(0.5, 0.49, 0.44))
+ M["wall_dark"] = lib.grimy("display_wall", (0.035, 0.038, 0.04), (0.02, 0.02, 0.02), rough=(0.5, 0.8), amount=0.2)
+ M["acoustic"] = lib.grimy("acoustic_panel", (0.23, 0.2, 0.17), (0.12, 0.1, 0.08), rough=(0.85, 0.95), amount=0.25, scale=6, bump=0.3)
+ M["ceiling"] = ceiling_tiles("ceiling_tiles")
+ M["alu"] = lib.grimy("aluminium", (0.55, 0.56, 0.57), (0.22, 0.21, 0.19), rough=(0.3, 0.5), metal=1.0, amount=0.2, bump=0.05)
+ M["tbar"] = lib.principled("tbar_white", (0.72, 0.72, 0.7), 0.4)
+ M["glass"] = lib.principled("window_glass", (0.92, 0.95, 0.95), 0.015, **{"Transmission Weight": 1.0, "IOR": 1.5})
+ M["door"] = lib.grimy("door_paint", (0.3, 0.32, 0.3), (0.12, 0.11, 0.1), rough=(0.4, 0.7), amount=0.3)
+ M["base"] = lib.principled("baseboard", (0.04, 0.04, 0.04), 0.6)
+ M["nosing"] = lib.grimy("stair_nosing", (0.45, 0.45, 0.43), (0.12, 0.11, 0.1), rough=(0.35, 0.6), metal=1.0, amount=0.35)
+ M["bezel"] = lib.principled("display_bezel", (0.025, 0.025, 0.027), 0.45)
+ M["blind"] = lib.grimy("blind_slats", (0.6, 0.58, 0.52), (0.3, 0.27, 0.2), rough=(0.4, 0.6), metal=0.2, amount=0.25)
+ M["tr_off"] = troffer_lens("troffer_off", False)
+ M["tr_on"] = troffer_lens("troffer_on", True)
+ M["tr_dim"] = troffer_lens("troffer_dim", True)
+ M["tr_dim"].node_tree.nodes["Principled BSDF"].inputs["Emission Strength"].default_value = 1.5
+ M["tr_frame"] = lib.principled("troffer_frame", (0.7, 0.7, 0.68), 0.35, Metallic=0.3)
+ M["black"] = lib.principled("sign_black", (0.015, 0.015, 0.015), 0.4)
+ M["sign_text"] = lib.principled("sign_text", (0.85, 0.85, 0.8), 0.5)
+
+
+TROFFERS_ON = {(1, 2): "tr_on", (2, 4): "tr_on", (3, 0): "tr_on", (3, 2): "tr_dim", (0, 3): "tr_on"} # (col, row) -> state
+
+
+def build():
+ materials()
+ C = collection("shell")
+ W, D, H, T = L.W, L.D, L.H, L.T
+ # floor tiers (tier slabs are separate objects so the validator / drops see the right top)
+ box("floor_t0", (-T, -T, -0.1), (W + T, D + T, 0.0), M["carpet"], C, bevel=0)
+ box("floor_t1", (0, 4.5, 0.0), (W, 7.5, 0.35), M["carpet"], C, bevel=0)
+ box("floor_t2", (0, 0.0, 0.0), (W, 4.5, 0.7), M["carpet"], C, bevel=0)
+ box("nosing_t1", (0, 7.47, 0.33), (W, 7.52, 0.352), M["nosing"], C, bevel=0.003)
+ box("nosing_t2", (0, 4.47, 0.68), (W, 4.52, 0.702), M["nosing"], C, bevel=0.003)
+ for side, (x0, x1) in (("l", L.AISLE_L), ("r", L.AISLE_R)): # two 175 mm steps at each riser in each aisle
+ box(f"step_t1_{side}", (x0, 7.5, 0.0), (x1, 7.8, 0.175), M["carpet"], C, bevel=0.004)
+ box(f"step_t2_{side}", (x0, 4.5, 0.35), (x1, 4.8, 0.525), M["carpet"], C, bevel=0.004)
+ box(f"stepnose_t1_{side}", (x0, 7.77, 0.16), (x1, 7.81, 0.177), M["nosing"], C, bevel=0.002)
+ box(f"stepnose_t2_{side}", (x0, 4.77, 0.51), (x1, 4.81, 0.527), M["nosing"], C, bevel=0.002)
+ box("ceiling", (-T, -T, H), (W + T, D + T, H + 0.05), M["ceiling"], C, bevel=0)
+
+ # left wall with the window band
+ box("wall_left_low", (-T, 0, -0.1), (0, D, L.WIN_Z0), M["wall"], C, bevel=0)
+ box("wall_left_high", (-T, 0, L.WIN_Z1), (0, D, H), M["wall"], C, bevel=0)
+ box("wall_left_a", (-T, 0, L.WIN_Z0), (0, L.WIN_Y0, L.WIN_Z1), M["wall"], C, bevel=0)
+ box("wall_left_b", (-T, L.WIN_Y1, L.WIN_Z0), (0, D, L.WIN_Z1), M["wall"], C, bevel=0)
+ box("sill", (-T, L.WIN_Y0, L.WIN_Z0 - 0.03), (0.08, L.WIN_Y1, L.WIN_Z0), M["alu"], C, bevel=0.004)
+ n = 5
+ step = (L.WIN_Y1 - L.WIN_Y0) / n
+ for i in range(n + 1):
+ y = L.WIN_Y0 + i * step
+ box(f"mullion_{i}", (-0.12, y - 0.04, L.WIN_Z0), (-0.04, y + 0.04, L.WIN_Z1), M["alu"], C, bevel=0.004)
+ box("transom", (-0.12, L.WIN_Y0, L.WIN_Z1 - 0.06), (-0.04, L.WIN_Y1, L.WIN_Z1), M["alu"], C, bevel=0.004)
+ box("window_glass", (-0.085, L.WIN_Y0, L.WIN_Z0), (-0.075, L.WIN_Y1, L.WIN_Z1), M["glass"], C, bevel=0.002)
+ # venetian blinds: half the panes have blinds partly down (slats tilted), the rest raised in a stack
+ for i in range(n):
+ y0, y1 = L.WIN_Y0 + i * step + 0.06, L.WIN_Y0 + (i + 1) * step - 0.06
+ drop = [0.55, 0.0, 1.0, 0.0, 0.35][i]
+ box(f"blind_head_{i}", (0.0, y0, L.WIN_Z1 - 0.1), (0.05, y1, L.WIN_Z1 - 0.04), M["blind"], C, bevel=0.003)
+ nsl = int(drop / 0.045)
+ for k in range(nsl):
+ z = L.WIN_Z1 - 0.12 - k * 0.045
+ s = box(f"blind_{i}_{k}", (-0.012, y0, z - 0.0005), (0.012, y1, z + 0.0005), M["blind"], C, bevel=0)
+ s.rotation_euler = (0, math.radians(55), 0)
+ stack = 0.08 if nsl else 0.14
+ box(f"blind_stack_{i}", (-0.01, y0, L.WIN_Z1 - 0.1 - stack - nsl * 0.045), (0.03, y1, L.WIN_Z1 - 0.1 - nsl * 0.045), M["blind"], C, bevel=0.002)
+
+ # right and back walls; front wall is the dark display wall
+ box("wall_right", (W, 0, -0.1), (W + T, D, H), M["wall"], C, bevel=0)
+ box("wall_back_a", (-T, -T, -0.1), (L.DOOR_X0, 0, H), M["wall"], C, bevel=0)
+ box("wall_back_b", (L.DOOR_X1, -T, -0.1), (W + T, 0, H), M["wall"], C, bevel=0)
+ box("wall_back_c", (L.DOOR_X0, -T, L.DOOR_Z1), (L.DOOR_X1, 0, H), M["wall"], C, bevel=0)
+ box("wall_front", (-T, D, -0.1), (W + T, D + T, H), M["wall_dark"], C, bevel=0)
+ # acoustic panel band on the right wall and the back wall (period fabric panels)
+ box("acoustic_right", (W - 0.03, 0.4, 1.0), (W, D - 0.4, 2.9), M["acoustic"], C, bevel=0.005)
+ box("acoustic_back_a", (0.3, 0, 1.4), (L.DOOR_X0 - 0.4, 0.03, 2.9), M["acoustic"], C, bevel=0.005)
+ box("acoustic_back_b", (L.DOOR_X1 + 0.4, 0, 1.4), (W - 0.3, 0.03, 2.9), M["acoustic"], C, bevel=0.005)
+ for nm, lo, hi in (("base_right", (W - 0.012, 0, 0), (W, D, 0.1)), ("base_front", (0, D - 0.012, 0), (W, D, 0.1))):
+ box(nm, lo, hi, M["base"], C, bevel=0)
+ # back door: two leaves with small wired-glass windows, push bars, exit sign above
+ zf = L.TIERS[2][0]
+ for i, (x0, x1) in enumerate(((L.DOOR_X0, 5.5), (5.5, L.DOOR_X1))):
+ box(f"door_leaf_{i}", (x0 + 0.005, -0.06, zf), (x1 - 0.005, -0.015, L.DOOR_Z1 - 0.01), M["door"], C, bevel=0.004)
+ box(f"door_bar_{i}", (x0 + 0.08, -0.012, zf + 1.0), (x1 - 0.08, 0.02, zf + 1.04), M["alu"], C, bevel=0.003)
+ box(f"door_window_{i}", (x0 + 0.17, -0.015, zf + 1.35), (x1 - 0.17, -0.01, zf + 1.85), M["glass"], C, bevel=0.002)
+ box("door_frame_top", (L.DOOR_X0 - 0.05, -0.02, L.DOOR_Z1 - 0.01), (L.DOOR_X1 + 0.05, 0.02, L.DOOR_Z1 + 0.05), M["alu"], C, bevel=0.003)
+ box("exit_sign_box", (5.3, 0.0, L.DOOR_Z1 + 0.12), (5.7, 0.09, L.DOOR_Z1 + 0.32), M["black"], C, bevel=0.004)
+
+ # ceiling grid troffers: 4 columns x 5 rows, a few on
+ CT = collection("ceiling_fixtures")
+ for ci, x in enumerate((1.8, 4.2, 6.6, 9.0)):
+ for ri, y in enumerate((1.6, 4.1, 6.6, 9.1, 11.6)):
+ st = TROFFERS_ON.get((ci, ri), "tr_off")
+ box(f"troffer_{ci}_{ri}", (x - 0.31, y - 0.61, H - 0.035), (x + 0.31, y + 0.61, H), M["tr_frame"], CT, bevel=0.003)
+ lens = box(f"troffer_lens_{ci}_{ri}", (x - 0.28, y - 0.58, H - 0.04), (x + 0.28, y + 0.58, H - 0.034), M[st], CT, bevel=0)
+ lens["state"] = st
+ # air diffusers (square) between the troffers
+ for x, y in ((3.0, 2.85), (7.8, 2.85), (3.0, 7.85), (7.8, 7.85), (5.4, 10.4)):
+ box(f"diffuser_{x}_{y}", (x - 0.3, y - 0.3, H - 0.02), (x + 0.3, y + 0.3, H), M["tbar"], CT, bevel=0.004)
+
+ # wall display: bezel box + three screens (materials replaced by fixscreens.py; emissive)
+ CD = collection("display")
+ box("display_bezel", (1.15, D - 0.16, L.DISP_Z0 - 0.15), (10.35, D, L.DISP_Z1 + 0.12), M["bezel"], CD, bevel=0.01)
+ for name, x0, x1 in L.DISP_PANELS:
+ p = plane(f"disp_{name}", ((x0 + x1) / 2, D - 0.165, (L.DISP_Z0 + L.DISP_Z1) / 2), x1 - x0, L.DISP_Z1 - L.DISP_Z0, "-Y", M["black"], CD)
+ p["screen"] = name
+ box("display_ledge", (1.1, D - 0.5, 0.0), (10.4, D - 0.16, 0.85), M["bezel"], CD, bevel=0.01)
+
+ # outside: night launch-pad backdrop far beyond the windows, a dark ground plane below the sill line
+ CX = collection("outside")
+ lp = os.path.join(TEX, "launch_pad_0.png")
+ if os.path.exists(lp):
+ mat = lib.image_mat("backdrop_launchpad", lp, rough=1.0, emission=2.2, extend="EXTEND")
+ # horizon (52 % up the image) near eye height, the rocket (68 % across) out past the middle windows
+ b = plane("backdrop", (-45, -3.4, 1.63), 72, 40.5, "X", mat, CX)
+ lib.set_uv_rect(b, -1, -1, 2, 2) # image in the middle third; EXTEND runs sky and marsh out past the window edges
+ b.visible_shadow = False
+ g = box("outside_ground", (-80, -40, -6.0), (-0.25, 50, -5.9), lib.principled("ground_dark", (0.01, 0.012, 0.012), 0.9), CX, bevel=0)
+ g.visible_shadow = False
diff --git a/scenes/mission-control-1970s/scripts/shoot.sh b/scenes/mission-control-1970s/scripts/shoot.sh
new file mode 100644
index 0000000..6896c1d
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/shoot.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# camrig through the GPU queue with OptiX enabled. scenes/mission-control-1970s/scripts/shoot.sh [shoot.py args...]
+cd "$(dirname "$0")/../../.."
+. pipeline/env.sh
+bash pipeline/gpu_run.sh "$B" -b ${BLEND:-scenes/mission-control-1970s/mc.blend} \
+ --python scenes/mission-control-1970s/scripts/gpu_prefs.py ${NOCURL:+--python scenes/mission-control-1970s/scripts/nocurl.py} --python camera/shoot.py -- \
+ --shots $ROOT_ABS/scenes/mission-control-1970s/shots.json \
+ --out $ROOT_ABS/scenes/mission-control-1970s/out/shots "$@"
diff --git a/scenes/mission-control-1970s/scripts/validate.py b/scenes/mission-control-1970s/scripts/validate.py
new file mode 100644
index 0000000..051080e
--- /dev/null
+++ b/scenes/mission-control-1970s/scripts/validate.py
@@ -0,0 +1,241 @@
+"""Placement validator for the dressed mission-control room.
+
+blender -b scenes/mission-control-1970s/mc.blend --python scenes/mission-control-1970s/scripts/validate.py
+Also imported by build.py (`validate.check(resolve=True)` after dressing: clashing / floating small props are
+spiral-searched to a clear spot on the same support).
+Flags: FLOAT (> 1 cm above the support under it; the ray starts above the support's top, with the prop moved away),
+GROUND (contact points, i.e. the prop's lowest vertices, > 2 mm above the nearest surface straight below, skipping the
+prop itself and volumes; resolve lowers the prop onto it, see settle()), CLIP (two props interpenetrating: BVH triangle
+overlap), FURNITURE (a prop's mesh, lifted 3 mm, intersects the shell
+or direct-modelled furniture), OUT (outside the room), SCALE (off the manifest size by > 25 %).
+Last line: "VALIDATE n issues over m props".
+"""
+import json
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Matrix, Vector
+from mathutils.bvhtree import BVHTree
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import layout as L # noqa: E402
+
+ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+SCN = os.path.join(ROOT, "scenes", "mission-control-1970s")
+FURN_COLLS = ("shell", "furniture", "display") # placards sit on console tops on purpose
+SMALL = 1.1 # props whose largest dimension is under this (desk clutter, chairs) may be moved by resolve
+
+
+def world_bb(o):
+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]
+ return (Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))),
+ Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts))))
+
+
+def tree(o, lift=0.0):
+ dg = bpy.context.evaluated_depsgraph_get()
+ eo = o.evaluated_get(dg)
+ me = eo.to_mesh()
+ me.transform(Matrix.Translation((0, 0, lift)) @ o.matrix_world)
+ t = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])
+ eo.to_mesh_clear()
+ return t
+
+
+def overlap(a, b):
+ return any(a[1][k] < b[0][k] or b[1][k] < a[0][k] for k in range(3)) is False
+
+
+def float_gap(o):
+ sc = bpy.context.scene
+ lo, hi = world_bb(o)
+ z0 = o.location.z
+ o.location.z -= 100
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ best = None
+ for fx, fy in ((0.5, 0.5), (0.3, 0.3), (0.7, 0.3), (0.3, 0.7), (0.7, 0.7)):
+ p = Vector((lo.x + (hi.x - lo.x) * fx, lo.y + (hi.y - lo.y) * fy, lo.z + 0.02))
+ hit, loc, n, i, ob, m = sc.ray_cast(dg, p, Vector((0, 0, -1)))
+ if hit:
+ g = lo.z - loc.z
+ best = g if best is None else min(best, g)
+ o.location.z = z0
+ bpy.context.view_layer.update()
+ return best
+
+
+GROUND_TOL = 0.002
+NOT_SURFACE = ("haze", "smoke_curl", "backdrop")
+
+
+def contact_gaps(props):
+ """Same measure as pipeline/grounding.py: rays straight down from each prop's lowest vertices (bottom 1.5 cm or 3 %
+ of its height), against every other visible mesh. Returns {name: (gap, support name)}, gap None = nothing below."""
+ dg = bpy.context.evaluated_depsgraph_get()
+ surf = {}
+ verts = {}
+ names = {o.name for o in props}
+ for o in bpy.context.scene.objects:
+ if o.type != "MESH" or not o.visible_get() or o.hide_render or o.name.startswith(NOT_SURFACE):
+ continue
+ eo = o.evaluated_get(dg)
+ me = eo.to_mesh()
+ vs = [o.matrix_world @ v.co for v in me.vertices]
+ if len(me.polygons):
+ surf[o.name] = BVHTree.FromPolygons(vs, [p.vertices[:] for p in me.polygons])
+ if o.name in names:
+ verts[o.name] = vs
+ eo.to_mesh_clear()
+ out = {}
+ for name, vs in verts.items():
+ if len(vs) < 4:
+ continue
+ zmin = min(v.z for v in vs)
+ band = max(0.015, 0.03 * (max(v.z for v in vs) - zmin))
+ feet = [v for v in vs if v.z <= zmin + band]
+ best = None
+ for f in feet[:: max(1, len(feet) // 40)]:
+ p = f + Vector((0, 0, 0.002))
+ for sname, t in surf.items():
+ if sname == name:
+ continue
+ hit = t.ray_cast(p, Vector((0, 0, -1)), 50.0)
+ if hit[0] is not None and (best is None or hit[3] - 0.002 < best[0]):
+ best = (hit[3] - 0.002, sname)
+ out[name] = best or (None, None)
+ return out
+
+
+def settle(props, verbose=True):
+ """Lower every floor/desk prop whose nearest contact point is 2 mm - 5 cm above a surface so that point touches.
+ (Drops take the *highest* hit under the base, so a prop whose feet overhang the desk's 2 mm edge lip hangs ~2.5 mm
+ over the laminate.) Wall-hung props are skipped. Repeated so stacks settle after what they sit on. Direct-modelled
+ pieces tagged "settle" (placards) go too, and anything tagged "follows" moves with the object it names."""
+ sc = bpy.context.scene
+ props = props + [o for o in sc.objects if o.get("settle")]
+ for _ in range(3):
+ moved = 0
+ for name, (g, under) in contact_gaps(props).items():
+ o = bpy.context.scene.objects[name]
+ if o.get("wall") or g is None or not (GROUND_TOL < g <= 0.05):
+ continue
+ o.location.z -= g
+ for f in sc.objects:
+ if f.get("follows") == name:
+ f.location.z -= g
+ moved += 1
+ if verbose:
+ print(f"SETTLED {name} -{g * 100:.1f} cm onto {under}")
+ bpy.context.view_layer.update()
+ if not moved:
+ break
+
+
+def check(resolve=False, verbose=True):
+ sc = bpy.context.scene
+ man = {a["id"]: a for a in json.load(open(os.path.join(SCN, "assets.json")))["generate"]}
+ props = [o for o in sc.objects if o.get("placed") and o.visible_get() and o.type == "MESH"]
+ furn = [o for o in sc.objects if o.type == "MESH" and o.visible_get() and not o.get("placed") and any(c.name in FURN_COLLS for c in o.users_collection)
+ and not o.name.startswith(("window_glass", "door_window", "disp_", "floor_t0"))]
+ issues = []
+ moved = []
+ ftrees = {f.name: (tree(f), world_bb(f)) for f in furn}
+ for _round in range(2 if resolve else 1):
+ issues.clear()
+ bpy.context.view_layer.update()
+ boxes = {o.name: world_bb(o) for o in props}
+ trees = {o.name: tree(o) for o in props}
+ bad = set()
+ for o in props:
+ lo, hi = boxes[o.name]
+ if lo.x < -0.02 or lo.y < -0.02 or hi.x > L.W + 0.02 or hi.y > L.D + 0.02 or hi.z > L.H + 0.01:
+ issues.append(f"OUT {o.name}")
+ if not o.get("wall"):
+ g = float_gap(o)
+ if g is None or g > 0.01:
+ issues.append(f"FLOAT {o.name} {('%.1f cm' % (g * 100)) if g is not None else 'no support'}")
+ bad.add(o.name)
+ a = man.get(o.get("prop_id"))
+ if a:
+ d = o.dimensions
+ if "dims" in a:
+ got, want = d.z, a["dims"][2]
+ elif "h" in a:
+ got, want = d.z, a["h"]
+ else:
+ got, want = max(d), a["max"]
+ if abs(got / want - 1) > 0.25:
+ issues.append(f"SCALE {o.name} {got:.2f} vs {want}")
+ names = [o.name for o in props]
+ for i, a_ in enumerate(names):
+ for b_ in names[i + 1:]:
+ if not overlap(boxes[a_], boxes[b_]):
+ continue
+ n = len(trees[a_].overlap(trees[b_]))
+ if n > 30:
+ issues.append(f"CLIP {a_} x {b_} ({n} tri pairs)")
+ sa, sb = max(sc.objects[a_].dimensions), max(sc.objects[b_].dimensions)
+ bad.add(a_ if sa < sb else b_)
+ for o in props:
+ t = tree(o, 0.003)
+ for fname, (ft, fb) in ftrees.items():
+ if not overlap(boxes[o.name], fb):
+ continue
+ n = len(t.overlap(ft))
+ if n > 20:
+ issues.append(f"FURNITURE {o.name} x {fname} ({n} tri pairs)")
+ bad.add(o.name)
+ if resolve and _round == 1:
+ settle(props, verbose)
+ if not resolve or _round == 1:
+ break
+ for name in sorted(bad):
+ o = sc.objects[name]
+ if max(o.dimensions) < SMALL and not o.get("wall"):
+ if spiral(o, props, trees):
+ moved.append(name)
+ trees[name] = tree(o)
+ for name, (g, under) in contact_gaps([o for o in props if not o.get("wall")] + [o for o in sc.objects if o.get("settle")]).items():
+ if g is None:
+ issues.append(f"GROUND {name} nothing below")
+ elif g > GROUND_TOL:
+ issues.append(f"GROUND {name} {g * 100:.1f} cm above {under}")
+ if verbose:
+ for s in issues:
+ print(s)
+ if moved:
+ print("RESOLVED (moved)", ", ".join(moved))
+ print(f"VALIDATE {len(issues)} issues over {len(props)} props", flush=True)
+ return issues
+
+
+def spiral(o, props, trees, rmax=0.5):
+ """Move o around its spot in a growing spiral, dropping it at each candidate until it sits flat (< 1 cm float)
+ and clashes with nothing. Returns True when it found a spot."""
+ import dress # noqa: E402 (drop helper)
+ x0, y0, z0 = o.location
+ lo, hi = world_bb(o)
+ start = lo.z + 0.25
+ for k in range(1, 60):
+ r = rmax * k / 60
+ a = k * 2.4
+ o.location = (x0 + r * math.cos(a), y0 + r * math.sin(a), z0)
+ dress.drop(o, start)
+ bpy.context.view_layer.update()
+ g = float_gap(o)
+ if g is None or g > 0.01:
+ continue
+ t = tree(o)
+ ob = world_bb(o)
+ if any(p is not o and overlap(ob, world_bb(p)) and len(t.overlap(trees[p.name])) > 30 for p in props):
+ continue
+ return True
+ o.location = (x0, y0, z0)
+ return False
+
+
+if __name__ == "__main__":
+ check()
diff --git a/scenes/mission-control-1970s/shots.json b/scenes/mission-control-1970s/shots.json
new file mode 100644
index 0000000..bea9e3d
--- /dev/null
+++ b/scenes/mission-control-1970s/shots.json
@@ -0,0 +1,404 @@
+{
+ "defaults": {
+ "fps": 24,
+ "res": [
+ 1920,
+ 1080
+ ],
+ "aspect": "2.39",
+ "samples": 48,
+ "shutter": 180,
+ "sensor": "s35",
+ "fstop": 2.8,
+ "ease": "inout",
+ "handheld": 0
+ },
+ "shots": [
+ {
+ "name": "orbital_push",
+ "move": "push_in",
+ "frames": 120,
+ "handheld": 0.15,
+ "fstop": 2,
+ "blades": 7,
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 5.2,
+ 8.15,
+ 1.48
+ ],
+ "aim": [
+ 5.42,
+ 9.55,
+ 0.82
+ ],
+ "lens": 32
+ },
+ {
+ "t": 1,
+ "pos": [
+ 5.45,
+ 8.95,
+ 1.27
+ ],
+ "aim": [
+ 5.54,
+ 10.05,
+ 1.06
+ ]
+ }
+ ],
+ "focus": {
+ "mode": "rack",
+ "keys": [
+ {
+ "t": 0,
+ "obj": "hero_ashtray"
+ },
+ {
+ "t": 0.35,
+ "obj": "hero_ashtray"
+ },
+ {
+ "t": 0.8,
+ "pos": [
+ 5.53,
+ 9.98,
+ 1.07
+ ]
+ }
+ ]
+ },
+ "lens_fx": {
+ "distortion": 0.008,
+ "dispersion": 0.006,
+ "glare": "fog"
+ }
+ },
+ {
+ "name": "fd_wide",
+ "move": "dolly",
+ "frames": 144,
+ "handheld": 0.12,
+ "fstop": 4,
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 6.25,
+ 1.45,
+ 2.35
+ ],
+ "aim": [
+ 5.85,
+ 12.9,
+ 1.95
+ ],
+ "lens": 24
+ },
+ {
+ "t": 1,
+ "pos": [
+ 5.95,
+ 2.15,
+ 2.27
+ ],
+ "aim": [
+ 5.75,
+ 12.9,
+ 2.05
+ ]
+ }
+ ],
+ "focus": {
+ "mode": "point",
+ "pos": [
+ 5.75,
+ 12.85,
+ 2.1
+ ]
+ },
+ "lens_fx": {
+ "distortion": 0.012,
+ "dispersion": 0.006,
+ "glare": "fog"
+ }
+ },
+ {
+ "name": "display_rack",
+ "move": "static",
+ "frames": 120,
+ "handheld": 0.3,
+ "breathing": 0.4,
+ "fstop": 2,
+ "blades": 7,
+ "ratio": 1.3,
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 9,
+ 6,
+ 2.05
+ ],
+ "aim": [
+ 5.85,
+ 12.85,
+ 1.6
+ ],
+ "lens": 50
+ }
+ ],
+ "focus": {
+ "mode": "rack",
+ "keys": [
+ {
+ "t": 0,
+ "obj": "placard_A_telemetry"
+ },
+ {
+ "t": 0.4,
+ "obj": "placard_A_telemetry"
+ },
+ {
+ "t": 0.75,
+ "pos": [
+ 5.2,
+ 12.84,
+ 2
+ ]
+ }
+ ]
+ },
+ "lens_fx": {
+ "distortion": 0.004,
+ "dispersion": 0.008,
+ "glare": "fog"
+ }
+ },
+ {
+ "name": "printer_crane",
+ "move": "crane",
+ "frames": 120,
+ "handheld": 0.1,
+ "fstop": 2.8,
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 8.9,
+ 4.1,
+ 2.95
+ ],
+ "aim": [
+ 10.5,
+ 2.2,
+ 1.1
+ ],
+ "lens": 28
+ },
+ {
+ "t": 1,
+ "pos": [
+ 9.15,
+ 3.7,
+ 1.75
+ ],
+ "aim": [
+ 10.4,
+ 2.4,
+ 1
+ ]
+ }
+ ],
+ "focus": {
+ "mode": "track",
+ "obj": "teleprinter"
+ },
+ "lens_fx": {
+ "distortion": 0.01,
+ "dispersion": 0.006,
+ "glare": "fog"
+ }
+ },
+ {
+ "name": "walk_windows",
+ "move": "path",
+ "frames": 480,
+ "fstop": 2.8,
+ "handheld": {
+ "profile": "walk"
+ },
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 4.6,
+ 1,
+ 2.3
+ ],
+ "aim": [
+ 3,
+ 8,
+ 1.7
+ ],
+ "lens": 24
+ },
+ {
+ "t": 0.18,
+ "pos": [
+ 1.3,
+ 1.5,
+ 2.3
+ ],
+ "aim": [
+ 1,
+ 8,
+ 1.9
+ ]
+ },
+ {
+ "t": 0.38,
+ "pos": [
+ 1,
+ 4,
+ 2.28
+ ],
+ "aim": [
+ 3.6,
+ 9,
+ 1.4
+ ]
+ },
+ {
+ "t": 0.58,
+ "pos": [
+ 1.05,
+ 6.6,
+ 1.95
+ ],
+ "aim": [
+ 4.2,
+ 8.6,
+ 1.3
+ ]
+ },
+ {
+ "t": 0.78,
+ "pos": [
+ 1.1,
+ 9,
+ 1.62
+ ],
+ "aim": [
+ 4,
+ 12.9,
+ 2
+ ]
+ },
+ {
+ "t": 1,
+ "pos": [
+ 1.4,
+ 11.5,
+ 1.6
+ ],
+ "aim": [
+ 5.8,
+ 12.9,
+ 2.2
+ ]
+ }
+ ],
+ "lens_fx": {
+ "distortion": 0.012,
+ "dispersion": 0.006,
+ "glare": "fog"
+ }
+ },
+ {
+ "name": "walk_rows",
+ "move": "path",
+ "frames": 408,
+ "fstop": 2.8,
+ "handheld": {
+ "profile": "walk"
+ },
+ "keys": [
+ {
+ "t": 0,
+ "pos": [
+ 9.6,
+ 8.3,
+ 1.62
+ ],
+ "aim": [
+ 6,
+ 10.2,
+ 1.2
+ ],
+ "lens": 24
+ },
+ {
+ "t": 0.25,
+ "pos": [
+ 7.6,
+ 8.15,
+ 1.62
+ ],
+ "aim": [
+ 6.8,
+ 10.1,
+ 1.1
+ ]
+ },
+ {
+ "t": 0.5,
+ "pos": [
+ 5.6,
+ 8.2,
+ 1.6
+ ],
+ "aim": [
+ 5.5,
+ 10,
+ 1.05
+ ]
+ },
+ {
+ "t": 0.75,
+ "pos": [
+ 3.8,
+ 8.2,
+ 1.62
+ ],
+ "aim": [
+ 4.8,
+ 12.9,
+ 2.1
+ ]
+ },
+ {
+ "t": 1,
+ "pos": [
+ 2.4,
+ 8.6,
+ 1.65
+ ],
+ "aim": [
+ -6,
+ 7.25,
+ 2.25
+ ]
+ }
+ ],
+ "lens_fx": {
+ "distortion": 0.012,
+ "dispersion": 0.006,
+ "glare": "fog"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/scenes/tokyo-electronics-repair/scripts/compare.py b/scenes/tokyo-electronics-repair/scripts/compare.py
index b2bd435..358791f 100644
--- a/scenes/tokyo-electronics-repair/scripts/compare.py
+++ b/scenes/tokyo-electronics-repair/scripts/compare.py
@@ -14,7 +14,13 @@ from mathutils import Vector
ARGS = sys.argv[sys.argv.index("--") + 1:]
ROOT, OUT = map(os.path.abspath, ARGS[:2])
IDS = set(ARGS[2].split(",")) if len(ARGS) > 2 else None
-HDRI = bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")
+# Blender's bundled studio HDRI. bpy.utils.system_resource() returns "" for this in 5.0.1, so build the path from the
+# version folder that sits next to the binary (Contents/Resources on macOS).
+_VER = "%d.%d" % bpy.app.version[:2]
+_BIN = os.path.dirname(bpy.app.binary_path)
+HDRI = next((p for p in (os.path.join(_BIN, _VER), os.path.join(_BIN, "..", "Resources", _VER))
+ if os.path.isdir(p)), os.path.join(_BIN, _VER))
+HDRI = os.path.join(HDRI, "datafiles", "studiolights", "world", "studio.exr")
RES = 640
PROBE = bool(os.environ.get("PROBE"))
# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.
diff --git a/scenes/tokyo-ramen-shop/scripts/compare.py b/scenes/tokyo-ramen-shop/scripts/compare.py
index a899cbe..322696f 100644
--- a/scenes/tokyo-ramen-shop/scripts/compare.py
+++ b/scenes/tokyo-ramen-shop/scripts/compare.py
@@ -12,7 +12,13 @@ import bpy
from mathutils import Vector
ROOT, OUT = map(os.path.abspath, sys.argv[sys.argv.index("--") + 1:][:2])
-HDRI = bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")
+# Blender's bundled studio HDRI. bpy.utils.system_resource() returns "" for this in 5.0.1, so build the path from the
+# version folder that sits next to the binary (Contents/Resources on macOS).
+_VER = "%d.%d" % bpy.app.version[:2]
+_BIN = os.path.dirname(bpy.app.binary_path)
+HDRI = next((p for p in (os.path.join(_BIN, _VER), os.path.join(_BIN, "..", "Resources", _VER))
+ if os.path.isdir(p)), os.path.join(_BIN, _VER))
+HDRI = os.path.join(HDRI, "datafiles", "studiolights", "world", "studio.exr")
RES = 640
PROBE = bool(os.environ.get("PROBE"))
# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.
diff --git a/web/.env.example b/web/.env.example
new file mode 100644
index 0000000..8c84b78
--- /dev/null
+++ b/web/.env.example
@@ -0,0 +1,22 @@
+# Copy to web/.env.local (gitignored) and fill in. Restart `npm run dev` after changing it.
+
+# Server only: the fal key the proxy adds to requests (never sent to the browser). `npm run env:local` writes it on
+# Windows from the FAL_SERVERLESS_KEY user env var.
+FAL_KEY=your-fal-key-id:your-fal-key-secret
+
+# The fal apps the UI calls, as <your-fal-username>/<app-name> (deploy them from builder/, endpoint/, kit/).
+# The proxy only forwards to these (plus fal storage uploads).
+NEXT_PUBLIC_ANYSCENE_APP=your-fal-username/anyscene
+NEXT_PUBLIC_ANYKIT_APP=your-fal-username/anykit
+# Optional: the older plan + build pipeline (?mode=pipeline); defaults to NEXT_PUBLIC_ANYSCENE_APP.
+# NEXT_PUBLIC_ANYSCENE_PIPELINE_APP=your-fal-username/anyscene-pipeline
+# Optional: a second builder deployment the gallery can show with ?gallery_app=<id>.
+# NEXT_PUBLIC_ANYSCENE_TEST_APP=your-fal-username/anyscene-builder
+
+# Optional, server only: shared secret every proxied request must carry (required in production; the proxy is
+# closed without it), and the per-IP job limit.
+# ANYSCENE_ACCESS_KEY=choose-a-long-random-string
+# ANYSCENE_JOBS_PER_HOUR=6
+
+# Optional: extra dev-server origins (comma-separated hosts, e.g. your LAN IP) allowed to load dev assets.
+# DEV_ORIGINS=192.168.1.20,*.local
diff --git a/web/.gitignore b/web/.gitignore
new file mode 100644
index 0000000..870ca1e
--- /dev/null
+++ b/web/.gitignore
@@ -0,0 +1,12 @@
+node_modules/
+.next/
+next-env.d.ts
+*.tsbuildinfo
+.env*.local
+.env
+# generated from fixtures/ by scripts/sync-fixtures.mjs
+public/replay/
+# the repo root ignores *.png; the replay fixtures and screenshots are small and belong with the UI
+!fixtures/**/*.png
+!screenshots/*.png
+!fixtures/**/*.glb
diff --git a/web/AGENTS.md b/web/AGENTS.md
new file mode 100644
index 0000000..af3b7c8
--- /dev/null
+++ b/web/AGENTS.md
@@ -0,0 +1,9 @@
+<!-- BEGIN:nextjs-agent-rules -->
+
+## This is NOT the Next.js you know
+
+This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
+
+This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
+
+<!-- END:nextjs-agent-rules -->
diff --git a/web/README.md b/web/README.md
new file mode 100644
index 0000000..98d9107
--- /dev/null
+++ b/web/README.md
@@ -0,0 +1,132 @@
+# AnyScene web
+
+The showcase UI for AnyScene. The default product is the agent builder (`builder/`, e.g. the public `apek/anyscene`): drop a reference
+image and one request builds the whole scene on a fal GPU worker (up to fal's 2 h cap), with a Claude agent looping
+against an independent critic. The UI shows the agent's production log, its milestones as a schedule, the newest
+render live, the critic's score sheet round by round, and the result (stills, 360, package, cost). The older
+plan + build pipeline (`endpoint/`) is still there at `?mode=pipeline`. Styled as a film call sheet.
+
+Next.js (App Router, TypeScript), three.js, `@fal-ai/client` in the browser through `@fal-ai/server-proxy` on the
+server. The fal key never reaches the browser.
+
+## Run
+
+```
+npm install
+cp .env.example .env.local # then fill in FAL_KEY and the app ids
+npm run env:local # (Windows) writes FAL_KEY into .env.local from the user env var FAL_SERVERLESS_KEY (never printed)
+npm run dev # http://localhost:3210
+```
+
+The fal apps come from `NEXT_PUBLIC_*` variables in `.env.local`, as `<your-fal-username>/<app>` (see `.env.example`):
+`NEXT_PUBLIC_ANYSCENE_APP` (the builder), `NEXT_PUBLIC_ANYKIT_APP` (AnyKit, for the kit gallery), and optionally
+`NEXT_PUBLIC_ANYSCENE_PIPELINE_APP` (the older pipeline; defaults to the builder's id) and
+`NEXT_PUBLIC_ANYSCENE_TEST_APP` (a second builder the gallery shows with `?gallery_app=<id>`). There are no defaults:
+a live call to an unset app fails with a message naming the variable. `DEV_ORIGINS` (comma-separated) adds LAN hosts
+allowed to open the dev server.
+
+`npm run dev` and `npm run build` first copy `fixtures/` into `public/replay/` (`npm run fixtures`).
+
+## Builder (default)
+
+- Live: **Build the scene** uploads the reference to fal storage and calls `<NEXT_PUBLIC_ANYSCENE_APP>/ref2scene` with
+ `{reference_image_urls, prompt, effort, scene: "scene"}`. Stage events come from the queue logs (prefix
+ `ANYSCENE_STAGE `, polled every 2 s, deduped by message).
+- Schedule: the milestones the agent reports (plan, props, layout, dressing, screens, materials, lighting, atmosphere,
+ cameras, finals, plus any it invents), with ROLLING on the current one, WRAPPED and a duration once it moves on, and
+ "take 2" when it returns to one after a critique. Then the critic's state and the package.
+- Production log (bottom): every `log` event (tool label and what it did), the agent's `thinking` notes, milestones
+ with a thumbnail, critic lines; filter by notes, tools or milestones. The caption under the frame is the agent's
+ latest note.
+- Frame: Live (newest `preview_url`, with a strip of recent frames you can hold), Compare (the plate against the
+ critic's reference-angle still, then the first final), Contact sheet (every reported frame), Stills and 360 after
+ the wrap.
+- Critic's report (right): the eight scores per round side by side with the change from the round before, lines under
+ 7 marked, the verdict stamp, the summary and the ranked fixes; earlier rounds' fixes fold away.
+- Result: stills, package, scene.blend and scene.glb, agent cost, minutes, critic rounds, anything `missing`.
+
+### Builder replay
+
+`/?replay=builder` plays `fixtures/builder/` (`events.jsonl` timed by each event's own `t`, `build.json` as the
+response); speeds 1x to 64x in the toolbar, `&auto=1` starts it. That fixture is **synthetic**
+(`npm run fixture:builder`): it follows the real schema, reuses the pipeline run's images, and its package link is
+the earlier pipeline package. To drop in a real run:
+
+```
+npm run import:builder -- <run dir> # -> fixtures/builder/
+npm run import:builder -- <run dir> fal_mc_1 # or keep both: ?replay=fal_mc_1
+```
+
+It copies `events.jsonl`, `build.json` and any `still_*.png` (served locally in place of the remote stills), plus a
+reference image. A run without `build.json` yet replays up to its last event and stops there.
+
+## Access key and rate limit
+
+The proxy checks a shared secret: set `ANYSCENE_ACCESS_KEY` in the server environment and every proxied request must
+carry it as `x-anyscene-key` (the page asks for it under **Access key** in the toolbar and keeps it in that browser's
+localStorage). With the variable unset the proxy is open in `next dev` and **closed** in production, so a fresh
+deployment can't start builds on the account. New jobs are also limited per IP (`ANYSCENE_JOBS_PER_HOUR`, default
+6; in memory, so per serverless instance: a backstop, not a quota).
+
+## Replay mode (pipeline)
+
+`/?replay=demo` plays the recorded pipeline run in `fixtures/` with its original timing. Click **Plan the scene**, then
+**Approve and build**.
+
+| param | |
+|---|---|
+| `replay=<name>` | `demo` is `fixtures/` itself; any subfolder `fixtures/<name>/` is another recording |
+| `speed=<n>` | 1 (real time) to 64; also switchable in the toolbar (1x to 16x) |
+| `auto=1` | plans on load and approves the build 3.5 s after the plan lands, for hands-off screen recordings |
+
+A recording is: `plan_events.jsonl` and `build_events.jsonl` (one `{"t": seconds, ...stage event}` per line, as written
+by `endpoint/client.py --events`), `plan.json`, `build.json` (the BuildResponse), `reference.png`, `floor_plan.png`,
+`blockout_reference.png`, `blockout_overview.png`, `comparison.png` and `still_*.png`. Recorded `preview_url`s that
+match a local file (floor plan, comparison, stills in `build.json` order) are served locally; the rest (layout and
+dressing previews, prop references, GLBs) still load from fal's CDN. Without `build_events.jsonl` the replay
+synthesizes a build from `plan.json`. The last two lines of `fixtures/plan_events.jsonl` are marked `"synthetic"`:
+the recorded plan run lost its final events when the client crashed, so `blockout done` and `done` were added.
+
+## Live mode
+
+Without `?replay`, **Plan the scene** uploads the reference to fal storage and calls `<pipeline app>/plan` through
+`/api/fal/proxy`; **Approve and build** calls `<pipeline app>/build` with the plan id and tier. Stage events are read
+from the queue logs (lines prefixed `ANYSCENE_STAGE `, deduped by message). The proxy only forwards to
+the configured `NEXT_PUBLIC_*_APP` apps (`<app>/**`) and fal storage uploads, so a deployment's key can't be used for
+other endpoints. On Vercel, set `FAL_KEY`, `ANYSCENE_ACCESS_KEY` and the `NEXT_PUBLIC_*_APP` ids in the project
+environment.
+
+## 360 and scene lighting (ahead of the endpoint)
+
+The UI already reads these optional fields, from events or the BuildResponse:
+
+| field | where | |
+|---|---|---|
+| `panorama_url` (+ `viewpoint`) | `rendering` event, one per viewpoint | equirectangular Cycles render, 2:1 |
+| `panorama_urls` | BuildResponse | the same, first = reference camera |
+| `scene_glb_url` | `packaging` event / BuildResponse | decimated scene glTF with KHR_lights_punctual |
+| `environment_url` | any event / BuildResponse | equirect .hdr or PNG of the scene's light for the prop viewer (else the first panorama) |
+
+Until real ones exist, `scripts/make-placeholders.mjs` builds `fixtures/panorama_ref.png`, `panorama_mid.png`
+(a ray-cast grey room from `plan.json`) and `fixtures/scene.glb` (the plan as boxes with its lights), and replay
+injects them where the endpoint will emit them, labelled "placeholder".
+
+## Screens
+
+- Left: reference plate, direction (prompt, the ten dials, planning effort, build tier), the schedule.
+- Centre: the camera-report frame with Floor plan (drawing, or the prop map that fills in as meshes land), Grey-box,
+ Live (newest `preview_url`), Compare (slider between the reference and the matching render), 3D (the selected
+ prop's GLB at the plan's real size, with dashed bounds and a ground shadow, lit by the scene's environment map once
+ there is one, studio light until then), 360 (drag-to-look panoramas per viewpoint, plus the scene glTF as a
+ free-orbit set model lit by the reference-camera panorama; hidden unless the build provides them), and Dailies
+ after the wrap (stills, timings, package). **Follow** moves the frame to whatever just arrived; picking a
+ view turns it off.
+- Bottom: the prop manifest, one card per `prop.id`: IN SHOP while meshing, TRIPO or MESHY with a turntable once the
+ mesh lands, FAILED, or STAND-IN if it never arrives. Click a card for the 3D view.
+- Right: the breakdown (room, setting, counts, lights, palette, dials), notes for a revision, Approve and build.
+
+Prop GLBs are 10-60 MB, so each card's turntable is rendered once into a sprite strip on a shared offscreen renderer
+and the model is freed; only the 3D view keeps a live model.
+
+`npm run screenshots` (pipeline) and `npm run screenshots:builder` (builder), with the dev server running, capture the
+main states into `screenshots/` with the installed Edge or Chrome.
diff --git a/web/app/api/fal/proxy/route.ts b/web/app/api/fal/proxy/route.ts
new file mode 100644
index 0000000..9a0a6be
--- /dev/null
+++ b/web/app/api/fal/proxy/route.ts
@@ -0,0 +1,80 @@
+import { timingSafeEqual } from "node:crypto";
+import type { NextRequest } from "next/server";
+import { createRouteHandler } from "@fal-ai/server-proxy/nextjs";
+import { ALL_APPS } from "@/lib/apps";
+
+// fal's server-side proxy: the browser talks to /api/fal/proxy and the server adds FAL_KEY (never sent to the client).
+// POSTs are limited to the AnyScene apps and fal storage uploads (for the reference image), so the key can't be used
+// for arbitrary fal endpoints. The apps are the NEXT_PUBLIC_*_APP ids the UI calls (lib/apps.ts, web/.env.example);
+// with none set, only uploads get through.
+const fal = createRouteHandler({
+ allowedEndpoints: [...ALL_APPS.map((app) => `${app}/**`), "storage/upload/**"],
+ allowUnauthorizedRequests: true, // our own guard below decides who gets through
+});
+
+// ---------------------------------------------------------------- guard
+// Shared secret: set ANYSCENE_ACCESS_KEY on the server and every proxied request must carry it as x-anyscene-key.
+// Off in local dev when the variable is unset; in production an unset key closes the proxy (fail closed), so a fresh
+// deployment can't be used to start builds on the owner's account.
+const ACCESS_KEY = process.env.ANYSCENE_ACCESS_KEY || "";
+const DEV_OPEN = !ACCESS_KEY && process.env.NODE_ENV !== "production";
+
+// Rate limit on new jobs (POSTs to an app; status polls and uploads are not counted), per client IP, in memory.
+// Per serverless instance only: a backstop behind the key, not a quota. ANYSCENE_JOBS_PER_HOUR, default 6.
+const JOBS_PER_HOUR = Number(process.env.ANYSCENE_JOBS_PER_HOUR || 6);
+const jobs = new Map<string, number[]>();
+
+function json(status: number, error: string) {
+ return new Response(JSON.stringify({ detail: error }), { status, headers: { "content-type": "application/json" } });
+}
+
+function keyOk(req: NextRequest) {
+ if (DEV_OPEN) return true;
+ if (!ACCESS_KEY) return false;
+ const got = Buffer.from(req.headers.get("x-anyscene-key") || "");
+ const want = Buffer.from(ACCESS_KEY);
+ return got.length === want.length && timingSafeEqual(got, want);
+}
+
+// Gallery reads (every build on storage, one build's events) are cheap lookups, not jobs: they don't count.
+const READ_ONLY = /\/(builds|build_events|kits|kit_events)\/?(\?.*)?$/;
+
+const APP_TARGETS = ALL_APPS.map((app) => `/${app}/`);
+
+function startsJob(req: NextRequest) {
+ const target = req.headers.get("x-fal-target-url") || "";
+ const m = target.match(/^https:\/\/(?:queue\.)?fal\.run(\/[^?]*)/);
+ return !!m && APP_TARGETS.some((p) => `${m[1]}/`.startsWith(p)) && !READ_ONLY.test(target);
+}
+
+function rateLimited(req: NextRequest) {
+ if (DEV_OPEN || !startsJob(req)) return false;
+ const ip = (req.headers.get("x-forwarded-for") || "").split(",")[0].trim() || req.headers.get("x-real-ip") || "unknown";
+ const now = Date.now();
+ const recent = (jobs.get(ip) || []).filter((t) => now - t < 3600_000);
+ if (recent.length >= JOBS_PER_HOUR) {
+ jobs.set(ip, recent);
+ return true;
+ }
+ recent.push(now);
+ jobs.set(ip, recent);
+ return false;
+}
+
+function guard(req: NextRequest): Response | null {
+ if (!keyOk(req)) {
+ return json(401, ACCESS_KEY ? "This AnyScene needs an access key." : "The AnyScene proxy is closed: ANYSCENE_ACCESS_KEY is not set on the server.");
+ }
+ if (req.method === "POST" && rateLimited(req)) return json(429, `Too many builds from this address: ${JOBS_PER_HOUR} an hour.`);
+ return null;
+}
+
+export async function GET(req: NextRequest) {
+ return guard(req) ?? fal.GET(req);
+}
+export async function POST(req: NextRequest) {
+ return guard(req) ?? fal.POST(req);
+}
+export async function PUT(req: NextRequest) {
+ return guard(req) ?? fal.PUT(req);
+}
diff --git a/web/app/globals.css b/web/app/globals.css
new file mode 100644
index 0000000..a1b8223
--- /dev/null
+++ b/web/app/globals.css
@@ -0,0 +1,720 @@
+/* AnyScene as a call sheet: production paperwork. Cream paper, typewriter ink, tan rules, one red for stamps.
+ Courier Prime for everything typed; Barlow Condensed (bold, uppercase, letter-spaced) for headings and labels.
+ Square corners, 1-2 px ink borders, dashed rules in tables, no soft shadows. */
+:root {
+ --paper: #f6f1e4;
+ --paper-2: #efe8d6; /* matte behind renders */
+ --card: #fffdf6;
+ --ink: #1f1d1a;
+ --rule: #cbbfa3;
+ --red: #b8382c;
+ --dim: #8a8172; /* large labels only (3.4:1) */
+ --dim-text: #645c4f; /* small muted text (5.6:1) */
+ --ok: #3f5e3a;
+ --tripo: #24497d;
+ --meshy: #6b3f75;
+ --ease: cubic-bezier(0.2, 0.7, 0.2, 1);
+ --font-type: "Courier Prime", "Courier New", monospace;
+ --font-head: "Barlow Condensed", "Arial Narrow", sans-serif;
+ color-scheme: light;
+}
+
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: var(--paper);
+ color: var(--ink);
+ font-family: var(--font-type);
+ font-size: 13.5px;
+ line-height: 1.45;
+ font-variant-numeric: tabular-nums;
+}
+button, input, select, textarea { font: inherit; color: inherit; }
+button { cursor: pointer; }
+button:disabled { cursor: default; }
+:focus-visible { outline: 2px solid var(--red); outline-offset: 2px; }
+.muted { color: var(--dim-text); }
+.bad { color: var(--red); }
+.fine { color: var(--dim-text); font-size: 12px; margin: 6px 0 0; }
+.typed { margin: 0; }
+
+.sheet-h {
+ font-family: var(--font-head);
+ font-weight: 700;
+ letter-spacing: 0.14em;
+ font-size: 13px;
+ text-transform: uppercase;
+ margin: 0 0 8px;
+ padding-bottom: 3px;
+ border-bottom: 2px solid var(--ink);
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+}
+.sheet-h-sub { color: var(--dim); font-weight: 500; letter-spacing: 0.1em; font-size: 12px; }
+
+/* ---------------------------------------------------------------- stamps */
+.stamp {
+ display: inline-block;
+ border: 2px solid var(--red);
+ color: var(--red);
+ font-family: var(--font-head);
+ font-weight: 800;
+ letter-spacing: 0.12em;
+ padding: 0 6px;
+ font-size: 12px;
+ line-height: 1.5;
+ transform: rotate(var(--tilt, -4deg));
+ animation: thunk 0.32s var(--ease) both;
+ mix-blend-mode: multiply;
+ white-space: nowrap;
+}
+.stamp.big { font-size: 34px; border-width: 4px; padding: 0 14px; letter-spacing: 0.16em; }
+@keyframes thunk {
+ 0% { opacity: 0; transform: scale(1.6) rotate(calc(var(--tilt, -4deg) - 6deg)); }
+ 70% { opacity: 1; transform: scale(0.96) rotate(var(--tilt, -4deg)); }
+ 100% { transform: scale(1) rotate(var(--tilt, -4deg)); }
+}
+
+/* ---------------------------------------------------------------- frame */
+.studio {
+ display: grid;
+ height: 100vh;
+ grid-template-columns: 300px minmax(0, 1fr) 340px;
+ grid-template-rows: auto minmax(0, 1fr) 262px;
+ grid-template-areas:
+ "top top top"
+ "left center right"
+ "left shelf shelf";
+ column-gap: 0;
+}
+.studio.right-closed { grid-template-columns: 300px minmax(0, 1fr) 0px; }
+.studio.right-closed .right { visibility: hidden; }
+
+/* slate */
+.topbar { grid-area: top; padding: 16px 20px 0; }
+.slate { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)) 1.2fr; border: 2px solid var(--ink); }
+.slate-cell { border-right: 1px solid var(--ink); padding: 5px 10px 6px; min-width: 0; }
+.slate small { display: block; font-family: var(--font-head); font-weight: 700; letter-spacing: 0.12em; font-size: 11px; color: var(--dim-text); text-transform: uppercase; }
+.slate b { display: block; font-family: var(--font-head); font-weight: 800; font-size: 26px; line-height: 1.05; text-transform: uppercase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.slate .clock { font-variant-numeric: tabular-nums; }
+.slate-stripe { background: repeating-linear-gradient(135deg, var(--ink) 0 14px, var(--paper) 14px 28px); }
+.toolbar { display: flex; align-items: center; gap: 18px; padding: 7px 2px 0; font-size: 12px; color: var(--dim-text); }
+.scene-name { flex: 1; text-align: center; font-style: italic; }
+.replay-ctl, .live-pill { display: flex; align-items: center; gap: 8px; }
+.live-pill::before { content: ""; width: 7px; height: 7px; background: var(--red); border-radius: 50%; }
+.speeds { display: flex; border: 1px solid var(--ink); }
+.speeds button { border: 0; border-right: 1px solid var(--rule); background: none; padding: 0 7px; font-size: 12px; color: var(--dim-text); }
+.speeds button:last-child { border-right: 0; }
+.speeds button.on { background: var(--ink); color: var(--paper); }
+.text-btn { background: none; border: 0; padding: 0; color: var(--ink); font-size: 12px; text-decoration: underline; text-underline-offset: 3px; text-decoration-color: var(--rule); }
+.text-btn:hover { text-decoration-color: var(--ink); }
+
+/* ---------------------------------------------------------------- left */
+.left {
+ grid-area: left;
+ overflow-y: auto;
+ padding: 16px 16px 24px 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 22px;
+ scrollbar-width: thin;
+ scrollbar-color: var(--rule) transparent;
+}
+.inputs { display: flex; flex-direction: column; gap: 10px; }
+.drop {
+ position: relative;
+ aspect-ratio: 16 / 10;
+ border: 1px dashed var(--ink);
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+ cursor: pointer;
+ background: var(--card);
+}
+.drop:hover, .drop.over { background: #fbf3dc; }
+.drop.over { border-style: solid; border-width: 2px; }
+.drop.has { border-style: solid; }
+.drop img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.drop-empty { display: flex; flex-direction: column; gap: 6px; padding: 16px; text-align: center; }
+.drop-title { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; font-size: 15px; }
+.drop-hint { color: var(--dim-text); font-size: 12px; }
+.drop-change { position: absolute; right: 6px; bottom: 6px; font-size: 11.5px; background: var(--paper); border: 1px solid var(--ink); padding: 0 6px; opacity: 0; }
+.drop:hover .drop-change, .drop:focus-visible .drop-change { opacity: 1; }
+.cap { font-size: 12px; color: var(--dim-text); margin: -4px 0 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
+.field-label { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.1em; font-size: 11px; color: var(--dim-text); text-transform: uppercase; }
+textarea, select {
+ background: var(--card);
+ border: 1px solid var(--ink);
+ border-radius: 0;
+ padding: 6px 8px;
+ resize: vertical;
+}
+textarea { background-image: repeating-linear-gradient(to bottom, transparent 0 calc(1.45em - 1px), var(--rule) calc(1.45em - 1px) 1.45em); background-position: 0 6px; line-height: 1.45em; }
+textarea::placeholder { color: #9b927f; }
+textarea:focus, select:focus { outline: 2px solid var(--ink); outline-offset: -1px; }
+.row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+.seg { display: flex; border: 1px solid var(--ink); background: var(--card); }
+.seg button { flex: 1; border: 0; border-right: 1px solid var(--ink); background: none; padding: 4px 8px; font-size: 13px; white-space: nowrap; }
+.seg button:last-child { border-right: 0; }
+.seg button.on { background: var(--ink); color: var(--paper); }
+.seg.small button { font-size: 12px; padding: 1px 9px; }
+
+.dials { border: 1px solid var(--ink); background: var(--card); }
+.dials-head { width: 100%; display: flex; align-items: center; gap: 8px; padding: 6px 9px; background: none; border: 0; text-align: left; }
+.dials-head > span:first-child { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; font-size: 12px; }
+.dials-sum { flex: 1; color: var(--dim-text); font-size: 12px; text-align: right; }
+.chev { width: 7px; height: 7px; border-right: 1.5px solid var(--ink); border-bottom: 1.5px solid var(--ink); transform: rotate(45deg) translateY(-2px); }
+.chev.open { transform: rotate(-135deg) translateY(-1px); }
+.dials-body { padding: 4px 9px 10px; display: flex; flex-direction: column; gap: 10px; border-top: 1px dashed var(--rule); }
+.dial { display: flex; flex-direction: column; gap: 2px; }
+.dial-top { display: flex; justify-content: space-between; align-items: baseline; }
+.dial-name { font-size: 13px; }
+.dial-auto { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.12em; color: var(--dim); font-size: 11px; }
+.dial-reset { background: none; color: var(--red); border: 1px solid var(--red); padding: 0 5px; font-size: 12px; }
+.dial-range { display: grid; grid-template-columns: 54px 1fr 54px; align-items: center; gap: 6px; font-size: 11px; color: var(--dim-text); }
+.dial-range span:last-child { text-align: right; }
+input[type="range"] { -webkit-appearance: none; appearance: none; background: transparent; width: 100%; height: 18px; }
+input[type="range"]::-webkit-slider-runnable-track { height: 1px; background: var(--ink); }
+input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; width: 9px; height: 15px; background: var(--paper); border: 1.5px solid var(--ink); margin-top: -7px; }
+input[type="range"]::-moz-range-track { height: 1px; background: var(--ink); }
+input[type="range"]::-moz-range-thumb { width: 9px; height: 15px; border: 1.5px solid var(--ink); border-radius: 0; background: var(--paper); }
+.dial:not(.set) input[type="range"] { opacity: 0.4; }
+.dial.set input[type="range"]::-webkit-slider-thumb { background: var(--ink); }
+.chips { display: flex; flex-wrap: wrap; gap: 4px; }
+.chips button { border: 1px solid var(--rule); background: none; padding: 0 7px; font-size: 12px; }
+.chips button.on { border-color: var(--ink); background: var(--ink); color: var(--paper); }
+
+.primary, .secondary {
+ border-radius: 0;
+ padding: 9px 12px;
+ border: 2px solid var(--ink);
+ font-family: var(--font-head);
+ font-weight: 800;
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ font-size: 15px;
+ text-align: center;
+}
+.primary { background: var(--ink); color: var(--paper); }
+.primary:hover:not(:disabled) { background: #3a3631; }
+.primary:active:not(:disabled) { transform: translateY(1px); }
+.primary:disabled { background: transparent; color: var(--dim); border-color: var(--rule); }
+.secondary { background: transparent; color: var(--ink); border-width: 1px; font-size: 13px; padding: 6px 10px; }
+.secondary:hover:not(:disabled) { background: var(--card); }
+.secondary:disabled { color: var(--dim); border-color: var(--rule); }
+.as-link { display: block; text-decoration: none; }
+
+/* ---------------------------------------------------------------- schedule */
+.sched { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+.sched th, .sched td { border-bottom: 1px dashed var(--rule); padding: 5px 4px; text-align: left; vertical-align: top; }
+.sched th { font-family: var(--font-head); letter-spacing: 0.1em; font-size: 11px; color: var(--dim-text); font-weight: 700; text-transform: uppercase; }
+.sched td:first-child { width: 18px; color: var(--dim-text); }
+.sched td.st { width: 106px; }
+.sched tr.pending td, .sched tr.skipped td { color: var(--dim-text); }
+.sched tr.running .dept { font-weight: 700; }
+.sched tr.prev td { color: var(--dim-text); }
+.dept-msg { font-size: 11.5px; color: var(--dim-text); margin-top: 2px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
+.wrapped { font-weight: 700; white-space: nowrap; }
+.standby { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.12em; color: var(--dim); font-size: 12px; }
+.st-sub { display: block; font-size: 11.5px; color: var(--dim-text); font-weight: 400; margin-top: 3px; white-space: pre; }
+.tick { height: 5px; margin-top: 5px; border: 1px solid var(--ink); }
+.tick span { display: block; height: 100%; background: repeating-linear-gradient(90deg, var(--ink) 0 2px, transparent 2px 4px); transition: width 0.6s var(--ease); }
+.error-note { color: var(--red); font-size: 12.5px; border: 1px solid var(--red); padding: 6px 8px; margin: 10px 0 0; }
+
+/* ---------------------------------------------------------------- viewport */
+.center { grid-area: center; min-width: 0; min-height: 0; padding: 16px 20px 0 8px; display: flex; }
+.viewport { flex: 1; display: flex; flex-direction: column; min-height: 0; min-width: 0; }
+.frame-title { margin-bottom: 6px; }
+.vp-tabs { display: flex; align-items: center; gap: 4px; padding-bottom: 8px; flex-wrap: wrap; }
+.vp-tab { background: none; border: 0; padding: 1px 6px; font-size: 13px; color: var(--dim-text); }
+.vp-tab::before { content: "[" / ""; margin-right: 4px; color: var(--rule); }
+.vp-tab::after { content: "]" / ""; margin-left: 4px; color: var(--rule); }
+.vp-tab.ready { color: var(--ink); }
+.vp-tab:hover { text-decoration: underline; text-decoration-color: var(--rule); text-underline-offset: 3px; }
+.vp-tab.on { font-weight: 700; color: var(--ink); }
+.vp-tab.on::before, .vp-tab.on::after { color: var(--ink); }
+.vp-spacer { flex: 1; }
+.follow { display: flex; align-items: center; gap: 6px; background: none; border: 0; color: var(--dim-text); font-size: 12px; margin-left: 10px; }
+.follow-dot { width: 9px; height: 9px; border: 1.5px solid var(--ink); }
+.follow.on { color: var(--ink); }
+.follow.on .follow-dot { background: var(--ink); }
+
+.vp-stage {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ background: var(--paper-2);
+ border: 2px solid var(--ink);
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.frame-note { position: absolute; right: 10px; top: 10px; z-index: 3; background: var(--paper); border: 1px solid var(--ink); padding: 2px 8px; font-size: 12px; }
+.frame-wrap { position: absolute; left: 24px; bottom: 24px; z-index: 3; pointer-events: none; }
+.fade { position: absolute; inset: 0; }
+.fade img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; opacity: 0; transition: opacity 0.7s var(--ease); }
+.fade img.shown { opacity: 1; }
+.fade.paper { inset: 14px; }
+.live-frame { position: absolute; inset: 0; }
+.live-tag { position: absolute; left: 10px; top: 10px; z-index: 2; font-size: 12px; background: var(--paper); border: 1px solid var(--ink); padding: 2px 8px; max-width: 60%; }
+.empty { display: flex; flex-direction: column; align-items: center; gap: 12px; color: var(--dim-text); max-width: 340px; text-align: center; }
+.empty p { margin: 0; }
+.empty-pulse { width: 28px; height: 28px; border: 2px solid var(--ink); animation: blink 1.2s steps(2) infinite; }
+
+.caption { display: flex; align-items: baseline; gap: 14px; padding: 9px 0 12px; min-height: 44px; border-bottom: 1px dashed var(--rule); }
+.caption::before { content: "NOTE" / ""; font-family: var(--font-head); font-weight: 700; letter-spacing: 0.14em; font-size: 11px; color: var(--dim-text); }
+.caption-text { flex: 1; font-size: 14px; animation: type-in 0.4s var(--ease); }
+.caption-time { font-weight: 700; }
+
+/* prop map: ink on paper */
+.livemap { position: absolute; inset: 0; display: flex; flex-direction: column; padding: 14px 14px 8px; }
+.livemap svg { flex: 1; min-height: 0; width: 100%; }
+#grid path { stroke: var(--rule) !important; stroke-width: 0.015 !important; }
+.map-wall { fill: none; stroke: var(--ink); stroke-width: 0.12; }
+.map-opening { stroke: var(--paper-2); stroke-width: 0.2; }
+.map-opening.window { stroke: #9fb2c2; }
+.fp rect { stroke-width: 0.035; transition: fill 0.8s var(--ease), stroke 0.8s var(--ease); }
+.fp.invented rect { stroke-dasharray: 0.14 0.09; }
+.fp.fixed rect { fill: rgba(203, 191, 163, 0.35); stroke: var(--rule); }
+.fp.planned rect, .fp.waiting rect { fill: transparent; stroke: var(--dim); }
+.fp.ref rect { fill: url(#hatch); stroke: var(--ink); }
+.fp.meshed rect { fill: rgba(31, 29, 26, 0.78); stroke: var(--ink); cursor: pointer; }
+.fp.meshed:hover rect { fill: var(--ink); }
+.fp.standin rect { fill: rgba(138, 129, 114, 0.25); stroke: var(--dim); stroke-dasharray: 0.06 0.06; }
+.fp.failed rect { fill: rgba(184, 56, 44, 0.18); stroke: var(--red); }
+.fp.sel rect { stroke: var(--red); stroke-width: 0.09; }
+.map-light { stroke: var(--ink); stroke-width: 0.02; }
+.map-cam path { fill: rgba(184, 56, 44, 0.08); stroke: var(--red); stroke-width: 0.035; }
+.map-cam circle { fill: var(--red); }
+.map-legend { display: flex; flex-wrap: wrap; justify-content: center; gap: 14px; padding-top: 8px; font-size: 11.5px; }
+.lg::before { content: ""; display: inline-block; width: 11px; height: 11px; margin-right: 5px; vertical-align: -1px; border: 1px solid var(--ink); }
+.lg.meshed::before { background: rgba(31, 29, 26, 0.78); }
+.lg.ref::before { background: repeating-linear-gradient(45deg, var(--ink) 0 1px, transparent 1px 4px); }
+.lg.waiting::before { border-color: var(--dim); border-style: dashed; }
+.lg.standin::before { background: rgba(138, 129, 114, 0.25); border-color: var(--dim); }
+.lg.failed::before { background: rgba(184, 56, 44, 0.18); border-color: var(--red); }
+.lg.fixed::before { background: rgba(203, 191, 163, 0.35); border-color: var(--rule); }
+
+/* compare */
+.compare-wrap { position: absolute; inset: 0; display: grid; place-items: center; }
+.compare { position: relative; max-width: 100%; max-height: 100%; width: 100%; cursor: ew-resize; user-select: none; touch-action: none; overflow: hidden; }
+.compare > img, .compare-left img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.compare-left { position: absolute; inset: 0; }
+.compare-line { position: absolute; top: 0; bottom: 0; width: 0; }
+.compare-line::before { content: ""; position: absolute; top: 0; bottom: 0; left: -1px; width: 2px; background: var(--paper); box-shadow: 0 0 0 1px var(--ink); }
+.compare-line span { position: absolute; top: 50%; left: -13px; width: 26px; height: 26px; margin-top: -13px; background: var(--paper); border: 2px solid var(--ink); }
+.compare-line span::before, .compare-line span::after { content: ""; position: absolute; top: 7px; border: 4px solid transparent; }
+.compare-line span::before { left: 0; border-right-color: var(--ink); }
+.compare-line span::after { right: 0; border-left-color: var(--ink); }
+.compare-tag { position: absolute; bottom: 10px; font-size: 12px; background: var(--paper); border: 1px solid var(--ink); padding: 1px 8px; }
+.compare-tag.l { left: 10px; }
+.compare-tag.r { right: 10px; }
+
+/* 3d */
+.viewer3d { position: absolute; inset: 0; }
+.viewer3d-canvas { position: absolute; inset: 0; background: radial-gradient(ellipse at 50% 45%, #fbf6ea 0%, var(--paper-2) 75%); }
+.viewer3d-canvas canvas { display: block; }
+.viewer3d-load { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; font-size: 12.5px; pointer-events: none; }
+.viewer3d-load .tick { width: 220px; }
+.viewer3d-info { position: absolute; left: 10px; bottom: 10px; display: flex; gap: 10px; align-items: flex-end; background: var(--paper); border: 1px solid var(--ink); padding: 6px; max-width: calc(100% - 20px); }
+.viewer3d-info img { width: 72px; height: 72px; object-fit: cover; border: 1px solid var(--ink); filter: sepia(0.15); }
+.v3-label { font-size: 13px; font-weight: 700; margin-bottom: 4px; max-width: 40ch; }
+.badge { font-family: var(--font-head); font-weight: 800; letter-spacing: 0.12em; font-size: 11px; text-transform: uppercase; border: 1px solid currentColor; padding: 0 5px; }
+.badge.tripo { color: var(--tripo); }
+.badge.meshy { color: var(--meshy); }
+
+/* result: dailies */
+.result { position: absolute; inset: 0; display: grid; grid-template-columns: minmax(0, 1fr) 270px; gap: 16px; padding: 14px; }
+.result-main { display: flex; flex-direction: column; gap: 8px; min-height: 0; }
+.result-still { flex: 1; min-height: 0; width: 100%; object-fit: contain; animation: fadein 0.7s var(--ease); }
+.result-thumbs { display: flex; gap: 8px; }
+.result-thumbs button { padding: 0; border: 1px solid var(--rule); width: 110px; aspect-ratio: 2.39; background: none; opacity: 0.7; }
+.result-thumbs button.on { opacity: 1; border: 2px solid var(--ink); }
+.result-thumbs img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.result-side { display: flex; flex-direction: column; gap: 10px; overflow-y: auto; background: var(--paper); border: 1px solid var(--ink); padding: 10px; }
+.result-head { display: flex; flex-direction: column; gap: 2px; }
+.result-head .serif { font-family: var(--font-head); font-weight: 800; font-size: 22px; letter-spacing: 0.06em; text-transform: uppercase; }
+.result-head .muted { font-size: 12px; }
+.timings { width: 100%; border-collapse: collapse; margin-top: 6px; font-size: 12px; }
+.timings caption { text-align: left; font-family: var(--font-head); font-weight: 700; letter-spacing: 0.14em; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--ink); padding-bottom: 2px; margin-bottom: 2px; }
+.timings th { text-align: left; font-weight: 400; padding: 3px 0; border-bottom: 1px dashed var(--rule); }
+.timings td { text-align: right; padding: 3px 0; border-bottom: 1px dashed var(--rule); font-weight: 700; }
+.timings tr.server th { color: var(--dim-text); }
+.timings tr.total th, .timings tr.total td { border-bottom: 0; border-top: 1px solid var(--ink); padding-top: 5px; }
+
+/* ---------------------------------------------------------------- prop manifest */
+.shelf-wrap { grid-area: shelf; min-width: 0; padding: 12px 20px 0 8px; }
+.shelf { height: 100%; display: flex; flex-direction: column; }
+.shelf-head { display: flex; align-items: baseline; gap: 14px; }
+.shelf-head .sheet-h { flex: 0 0 auto; margin: 0; border: 0; padding: 0; }
+.shelf-head { border-bottom: 2px solid var(--ink); padding-bottom: 3px; margin-bottom: 10px; }
+.shelf-count { font-size: 12px; }
+.shelf-count b { font-weight: 700; }
+.shelf-row {
+ flex: 1; display: flex; gap: 10px; overflow-x: auto; overflow-y: hidden; padding: 0 0 12px;
+ scrollbar-width: thin; scrollbar-color: var(--rule) transparent;
+}
+.shelf-empty { display: flex; gap: 10px; }
+.tile {
+ flex: 0 0 132px; display: flex; flex-direction: column; gap: 4px; padding: 6px; border: 1px solid var(--ink); background: var(--card); text-align: left;
+ font-size: 11.5px; align-self: flex-start;
+ animation: tile-in 0.5s var(--ease) both;
+}
+.tile:not(:disabled):hover { outline: 1px solid var(--ink); }
+.tile.sel { outline: 2px solid var(--red); outline-offset: 1px; }
+.tile-media { position: relative; width: 100%; aspect-ratio: 1; overflow: hidden; background: var(--paper-2); }
+.tile-ref { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; filter: sepia(0.15); transition: opacity 0.8s var(--ease), filter 0.8s; }
+.tile.meshing .tile-ref { filter: sepia(0.25) contrast(0.9); }
+.tile.spinning .tile-ref { opacity: 0; }
+.tile.failed .tile-ref { filter: grayscale(1) contrast(0.8); opacity: 0.55; }
+.tile.failed { border-color: var(--red); }
+.tile.standin .tile-ref { filter: grayscale(1) contrast(0.8); opacity: 0.55; }
+.tile.standin .tile-label { color: var(--dim-text); }
+.tile-initial { position: absolute; inset: 0; display: grid; place-items: center; font-family: var(--font-head); font-weight: 800; font-size: 44px; color: var(--dim); }
+.tile-sprite {
+ position: absolute; inset: 0;
+ background-color: var(--paper-2);
+ background-size: calc(var(--frames) * 100%) 100%;
+ background-repeat: no-repeat;
+ animation: turntable 5.6s steps(48, jump-none) infinite, fadein 0.9s var(--ease);
+}
+@keyframes turntable { from { background-position: 0% 0; } to { background-position: 100% 0; } }
+.tile-spin {
+ position: absolute; right: 6px; top: 6px; width: 14px; height: 14px; border-radius: 50%;
+ border: 2px solid rgba(31, 29, 26, 0.2); border-top-color: var(--ink); animation: spin 0.9s linear infinite;
+}
+.tile-spin.small { width: 11px; height: 11px; }
+.tile-label { line-height: 1.25; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; min-height: 2.5em; }
+.tile-tag { display: flex; justify-content: space-between; align-items: baseline; gap: 4px; }
+.tile-tag .no { font-weight: 700; }
+.tag { font-family: var(--font-head); font-weight: 800; letter-spacing: 0.1em; font-size: 11px; }
+.tag.meshing { color: var(--dim-text); }
+.tag.spinning, .tag.loading { color: var(--ink); }
+.tag.failed { color: var(--red); }
+.tag.standin { color: var(--dim-text); border: 1px dashed var(--dim); padding: 0 3px; }
+.tile.ghost { animation: none; border-style: dashed; border-color: var(--rule); background: transparent; }
+.tile.ghost .tile-media { background: transparent; border: 1px dashed var(--rule); }
+.tile.ghost .tile-label { min-height: 2.5em; }
+.tile.ghost .tag, .tile.ghost .no { color: var(--dim); }
+
+/* ---------------------------------------------------------------- breakdown */
+.right { grid-area: right; overflow-y: auto; overflow-x: hidden; scrollbar-width: thin; scrollbar-color: var(--rule) transparent; }
+.plan-panel { padding: 16px 20px 20px 8px; display: flex; flex-direction: column; gap: 12px; width: 340px; min-height: 100%; }
+.plan-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
+.plan-title { margin: 0; font-family: var(--font-head); font-weight: 800; font-size: 24px; line-height: 1.05; letter-spacing: 0.04em; text-transform: uppercase; }
+.approved { flex: 0 0 auto; margin-top: 2px; }
+.approved .stamp { font-size: 15px; border-width: 3px; }
+.plan-summary { font-size: 12.5px; }
+.typing { display: flex; flex-direction: column; gap: 8px; }
+.typing span { height: 1px; border-top: 1px dashed var(--rule); position: relative; }
+.typing span::after { content: ""; position: absolute; left: 0; top: -12px; width: 8px; height: 13px; background: var(--ink); animation: caret 2.4s steps(30) infinite; }
+.typing span:nth-child(2)::after { animation-delay: 0.8s; }
+.typing span:nth-child(3)::after { animation-delay: 1.6s; }
+.breakdown { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+.breakdown th { width: 76px; text-align: left; vertical-align: top; font-family: var(--font-head); font-weight: 700; letter-spacing: 0.1em; font-size: 11px; color: var(--dim-text); text-transform: uppercase; padding: 5px 6px 5px 0; border-bottom: 1px dashed var(--rule); }
+.breakdown td { padding: 4px 0; border-bottom: 1px dashed var(--rule); }
+.light-dots { display: flex; flex-wrap: wrap; gap: 3px; margin-top: 4px; }
+.light-dots span { width: 9px; height: 9px; border: 1px solid var(--ink); border-radius: 50%; }
+.palette { display: flex; height: 14px; border: 1px solid var(--ink); }
+.palette span { flex: 1; }
+.notes ol { margin: 6px 0 0; padding-left: 20px; font-size: 12px; display: flex; flex-direction: column; gap: 4px; }
+.plan-actions { display: flex; flex-direction: column; gap: 8px; margin-top: auto; position: sticky; bottom: 0; background: var(--paper); padding: 10px 0 4px; border-top: 2px solid var(--ink); }
+.plan-id { margin: 0; }
+
+/* ---------------------------------------------------------------- motion */
+@keyframes spin { to { transform: rotate(360deg); } }
+@keyframes blink { 50% { opacity: 0.2; } }
+@keyframes fadein { from { opacity: 0; } }
+@keyframes type-in { from { clip-path: inset(0 100% 0 0); } to { clip-path: inset(0 0 0 0); } }
+@keyframes caret { from { left: 0; } to { left: 100%; } }
+@keyframes tile-in { from { opacity: 0; } to { opacity: 1; } }
+
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }
+ .tile-sprite { animation: none; }
+}
+
+/* ---------------------------------------------------------------- narrow screens */
+@media (max-width: 1180px) {
+ .studio { grid-template-columns: 270px minmax(0, 1fr) 0; }
+ .studio .right { display: none; }
+ .slate b { font-size: 21px; }
+}
+@media (max-width: 760px) {
+ .studio {
+ height: auto; min-height: 100vh;
+ grid-template-columns: minmax(0, 1fr); grid-template-rows: auto auto 64vh 270px auto;
+ grid-template-areas: "top" "left" "center" "shelf" "right";
+ }
+ .topbar { padding: 12px 16px 0; }
+ .slate { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+ .slate-cell:nth-child(3) { border-right: 0; }
+ .slate-cell:nth-child(-n + 3) { border-bottom: 1px solid var(--ink); }
+ .slate-stripe { display: none; }
+ .scene-name { display: none; }
+ .toolbar { flex-wrap: wrap; justify-content: space-between; }
+ .studio .right { display: block; }
+ .plan-panel { width: auto; padding: 16px; }
+ .left { padding: 16px; }
+ .center { padding: 8px 16px 0; }
+ .shelf-wrap { padding: 12px 16px 0; }
+ .result { grid-template-columns: minmax(0, 1fr); overflow-y: auto; }
+}
+
+/* 360 plate and viewer captions */
+.pano { position: absolute; inset: 0; }
+.pano-canvas { position: absolute; inset: 0; cursor: grab; touch-action: none; }
+.pano-canvas:active { cursor: grabbing; }
+.pano-canvas canvas { display: block; }
+.viewer-hint { position: absolute; right: 10px; bottom: 8px; margin: 0; font-size: 11.5px; background: var(--paper); border: 1px solid var(--rule); padding: 0 6px; pointer-events: none; }
+.v3-no { font-weight: 700; font-size: 12px; }
+.v3-dims { font-size: 12px; margin-bottom: 4px; }
+.v3-meta { display: flex; gap: 8px; align-items: baseline; }
+.v3-env { font-size: 11.5px; color: var(--dim-text); }
+.slate { position: relative; }
+.slate-wrap { position: absolute; right: 7%; top: 50%; transform: translateY(-50%); pointer-events: none; z-index: 2; }
+.slate-wrap .stamp { background: var(--paper); }
+@media (max-width: 760px) {
+ .slate-wrap { right: 4%; }
+ .slate-wrap .stamp.big { font-size: 18px; border-width: 3px; padding: 0 8px; }
+}
+
+/* ---------------------------------------------------------------- builder */
+.studio.builder { grid-template-rows: auto minmax(0, 1fr) 270px; }
+.mode-switch { font-size: 12px; color: var(--dim-text); }
+.key-ctl form { display: flex; gap: 6px; align-items: center; }
+.key-ctl input { width: 150px; font-size: 12px; padding: 1px 6px; border: 1px solid var(--ink); background: var(--card); border-radius: 0; }
+.text-btn.bad { color: var(--red); text-decoration-color: var(--red); }
+.take { font-weight: 400; color: var(--red); font-size: 11.5px; }
+.wrapped.notyet { color: var(--red); }
+
+/* live filmstrip inside the frame */
+.strip {
+ position: absolute; left: 10px; right: 10px; bottom: 10px; z-index: 2; display: flex; gap: 4px; justify-content: flex-end;
+ overflow: hidden; pointer-events: none;
+}
+.strip button { pointer-events: auto; flex: 0 0 auto; width: 64px; aspect-ratio: 16 / 9; padding: 0; border: 1px solid var(--ink); background: var(--paper); opacity: 0.8; }
+.strip button.on { opacity: 1; outline: 2px solid var(--red); outline-offset: 0; }
+.strip button:hover { opacity: 1; }
+.strip img { width: 100%; height: 100%; object-fit: cover; display: block; filter: sepia(0.1); }
+
+/* contact sheet */
+.contact { position: absolute; inset: 0; overflow-y: auto; padding: 14px; display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; align-content: start; }
+.contact figure { margin: 0; background: var(--card); border: 1px solid var(--ink); padding: 5px; }
+.contact button { padding: 0; border: 0; background: none; display: block; width: 100%; aspect-ratio: 16 / 9; }
+.contact img { width: 100%; height: 100%; object-fit: cover; display: block; filter: sepia(0.12); }
+.contact figcaption { font-size: 11.5px; margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+
+/* critic */
+.scores { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+.scores th, .scores td { border-bottom: 1px dashed var(--rule); padding: 3px 4px; }
+.scores thead th { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.1em; font-size: 11px; color: var(--dim-text); text-align: right; border-bottom: 1px solid var(--ink); }
+.scores thead th.cur { color: var(--ink); }
+.scores tbody th { text-align: left; font-weight: 400; white-space: nowrap; }
+.scores td { text-align: right; font-weight: 700; white-space: nowrap; }
+.scores td:not(.cur) { color: var(--dim-text); font-weight: 400; }
+.scores td.low { color: var(--red); text-decoration: underline; text-decoration-style: wavy; text-decoration-thickness: 1px; text-underline-offset: 3px; }
+.scores td.cur { background: rgba(203, 191, 163, 0.18); }
+.scores sup { font-size: 9.5px; margin-left: 1px; font-weight: 400; }
+.scores sup.up { color: var(--ok); }
+.scores sup.down { color: var(--red); }
+.scores tr.total th, .scores tr.total td { border-top: 1px solid var(--ink); border-bottom: 0; }
+.scores tr.verdicts th { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.1em; font-size: 11px; color: var(--dim-text); }
+.scores tr.verdicts td { font-family: var(--font-head); font-weight: 800; letter-spacing: 0.08em; font-size: 11px; border-bottom: 0; }
+.scores tr.verdicts td.pass { color: var(--ok); }
+.scores tr.verdicts td.fail { color: var(--red); }
+.verdict-head { display: flex; align-items: center; justify-content: space-between; margin-top: 4px; }
+.verdict-round { font-family: var(--font-head); font-weight: 800; font-size: 22px; letter-spacing: 0.04em; text-transform: uppercase; }
+.verdict-head .stamp { font-size: 16px; border-width: 3px; }
+.fixes { margin: 0; padding-left: 22px; font-size: 12.5px; display: flex; flex-direction: column; gap: 6px; }
+.fixes li::marker { font-weight: 700; }
+.fixes.old { color: var(--dim-text); margin-top: 6px; }
+.old-round + .old-round { margin-top: 6px; }
+.missing { font-size: 12px; color: var(--red); }
+.missing ul { margin: 4px 0 0; padding-left: 18px; }
+
+/* production log */
+.prodlog { height: 100%; display: flex; flex-direction: column; min-height: 0; }
+.prodlog .shelf-head { align-items: center; }
+.log-lines {
+ flex: 1; min-height: 0; overflow-y: auto; padding: 2px 0 12px; font-size: 12.5px;
+ background-image: repeating-linear-gradient(to bottom, transparent 0 calc(1.6em - 1px), rgba(203, 191, 163, 0.5) calc(1.6em - 1px) 1.6em);
+ scrollbar-width: thin; scrollbar-color: var(--rule) transparent;
+}
+.ll { display: grid; grid-template-columns: 62px 104px minmax(0, 1fr); gap: 10px; line-height: 1.6em; animation: fadein 0.4s var(--ease); }
+.ll-t { color: var(--dim-text); }
+.ll-k { font-family: var(--font-head); font-weight: 700; letter-spacing: 0.1em; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.ll-x { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.ll.tool .ll-k { color: var(--dim-text); }
+.ll.note .ll-x { white-space: normal; font-style: italic; }
+.ll.milestone { font-weight: 700; }
+.ll.milestone .ll-k::before { content: "■ " / ""; }
+.ll.critic .ll-k, .ll.critic .ll-x { color: var(--red); }
+.ll.critic .ll-x { white-space: normal; }
+.ll.system .ll-k { color: var(--ink); }
+.ll img { height: 1.3em; width: auto; vertical-align: -0.3em; margin-left: 8px; border: 1px solid var(--ink); }
+.ll.cursor .caret { display: inline-block; width: 8px; height: 1.1em; vertical-align: -0.2em; background: var(--ink); animation: blink 1s steps(2) infinite; }
+.earlier { display: block; margin: 0 0 6px 72px; }
+@media (max-width: 760px) {
+ .studio.builder { grid-template-rows: auto auto 64vh 320px auto; }
+ .ll { grid-template-columns: 52px 70px minmax(0, 1fr); gap: 6px; }
+ .mode-switch { display: none; }
+}
+.studio.builder { grid-template-columns: 300px minmax(0, 1fr) 370px; }
+.studio.builder.right-closed { grid-template-columns: 300px minmax(0, 1fr) 0px; }
+.studio.builder .plan-panel { width: 370px; }
+.scores { table-layout: fixed; }
+.scores col.lbl, .scores thead th:first-child { width: 112px; }
+.scores tbody th { white-space: normal; line-height: 1.2; }
+.scores th, .scores td { padding: 3px 3px; }
+.scores sup { font-size: 9px; }
+@media (max-width: 1180px) { .studio.builder { grid-template-columns: 270px minmax(0, 1fr) 0; } }
+@media (max-width: 760px) { .studio.builder { grid-template-columns: minmax(0, 1fr); } .studio.builder .plan-panel { width: auto; } }
+.live-tag { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
+
+/* ---------------------------------------------------------------- hit targets
+ Every control is at least 40px tall on desktop, 44px on touch screens, without changing the call-sheet look. */
+:root { --hit: 40px; }
+@media (max-width: 760px), (pointer: coarse) { :root { --hit: 44px; } }
+.speeds button, .seg button, .seg.small button, .chips button, .vp-tab, .follow, .dials-head, .dial-reset,
+.text-btn, .secondary, .primary {
+ min-height: var(--hit);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+}
+.speeds button { padding: 0 12px; }
+.seg.small button { padding: 0 14px; font-size: 12.5px; }
+.chips { gap: 6px; }
+.chips button { padding: 0 12px; }
+.vp-tab { padding: 0 12px; }
+.text-btn { padding: 0 6px; }
+.dials-head { padding: 0 10px; }
+.dial-reset { padding: 0 10px; }
+.dial-range input[type="range"] { height: var(--hit); }
+.strip button { width: 80px; }
+.toolbar { flex-wrap: wrap; row-gap: 4px; }
+.dials-built { margin-top: 10px; }
+.dials-built caption { text-align: left; font-family: var(--font-head); font-weight: 700; letter-spacing: 0.14em; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--ink); padding-bottom: 2px; }
+.dials-built th { text-transform: capitalize; font-weight: 400; text-align: left; vertical-align: top; padding: 4px 8px 4px 0; border-bottom: 1px dashed var(--rule); white-space: nowrap; }
+.dials-built td { padding: 4px 0; border-bottom: 1px dashed var(--rule); }
+.dial-note { display: block; color: var(--dim-text); font-size: 11.5px; }
+
+/* ---------------------------------------------------------------- shot orders (scene to images / video) */
+.shots-order { display: flex; flex-direction: column; gap: 10px; margin: 6px 0 18px; }
+.shots-previews { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 6px; }
+.shots-previews button { display: flex; flex-direction: column; gap: 3px; padding: 3px; background: none; border: 1px solid var(--rule); text-align: left; font-size: 11px; color: var(--dim-text); min-height: var(--hit); }
+.shots-previews button.on { border: 2px solid var(--ink); color: var(--ink); }
+.shots-previews img { width: 100%; aspect-ratio: 2.39; object-fit: cover; display: block; }
+.shots-describe { display: flex; gap: 6px; }
+.shots-describe input { flex: 1; min-width: 0; min-height: var(--hit); border: 1px solid var(--ink); background: var(--paper); padding: 0 8px; }
+.shots-list { margin: 0; padding-left: 18px; font-size: 12.5px; }
+.shots-settings { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+.field.inline { flex-direction: row; align-items: center; gap: 6px; }
+.field.inline input { width: 64px; min-height: var(--hit); }
+.shots-log { margin: 0; padding-left: 18px; font-size: 12px; max-height: 260px; overflow-y: auto; }
+.shots-log img { display: block; width: 100%; margin: 4px 0; border: 1px solid var(--rule); }
+.shots-out { display: flex; flex-direction: column; gap: 6px; }
+.shots-out img, .shots-out video { width: 100%; border: 1px solid var(--ink); display: block; }
+
+/* ---------------------------------------------------------------- product switch (AnyAll) */
+.product-switch select {
+ appearance: none; -webkit-appearance: none; background: transparent; border: 0; padding: 0 22px 0 0; margin: 0;
+ font-family: var(--font-head); font-weight: 800; font-size: 26px; line-height: 1.05; text-transform: uppercase;
+ color: var(--ink); cursor: pointer; min-height: var(--hit); max-width: 100%;
+ background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%);
+ background-position: right 8px center, right 2px center; background-size: 6px 6px; background-repeat: no-repeat;
+}
+.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+/* scouting previews: 2.39 frames, bigger cells than the contact sheet */
+.contact.scouting { grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); }
+.contact.scouting button { aspect-ratio: 2.39; }
+.contact.scouting figcaption { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
+
+/* ---------------------------------------------------------------- info tips (ⓘ) */
+.infotip { position: relative; display: inline-flex; align-items: center; vertical-align: middle; margin-left: 4px; }
+.infotip-i {
+ display: inline-flex; align-items: center; justify-content: center; width: 15px; height: 15px; border-radius: 50%;
+ border: 1px solid currentColor; font: italic 700 10px/1 Georgia, "Times New Roman", serif; color: var(--dim-text);
+ cursor: help; text-transform: none; letter-spacing: 0;
+}
+.infotip-i:hover, .infotip-i:focus-visible { color: var(--ink); outline: none; background: var(--paper); }
+.infotip-box {
+ position: absolute; left: 50%; top: calc(100% + 6px); transform: translateX(-50%); z-index: 40; width: max-content;
+ max-width: min(280px, 80vw); background: var(--ink); color: var(--paper); padding: 8px 10px; font: 400 12px/1.45 var(--font-body, inherit);
+ text-transform: none; letter-spacing: 0; white-space: normal; text-align: left; box-shadow: 0 4px 14px rgb(0 0 0 / 0.18);
+}
+.infotip-box::before { content: ""; position: absolute; top: -5px; left: 50%; transform: translateX(-50%); border: 5px solid transparent; border-top: 0; border-bottom-color: var(--ink); }
+
+/* ---------------------------------------------------------------- lightbox */
+.lightbox {
+ position: fixed; inset: 0; z-index: 100; background: rgb(20 18 14 / 0.94); color: #f3eee2;
+ display: grid; grid-template-columns: 64px minmax(0, 1fr) 64px; grid-template-rows: auto minmax(0, 1fr) auto;
+ padding: env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px) env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px);
+ animation: fadein 0.15s ease;
+}
+.lightbox-top { grid-column: 1 / -1; display: flex; align-items: center; gap: 18px; padding: 10px 16px; font-size: 12.5px; }
+.lightbox-top .text-btn { color: #f3eee2; text-decoration-color: rgb(243 238 226 / 0.4); }
+.lightbox-count { font-family: var(--font-head); font-weight: 800; letter-spacing: 0.12em; font-size: 16px; }
+.lightbox-keys { opacity: 0.6; flex: 1; }
+.lightbox-close { background: none; border: 1px solid rgb(243 238 226 / 0.5); color: inherit; font-size: 22px; line-height: 1; width: 44px; height: 44px; cursor: pointer; }
+.lightbox-figure { grid-row: 2; grid-column: 2; margin: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 0; gap: 8px; }
+.lightbox-figure img { max-width: 100%; max-height: calc(100% - 40px); object-fit: contain; display: block; box-shadow: 0 10px 40px rgb(0 0 0 / 0.5); }
+.lightbox-figure figcaption { font-size: 13px; max-width: 90ch; text-align: center; opacity: 0.85; }
+.lightbox-nav {
+ grid-row: 2; align-self: center; justify-self: center; width: 52px; height: 88px; background: none; border: 0; color: inherit;
+ font-size: 56px; line-height: 1; cursor: pointer; opacity: 0.7;
+}
+.lightbox-nav:hover, .lightbox-nav:focus-visible { opacity: 1; background: rgb(243 238 226 / 0.08); }
+.lightbox-nav.prev { grid-column: 1; }
+.lightbox-nav.next { grid-column: 3; }
+.lightbox-strip { grid-column: 1 / -1; display: flex; gap: 6px; overflow-x: auto; padding: 8px 16px 12px; justify-content: safe center; }
+.lightbox-strip button { flex: 0 0 auto; width: 72px; aspect-ratio: 16 / 9; padding: 0; border: 1px solid rgb(243 238 226 / 0.25); background: none; opacity: 0.55; cursor: pointer; }
+.lightbox-strip button.on { opacity: 1; border: 2px solid #f3eee2; }
+.lightbox-strip img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.live-open { all: unset; display: contents; cursor: zoom-in; }
+.contact button, .result-still { cursor: zoom-in; }
+@media (max-width: 620px) {
+ .lightbox { grid-template-columns: 40px minmax(0, 1fr) 40px; }
+ .lightbox-keys { display: none; }
+ .lightbox-nav { width: 40px; font-size: 40px; }
+}
+
+/* ---------------------------------------------------------------- gallery (everyone's builds, from storage) */
+.gallery-page { min-height: 100vh; display: flex; flex-direction: column; }
+.gallery-slate { grid-template-columns: repeat(5, minmax(0, 1fr)) 1.2fr; }
+.gallery-page .toolbar { gap: 12px; }
+.seg-link { flex: 1; display: inline-flex; align-items: center; justify-content: center; min-height: var(--hit); padding: 0 14px; font-size: 12.5px; color: var(--ink); text-decoration: none; border-right: 1px solid var(--ink); white-space: nowrap; }
+.seg-link:last-child { border-right: 0; }
+.seg-link.on { background: var(--ink); color: var(--paper); }
+a.text-btn { display: inline-flex; align-items: center; min-height: var(--hit); }
+.gallery-main { flex: 1; padding: 14px 20px 32px; }
+.gallery-empty { margin: 80px auto; }
+.gallery-grid { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 14px; }
+.gallery-card { background: var(--card); border: 1px solid var(--ink); }
+.gallery-card > a { display: flex; flex-direction: column; color: inherit; text-decoration: none; height: 100%; min-height: var(--hit); }
+.gallery-card > a:hover .gallery-title { text-decoration: underline; text-underline-offset: 3px; text-decoration-color: var(--rule); }
+.gallery-card > a:hover { outline: 2px solid var(--ink); outline-offset: -1px; }
+.gallery-cover { position: relative; aspect-ratio: 16 / 9; background: var(--paper-2); border-bottom: 1px solid var(--ink); overflow: hidden; }
+.gallery-cover > img:first-child { width: 100%; height: 100%; object-fit: cover; display: block; filter: sepia(0.12); }
+.gallery-nocover { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--dim-text); font-size: 12px; }
+.gallery-ref { position: absolute; left: 6px; bottom: 6px; width: 22%; aspect-ratio: 16 / 9; object-fit: cover; border: 2px solid var(--card); box-shadow: 0 0 0 1px var(--ink); }
+.gallery-stamp { position: absolute; right: 8px; top: 8px; background: rgb(255 253 246 / 0.85); padding: 2px 4px; }
+.rolling-tag { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-head); font-weight: 800; letter-spacing: 0.12em; font-size: 12px; text-transform: uppercase; color: var(--red); }
+.rolling-tag::before { content: ""; width: 7px; height: 7px; background: var(--red); border-radius: 50%; animation: blink 1.2s steps(2) infinite; }
+.gallery-body { padding: 8px 10px 10px; display: flex; flex-direction: column; gap: 4px; }
+.gallery-title { margin: 0; font-size: 13px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; min-height: 2.9em; }
+.gallery-meta { margin: 0; display: flex; gap: 10px; flex-wrap: wrap; font-size: 12px; color: var(--dim-text); }
+.gallery-meta b { font-family: var(--font-head); font-weight: 800; letter-spacing: 0.08em; color: var(--ink); font-size: 13px; }
+.gallery-sub { margin: 0; font-size: 11.5px; color: var(--dim-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-height: 1.4em; }
+.gallery-card.status-stopped .gallery-cover > img:first-child { filter: sepia(0.3) grayscale(0.4); }
+@media (max-width: 760px) {
+ .gallery-slate { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+ .gallery-slate .slate-cell:nth-child(n + 4), .gallery-slate .slate-stripe { display: none; }
+ .gallery-main { padding: 12px 16px 28px; }
+ .gallery-grid { grid-template-columns: 1fr; }
+}
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
new file mode 100644
index 0000000..07ee570
--- /dev/null
+++ b/web/app/layout.tsx
@@ -0,0 +1,19 @@
+import type { Metadata } from "next";
+import { Barlow_Condensed, Courier_Prime } from "next/font/google";
+import "./globals.css";
+
+const type = Courier_Prime({ subsets: ["latin"], weight: ["400", "700"], variable: "--font-type", display: "swap" });
+const head = Barlow_Condensed({ subsets: ["latin"], weight: ["500", "700", "800"], variable: "--font-head", display: "swap" });
+
+export const metadata: Metadata = {
+ title: "AnyScene",
+ description: "Turn a reference image into a photoreal Blender scene, and watch it being built.",
+};
+
+export default function RootLayout({ children }: { children: React.ReactNode }) {
+ return (
+ <html lang="en" className={`${type.variable} ${head.variable}`}>
+ <body>{children}</body>
+ </html>
+ );
+}
diff --git a/web/app/page.tsx b/web/app/page.tsx
new file mode 100644
index 0000000..b564ae3
--- /dev/null
+++ b/web/app/page.tsx
@@ -0,0 +1,10 @@
+import { Suspense } from "react";
+import Shell from "@/components/Shell";
+
+export default function Page() {
+ return (
+ <Suspense>
+ <Shell />
+ </Suspense>
+ );
+}
diff --git a/web/components/BuilderInputs.tsx b/web/components/BuilderInputs.tsx
new file mode 100644
index 0000000..24b3def
--- /dev/null
+++ b/web/components/BuilderInputs.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { useRef, useState } from "react";
+import Dials, { type DialValues } from "./Dials";
+import InfoTip, { HELP } from "./InfoTip";
+
+export interface BuilderInputsState {
+ file: File | null;
+ previewUrl: string;
+ prompt: string;
+ effort: string;
+ dials: DialValues;
+ floorPlan: File | null;
+}
+
+interface Props {
+ value: BuilderInputsState;
+ onChange: (v: BuilderInputsState) => void;
+ disabled: boolean;
+ canBuild: boolean;
+ building: boolean;
+ onBuild: () => void;
+}
+
+export default function BuilderInputs({ value, onChange, disabled, canBuild, building, onBuild }: Props) {
+ const fileRef = useRef<HTMLInputElement>(null);
+ const [over, setOver] = useState(false);
+ const set = (patch: Partial<BuilderInputsState>) => onChange({ ...value, ...patch });
+ const take = (f: File | undefined) => {
+ if (!f || !f.type.startsWith("image/")) return;
+ if (value.previewUrl.startsWith("blob:")) URL.revokeObjectURL(value.previewUrl);
+ set({ file: f, previewUrl: URL.createObjectURL(f) });
+ };
+
+ return (
+ <div className="inputs">
+ <h3 className="sheet-h">Reference plate</h3>
+ <div
+ className={`drop ${over ? "over" : ""} ${value.previewUrl ? "has" : ""}`}
+ onDragOver={(e) => {
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ if (!disabled) take(e.dataTransfer.files?.[0]);
+ }}
+ onClick={() => !disabled && fileRef.current?.click()}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && fileRef.current?.click()}
+ aria-label="Reference image: drop or choose a file"
+ >
+ {value.previewUrl ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={value.previewUrl} alt="Reference" />
+ ) : (
+ <div className="drop-empty">
+ <span className="drop-title">Drop the reference plate</span>
+ <span className="drop-hint">or click to choose. The builder matches its look, props and light.</span>
+ </div>
+ )}
+ {value.previewUrl && <span className="drop-change">Replace</span>}
+ <input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => take(e.target.files?.[0])} />
+ </div>
+ <p className="cap">
+ {value.previewUrl ? `plate 1 of 1: ${value.file ? value.file.name : "recorded reference"}` : "no plate loaded"}
+ </p>
+
+ <label className="field">
+ <span className="field-label">
+ Floor plan <span className="dim">optional</span>{" "}
+ <InfoTip label="the floor plan" text="A sketch, photo or drawing of the layout. It decides the room's shape and where things go; the reference decides how they look." />
+ </span>
+ <input
+ id="floor-plan"
+ type="file"
+ accept="image/*"
+ disabled={disabled}
+ onChange={(e) => set({ floorPlan: e.target.files?.[0] ?? null })}
+ />
+ </label>
+
+ <h3 className="sheet-h">Direction</h3>
+ <label className="field">
+ <span className="field-label">Prompt</span>
+ <textarea
+ rows={3}
+ value={value.prompt}
+ disabled={disabled}
+ placeholder="Anything the image can't show: it's 1 AM, rain outside, twice as deep"
+ onChange={(e) => set({ prompt: e.target.value })}
+ />
+ </label>
+ <Dials
+ value={value.dials}
+ onChange={(dials) => set({ dials })}
+ disabled={disabled}
+ note="Set a dial to override the reference; AUTO reads it from the image. The scene is delivered as a rig, so dials can be changed after the build."
+ />
+ <label className="field">
+ <span className="field-label">Builder effort <InfoTip label="builder effort" text={HELP.effort} /></span>
+ <select value={value.effort} disabled={disabled} onChange={(e) => set({ effort: e.target.value })}>
+ {["low", "medium", "high", "xhigh", "max"].map((o) => (
+ <option key={o} value={o}>
+ {o}
+ </option>
+ ))}
+ </select>
+ </label>
+ <button className="primary" disabled={!canBuild} onClick={onBuild}>
+ {building ? "Building" : "Build the scene"}
+ </button>
+ <p className="fine">One agent builds it end to end and loops with a critic. Up to 2 hours.</p>
+ </div>
+ );
+}
diff --git a/web/components/BuilderResult.tsx b/web/components/BuilderResult.tsx
new file mode 100644
index 0000000..5699b36
--- /dev/null
+++ b/web/components/BuilderResult.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import { useState } from "react";
+import { clock, type BuilderResponse, type BuilderState } from "@/lib/builder";
+
+/** Dailies: the stills, the package, and what the build cost. */
+export default function BuilderResult({ res, run, onOpen }: { res: BuilderResponse; run: BuilderState; onOpen?: (i: number) => void }) {
+ const [i, setI] = useState(0);
+ const still = res.stills[i];
+ const last = res.critiques[res.critiques.length - 1] ?? run.critiques[run.critiques.length - 1];
+ const tools = run.lines.filter((l) => l.kind === "tool").length;
+ return (
+ <div className="result">
+ <div className="result-main">
+ {still ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img className="result-still" src={still} alt={`Still ${i + 1}`} onClick={() => onOpen?.(i)} style={{ cursor: onOpen ? "zoom-in" : undefined }} />
+ ) : (
+ <div className="empty">
+ <p>No stills came back.</p>
+ </div>
+ )}
+ {res.stills.length > 1 && (
+ <div className="result-thumbs">
+ {res.stills.map((s, k) => (
+ <button key={s} className={k === i ? "on" : ""} onClick={() => setI(k)} aria-label={`Still ${k + 1}`}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={s} alt="" />
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="result-side">
+ <div className="result-head">
+ <span className="serif">{res.build_id || run.buildId}</span>
+ <span className="muted">
+ {res.stills.length} stills, {res.panorama_urls?.length ?? 0} panoramas{res.scene_glb_url ? ", scene glTF" : ""}
+ </span>
+ </div>
+ {res.package_url ? (
+ <a className="primary as-link" href={res.package_url} download>
+ Download scene package
+ </a>
+ ) : (
+ <span className="muted">No package in this build.</span>
+ )}
+ {res.scene_blend_url && (
+ <a className="secondary as-link" href={res.scene_blend_url} download>
+ scene.blend only
+ </a>
+ )}
+ {res.scene_glb_url && (
+ <a className="secondary as-link" href={res.scene_glb_url} download>
+ scene.glb
+ </a>
+ )}
+ <table className="timings">
+ <caption>Wrap report</caption>
+ <tbody>
+ <tr>
+ <th>Agent cost</th>
+ <td>{res.agent_cost_usd != null ? `$${res.agent_cost_usd.toFixed(2)}` : "n/a"}</td>
+ </tr>
+ <tr>
+ <th>Minutes</th>
+ <td>{res.minutes != null ? res.minutes.toFixed(1) : clock(run.lastT)}</td>
+ </tr>
+ <tr>
+ <th>Critic rounds</th>
+ <td>{res.critiques.length || run.critiques.length}</td>
+ </tr>
+ <tr>
+ <th>Last verdict</th>
+ <td className={last?.passed ? "" : "bad"}>{last ? (last.passed ? "PASS" : "NOT YET") : "none"}</td>
+ </tr>
+ <tr className="server">
+ <th>Tool calls</th>
+ <td>{tools}</td>
+ </tr>
+ <tr className="server">
+ <th>Frames reported</th>
+ <td>{run.previews.length}</td>
+ </tr>
+ </tbody>
+ </table>
+ {res.missing?.length > 0 && (
+ <div className="missing">
+ <b>Missing</b>
+ <ul>
+ {res.missing.map((m) => (
+ <li key={m}>{m}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {res.dials && Object.keys(res.dials).length > 0 && (
+ <table className="kv dials-built">
+ <caption>Dials as built</caption>
+ <tbody>
+ {Object.entries(res.dials).map(([k, v]) => {
+ // the agent decides the shape: a bare value, or {value, ...what it controls}
+ const o = v && typeof v === "object" ? (v as Record<string, unknown>) : { value: v };
+ const rest = Object.entries(o).filter(([kk]) => kk !== "value");
+ return (
+ <tr key={k}>
+ <th>{k.replace(/_/g, " ")}</th>
+ <td>
+ <b>{String(o.value ?? "")}</b>
+ {rest.map(([kk, vv]) => (
+ <span className="dial-note" key={kk}>
+ {typeof vv === "string" ? vv : JSON.stringify(vv)}
+ </span>
+ ))}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/BuilderSchedule.tsx b/web/components/BuilderSchedule.tsx
new file mode 100644
index 0000000..6f98851
--- /dev/null
+++ b/web/components/BuilderSchedule.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import { clock, MILESTONE_LABELS, type BuilderState } from "@/lib/builder";
+import Stamp from "./Stamp";
+import InfoTip, { HELP } from "./InfoTip";
+
+/** Milestones as a call-sheet schedule. The agent picks its milestones; the usual ones are listed up front so the
+ * shape of the day is visible, and any it adds are appended. */
+export default function BuilderSchedule({ run, now }: { run: BuilderState; now: number }) {
+ const idle = run.status === "idle";
+ const ended = run.status === "done" || run.status === "failed" || run.doneAt !== undefined;
+ const last = run.critiques[run.critiques.length - 1];
+ let n = 0;
+ return (
+ <section className="schedule" aria-label="Schedule">
+ <h3 className="sheet-h">
+ Schedule <span className="sheet-h-sub">builder</span> <InfoTip label="the schedule" text={HELP.schedule} />
+ </h3>
+ <table className="sched">
+ <thead>
+ <tr>
+ <th scope="col">#</th>
+ <th scope="col">Dept</th>
+ <th scope="col">Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr className={run.received !== undefined ? "done" : "pending"}>
+ <td>{n++}</td>
+ <td>Call received</td>
+ <td className="st">{run.received !== undefined ? <span className="wrapped">WRAPPED {clock(run.received)}</span> : <span className="standby">STANDBY</span>}</td>
+ </tr>
+ {run.order.map((stage) => {
+ const m = run.milestones[stage];
+ const isCur = run.current === stage && !ended;
+ const status = idle ? "pending" : !m ? (ended ? "skipped" : "pending") : isCur ? "running" : "done";
+ return (
+ <tr key={stage} className={status}>
+ <td>{n++}</td>
+ <td>
+ <div className="dept">
+ {MILESTONE_LABELS[stage] ?? stage.replace(/_/g, " ")}
+ {m && m.takes > 1 ? <span className="take"> take {m.takes}</span> : null}
+ </div>
+ {isCur && m.message && <div className="dept-msg">{m.message}</div>}
+ </td>
+ <td className="st">
+ {status === "running" && (
+ <>
+ <Stamp tilt={-5}>ROLLING</Stamp>
+ <span className="st-sub">{clock(now - m.start)}</span>
+ </>
+ )}
+ {status === "done" && <span className="wrapped">WRAPPED {clock((m.end ?? now) - m.start)}</span>}
+ {status === "pending" && <span className="standby">STANDBY</span>}
+ {status === "skipped" && <span className="standby">N/A</span>}
+ </td>
+ </tr>
+ );
+ })}
+ <tr className={run.criticBusy ? "running" : last ? "done" : "pending"}>
+ <td>{n++}</td>
+ <td>
+ <div className="dept">Critic review</div>
+ {last && <div className="dept-msg">round {last.round}</div>}
+ </td>
+ <td className="st">
+ {run.criticBusy ? (
+ <Stamp tilt={-5}>IN REVIEW</Stamp>
+ ) : last ? (
+ last.passed ? (
+ <span className="wrapped">PASSED</span>
+ ) : (
+ <span className="wrapped notyet">NOT YET</span>
+ )
+ ) : (
+ <span className="standby">STANDBY</span>
+ )}
+ </td>
+ </tr>
+ <tr className={run.packagedAt !== undefined ? "done" : run.doneAt !== undefined ? "running" : "pending"}>
+ <td>{n++}</td>
+ <td>Package</td>
+ <td className="st">
+ {run.packagedAt !== undefined ? (
+ <span className="wrapped">WRAPPED {clock(run.packagedAt - (run.doneAt ?? run.packagedAt))}</span>
+ ) : run.doneAt !== undefined && run.status === "running" ? (
+ <Stamp tilt={-5}>ROLLING</Stamp>
+ ) : (
+ <span className="standby">STANDBY</span>
+ )}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ {run.status === "failed" && run.error && <p className="error-note">{run.error}</p>}
+ </section>
+ );
+}
diff --git a/web/components/BuilderStudio.tsx b/web/components/BuilderStudio.tsx
new file mode 100644
index 0000000..53f6f73
--- /dev/null
+++ b/web/components/BuilderStudio.tsx
@@ -0,0 +1,406 @@
+"use client";
+
+import { useCallback, useEffect, useReducer, useRef, useState } from "react";
+import { useSearchParams } from "next/navigation";
+import { builderReducer, clock, initialBuilder, type BuilderResponse } from "@/lib/builder";
+import { LiveSource, ReplaySource, getAccessKey, setAccessKey, type Source } from "@/lib/sources";
+import { BUILDER_APP } from "@/lib/apps";
+import { galleryApp, galleryEvents, toBuilderResponse, type GalleryItem, type GalleryKind } from "@/lib/gallery";
+import BuilderInputs, { type BuilderInputsState } from "./BuilderInputs";
+import { setDials } from "./Dials";
+import BuilderSchedule from "./BuilderSchedule";
+import ShotsOrder from "./ShotsOrder";
+import ProductSwitch from "./ProductSwitch";
+import BuilderViewport, { type BTab } from "./BuilderViewport";
+import ProductionLog from "./ProductionLog";
+import CriticPanel from "./CriticPanel";
+import Stamp from "./Stamp";
+
+const SPEEDS = [1, 4, 16, 32, 64];
+
+/** The agent builder (NEXT_PUBLIC_ANYSCENE_APP): one request builds the whole scene; the agent's log streams in, its
+ * milestones fill the schedule, the critic scores each round. */
+export default function BuilderStudio() {
+ const params = useSearchParams();
+ const replayName = params.get("replay");
+ const watchId = params.get("watch");
+ // ?open=<build id>: a build from the gallery, read from storage (anyone's build, running or finished)
+ const openId = params.get("open");
+ const openKind: GalleryKind = params.get("kind") === "kit" ? "kit" : "scene";
+ const galleryOverride = params.get("gallery_app");
+ const openApp = galleryApp(openKind, galleryOverride);
+ const galleryHref = `/?${new URLSearchParams({ view: "gallery", ...(openKind === "kit" ? { kind: "kit" } : {}), ...(galleryOverride ? { gallery_app: galleryOverride } : {}) })}`;
+ const [opened, setOpened] = useState<GalleryItem | null>(null);
+ const auto = params.get("auto") === "1";
+ const initialSpeed = Math.max(0.25, Math.min(256, Number(params.get("speed")) || 1));
+
+ const [source, setSource] = useState<Source | null>(null);
+ const [sourceError, setSourceError] = useState("");
+ const [speed, setSpeed] = useState(initialSpeed);
+ const [inputs, setInputs] = useState<BuilderInputsState>({ file: null, previewUrl: "", prompt: "", effort: "medium", dials: {}, floorPlan: null });
+ const [run, dispatch] = useReducer(builderReducer, undefined, () => initialBuilder());
+ const [res, setRes] = useState<BuilderResponse | null>(null);
+ const [endAt, setEndAt] = useState<number | null>(null);
+ const [tab, setTab] = useState<BTab>("live");
+ const [follow, setFollow] = useState(true);
+ const followRef = useRef(true);
+ followRef.current = follow;
+ const [rightOpen, setRightOpen] = useState(true);
+ const [keyOpen, setKeyOpen] = useState(false);
+ const [keyDraft, setKeyDraft] = useState("");
+ const [needsKey, setNeedsKey] = useState(false);
+ const [, tick] = useState(0);
+ const refUrl = useRef("");
+ // event times are the builder's own clock (from when the worker started); the slate clock counts from the click
+ const offset = useRef<number | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ if (replayName) {
+ ReplaySource.load(replayName, initialSpeed)
+ .then((s) => {
+ if (cancelled) return;
+ setSource(s);
+ setInputs((i) => ({ ...i, previewUrl: s.referenceUrl }));
+ refUrl.current = s.referenceUrl;
+ })
+ .catch((e) => setSourceError(String(e.message || e)));
+ } else setSource(new LiveSource());
+ return () => {
+ cancelled = true;
+ };
+ }, [replayName, initialSpeed]);
+
+ useEffect(() => {
+ if (source instanceof ReplaySource) source.speed = speed;
+ }, [source, speed]);
+
+ const running = run.status === "running";
+ useEffect(() => {
+ if (!running) return;
+ const id = setInterval(() => tick((n) => n + 1), 250);
+ return () => clearInterval(id);
+ }, [running]);
+ const now = endAt ?? (run.status === "idle" || !source ? 0 : source.clock());
+ const serverNow = offset.current === null ? run.lastT : Math.max(run.lastT, now - offset.current);
+
+ // follow: the newest image goes to the live view; the result to the stills
+ const lastPreview = run.previews[run.previews.length - 1]?.url;
+ useEffect(() => {
+ if (followRef.current && lastPreview) setTab("live");
+ }, [lastPreview]);
+
+ const doBuild = useCallback(async () => {
+ if (!source) return;
+ setFollow(true);
+ setRes(null);
+ setEndAt(null);
+ setTab("live");
+ offset.current = null;
+ dispatch({ type: "start" });
+ try {
+ let url = refUrl.current;
+ if (inputs.file && source.mode === "live") {
+ url = await source.uploadReference(inputs.file);
+ refUrl.current = url;
+ }
+ if (!url) throw new Error("Add a reference image first.");
+ const floorPlanUrl = inputs.floorPlan && source.mode === "live" ? await source.uploadReference(inputs.floorPlan) : undefined;
+ const r = await source.builder(
+ { reference_image_urls: [url], prompt: inputs.prompt, effort: inputs.effort, scene: "scene", dials: setDials(inputs.dials), floor_plan_url: floorPlanUrl },
+ {
+ onEvent: (ev) => {
+ if (offset.current === null && typeof ev.t === "number") offset.current = source.clock() - ev.t;
+ dispatch({ type: "event", ev });
+ },
+ },
+ );
+ if ((r as { _partial?: boolean })._partial) {
+ dispatch({ type: "ended" });
+ setEndAt(source.clock());
+ return;
+ }
+ setRes(r);
+ dispatch({ type: "result", res: r });
+ setEndAt(source.clock());
+ if (followRef.current) setTab("stills");
+ } catch (e) {
+ const msg = errorMessage(e);
+ if (/access key|proxy is closed/i.test(msg)) setNeedsKey(true);
+ dispatch({ type: "fail", message: msg });
+ setEndAt(source.clock());
+ }
+ }, [source, inputs]);
+
+ // ?watch=<fal request id>: follow a build started elsewhere. Its "received" event carries the request's inputs
+ // (reference, prompt, dials, effort), which fill the form so the page shows what the build was given.
+ const watchStarted = useRef(false);
+ useEffect(() => {
+ if (!watchId || !(source instanceof LiveSource) || watchStarted.current) return;
+ watchStarted.current = true;
+ setFollow(true);
+ offset.current = null;
+ dispatch({ type: "start" });
+ source
+ .watchBuilder(watchId, {
+ onEvent: (ev) => {
+ if (typeof ev.t === "number") offset.current = source.clock() - ev.t;
+ const given = ev as unknown as { reference_urls?: string[]; prompt?: string; dials?: Record<string, number | string>; effort?: string };
+ if (given.reference_urls?.length)
+ setInputs((i) => ({
+ ...i,
+ previewUrl: given.reference_urls![0],
+ prompt: given.prompt ?? i.prompt,
+ effort: given.effort ?? i.effort,
+ dials: given.dials ?? i.dials,
+ }));
+ dispatch({ type: "event", ev });
+ },
+ })
+ .then((r) => {
+ setRes(r);
+ dispatch({ type: "result", res: r });
+ setEndAt(source.clock());
+ if (followRef.current) setTab("stills");
+ })
+ .catch((e) => {
+ const msg = errorMessage(e);
+ if (/access key|proxy is closed/i.test(msg)) setNeedsKey(true);
+ dispatch({ type: "fail", message: msg });
+ setEndAt(source.clock());
+ });
+ }, [watchId, source]);
+ // ?open=<id>: replay the build's stored events, then (while it runs) poll for new ones every few seconds
+ const openStarted = useRef(false);
+ useEffect(() => {
+ if (!openId || !(source instanceof LiveSource) || openStarted.current) return;
+ openStarted.current = true;
+ let stop = false;
+ setFollow(true);
+ offset.current = null;
+ dispatch({ type: "start" });
+ (async () => {
+ let after = 0;
+ let given = false;
+ for (;;) {
+ let page;
+ try {
+ page = await galleryEvents(openKind, openApp, openId, after);
+ } catch (e) {
+ if (stop) return;
+ const msg = errorMessage(e);
+ if (/access key|proxy is closed/i.test(msg)) setNeedsKey(true);
+ dispatch({ type: "fail", message: msg });
+ setEndAt(source.clock());
+ return;
+ }
+ if (stop) return;
+ const s = page.summary;
+ setOpened(s);
+ if (!given) {
+ given = true;
+ setInputs((i) => ({
+ ...i,
+ previewUrl: s.reference_urls?.[0] || i.previewUrl,
+ prompt: s.prompt ?? i.prompt,
+ effort: s.effort || i.effort,
+ dials: s.dials ?? i.dials,
+ }));
+ }
+ for (const ev of page.events) dispatch({ type: "event", ev });
+ const lastT = page.events.length ? page.events[page.events.length - 1].t : undefined;
+ if (s.status === "running" && typeof lastT === "number") offset.current = source.clock() - lastT;
+ after = page.next;
+ if (page.more) continue;
+ if (s.status !== "running") {
+ offset.current = null;
+ const r = toBuilderResponse(openKind, page.response, openId);
+ if (r) {
+ setRes(r);
+ dispatch({ type: "result", res: r });
+ }
+ if (s.status === "stopped") dispatch({ type: "fail", message: "This build stopped before it delivered (its worker went away). What it made is here." });
+ setEndAt(source.clock());
+ // a finished build opens on its results; follow off, or the replayed frames would pull the view back to live
+ if (followRef.current) {
+ setFollow(false);
+ setTab(r?.stills.length ? "stills" : r?.previews?.length ? "previews" : "live");
+ }
+ return;
+ }
+ await new Promise((r) => setTimeout(r, 4000));
+ if (stop) return;
+ }
+ })();
+ return () => {
+ stop = true;
+ openStarted.current = false;
+ };
+ }, [openId, openKind, openApp, source]);
+
+ useEffect(() => {
+ const ref = params.get("ref");
+ if (watchId && ref) setInputs((i) => (i.previewUrl ? i : { ...i, previewUrl: ref }));
+ }, [watchId, params]);
+
+ const autoDone = useRef(false);
+ useEffect(() => {
+ if (auto && source && !autoDone.current) {
+ autoDone.current = true;
+ setTimeout(() => doBuild(), 1200);
+ }
+ }, [auto, source, doBuild]);
+
+ const replay = source instanceof ReplaySource ? source : null;
+ const round = run.critiques.length;
+ const passed = run.critiques[run.critiques.length - 1]?.passed;
+
+ return (
+ <div className={`studio builder ${rightOpen ? "" : "right-closed"}`}>
+ <header className="topbar">
+ <div className="slate" role="group" aria-label="Slate">
+ <div className="slate-cell">
+ <small>Production</small>
+ <ProductSwitch current="anyscene" />
+ </div>
+ <div className="slate-cell">
+ <small>Scene</small>
+ <b>{run.buildId ? run.buildId.replace(/^[bk]_/, "").slice(0, 6).toUpperCase() : "--"}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Take</small>
+ <b title="critic round">{String(round).padStart(2, "0")}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Roll</small>
+ <b>{inputs.effort.toUpperCase()}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Clock</small>
+ <b className="clock">{clock(watchId || openId ? serverNow : now)}</b>
+ </div>
+ <div className="slate-stripe" aria-hidden />
+ {run.status === "done" && (
+ <span className="slate-wrap">
+ <Stamp big tilt={-6}>WRAPPED</Stamp>
+ </span>
+ )}
+ {run.status === "failed" && (
+ <span className="slate-wrap">
+ <Stamp big tilt={-4}>HOLD</Stamp>
+ </span>
+ )}
+ </div>
+ <div className="toolbar">
+ {replay ? (
+ <div className="replay-ctl" title="Replaying a recorded build">
+ <span>Replay: {replay.manifest.name}</span>
+ <div className="speeds" role="group" aria-label="Replay speed">
+ {SPEEDS.map((s) => (
+ <button key={s} className={speed === s ? "on" : ""} onClick={() => setSpeed(s)} aria-pressed={speed === s}>
+ {s}x
+ </button>
+ ))}
+ </div>
+ </div>
+ ) : (
+ source && (
+ <span className="live-pill">
+ {openId ? `${opened?.status === "running" ? "Following" : "From storage"}: ${openApp} · ${openId}` : `Live: ${BUILDER_APP || "no app set (NEXT_PUBLIC_ANYSCENE_APP)"}`}
+ </span>
+ )
+ )}
+ {!replay && (
+ <a className="text-btn" href={galleryHref}>
+ {openId ? "Back to gallery" : "Gallery"}
+ </a>
+ )}
+ {!replay && (
+ <span className="key-ctl">
+ {keyOpen ? (
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ setAccessKey(keyDraft.trim());
+ setKeyOpen(false);
+ setNeedsKey(false);
+ }}
+ >
+ <input
+ type="password"
+ autoComplete="off"
+ aria-label="Access key"
+ placeholder="access key"
+ value={keyDraft}
+ onChange={(e) => setKeyDraft(e.target.value)}
+ />
+ <button className="text-btn" type="submit">
+ Save
+ </button>
+ </form>
+ ) : (
+ <button className={`text-btn ${needsKey ? "bad" : ""}`} onClick={() => setKeyOpen(true)}>
+ {needsKey ? "Access key needed" : getAccessKey() ? "Access key set" : "Access key"}
+ </button>
+ )}
+ </span>
+ )}
+ <button className="text-btn" onClick={() => setRightOpen((o) => !o)} aria-expanded={rightOpen}>
+ {rightOpen ? "Hide critic" : "Show critic"}
+ </button>
+ </div>
+ </header>
+
+ <aside className="left">
+ <BuilderInputs
+ value={inputs}
+ onChange={(v) => {
+ if (v.file !== inputs.file) refUrl.current = "";
+ setInputs(v);
+ }}
+ disabled={running}
+ canBuild={!!(inputs.file || refUrl.current) && !running && !!source}
+ building={running}
+ onBuild={doBuild}
+ />
+ {res && res.build_id && openKind === "scene" && <ShotsOrder res={res} source={source instanceof LiveSource ? source : null} />}
+ <BuilderSchedule run={run} now={serverNow} />
+ {sourceError && <p className="error-note">{sourceError}</p>}
+ </aside>
+
+ <main className="center">
+ <BuilderViewport
+ tab={tab}
+ onTab={(t) => {
+ setTab(t);
+ setFollow(false);
+ }}
+ follow={follow}
+ onFollow={() => setFollow(true)}
+ run={run}
+ res={res}
+ referenceUrl={inputs.previewUrl}
+ now={serverNow}
+ passed={passed}
+ />
+ </main>
+
+ <section className="shelf-wrap">
+ <ProductionLog run={run} />
+ </section>
+
+ <aside className="right" aria-hidden={!rightOpen}>
+ <CriticPanel run={run} />
+ </aside>
+ </div>
+ );
+}
+
+function errorMessage(e: unknown): string {
+ if (!e) return "Request failed";
+ const anyE = e as { body?: { detail?: unknown }; message?: string; status?: number };
+ const d = anyE.body?.detail;
+ if (typeof d === "string") return d;
+ if (Array.isArray(d) && d[0]?.msg) return String(d[0].msg);
+ return anyE.message || String(e);
+}
diff --git a/web/components/BuilderViewport.tsx b/web/components/BuilderViewport.tsx
new file mode 100644
index 0000000..635b976
--- /dev/null
+++ b/web/components/BuilderViewport.tsx
@@ -0,0 +1,266 @@
+"use client";
+
+import { useState } from "react";
+import { clock, MILESTONE_LABELS, type BuilderResponse, type BuilderState } from "@/lib/builder";
+import Fade from "./Fade";
+import Compare from "./Compare";
+import Pano360 from "./Pano360";
+import SceneView from "./SceneView";
+import BuilderResult from "./BuilderResult";
+import InfoTip, { HELP } from "./InfoTip";
+import Lightbox, { type LightboxItem } from "./Lightbox";
+
+export type BTab = "live" | "compare" | "previews" | "contact" | "stills" | "360";
+
+interface Props {
+ tab: BTab;
+ onTab: (t: BTab) => void;
+ follow: boolean;
+ onFollow: () => void;
+ run: BuilderState;
+ res: BuilderResponse | null;
+ referenceUrl: string;
+ now: number;
+ passed?: boolean;
+}
+
+const stageName = (s: string) => MILESTONE_LABELS[s] ?? (s === "critique" ? "Critic" : s.replace(/_/g, " "));
+
+export default function BuilderViewport(p: Props) {
+ const { tab, run, res } = p;
+ const [pinned, setPinned] = useState<string | null>(null);
+ const [view360, setView360] = useState(0);
+ const [box, setBox] = useState<{ items: LightboxItem[]; index: number } | null>(null);
+
+ const previews = run.previews;
+ const latest = previews[previews.length - 1];
+ const shown = (pinned && previews.find((x) => x.url === pinned)) || latest;
+ const stills = res?.stills ?? [];
+ // the critic's first image is the reference-angle still; that is what to hold against the plate
+ const lastCritic = [...previews].reverse().find((x) => x.stage === "critique");
+ const compareRender = stills[0] ?? lastCritic?.url ?? latest?.url;
+ // the scouting previews: named ones from the finished build, else every frame reported as a preview so far
+ const scouting: { url: string; label: string }[] = res?.previews?.length
+ ? res.previews.map((x) => ({ url: x.url, label: x.name.replace(/_/g, " ") }))
+ : previews.filter((x) => x.stage === "previews").map((x) => ({ url: x.url, label: x.message || "preview" }));
+ const panoramas = res?.panorama_urls ?? [];
+ const sceneGlb = res?.scene_glb_url ?? null;
+ const has360 = panoramas.length > 0 || !!sceneGlb;
+ const v360 = view360 >= 0 && view360 < panoramas.length ? view360 : sceneGlb ? -1 : 0;
+
+ const tabs: { id: BTab; label: string; ready: boolean; show: boolean }[] = [
+ { id: "live", label: "Live", ready: !!latest, show: true },
+ { id: "compare", label: "Compare", ready: !!(p.referenceUrl && compareRender), show: true },
+ { id: "previews", label: `Previews${scouting.length ? ` (${scouting.length})` : ""}`, ready: scouting.length > 0, show: true },
+ { id: "contact", label: "Contact sheet", ready: previews.length > 1, show: true },
+ { id: "stills", label: "Stills", ready: !!res, show: !!res },
+ { id: "360", label: "360", ready: has360, show: has360 },
+ ];
+
+ const title =
+ tab === "live"
+ ? `Camera A · ${shown ? stageName(shown.stage) : "standing by"}${pinned ? " · held frame" : " · live"}`
+ : tab === "compare"
+ ? "Plate vs camera A · reference angle"
+ : tab === "previews"
+ ? `Scouting previews · ${scouting.length}`
+ : tab === "contact"
+ ? `Contact sheet · ${previews.length} frames`
+ : tab === "stills"
+ ? "Dailies"
+ : v360 >= 0
+ ? `Camera B · 360 plate · ${v360 === 0 ? "reference angle" : `spot ${v360 + 1}`}`
+ : "Set model · glTF · free camera";
+
+ const last = run.critiques[run.critiques.length - 1];
+ const tools = run.lines.filter((l) => l.kind === "tool").length;
+ const note =
+ run.status === "idle"
+ ? ""
+ : run.criticBusy
+ ? `critic reviewing round ${run.critiques.length + 1}`
+ : last
+ ? `round ${last.round}: ${last.passed ? "passed" : "not yet"}`
+ : `${tools} tool calls`;
+
+ return (
+ <div className="viewport">
+ {box && <Lightbox items={box.items} index={box.index} onIndex={(index) => setBox({ ...box, index })} onClose={() => setBox(null)} />}
+ <h3 className="sheet-h frame-title">{title}</h3>
+ <div className="vp-tabs" role="tablist">
+ {tabs
+ .filter((t) => t.show)
+ .map((t) => (
+ <button
+ key={t.id}
+ role="tab"
+ aria-selected={tab === t.id}
+ className={`vp-tab ${tab === t.id ? "on" : ""} ${t.ready ? "ready" : ""}`}
+ onClick={() => p.onTab(t.id)}
+ >
+ {t.label}
+ <InfoTip label={t.label} text={HELP[t.id]} />
+ </button>
+ ))}
+ <span className="vp-spacer" />
+ {tab === "360" && has360 && (
+ <div className="seg small" role="group" aria-label="360 viewpoint">
+ {panoramas.map((u, i) => (
+ <button key={u} className={v360 === i ? "on" : ""} onClick={() => setView360(i)}>
+ {i === 0 ? "Ref angle" : `Spot ${i + 1}`}
+ </button>
+ ))}
+ {sceneGlb && (
+ <button className={v360 === -1 ? "on" : ""} onClick={() => setView360(-1)}>
+ Set model
+ </button>
+ )}
+ </div>
+ )}
+ {tab === "live" && pinned && (
+ <button className="text-btn" onClick={() => setPinned(null)}>
+ Back to live
+ </button>
+ )}
+ <button className={`follow ${p.follow ? "on" : ""}`} onClick={p.onFollow} title="Switch views as new results arrive">
+ <span className="follow-dot" aria-hidden /> Follow
+ </button>
+ </div>
+
+ <div className="vp-stage">
+ {note && tab !== "stills" && tab !== "360" && <span className="frame-note">{note}</span>}
+ {tab === "live" &&
+ (shown ? (
+ <div className="live-frame">
+ <button
+ className="live-open"
+ aria-label="Open full screen"
+ onClick={() =>
+ setBox({
+ items: previews.map((y) => ({
+ url: y.url,
+ caption: `${clock(y.t)} ${stageName(y.stage)}${y.message ? `: ${y.message}` : ""}`,
+ })),
+ index: Math.max(0, previews.findIndex((y) => y.url === shown.url)),
+ })
+ }
+ >
+ <Fade src={shown.url} alt={shown.message || shown.stage} />
+ </button>
+ <span className="live-tag">
+ {clock(shown.t)} {stageName(shown.stage)}
+ {shown.message ? `: ${shown.message}` : ""}
+ </span>
+ {previews.length > 1 && (
+ <div className="strip" aria-label="Recent frames">
+ {previews.slice(-14).map((x) => (
+ <button
+ key={x.url}
+ className={x.url === shown.url ? "on" : ""}
+ onClick={() => setPinned(x.url === latest.url ? null : x.url)}
+ title={`${clock(x.t)} ${stageName(x.stage)}`}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={x.url} alt="" loading="lazy" />
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ ) : (
+ <Empty running={run.status === "running"} text="Each image the builder reports, from the layout to the finals, lands here." />
+ ))}
+ {tab === "compare" &&
+ (p.referenceUrl && compareRender ? (
+ <Compare left={p.referenceUrl} right={compareRender} rightLabel={stills[0] ? "Final" : lastCritic ? `Round ${run.critiques.length}` : "Latest"} />
+ ) : (
+ <Empty running={run.status === "running"} text="Hold the plate against the reference-angle render once there is one." />
+ ))}
+ {tab === "previews" &&
+ (scouting.length ? (
+ <div className="contact scouting">
+ {scouting.map((x, i) => (
+ <figure key={x.url}>
+ <button
+ onClick={() => setBox({ items: scouting.map((y) => ({ url: y.url, caption: y.label })), index: i })}
+ aria-label={`Preview ${i + 1}: ${x.label}`}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={x.url} alt="" loading="lazy" />
+ </button>
+ <figcaption title={x.label}>
+ <b>{String(i + 1).padStart(2, "0")}</b> {x.label}
+ </figcaption>
+ </figure>
+ ))}
+ </div>
+ ) : (
+ <Empty running={run.status === "running"} text="The builder scouts the finished set at the end: every zone, every hero material, wides and details. They land here." />
+ ))}
+ {tab === "contact" &&
+ (previews.length ? (
+ <div className="contact">
+ {previews.map((x, i) => (
+ <figure key={x.url}>
+ <button
+ onClick={() =>
+ setBox({
+ items: previews.map((y) => ({
+ url: y.url,
+ caption: `${clock(y.t)} ${stageName(y.stage)}${y.message ? `: ${y.message}` : ""}`,
+ })),
+ index: i,
+ })
+ }
+ aria-label={`Frame ${i + 1}: ${stageName(x.stage)}`}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={x.url} alt="" loading="lazy" />
+ </button>
+ <figcaption>
+ <b>{String(i + 1).padStart(2, "0")}</b> {clock(x.t)} {stageName(x.stage)}
+ </figcaption>
+ </figure>
+ ))}
+ </div>
+ ) : (
+ <Empty running={run.status === "running"} text="Every reported frame, in order." />
+ ))}
+ {tab === "stills" && res && (
+ <BuilderResult res={res} run={run} onOpen={(i) => setBox({ items: res.stills.map((u, k) => ({ url: u, caption: `Still ${k + 1}` })), index: i })} />
+ )}
+ {tab === "360" &&
+ has360 &&
+ (v360 >= 0 && panoramas[v360] ? <Pano360 url={panoramas[v360]} /> : sceneGlb ? <SceneView url={sceneGlb} envUrl={panoramas[0]} /> : null)}
+ </div>
+
+ <div className="caption" aria-live="polite">
+ <span className="caption-text" key={run.working?.what || run.thought || run.status}>
+ {run.status === "idle"
+ ? "Drop a reference and build. One agent builds the scene and loops with a critic until it passes."
+ : run.status === "failed"
+ ? run.error
+ : run.status === "ended"
+ ? "The recording stops here: the run was still going when it was copied."
+ : run.status === "done"
+ ? p.passed === false
+ ? "Wrapped without a pass: the critic stopped improving. The stills and package are below."
+ : "Wrapped. The critic passed it; stills, 360 and the package are in."
+ : run.working
+ ? `Running: ${run.working.what} (${clock(Math.max(0, p.now - run.working.since))})`
+ : run.thought || "The builder is starting."}
+ </span>
+ <span className="caption-time">{run.status === "idle" ? "" : clock(p.now)}</span>
+ </div>
+ </div>
+ );
+}
+
+function Empty({ running, text }: { running: boolean; text: string }) {
+ return (
+ <div className="empty">
+ {running && <span className="empty-pulse" />}
+ <p>{text}</p>
+ </div>
+ );
+}
diff --git a/web/components/Compare.tsx b/web/components/Compare.tsx
new file mode 100644
index 0000000..14bf1da
--- /dev/null
+++ b/web/components/Compare.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import { useRef, useState } from "react";
+
+/** Reference on the left, render on the right, split by a draggable line. Both fill the render's frame. */
+export default function Compare({ left, right, rightLabel }: { left: string; right: string; rightLabel: string }) {
+ const [pos, setPos] = useState(0.5);
+ const [aspect, setAspect] = useState(16 / 9);
+ const box = useRef<HTMLDivElement>(null);
+ const drag = (clientX: number) => {
+ const r = box.current?.getBoundingClientRect();
+ if (r) setPos(Math.min(1, Math.max(0, (clientX - r.left) / r.width)));
+ };
+ return (
+ <div className="compare-wrap">
+ <div
+ className="compare"
+ ref={box}
+ style={{ aspectRatio: String(aspect) }}
+ onPointerDown={(e) => {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ drag(e.clientX);
+ }}
+ onPointerMove={(e) => e.buttons && drag(e.clientX)}
+ role="slider"
+ aria-label="Compare reference and render"
+ aria-valuenow={Math.round(pos * 100)}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ tabIndex={0}
+ onKeyDown={(e) => {
+ if (e.key === "ArrowLeft") setPos((p) => Math.max(0, p - 0.05));
+ if (e.key === "ArrowRight") setPos((p) => Math.min(1, p + 0.05));
+ }}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img
+ src={right}
+ alt={rightLabel}
+ onLoad={(e) => setAspect(e.currentTarget.naturalWidth / e.currentTarget.naturalHeight)}
+ draggable={false}
+ />
+ <div className="compare-left" style={{ clipPath: `inset(0 ${(1 - pos) * 100}% 0 0)` }}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={left} alt="Reference" draggable={false} />
+ </div>
+ <div className="compare-line" style={{ left: `${pos * 100}%` }}>
+ <span />
+ </div>
+ <span className="compare-tag l">Reference</span>
+ <span className="compare-tag r">{rightLabel}</span>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/CriticPanel.tsx b/web/components/CriticPanel.tsx
new file mode 100644
index 0000000..9bab599
--- /dev/null
+++ b/web/components/CriticPanel.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import { useState } from "react";
+import { PASS_MARK, SCORE_KEYS, SCORE_LABELS, type BuilderState } from "@/lib/builder";
+import Stamp from "./Stamp";
+import InfoTip, { HELP } from "./InfoTip";
+
+/** The critic's rounds as a score sheet (categories down, rounds across), the latest verdict and its ranked fixes. */
+export default function CriticPanel({ run }: { run: BuilderState }) {
+ const [openRound, setOpenRound] = useState<number | null>(null);
+ const rounds = run.critiques;
+ const shownRounds = rounds.slice(-6);
+ const last = rounds[rounds.length - 1];
+
+ return (
+ <div className="plan-panel critic">
+ <h3 className="sheet-h">
+ Critic&apos;s report <span className="sheet-h-sub">pass = none under 6, avg {PASS_MARK}+</span>{" "}
+ <InfoTip label="the critic" text={HELP.critic} />
+ </h3>
+
+ {!rounds.length && (
+ <p className="typed muted">
+ {run.criticBusy
+ ? "The critic is comparing the reference with the first stills."
+ : run.status === "idle"
+ ? "An independent critic judges each round of stills on eight lines: is this a good production base in the reference's world? The builder keeps going until it passes (none under 6, average 7+), for at most 8 rounds."
+ : "No round yet. The builder calls the critic once it has finals to show."}
+ </p>
+ )}
+ {run.criticBusy && (
+ <div className="typing" aria-label="Critic reviewing">
+ <span />
+ <span />
+ </div>
+ )}
+
+ {rounds.length > 0 && (
+ <>
+ <table className="scores">
+ <thead>
+ <tr>
+ <th scope="col" />
+ {shownRounds.map((c) => (
+ <th key={c.round} scope="col" className={c === last ? "cur" : ""}>
+ R{c.round}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {SCORE_KEYS.map((k) => (
+ <tr key={k}>
+ <th scope="row">{SCORE_LABELS[k]}</th>
+ {shownRounds.map((c, i) => {
+ const v = c.scores?.[k];
+ const prev = i > 0 ? shownRounds[i - 1].scores?.[k] : undefined;
+ const d = v !== undefined && prev !== undefined ? v - prev : 0;
+ return (
+ <td key={c.round} className={`${v !== undefined && v < 6 ? "low" : ""} ${c === last ? "cur" : ""}`}>
+ {v ?? "-"}
+ {d !== 0 && <sup className={d > 0 ? "up" : "down"}>{d > 0 ? `+${d}` : d}</sup>}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ <tr className="total">
+ <th scope="row">Total</th>
+ {shownRounds.map((c) => (
+ <td key={c.round} className={c === last ? "cur" : ""}>
+ {Object.values(c.scores || {}).reduce((a, b) => a + b, 0)}
+ </td>
+ ))}
+ </tr>
+ <tr className="verdicts">
+ <th scope="row">Verdict</th>
+ {shownRounds.map((c) => (
+ <td key={c.round} className={c.passed ? "pass" : "fail"}>
+ {c.passed ? "PASS" : "NOT YET"}
+ </td>
+ ))}
+ </tr>
+ </tbody>
+ </table>
+
+ <div className="verdict-head">
+ <span className="verdict-round">Round {last.round}</span>
+ <span key={last.round}>
+ {last.passed ? <Stamp tilt={-7}>PASSED</Stamp> : <Stamp tilt={-4}>NOT YET</Stamp>}
+ </span>
+ </div>
+ {last.summary && <p className="typed plan-summary">{last.summary}</p>}
+
+ {last.fixes?.length > 0 && (
+ <>
+ <h3 className="sheet-h">{last.passed ? "Notes" : "Fixes, worst first"}</h3>
+ <ol className="fixes">
+ {last.fixes.map((f, i) => (
+ <li key={i}>{f}</li>
+ ))}
+ </ol>
+ </>
+ )}
+
+ {rounds.length > 1 && (
+ <div className="notes">
+ {rounds
+ .slice(0, -1)
+ .reverse()
+ .map((c) => (
+ <div key={c.round} className="old-round">
+ <button className="text-btn" onClick={() => setOpenRound(openRound === c.round ? null : c.round)} aria-expanded={openRound === c.round}>
+ Round {c.round} fixes ({c.fixes?.length ?? 0})
+ </button>
+ {openRound === c.round && (
+ <ol className="fixes old">
+ {c.fixes.map((f, i) => (
+ <li key={i}>{f}</li>
+ ))}
+ </ol>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/Dials.tsx b/web/components/Dials.tsx
new file mode 100644
index 0000000..16eae55
--- /dev/null
+++ b/web/components/Dials.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { useState } from "react";
+import { DIALS } from "@/lib/types";
+import InfoTip, { HELP } from "./InfoTip";
+
+export type DialValues = Record<string, number | string | undefined>;
+
+/** Only the dials the user set; the endpoint reads the rest from the reference. */
+export const setDials = (d: DialValues) =>
+ Object.fromEntries(Object.entries(d).filter(([, v]) => v !== undefined)) as Record<string, number | string>;
+
+interface Props {
+ value: DialValues;
+ onChange: (v: DialValues) => void;
+ disabled: boolean;
+ note: string;
+}
+
+export default function Dials({ value, onChange, disabled, note }: Props) {
+ const [open, setOpen] = useState(false);
+ const setDial = (k: string, v: number | string | undefined) => onChange({ ...value, [k]: v });
+ const count = Object.values(value).filter((v) => v !== undefined).length;
+
+ return (
+ <div className="dials">
+ <button className="dials-head" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
+ <span>Dials <InfoTip label="dials" text={HELP.dials} /></span>
+ <span className="dials-sum">{count ? `${count} set` : "read from the image"}</span>
+ <span className={`chev ${open ? "open" : ""}`} aria-hidden />
+ </button>
+ {open && (
+ <div className="dials-body">
+ {DIALS.map((d) => {
+ const v = value[d.key];
+ const isSet = v !== undefined;
+ return (
+ <div className={`dial ${isSet ? "set" : ""}`} key={d.key}>
+ <div className="dial-top">
+ <span className="dial-name">{d.label}</span>
+ {isSet ? (
+ <button className="dial-reset" onClick={() => setDial(d.key, undefined)} disabled={disabled}>
+ {d.kind === "range" ? Number(v).toFixed(2) : String(v)} <span aria-hidden>×</span>
+ </button>
+ ) : (
+ <span className="dial-auto">AUTO</span>
+ )}
+ </div>
+ {d.kind === "range" ? (
+ <div className="dial-range">
+ <span>{d.lo}</span>
+ <input
+ type="range"
+ min={d.min}
+ max={d.max}
+ step={0.05}
+ disabled={disabled}
+ value={isSet ? Number(v) : (d.min + d.max) / 2}
+ onChange={(e) => setDial(d.key, Number(e.target.value))}
+ aria-label={d.label}
+ />
+ <span>{d.hi}</span>
+ </div>
+ ) : (
+ <div className="chips" role="group" aria-label={d.label}>
+ {d.options.map((o) => (
+ <button
+ key={o}
+ className={v === o ? "on" : ""}
+ disabled={disabled}
+ onClick={() => setDial(d.key, v === o ? undefined : o)}
+ >
+ {o}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ <p className="fine">{note}</p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/Fade.tsx b/web/components/Fade.tsx
new file mode 100644
index 0000000..8bef5d6
--- /dev/null
+++ b/web/components/Fade.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+/** Crossfades to a new image once it has loaded, so arriving renders dissolve in rather than pop. */
+export default function Fade({ src, alt, className = "" }: { src: string; alt: string; className?: string }) {
+ const [layers, setLayers] = useState<{ src: string; key: number; shown: boolean }[]>([]);
+ useEffect(() => {
+ if (!src) return;
+ const key = Date.now() + Math.random();
+ setLayers((l) => (l[l.length - 1]?.src === src ? l : [...l.slice(-1), { src, key, shown: false }]));
+ }, [src]);
+ const loaded = (key: number) => {
+ setLayers((l) => l.map((x) => (x.key === key ? { ...x, shown: true } : x)));
+ setTimeout(() => setLayers((l) => (l[l.length - 1]?.key === key ? l.filter((x) => x.key === key) : l)), 700);
+ };
+ return (
+ <div className={`fade ${className}`}>
+ {layers.map((l) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={l.key} src={l.src} alt={alt} className={l.shown ? "shown" : ""} onLoad={() => loaded(l.key)} />
+ ))}
+ </div>
+ );
+}
diff --git a/web/components/Gallery.tsx b/web/components/Gallery.tsx
new file mode 100644
index 0000000..0d13938
--- /dev/null
+++ b/web/components/Gallery.tsx
@@ -0,0 +1,187 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useSearchParams } from "next/navigation";
+import { SCORE_KEYS } from "@/lib/builder";
+import { ago, cachedList, galleryApp, listGallery, storeList, STATUS_LABEL, type GalleryItem, type GalleryKind, type GalleryList } from "@/lib/gallery";
+import { getAccessKey } from "@/lib/sources";
+import Stamp from "./Stamp";
+
+const POLL_MS = 30_000; // the list refreshes while open, so new and running builds show up
+
+/** Everyone's builds, newest first, read from the fal apps' storage. A card opens the build in the results view. */
+export default function Gallery() {
+ const params = useSearchParams();
+ const kind: GalleryKind = params.get("kind") === "kit" ? "kit" : "scene";
+ const override = params.get("gallery_app");
+ const app = galleryApp(kind, override);
+ const [list, setList] = useState<GalleryList | null>(null);
+ const [stale, setStale] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState("");
+ const [filter, setFilter] = useState<"all" | "running" | "done">("all");
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const l = await listGallery(kind, app);
+ setList(l);
+ setStale(false);
+ setError("");
+ storeList(kind, app, l);
+ } catch (e) {
+ const anyE = e as { body?: { detail?: unknown }; message?: string };
+ setError(typeof anyE.body?.detail === "string" ? anyE.body.detail : anyE.message || String(e));
+ } finally {
+ setLoading(false);
+ }
+ }, [kind, app]);
+
+ useEffect(() => {
+ const c = cachedList(kind, app);
+ setList(c);
+ setStale(!!c);
+ load();
+ const id = setInterval(load, POLL_MS);
+ return () => clearInterval(id);
+ }, [kind, app, load]);
+
+ const href = (q: Record<string, string>) => {
+ const p = new URLSearchParams(q);
+ if (override) p.set("gallery_app", override);
+ return `/?${p.toString()}`;
+ };
+ const builds = (list?.builds ?? []).filter((b) => filter === "all" || (filter === "running" ? b.status === "running" : b.status !== "running"));
+ const running = (list?.builds ?? []).filter((b) => b.status === "running").length;
+
+ return (
+ <div className="gallery-page">
+ <header className="topbar">
+ <div className="slate gallery-slate" role="group" aria-label="Slate">
+ <div className="slate-cell">
+ <small>Production</small>
+ <b>{kind === "kit" ? "AnyKit" : "AnyScene"}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Reel</small>
+ <b>Gallery</b>
+ </div>
+ <div className="slate-cell">
+ <small>Takes</small>
+ <b>{list ? String(list.total).padStart(2, "0") : "--"}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Rolling</small>
+ <b>{list ? String(running).padStart(2, "0") : "--"}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Source</small>
+ <b title={app}>{app.replace(/^[^/]+\//, "") || "not set"}</b>
+ </div>
+ <div className="slate-stripe" aria-hidden />
+ </div>
+ <div className="toolbar">
+ <div className="seg small" role="group" aria-label="Product">
+ <a className={`seg-link ${kind === "scene" ? "on" : ""}`} href={href({ view: "gallery" })} aria-current={kind === "scene" ? "page" : undefined}>
+ Scenes
+ </a>
+ <a className={`seg-link ${kind === "kit" ? "on" : ""}`} href={href({ view: "gallery", kind: "kit" })} aria-current={kind === "kit" ? "page" : undefined}>
+ Kits
+ </a>
+ </div>
+ <div className="seg small" role="group" aria-label="Show">
+ {(["all", "running", "done"] as const).map((f) => (
+ <button key={f} className={filter === f ? "on" : ""} aria-pressed={filter === f} onClick={() => setFilter(f)}>
+ {f === "all" ? "All" : f === "running" ? "Rolling" : "Finished"}
+ </button>
+ ))}
+ </div>
+ <span className="live-pill">{loading ? (list ? "Refreshing" : "Waking the worker (a cold start can take a few minutes)") : stale ? "Cached" : `Storage: ${app}`}</span>
+ <span className="vp-spacer" />
+ <button className="text-btn" onClick={load} disabled={loading}>
+ Refresh
+ </button>
+ <a className="text-btn" href={href({})}>
+ New build
+ </a>
+ </div>
+ </header>
+
+ <main className="gallery-main">
+ {error && (
+ <p className="error-note">
+ {error}
+ {/access key|proxy is closed/i.test(error) && !getAccessKey() ? " Set the access key on the build page first." : ""}
+ </p>
+ )}
+ {!list && !error && (
+ <div className="empty gallery-empty">
+ <span className="empty-pulse" />
+ <p>Reading every build from storage. The first look can wait on a cold GPU worker for a few minutes.</p>
+ </div>
+ )}
+ {list && builds.length === 0 && (
+ <div className="empty gallery-empty">
+ <p>{filter === "all" ? `No ${kind === "kit" ? "kits" : "builds"} on ${app} yet.` : "Nothing here with this filter."}</p>
+ </div>
+ )}
+ <ul className="gallery-grid">
+ {builds.map((b) => (
+ <Card key={b.id} b={b} href={href(kind === "kit" ? { open: b.id, kind: "kit" } : { open: b.id })} now={list?.now} />
+ ))}
+ </ul>
+ </main>
+ </div>
+ );
+}
+
+function Card({ b, href, now }: { b: GalleryItem; href: string; now?: number }) {
+ const scores = b.last_scores ? Object.values(b.last_scores) : [];
+ const avg = scores.length ? scores.reduce((s, v) => s + v, 0) / scores.length : null;
+ const low = b.last_scores ? SCORE_KEYS.filter((k) => (b.last_scores?.[k] ?? 10) < 6) : [];
+ const title = b.prompt?.trim() || b.name || b.milestone?.message || "(no prompt: built from the reference)";
+ const ref = b.reference_urls?.[0];
+ return (
+ <li className={`gallery-card status-${b.status}`}>
+ <a href={href} aria-label={`Open ${b.id}: ${title}`}>
+ <div className="gallery-cover">
+ {b.cover ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={b.cover} alt="" loading="lazy" />
+ ) : (
+ <span className="gallery-nocover">{b.status === "running" ? "Rolling: no frame yet" : "No frames"}</span>
+ )}
+ {ref && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img className="gallery-ref" src={ref} alt="" loading="lazy" title="Reference" />
+ )}
+ <span className="gallery-stamp">
+ {b.status === "running" ? (
+ <span className="rolling-tag">Rolling</span>
+ ) : (
+ <Stamp tilt={-5}>{b.status === "done" && b.passed ? "Passed" : STATUS_LABEL[b.status]}</Stamp>
+ )}
+ </span>
+ </div>
+ <div className="gallery-body">
+ <p className="gallery-title" title={title}>
+ {title}
+ </p>
+ <p className="gallery-meta">
+ <b>{b.id.replace(/^[bk]_/, "").slice(0, 6).toUpperCase()}</b>
+ <span title={b.started ? new Date(b.started * 1000).toLocaleString() : ""}>{b.started ? ago(b.started, now) : ""}</span>
+ <span>{b.minutes != null ? `${Math.round(b.minutes)} min` : ""}</span>
+ <span>
+ {b.critic_rounds ? `${b.critic_rounds} round${b.critic_rounds === 1 ? "" : "s"}${avg != null ? `, avg ${avg.toFixed(1)}` : ""}` : "no critic"}
+ </span>
+ </p>
+ <p className="gallery-sub">
+ {b.status === "running" && b.milestone ? `${b.milestone.stage}: ${b.milestone.message}` : ""}
+ {b.status !== "running" && low.length ? `low: ${low.join(", ").replace(/_/g, " ")}` : ""}
+ {b.status !== "running" && !low.length ? `${b.n_previews ? `${b.n_previews} previews · ` : ""}${b.frames} frames${b.effort ? ` · ${b.effort}` : ""}` : ""}
+ </p>
+ </div>
+ </a>
+ </li>
+ );
+}
diff --git a/web/components/InfoTip.tsx b/web/components/InfoTip.tsx
new file mode 100644
index 0000000..256f1c9
--- /dev/null
+++ b/web/components/InfoTip.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { useId, useState } from "react";
+
+/** A small ⓘ next to a label: hover, focus or tap shows what the thing is. */
+export default function InfoTip({ text, label }: { text: string; label: string }) {
+ const [open, setOpen] = useState(false);
+ const id = useId();
+ return (
+ <span className="infotip" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
+ <span
+ role="button"
+ tabIndex={0}
+ className="infotip-i"
+ aria-label={`What is ${label}?`}
+ aria-describedby={open ? id : undefined}
+ aria-expanded={open}
+ onClick={(e) => {
+ // focus already opened it; a click or tap only ever opens (blur, mouse-out or Escape closes)
+ e.stopPropagation();
+ setOpen(true);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ e.stopPropagation();
+ setOpen((o) => !o);
+ }
+ if (e.key === "Escape") setOpen(false);
+ }}
+ onFocus={() => setOpen(true)}
+ onBlur={() => setOpen(false)}
+ >
+ i
+ </span>
+ {open && (
+ <span role="tooltip" id={id} className="infotip-box">
+ {text}
+ </span>
+ )}
+ </span>
+ );
+}
+
+/** What each part of the builder page is, in one place so the wording stays consistent. */
+export const HELP = {
+ live: "The newest image the builder made or looked at, as it works. Click a thumbnail in the strip to hold one.",
+ compare: "Your reference image next to the builder's render from the same camera angle. Drag the divider to compare.",
+ previews: "Scouting shots of the finished set: every area and hero material, at different lenses and heights. Pick any of them to order as a still or a video.",
+ contact: "Every image the builder produced during the build, in order: tests, layouts, critic rounds, finals. Its working notebook.",
+ stills: "The finished, graded stills the critic judged, plus the downloads: package, scene.blend, glTF, and what the build cost.",
+ "360": "Look around the finished set: 360° panoramas rendered with the scene's real lighting, or the scene model you can fly through.",
+ schedule: "The build's milestones in order. ROLLING is the one in progress, WRAPPED ones show how long they took.",
+ log: "Every step the builder takes: commands it runs, files it writes, images it looks at, and its own notes.",
+ critic: "An independent reviewer that scores the stills on 8 lines out of 10: is this a good production base in your reference's world? It doesn't mark down angles or lighting for differing from the reference. The build keeps improving until it passes (none under 6, average 7+), for at most 8 rounds.",
+ dials: "Settings the builder must follow, like time of day or wear. Leave one on AUTO and the builder reads it from your reference.",
+ effort: "How hard Claude thinks at each step. Medium is the default; higher is slower and costs more.",
+ shots: "Order finished stills or video clips of this scene: pick scouting previews or describe new shots in words.",
+} as const;
diff --git a/web/components/Inputs.tsx b/web/components/Inputs.tsx
new file mode 100644
index 0000000..48f1f30
--- /dev/null
+++ b/web/components/Inputs.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { useRef, useState } from "react";
+import Dials from "./Dials";
+
+export interface InputsState {
+ file: File | null;
+ previewUrl: string;
+ prompt: string;
+ dials: Record<string, number | string | undefined>;
+ effort: string;
+ tier: "draft" | "full";
+}
+
+interface Props {
+ value: InputsState;
+ onChange: (v: InputsState) => void;
+ disabled: boolean;
+ onPlan: () => void;
+ canPlan: boolean;
+ planning: boolean;
+}
+
+export default function Inputs({ value, onChange, disabled, onPlan, canPlan, planning }: Props) {
+ const fileRef = useRef<HTMLInputElement>(null);
+ const [over, setOver] = useState(false);
+ const set = (patch: Partial<InputsState>) => onChange({ ...value, ...patch });
+
+ const take = (f: File | undefined) => {
+ if (!f || !f.type.startsWith("image/")) return;
+ if (value.previewUrl.startsWith("blob:")) URL.revokeObjectURL(value.previewUrl);
+ set({ file: f, previewUrl: URL.createObjectURL(f) });
+ };
+
+ return (
+ <div className="inputs">
+ <h3 className="sheet-h">Reference plate</h3>
+ <div
+ className={`drop ${over ? "over" : ""} ${value.previewUrl ? "has" : ""}`}
+ onDragOver={(e) => {
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ if (!disabled) take(e.dataTransfer.files?.[0]);
+ }}
+ onClick={() => !disabled && fileRef.current?.click()}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && fileRef.current?.click()}
+ aria-label="Reference image: drop or choose a file"
+ >
+ {value.previewUrl ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={value.previewUrl} alt="Reference" />
+ ) : (
+ <div className="drop-empty">
+ <span className="drop-title">Drop the reference plate</span>
+ <span className="drop-hint">or click to choose. The look, the materials and the props come from here.</span>
+ </div>
+ )}
+ {value.previewUrl && <span className="drop-change">Replace</span>}
+ <input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => take(e.target.files?.[0])} />
+ </div>
+ <p className="cap">
+ {value.previewUrl ? `plate 1 of 1: ${value.file ? value.file.name : "recorded reference"}` : "no plate loaded"}
+ </p>
+ <h3 className="sheet-h">Direction</h3>
+
+ <label className="field">
+ <span className="field-label">Prompt</span>
+ <textarea
+ rows={2}
+ value={value.prompt}
+ disabled={disabled}
+ placeholder="Anything the image can’t show: it’s 1 AM, rain outside, twice as deep"
+ onChange={(e) => set({ prompt: e.target.value })}
+ />
+ </label>
+
+ <Dials
+ value={value.dials}
+ onChange={(dials) => set({ dials })}
+ disabled={disabled}
+ note="The old pipeline records dials but doesn't apply them; the scene builder does."
+ />
+
+ <div className="row2">
+ <label className="field">
+ <span className="field-label">Planning effort</span>
+ <select value={value.effort} disabled={disabled} onChange={(e) => set({ effort: e.target.value })}>
+ {["low", "medium", "high", "xhigh", "max"].map((o) => (
+ <option key={o} value={o}>
+ {o}
+ </option>
+ ))}
+ </select>
+ </label>
+ <div className="field">
+ <span className="field-label">Build tier</span>
+ <div className="seg" role="group" aria-label="Build tier">
+ {(["draft", "full"] as const).map((t) => (
+ <button key={t} className={value.tier === t ? "on" : ""} disabled={disabled} onClick={() => set({ tier: t })}>
+ {t === "draft" ? "Draft" : "Full"}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ <button className="primary" disabled={!canPlan} onClick={onPlan}>
+ {planning ? "Planning…" : "Plan the scene"}
+ </button>
+ </div>
+ );
+}
diff --git a/web/components/Lightbox.tsx b/web/components/Lightbox.tsx
new file mode 100644
index 0000000..8d611b8
--- /dev/null
+++ b/web/components/Lightbox.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { useCallback, useEffect, useRef } from "react";
+
+export interface LightboxItem {
+ url: string;
+ caption?: string;
+}
+
+/** Full-screen viewer for a set of images: chevrons or ←/→ to move, Esc or a click outside to close. */
+export default function Lightbox({ items, index, onIndex, onClose }: {
+ items: LightboxItem[];
+ index: number;
+ onIndex: (i: number) => void;
+ onClose: () => void;
+}) {
+ const n = items.length;
+ const go = useCallback((d: number) => onIndex((index + d + n) % n), [index, n, onIndex]);
+ const closeRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "ArrowRight") go(1);
+ else if (e.key === "ArrowLeft") go(-1);
+ else if (e.key === "Escape") onClose();
+ else if (e.key === "Home") onIndex(0);
+ else if (e.key === "End") onIndex(n - 1);
+ else return;
+ e.preventDefault();
+ };
+ window.addEventListener("keydown", onKey);
+ const prev = document.body.style.overflow;
+ document.body.style.overflow = "hidden";
+ closeRef.current?.focus();
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ document.body.style.overflow = prev;
+ };
+ }, [go, onClose, onIndex, n]);
+
+ // swipe on touch screens
+ const touchX = useRef<number | null>(null);
+ const item = items[index];
+ if (!item) return null;
+
+ return (
+ <div
+ className="lightbox"
+ role="dialog"
+ aria-modal="true"
+ aria-label={`Image ${index + 1} of ${n}`}
+ onClick={onClose}
+ onTouchStart={(e) => (touchX.current = e.touches[0].clientX)}
+ onTouchEnd={(e) => {
+ if (touchX.current === null) return;
+ const dx = e.changedTouches[0].clientX - touchX.current;
+ if (Math.abs(dx) > 50) go(dx < 0 ? 1 : -1);
+ touchX.current = null;
+ }}
+ >
+ <div className="lightbox-top" onClick={(e) => e.stopPropagation()}>
+ <span className="lightbox-count">
+ {String(index + 1).padStart(2, "0")} / {String(n).padStart(2, "0")}
+ </span>
+ <span className="lightbox-keys">← → to move · Esc to close</span>
+ <a className="text-btn" href={item.url} target="_blank" rel="noreferrer">
+ Open full size
+ </a>
+ <button ref={closeRef} className="lightbox-close" onClick={onClose} aria-label="Close">
+ ×
+ </button>
+ </div>
+ {n > 1 && (
+ <button className="lightbox-nav prev" aria-label="Previous image" onClick={(e) => { e.stopPropagation(); go(-1); }}>
+ <span aria-hidden>‹</span>
+ </button>
+ )}
+ <figure className="lightbox-figure" onClick={(e) => e.stopPropagation()}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img key={item.url} src={item.url} alt={item.caption || `Image ${index + 1}`} />
+ {item.caption && <figcaption>{item.caption}</figcaption>}
+ </figure>
+ {n > 1 && (
+ <button className="lightbox-nav next" aria-label="Next image" onClick={(e) => { e.stopPropagation(); go(1); }}>
+ <span aria-hidden>›</span>
+ </button>
+ )}
+ {n > 1 && (
+ <div className="lightbox-strip" onClick={(e) => e.stopPropagation()}>
+ {items.map((x, i) => (
+ <button key={x.url + i} className={i === index ? "on" : ""} onClick={() => onIndex(i)} aria-label={`Image ${i + 1}`}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={x.url} alt="" loading="lazy" />
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/LiveMap.tsx b/web/components/LiveMap.tsx
new file mode 100644
index 0000000..942ab68
--- /dev/null
+++ b/web/components/LiveMap.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import { useMemo } from "react";
+import { assetKey, type RunState } from "@/lib/run";
+import type { Plan } from "@/lib/types";
+
+/** The plan drawn top-down, entrance at the bottom; generated footprints fill in as their props arrive. */
+export default function LiveMap({
+ plan,
+ run,
+ selected,
+ onSelect,
+}: {
+ plan: Plan;
+ run: RunState;
+ selected: string | null;
+ onSelect: (id: string) => void;
+}) {
+ const { width: W, depth: D } = plan.room;
+ const pad = Math.max(W, D) * 0.06;
+ const Y = (y: number) => D - y;
+ const meshesDone = run.stages.generating_meshes?.status === "done" || run.status === "done";
+
+ const objects = useMemo(
+ () => [...plan.objects].sort((a, b) => b.w * b.d - a.w * a.d), // big ones underneath
+ [plan.objects],
+ );
+
+ const stateOf = (o: Plan["objects"][0]) => {
+ if (!o.generate) return "fixed";
+ const p = run.props[assetKey(o)];
+ if (!p) return run.kind ? "waiting" : "planned";
+ if (p.status === "failed") return "failed";
+ if (p.mesh_url) return "meshed";
+ return meshesDone ? "standin" : "ref";
+ };
+
+ const cam = plan.reference_camera;
+ const camAngle = cam ? Math.atan2(cam.look_at[1] - cam.position[1], cam.look_at[0] - cam.position[0]) : 0;
+ const fov = cam ? 2 * Math.atan(18 / cam.lens_mm) : 0.8;
+ const reach = Math.max(W, D) * 0.22;
+
+ return (
+ <div className="livemap">
+ <svg viewBox={`${-pad} ${-pad} ${W + pad * 2} ${D + pad * 2}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label="Prop map">
+ <defs>
+ <pattern id="grid" width="1" height="1" patternUnits="userSpaceOnUse">
+ <path d="M1 0H0V1" fill="none" stroke="var(--map-grid)" strokeWidth="0.012" />
+ </pattern>
+ <pattern id="hatch" width="0.18" height="0.18" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
+ <line x1="0" y1="0" x2="0" y2="0.18" stroke="#1f1d1a" strokeWidth="0.03" />
+ </pattern>
+ </defs>
+ <rect x={0} y={0} width={W} height={D} fill="url(#grid)" />
+ <rect x={0} y={0} width={W} height={D} className="map-wall" />
+ {plan.openings.map((op, i) => {
+ const half = op.width / 2;
+ const [x1, y1, x2, y2] =
+ op.wall === "front"
+ ? [op.center - half, 0, op.center + half, 0]
+ : op.wall === "back"
+ ? [op.center - half, D, op.center + half, D]
+ : op.wall === "left"
+ ? [0, op.center - half, 0, op.center + half]
+ : [W, op.center - half, W, op.center + half];
+ return <line key={i} x1={x1} y1={Y(y1)} x2={x2} y2={Y(y2)} className={`map-opening ${op.kind}`} />;
+ })}
+ {objects.map((o) => {
+ const st = stateOf(o);
+ const key = assetKey(o);
+ return (
+ <g
+ key={o.id}
+ transform={`translate(${o.x} ${Y(o.y)}) rotate(${-o.rot})`}
+ className={`fp ${st} ${o.source} ${selected === key ? "sel" : ""}`}
+ onClick={() => o.generate && run.props[key]?.mesh_url && onSelect(key)}
+ >
+ <title>{`${o.label}${o.source === "invented" ? " (invented)" : ""}`}</title>
+ <rect x={-o.w / 2} y={-o.d / 2} width={Math.max(o.w, 0.04)} height={Math.max(o.d, 0.04)} rx={Math.min(o.w, o.d) * 0.08} />
+ </g>
+ );
+ })}
+ {plan.lights.map((l) => (
+ <circle key={l.id} cx={l.x} cy={Y(l.y)} r={Math.max(W, D) * 0.006} fill={l.color} className="map-light" />
+ ))}
+ {cam && (
+ <g className="map-cam" transform={`translate(${cam.position[0]} ${Y(cam.position[1])})`}>
+ <path
+ d={`M0 0 L${Math.cos(camAngle - fov / 2) * reach} ${-Math.sin(camAngle - fov / 2) * reach} L${Math.cos(camAngle + fov / 2) * reach} ${-Math.sin(camAngle + fov / 2) * reach} Z`}
+ />
+ <circle r={Math.max(W, D) * 0.008} />
+ </g>
+ )}
+ </svg>
+ <div className="map-legend">
+ <span className="lg meshed">Mesh in</span>
+ <span className="lg ref">Reference ready</span>
+ <span className="lg waiting">Waiting</span>
+ <span className="lg standin">Stand-in</span>
+ <span className="lg failed">Failed</span>
+ <span className="lg fixed">Built from the plan</span>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/Pano360.tsx b/web/components/Pano360.tsx
new file mode 100644
index 0000000..3c182fa
--- /dev/null
+++ b/web/components/Pano360.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import * as THREE from "three";
+import { loadEquirect } from "@/lib/three-util";
+
+/** Drag-to-look viewer for one equirectangular render: the texture on the inside of a sphere. */
+export default function Pano360({ url }: { url: string }) {
+ const host = useRef<HTMLDivElement>(null);
+ const [state, setState] = useState<"loading" | "ready" | "error">("loading");
+
+ useEffect(() => {
+ const el = host.current!;
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ el.appendChild(renderer.domElement);
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0xefe8d6);
+ const cam = new THREE.PerspectiveCamera(75, 1, 0.1, 100);
+ let tex: THREE.Texture | null = null;
+ let disposed = false;
+ setState("loading");
+ loadEquirect(url)
+ .then((t) => {
+ if (disposed) return t.dispose();
+ tex = t;
+ scene.background = t; // equirect background renders as the inside of a sphere
+ setState("ready");
+ })
+ .catch(() => !disposed && setState("error"));
+
+ // look state: yaw 0 looks at the centre of the image (u = 0.5)
+ let yaw = 0;
+ let pitch = 0;
+ let fov = 75;
+ let dragging = false;
+ let idle = true;
+ let lx = 0;
+ let ly = 0;
+ const down = (e: PointerEvent) => {
+ dragging = true;
+ idle = false;
+ lx = e.clientX;
+ ly = e.clientY;
+ el.setPointerCapture(e.pointerId);
+ };
+ const move = (e: PointerEvent) => {
+ if (!dragging) return;
+ const k = (fov / el.clientHeight) * (Math.PI / 180);
+ yaw += (e.clientX - lx) * k;
+ pitch = Math.max(-1.45, Math.min(1.45, pitch + (e.clientY - ly) * k));
+ lx = e.clientX;
+ ly = e.clientY;
+ };
+ const up = () => (dragging = false);
+ const wheel = (e: WheelEvent) => {
+ e.preventDefault();
+ fov = Math.max(30, Math.min(100, fov + e.deltaY * 0.04));
+ cam.fov = fov;
+ cam.updateProjectionMatrix();
+ };
+ const key = (e: KeyboardEvent) => {
+ const step = 0.08;
+ if (e.key === "ArrowLeft") yaw += step;
+ else if (e.key === "ArrowRight") yaw -= step;
+ else if (e.key === "ArrowUp") pitch = Math.min(1.45, pitch + step);
+ else if (e.key === "ArrowDown") pitch = Math.max(-1.45, pitch - step);
+ else return;
+ idle = false;
+ e.preventDefault();
+ };
+ el.addEventListener("pointerdown", down);
+ el.addEventListener("pointermove", move);
+ el.addEventListener("pointerup", up);
+ el.addEventListener("wheel", wheel, { passive: false });
+ el.addEventListener("keydown", key);
+
+ const resize = () => {
+ renderer.setSize(el.clientWidth, el.clientHeight);
+ cam.aspect = el.clientWidth / Math.max(1, el.clientHeight);
+ cam.updateProjectionMatrix();
+ };
+ const ro = new ResizeObserver(resize);
+ ro.observe(el);
+ resize();
+ let raf = 0;
+ const dir = new THREE.Vector3();
+ const loop = () => {
+ raf = requestAnimationFrame(loop);
+ if (idle) yaw -= 0.0007;
+ // three maps u = 0.5 of an equirect background to -Z
+ dir.set(-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch));
+ cam.lookAt(dir);
+ renderer.render(scene, cam);
+ };
+ loop();
+ return () => {
+ disposed = true;
+ cancelAnimationFrame(raf);
+ ro.disconnect();
+ el.removeEventListener("pointerdown", down);
+ el.removeEventListener("pointermove", move);
+ el.removeEventListener("pointerup", up);
+ el.removeEventListener("wheel", wheel);
+ el.removeEventListener("keydown", key);
+ tex?.dispose();
+ renderer.dispose();
+ el.removeChild(renderer.domElement);
+ };
+ }, [url]);
+
+ return (
+ <div className="pano">
+ <div className="pano-canvas" ref={host} tabIndex={0} aria-label="360 view: drag or use arrow keys to look around, scroll to zoom" role="img" />
+ {state === "loading" && <div className="viewer3d-load">Loading 360 plate</div>}
+ {state === "error" && <div className="viewer3d-load">This panorama couldn&apos;t be loaded.</div>}
+ <p className="viewer-hint">drag to look around, scroll to zoom</p>
+ </div>
+ );
+}
diff --git a/web/components/PlanPanel.tsx b/web/components/PlanPanel.tsx
new file mode 100644
index 0000000..69a492c
--- /dev/null
+++ b/web/components/PlanPanel.tsx
@@ -0,0 +1,192 @@
+"use client";
+
+import { useState } from "react";
+import type { RunState } from "@/lib/run";
+import type { BuildResponse, PlanResponse } from "@/lib/types";
+import Stamp from "./Stamp";
+
+interface Props {
+ planRes: PlanResponse | null;
+ planRun: RunState;
+ buildRun: RunState;
+ buildRes: BuildResponse | null;
+ onEdit: (text: string) => void;
+ onBuild: () => void;
+ tier: "draft" | "full";
+ busy: boolean;
+}
+
+/** The plan as a breakdown sheet, with the notes box and the one ink button. */
+export default function PlanPanel({ planRes, planRun, buildRun, buildRes, onEdit, onBuild, tier, busy }: Props) {
+ const [edit, setEdit] = useState("");
+ const [notesOpen, setNotesOpen] = useState(false);
+ const plan = planRes?.plan;
+
+ if (!plan) {
+ return (
+ <div className="plan-panel">
+ <h3 className="sheet-h">Breakdown</h3>
+ <p className="typed muted">
+ {planRun.status === "running"
+ ? "The planner is reading the plate and laying out the whole space, including what the camera can't see."
+ : "Room size, objects and lights are typed up here once a plan comes back. Revise it in words, then approve it to build."}
+ </p>
+ {planRun.status === "running" && (
+ <div className="typing" aria-hidden>
+ <span />
+ <span />
+ <span />
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ const objects = plan.objects.length;
+ const invented = plan.objects.filter((o) => o.source === "invented").length;
+ const generated = plan.objects.filter((o) => o.generate).length;
+ const inventedLights = plan.lights.filter((l) => l.source === "invented").length;
+ const r = plan.room;
+ const building = buildRun.kind !== null;
+
+ return (
+ <div className="plan-panel">
+ <h3 className="sheet-h">Breakdown</h3>
+ <div className="plan-head">
+ <h2 className="plan-title">{plan.name.replace(/-/g, " ")}</h2>
+ {building && (
+ <span className="approved">
+ <Stamp tilt={-9}>APPROVED</Stamp>
+ </span>
+ )}
+ </div>
+ <p className="typed plan-summary">{plan.summary}</p>
+
+ <table className="breakdown">
+ <tbody>
+ <tr>
+ <th scope="row">Room</th>
+ <td>
+ {fmtM(r.width)} x {fmtM(r.depth)} m, {fmtM(r.height)} m high
+ </td>
+ </tr>
+ <tr>
+ <th scope="row">Setting</th>
+ <td>
+ {plan.setting.replace(/_/g, " ")}
+ {plan.time_of_day ? `, ${plan.time_of_day}` : ""}
+ </td>
+ </tr>
+ <tr>
+ <th scope="row">Objects</th>
+ <td>
+ <b>{objects}</b> ({invented} invented)
+ </td>
+ </tr>
+ <tr>
+ <th scope="row">To build</th>
+ <td>{generated} generated props</td>
+ </tr>
+ <tr>
+ <th scope="row">Lights</th>
+ <td>
+ <b>{plan.lights.length}</b>
+ {inventedLights ? ` (${inventedLights} invented)` : ""}
+ <span className="light-dots">
+ {plan.lights.slice(0, 20).map((l) => (
+ <span key={l.id} style={{ background: l.color }} title={`${l.id}: ${l.kind}, ${l.power}`} />
+ ))}
+ </span>
+ </td>
+ </tr>
+ {plan.mood && plan.mood.length > 0 && (
+ <tr>
+ <th scope="row">Mood</th>
+ <td>{plan.mood.join(", ")}</td>
+ </tr>
+ )}
+ {plan.palette && plan.palette.length > 0 && (
+ <tr>
+ <th scope="row">Palette</th>
+ <td>
+ <span className="palette" aria-label="Palette">
+ {plan.palette.map((c) => (
+ <span key={c} style={{ background: c }} title={c} />
+ ))}
+ </span>
+ </td>
+ </tr>
+ )}
+ {plan.dials &&
+ Object.entries(plan.dials).map(([k, d]) => (
+ <tr key={k}>
+ <th scope="row">{k.replace(/_/g, " ")}</th>
+ <td>
+ <b>{String(d.value)}</b> {d.means}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+
+ {plan.notes && plan.notes.length > 0 && (
+ <div className="notes">
+ <button className="text-btn" onClick={() => setNotesOpen((o) => !o)} aria-expanded={notesOpen}>
+ {notesOpen ? "Hide planner notes" : `Planner notes (${plan.notes.length})`}
+ </button>
+ {notesOpen && (
+ <ol>
+ {plan.notes.map((n, i) => (
+ <li key={i}>{n}</li>
+ ))}
+ </ol>
+ )}
+ </div>
+ )}
+
+ <div className="plan-actions">
+ {!building && (
+ <>
+ <label className="field">
+ <span className="field-label">Notes for a revision</span>
+ <textarea
+ className="notes-box"
+ rows={3}
+ value={edit}
+ disabled={busy}
+ placeholder="Move the wall display to the right wall. Add a second row of consoles."
+ onChange={(e) => setEdit(e.target.value)}
+ />
+ </label>
+ <button
+ className="secondary"
+ disabled={busy || !edit.trim()}
+ onClick={() => {
+ onEdit(edit.trim());
+ setEdit("");
+ }}
+ >
+ Revise plan
+ </button>
+ </>
+ )}
+ {buildRes?.package_url ? (
+ <a className="primary as-link" href={buildRes.package_url} download>
+ Download scene package
+ </a>
+ ) : buildRun.status === "failed" ? (
+ <button className="primary" disabled={busy} onClick={onBuild}>
+ Retry build
+ </button>
+ ) : (
+ <button className="primary" disabled={busy || building} onClick={onBuild}>
+ {buildRun.status === "running" ? "Building" : `Approve and build (${tier})`}
+ </button>
+ )}
+ <p className="fine plan-id">plan {planRes.plan_id}</p>
+ </div>
+ </div>
+ );
+}
+
+const fmtM = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(1));
diff --git a/web/components/ProductSwitch.tsx b/web/components/ProductSwitch.tsx
new file mode 100644
index 0000000..2a68f2e
--- /dev/null
+++ b/web/components/ProductSwitch.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+/** The AnyAll products, picked from the slate's PRODUCTION cell. Each is its own fal app behind the same call sheet. */
+const PRODUCTS = [
+ { id: "anyscene", label: "AnyScene", href: "/", ready: true },
+ { id: "anykit", label: "AnyKit", href: "/?product=anykit", ready: false },
+] as const;
+
+export default function ProductSwitch({ current }: { current: string }) {
+ return (
+ <label className="product-switch">
+ <span className="sr-only">Product</span>
+ <select
+ id="product-switch"
+ value={current}
+ onChange={(e) => {
+ const p = PRODUCTS.find((x) => x.id === e.target.value);
+ if (p && p.ready) window.location.href = p.href;
+ }}
+ >
+ {PRODUCTS.map((p) => (
+ <option key={p.id} value={p.id} disabled={!p.ready}>
+ {p.label}
+ {p.ready ? "" : " (soon)"}
+ </option>
+ ))}
+ </select>
+ </label>
+ );
+}
diff --git a/web/components/ProductionLog.tsx b/web/components/ProductionLog.tsx
new file mode 100644
index 0000000..0416b73
--- /dev/null
+++ b/web/components/ProductionLog.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { clock, MILESTONE_LABELS, type BuilderState, type LogLine } from "@/lib/builder";
+import InfoTip, { HELP } from "./InfoTip";
+
+type Filter = "all" | "notes" | "tools" | "milestones";
+const FILTERS: { id: Filter; label: string }[] = [
+ { id: "all", label: "All" },
+ { id: "notes", label: "Notes" },
+ { id: "tools", label: "Tools" },
+ { id: "milestones", label: "Milestones" },
+];
+const MAX_LINES = 500;
+
+const keep = (f: Filter, l: LogLine) =>
+ f === "all" ||
+ (f === "notes" && l.kind === "note") ||
+ (f === "tools" && l.kind === "tool") ||
+ (f === "milestones" && (l.kind === "milestone" || l.kind === "critic" || l.kind === "system"));
+
+/** The agent's work as a typed production log: every tool call, every note, milestones and critic rounds. */
+export default function ProductionLog({ run }: { run: BuilderState }) {
+ const [filter, setFilter] = useState<Filter>("all");
+ const [all, setAll] = useState(false);
+ const box = useRef<HTMLDivElement>(null);
+ const stick = useRef(true);
+ const lines = run.lines.filter((l) => keep(filter, l));
+ const hidden = all ? 0 : Math.max(0, lines.length - MAX_LINES);
+ const shown = hidden ? lines.slice(-MAX_LINES) : lines;
+ const tools = run.lines.filter((l) => l.kind === "tool").length;
+ const notes = run.lines.filter((l) => l.kind === "note").length;
+
+ // stay pinned to the newest line unless the reader has scrolled up
+ useLayoutEffect(() => {
+ const el = box.current;
+ if (el && stick.current) el.scrollTop = el.scrollHeight;
+ }, [shown.length, filter]);
+ useEffect(() => {
+ const el = box.current;
+ if (!el) return;
+ const onScroll = () => (stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40);
+ el.addEventListener("scroll", onScroll);
+ return () => el.removeEventListener("scroll", onScroll);
+ }, []);
+
+ return (
+ <div className="prodlog">
+ <div className="shelf-head">
+ <h3 className="sheet-h shelf-title">Production log <InfoTip label="the production log" text={HELP.log} /></h3>
+ <span className="shelf-count">
+ {run.status === "idle" ? (
+ <span className="muted">Every tool call and note from the builder is typed up here.</span>
+ ) : (
+ <>
+ <b>{tools}</b> tool calls, <b>{notes}</b> notes, <b>{run.critiques.length}</b> critic rounds
+ </>
+ )}
+ </span>
+ <span className="vp-spacer" />
+ <div className="seg small" role="group" aria-label="Log filter">
+ {FILTERS.map((f) => (
+ <button key={f.id} className={filter === f.id ? "on" : ""} onClick={() => setFilter(f.id)} aria-pressed={filter === f.id}>
+ {f.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="log-lines" ref={box} role="log" aria-live="off">
+ {hidden > 0 && (
+ <button className="text-btn earlier" onClick={() => setAll(true)}>
+ {hidden} earlier lines
+ </button>
+ )}
+ {shown.map((l) => (
+ <div key={l.id} className={`ll ${l.kind}`}>
+ <span className="ll-t">{clock(l.t)}</span>
+ <span className="ll-k">{label(l)}</span>
+ <span className="ll-x">
+ {l.text}
+ {l.image && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={l.image} alt="" loading="lazy" />
+ )}
+ </span>
+ </div>
+ ))}
+ {run.status === "running" && (
+ <div className="ll cursor" aria-hidden>
+ <span className="ll-t" />
+ <span className="ll-k" />
+ <span className="ll-x">
+ <i className="caret" />
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function label(l: LogLine) {
+ if (l.kind === "tool") return (l.tool || "tool").replace(/^mcp__\w+__/, "").toUpperCase();
+ if (l.kind === "note") return "NOTE";
+ if (l.kind === "critic") return "CRITIC";
+ if (l.kind === "milestone") return (MILESTONE_LABELS[l.stage] ?? l.stage).toUpperCase();
+ return l.stage === "failed" ? "HOLD" : l.stage.toUpperCase();
+}
diff --git a/web/components/PropShelf.tsx b/web/components/PropShelf.tsx
new file mode 100644
index 0000000..da16d31
--- /dev/null
+++ b/web/components/PropShelf.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import type { PropTile, RunState } from "@/lib/run";
+import type { Plan } from "@/lib/types";
+import { SPRITE_FRAMES, turntableSprite } from "@/lib/three-util";
+import { modelName } from "./Viewer3D";
+
+interface Props {
+ run: RunState;
+ plan: Plan | null;
+ selected: string | null;
+ onSelect: (id: string) => void;
+}
+
+export default function PropShelf({ run, plan, selected, onSelect }: Props) {
+ const scroller = useRef<HTMLDivElement>(null);
+ const tiles = run.propOrder.map((id) => run.props[id]);
+ const meshed = tiles.filter((t) => t.mesh_url).length;
+ const failed = tiles.filter((t) => t.status === "failed").length;
+ const total = run.totalProps ?? 0;
+ const ghosts = Math.max(0, total - tiles.length);
+ const meshPhaseOver = run.stages.generating_meshes?.status === "done" || run.status === "done";
+ const finalStandins = run.status === "done";
+ const generated = plan ? plan.objects.filter((o) => o.generate).length : 0;
+
+ // keep the newest arrival in view
+ const n = tiles.length;
+ useEffect(() => {
+ const el = scroller.current;
+ if (el && n) el.scrollTo({ left: el.scrollWidth, behavior: "smooth" });
+ }, [n]);
+
+ return (
+ <div className="shelf">
+ <div className="shelf-head">
+ <h3 className="sheet-h shelf-title">Prop manifest</h3>
+ {run.kind ? (
+ <span className="shelf-count">
+ <b>{meshed}</b> of {total || "…"} meshed
+ {run.totalPlacements ? <span className="muted">, placed {run.totalPlacements} times</span> : null}
+ {failed ? <span className="bad">, {failed} failed</span> : null}
+ </span>
+ ) : (
+ <span className="shelf-count muted">
+ {plan ? `${generated} objects will be generated. Approve the plan to start.` : "Every generated prop appears here during the build."}
+ </span>
+ )}
+ </div>
+ <div className="shelf-row" ref={scroller}>
+ {tiles.map((t, i) => (
+ <Tile
+ key={t.id}
+ no={i + 1}
+ tile={t}
+ selected={selected === t.id}
+ onSelect={onSelect}
+ standin={!t.mesh_url && t.status !== "failed" && meshPhaseOver}
+ final={finalStandins}
+ />
+ ))}
+ {Array.from({ length: ghosts }).map((_, i) => (
+ <div className="tile ghost" key={`g${i}`} aria-hidden>
+ <div className="tile-media" />
+ <div className="tile-label" />
+ <div className="tile-tag">
+ <span className="no">P-{String(tiles.length + i + 1).padStart(3, "0")}</span>
+ <span className="tag">CALLED</span>
+ </div>
+ </div>
+ ))}
+ {!run.kind && (
+ <div className="shelf-empty">
+ {Array.from({ length: 7 }).map((_, i) => (
+ <div className="tile ghost" key={i} style={{ opacity: 1 - i * 0.13 }} aria-hidden>
+ <div className="tile-media" />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Tile({ no, tile, selected, onSelect, standin, final }: { no: number; tile: PropTile; selected: boolean; onSelect: (id: string) => void; standin: boolean; final: boolean }) {
+ const [sprite, setSprite] = useState<string | null>(null);
+ const [spriteErr, setSpriteErr] = useState(false);
+ useEffect(() => {
+ if (!tile.mesh_url) return;
+ let live = true;
+ turntableSprite(tile.mesh_url)
+ .then((u) => live && setSprite(u))
+ .catch(() => live && setSpriteErr(true));
+ return () => {
+ live = false;
+ };
+ }, [tile.mesh_url]);
+
+ const state = tile.status === "failed" ? "failed" : tile.mesh_url ? (sprite ? "spinning" : "loading") : standin ? "standin" : "meshing";
+ const clickable = !!tile.mesh_url;
+ const tag =
+ state === "failed" ? "FAILED" : state === "standin" ? "STAND-IN" : tile.mesh_url ? modelName(tile.model).toUpperCase() || "IN" : "IN SHOP";
+ return (
+ <button
+ className={`tile ${state} ${selected ? "sel" : ""}`}
+ onClick={() => clickable && onSelect(tile.id)}
+ disabled={!clickable}
+ title={tile.label + (state === "standin" && !final ? " (stand-in until its mesh lands)" : "")}
+ aria-label={`P-${String(no).padStart(3, "0")} ${tile.label}: ${tag}`}
+ >
+ <div className="tile-media">
+ {tile.ref_url ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img className="tile-ref" src={tile.ref_url} alt="" loading="lazy" />
+ ) : (
+ <span className="tile-initial">{tile.label.slice(0, 1)}</span>
+ )}
+ {sprite && (
+ <div
+ className="tile-sprite"
+ style={{ backgroundImage: `url(${sprite})`, ["--frames" as string]: SPRITE_FRAMES } as React.CSSProperties}
+ />
+ )}
+ {state === "meshing" && <span className="tile-spin" aria-hidden />}
+ {state === "loading" && !spriteErr && <span className="tile-spin small" aria-hidden />}
+ </div>
+ <div className="tile-label">{tile.label}</div>
+ <div className="tile-tag">
+ <span className="no">P-{String(no).padStart(3, "0")}</span>
+ <span className={`tag ${state}`}>{tag}</span>
+ </div>
+ </button>
+ );
+}
diff --git a/web/components/Result.tsx b/web/components/Result.tsx
new file mode 100644
index 0000000..4466b23
--- /dev/null
+++ b/web/components/Result.tsx
@@ -0,0 +1,96 @@
+"use client";
+
+import { useState } from "react";
+import { fmtTime, type RunState } from "@/lib/run";
+import { STAGE_LABELS, type BuildResponse } from "@/lib/types";
+
+const TIMING_LABELS: Record<string, string> = {
+ meshes_s: "Meshes, to deadline",
+ assemble_s: "Assembly",
+ render_s: "Final stills",
+ package_s: "Package upload",
+ total_s: "Total",
+};
+
+/** End state: stills, timings, package. */
+export default function Result({ res, run, planRun }: { res: BuildResponse; run: RunState; planRun: RunState }) {
+ const [i, setI] = useState(0);
+ const still = res.stills[i];
+ const stageRows = run.order
+ .filter((s) => s !== "done" && run.stages[s].start !== undefined)
+ .map((s) => ({ s, d: (run.stages[s].end ?? run.lastAt) - (run.stages[s].start ?? 0) }));
+ const planTotal = planRun.stages.done?.end ?? planRun.lastAt;
+ const meshed = Object.values(run.props).filter((p) => p.mesh_url).length;
+ const total = run.totalProps ?? run.propOrder.length;
+
+ return (
+ <div className="result">
+ <div className="result-main">
+ {still ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img className="result-still" src={still} alt={`Still ${i + 1}`} />
+ ) : (
+ <div className="empty">
+ <p>No stills were returned.</p>
+ </div>
+ )}
+ {res.stills.length > 1 && (
+ <div className="result-thumbs">
+ {res.stills.map((s, k) => (
+ <button key={s} className={k === i ? "on" : ""} onClick={() => setI(k)} aria-label={`Still ${k + 1}`}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={s} alt="" />
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="result-side">
+ <div className="result-head">
+ <span className="serif">{res.scene_id}</span>
+ <span className="muted">
+ {meshed} of {total} props meshed{res.standins_left.length ? `, ${res.standins_left.length} stand-ins` : ""}
+ </span>
+ </div>
+ {res.package_url ? (
+ <a className="primary as-link" href={res.package_url} download>
+ Download scene package
+ </a>
+ ) : (
+ <span className="muted">No package URL in this run.</span>
+ )}
+ {res.scene_blend_url && (
+ <a className="secondary as-link" href={res.scene_blend_url} download>
+ scene.blend only
+ </a>
+ )}
+ <table className="timings">
+ <caption>Timings</caption>
+ <tbody>
+ {planTotal > 0 && (
+ <tr>
+ <th>Plan</th>
+ <td>{fmtTime(planTotal)}</td>
+ </tr>
+ )}
+ {stageRows.map((r) => (
+ <tr key={r.s}>
+ <th>{STAGE_LABELS[r.s] ?? r.s}</th>
+ <td>{fmtTime(r.d)}</td>
+ </tr>
+ ))}
+ {Object.entries(res.timings).map(([k, v]) => (
+ <tr key={k} className={k === "total_s" ? "total" : "server"}>
+ <th>{TIMING_LABELS[k] ?? k.replace(/_s$/, "").replace(/_/g, " ")}</th>
+ <td>{fmtTime(v)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {res.standins_left.length > 0 && (
+ <p className="fine">Still stand-in boxes: {res.standins_left.join(", ").replace(/_/g, " ")}</p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/SceneView.tsx b/web/components/SceneView.tsx
new file mode 100644
index 0000000..f8979f3
--- /dev/null
+++ b/web/components/SceneView.tsx
@@ -0,0 +1,138 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import * as THREE from "three";
+import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
+import { disposeObject, envFor, loadEquirect, loadGlb, pmremFrom } from "@/lib/three-util";
+
+/** Free-orbit view of the assembled scene glTF (KHR_lights_punctual lights come in with it), lit by the
+ * reference-camera panorama so it approximates Blender's lighting. */
+export default function SceneView({
+ url,
+ envUrl,
+ camera,
+}: {
+ url: string;
+ envUrl?: string | null;
+ camera?: { position: number[]; look_at: number[]; lens_mm: number } | null;
+}) {
+ const host = useRef<HTMLDivElement>(null);
+ const [progress, setProgress] = useState(0);
+ const [state, setState] = useState<"loading" | "ready" | "error">("loading");
+ const [info, setInfo] = useState("");
+
+ useEffect(() => {
+ const el = host.current!;
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ el.appendChild(renderer.domElement);
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0xefe8d6);
+ const studio = envFor(renderer);
+ scene.environment = studio;
+ let env: THREE.Texture | null = null;
+ const cam = new THREE.PerspectiveCamera(45, 1, 0.05, 500);
+ const controls = new OrbitControls(cam, renderer.domElement);
+ controls.enableDamping = true;
+ let model: THREE.Object3D | null = null;
+ let disposed = false;
+ setState("loading");
+
+ if (envUrl) {
+ loadEquirect(envUrl)
+ .then((tex) => {
+ if (disposed) return tex.dispose();
+ env = pmremFrom(renderer, tex);
+ tex.dispose();
+ scene.environment = env;
+ scene.environmentIntensity = 0.8;
+ })
+ .catch(() => {});
+ }
+
+ loadGlb(url, setProgress)
+ .then((g) => {
+ if (disposed) return disposeObject(g);
+ scene.add(g);
+ model = g;
+ let lights = 0;
+ let meshes = 0;
+ g.traverse((o) => {
+ if ((o as THREE.Light).isLight) lights++;
+ if ((o as THREE.Mesh).isMesh) meshes++;
+ });
+ setInfo(`${meshes} meshes, ${lights} lights`);
+ const box = new THREE.Box3().setFromObject(g);
+ const size = box.getSize(new THREE.Vector3());
+ const c = box.getCenter(new THREE.Vector3());
+ const r = Math.max(size.x, size.z);
+ controls.target.set(c.x, size.y * 0.25 + box.min.y, c.z);
+ // high three-quarter view from the entrance side (glTF +Z is the plan's front wall)
+ cam.position.set(c.x + r * 0.35, box.min.y + r * 0.75, box.max.z + r * 0.55);
+ if (!camera) {
+ // no camera from the build: stand inside the set at eye height, looking down its length
+ cam.position.set(c.x, box.min.y + Math.min(1.7, size.y * 0.5), c.z + size.z * 0.35);
+ controls.target.set(c.x, box.min.y + Math.min(1.2, size.y * 0.35), c.z - size.z * 0.2);
+ } else {
+ // start where the reference camera stands (plan x, y, z -> glTF x, z, -y), inside the set
+ const [px, py, pz] = camera.position;
+ const [lx, ly, lz] = camera.look_at;
+ const inside = (v: number, lo: number, hi: number) => Math.min(hi - 0.3, Math.max(lo + 0.3, v));
+ cam.position.set(inside(px, box.min.x, box.max.x), inside(pz, box.min.y, box.max.y), inside(-py, box.min.z, box.max.z));
+ controls.target.set(lx, lz, -ly);
+ cam.fov = (2 * Math.atan(12 / camera.lens_mm) * 180) / Math.PI;
+ cam.updateProjectionMatrix();
+ }
+ controls.maxDistance = r * 3;
+ setState("ready");
+ })
+ .catch(() => !disposed && setState("error"));
+
+ const resize = () => {
+ renderer.setSize(el.clientWidth, el.clientHeight);
+ cam.aspect = el.clientWidth / Math.max(1, el.clientHeight);
+ cam.updateProjectionMatrix();
+ };
+ const ro = new ResizeObserver(resize);
+ ro.observe(el);
+ resize();
+ let raf = 0;
+ const loop = () => {
+ raf = requestAnimationFrame(loop);
+ controls.update();
+ renderer.render(scene, cam);
+ };
+ loop();
+ return () => {
+ disposed = true;
+ cancelAnimationFrame(raf);
+ ro.disconnect();
+ controls.dispose();
+ if (model) disposeObject(model);
+ env?.dispose();
+ studio.dispose();
+ renderer.dispose();
+ el.removeChild(renderer.domElement);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [url, envUrl]);
+
+ return (
+ <div className="viewer3d">
+ <div className="viewer3d-canvas" ref={host} />
+ {state === "loading" && (
+ <div className="viewer3d-load">
+ <div className="tick">
+ <span style={{ width: `${Math.max(2, progress * 100)}%` }} />
+ </div>
+ <span>Loading set model {Math.round(progress * 100)}%</span>
+ </div>
+ )}
+ {state === "error" && <div className="viewer3d-load">The set model couldn&apos;t be loaded.</div>}
+ {info && <span className="live-tag">{info}{envUrl ? ", lit by the 360 plate" : ""}</span>}
+ <p className="viewer-hint">drag to orbit, right-drag to pan, scroll to zoom</p>
+ </div>
+ );
+}
diff --git a/web/components/Shell.tsx b/web/components/Shell.tsx
new file mode 100644
index 0000000..b375d07
--- /dev/null
+++ b/web/components/Shell.tsx
@@ -0,0 +1,34 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useSearchParams } from "next/navigation";
+import Studio from "./Studio";
+import BuilderStudio from "./BuilderStudio";
+import Gallery from "./Gallery";
+
+/** Picks the product: the agent builder (default) or the older plan + build pipeline.
+ * ?mode=pipeline forces the pipeline; a replay picks whichever kind its recording is; ?view=gallery shows everyone's
+ * builds (a card opens one in the builder view as ?open=<id>). */
+export default function Shell() {
+ const params = useSearchParams();
+ const mode = params.get("mode");
+ const replay = params.get("replay");
+ const [kind, setKind] = useState<"builder" | "pipeline" | null>(mode === "pipeline" ? "pipeline" : !replay ? "builder" : null);
+
+ useEffect(() => {
+ if (mode === "pipeline") return setKind("pipeline");
+ if (!replay) return setKind("builder");
+ let live = true;
+ fetch(`/replay/${encodeURIComponent(replay)}/manifest.json`)
+ .then((r) => (r.ok ? r.json() : null))
+ .then((m) => live && setKind(m?.kind === "pipeline" ? "pipeline" : "builder"))
+ .catch(() => live && setKind("builder"));
+ return () => {
+ live = false;
+ };
+ }, [mode, replay]);
+
+ if (params.get("view") === "gallery") return <Gallery />;
+ if (!kind) return null;
+ return kind === "pipeline" ? <Studio /> : <BuilderStudio />;
+}
diff --git a/web/components/ShotsOrder.tsx b/web/components/ShotsOrder.tsx
new file mode 100644
index 0000000..248daea
--- /dev/null
+++ b/web/components/ShotsOrder.tsx
@@ -0,0 +1,169 @@
+"use client";
+
+import { useState } from "react";
+import type { BuilderEvent, BuilderResponse, ShotsResponse } from "@/lib/builder";
+import { LiveSource } from "@/lib/sources";
+import Dials, { setDials, type DialValues } from "./Dials";
+import InfoTip, { HELP } from "./InfoTip";
+
+type Line = { t: number; stage: string; text: string; image?: string };
+
+/** Order shots of a finished build: pick scouting previews or describe new ones, as stills or as video
+ * (the builder app's /scene2image, /scene2video). The shots agent's events stream into a short log; results land below. */
+export default function ShotsOrder({ res, source }: { res: BuilderResponse; source: LiveSource | null }) {
+ const [picked, setPicked] = useState<string[]>([]);
+ const [described, setDescribed] = useState<string[]>([]);
+ const [draft, setDraft] = useState("");
+ const [mode, setMode] = useState<"images" | "video">("images");
+ const [seconds, setSeconds] = useState(6);
+ const [handheld, setHandheld] = useState<"none" | "walk" | "subtle">("subtle");
+ const [dials, setDialValues] = useState<DialValues>({});
+ const [lines, setLines] = useState<Line[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [out, setOut] = useState<ShotsResponse | null>(null);
+ const [error, setError] = useState("");
+
+ const previews = res.previews ?? [];
+ const count = picked.length + described.length;
+ const toggle = (n: string) => setPicked((p) => (p.includes(n) ? p.filter((x) => x !== n) : [...p, n]));
+
+ const order = async () => {
+ if (!source || !count) return;
+ setBusy(true);
+ setOut(null);
+ setError("");
+ setLines([]);
+ try {
+ const r = await source.shots(
+ {
+ build_id: res.build_id,
+ mode,
+ shots: [...picked.map((name) => ({ name })), ...described.map((description) => ({ description }))],
+ settings: mode === "video" ? { seconds, handheld } : {},
+ dials: setDials(dials),
+ },
+ {
+ onEvent: (ev: BuilderEvent) => {
+ if (ev.stage === "heartbeat" || ev.stage === "log") return;
+ setLines((l) => [...l, { t: ev.t, stage: ev.stage, text: ev.message, image: ev.preview_url }]);
+ },
+ },
+ );
+ setOut(r);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <section className="shots-order">
+ <h3 className="sheet-h">
+ Order shots <span className="sheet-h-sub">scene to {mode === "images" ? "images" : "video"}</span>{" "}
+ <InfoTip label="shot orders" text={HELP.shots} />
+ </h3>
+ {!source && <p className="fine">Shot orders run on a live build. Open a finished build without ?replay.</p>}
+
+ {previews.length > 0 && (
+ <div className="shots-previews" role="group" aria-label="Scouting previews">
+ {previews.map((p) => (
+ <button key={p.name} className={picked.includes(p.name) ? "on" : ""} onClick={() => toggle(p.name)}
+ aria-pressed={picked.includes(p.name)} disabled={busy}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={p.url} alt="" />
+ <span>{p.name.replace(/_/g, " ")}</span>
+ </button>
+ ))}
+ </div>
+ )}
+
+ <div className="shots-describe">
+ <input id="shot-describe" value={draft} disabled={busy} onChange={(e) => setDraft(e.target.value)}
+ placeholder="Describe a shot: slow push along the pastry case, ending close on the croissants"
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && draft.trim()) {
+ setDescribed((d) => [...d, draft.trim()]);
+ setDraft("");
+ }
+ }} />
+ <button className="secondary" disabled={busy || !draft.trim()}
+ onClick={() => { setDescribed((d) => [...d, draft.trim()]); setDraft(""); }}>Add</button>
+ </div>
+ {described.length > 0 && (
+ <ul className="shots-list">
+ {described.map((d, i) => (
+ <li key={i}>
+ {d}{" "}
+ <button className="text-btn" disabled={busy} onClick={() => setDescribed((x) => x.filter((_, k) => k !== i))}>
+ remove
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ <div className="shots-settings">
+ <div className="seg small" role="group" aria-label="Output">
+ {(["images", "video"] as const).map((m) => (
+ <button key={m} className={mode === m ? "on" : ""} onClick={() => setMode(m)} disabled={busy}>
+ {m === "images" ? "Stills" : "Video"}
+ </button>
+ ))}
+ </div>
+ {mode === "video" && (
+ <>
+ <label className="field inline">
+ <span className="field-label">Seconds</span>
+ <input id="shot-seconds" type="number" min={2} max={30} value={seconds} disabled={busy}
+ onChange={(e) => setSeconds(Number(e.target.value) || 6)} />
+ </label>
+ <div className="seg small" role="group" aria-label="Camera">
+ {(["none", "subtle", "walk"] as const).map((h) => (
+ <button key={h} className={handheld === h ? "on" : ""} onClick={() => setHandheld(h)} disabled={busy}>
+ {h === "none" ? "Locked off" : h === "subtle" ? "Subtle handheld" : "Walk"}
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ <Dials value={dials} onChange={setDialValues} disabled={busy}
+ note="Changes the set for this order only; the build stays as it is." />
+ <button className="primary" disabled={!source || !count || busy} onClick={order}>
+ {busy ? "Shooting" : `Shoot ${count || ""} ${mode === "images" ? "still" : "clip"}${count === 1 ? "" : "s"}`}
+ </button>
+ {error && <p className="error-note">{error}</p>}
+
+ {lines.length > 0 && (
+ <ol className="shots-log">
+ {lines.map((l, i) => (
+ <li key={i}>
+ <b>{l.stage}</b> {l.text}
+ {l.image && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={l.image} alt="" />
+ )}
+ </li>
+ ))}
+ </ol>
+ )}
+
+ {out && (
+ <div className="shots-out">
+ {out.stills.map((u) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <a key={u} href={u} target="_blank" rel="noreferrer"><img src={u} alt="Still" /></a>
+ ))}
+ {out.videos.map((u) => (
+ <video key={u} src={u} controls playsInline muted loop />
+ ))}
+ <p className="fine">
+ {out.minutes.toFixed(0)} min{out.agent_cost_usd != null ? `, agent $${out.agent_cost_usd.toFixed(2)}` : ""}
+ {out.missing.length ? `. Missing: ${out.missing.join("; ")}` : ""}
+ </p>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/web/components/Stages.tsx b/web/components/Stages.tsx
new file mode 100644
index 0000000..89bf90e
--- /dev/null
+++ b/web/components/Stages.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import { fmtTime, type RunState } from "@/lib/run";
+import { STAGE_LABELS } from "@/lib/types";
+import Stamp from "./Stamp";
+
+interface Props {
+ run: RunState;
+ now: number;
+ kind: "plan" | "build";
+ previous: { label: string; time?: number } | null;
+}
+
+/** The stages as a call-sheet schedule: #, department, status. */
+export default function Stages({ run, now, kind, previous }: Props) {
+ const rows = run.order.filter((s) => s !== "done");
+ return (
+ <section className="schedule" aria-label="Schedule">
+ <h3 className="sheet-h">
+ Schedule <span className="sheet-h-sub">{kind === "build" ? "build" : "plan"}</span>
+ </h3>
+ <table className="sched">
+ <thead>
+ <tr>
+ <th scope="col">#</th>
+ <th scope="col">Dept</th>
+ <th scope="col">Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ {previous && (
+ <tr className="prev">
+ <td>0</td>
+ <td>{previous.label}</td>
+ <td className="wrapped">WRAPPED {fmtTime(previous.time)}</td>
+ </tr>
+ )}
+ {rows.map((s, i) => {
+ const st = run.stages[s];
+ const status = run.status === "idle" ? "pending" : st.status;
+ const dur = st.start === undefined ? undefined : (st.end ?? now) - st.start;
+ const counts = s === "generating_meshes" || s === "prop_references";
+ const pct = st.progress !== undefined ? st.progress : undefined;
+ return (
+ <tr key={s} className={status}>
+ <td>{i + 1}</td>
+ <td>
+ <div className="dept">{STAGE_LABELS[s] ?? s}</div>
+ {status === "running" && st.message && <div className="dept-msg">{st.message}</div>}
+ {status === "running" && pct !== undefined && (
+ <div className="tick" aria-hidden>
+ <span style={{ width: `${Math.max(2, pct * 100)}%` }} />
+ </div>
+ )}
+ </td>
+ <td className="st">
+ {status === "done" && (
+ <span className="wrapped">
+ WRAPPED {fmtTime(dur)}
+ {counts && run.totalProps ? <span className="st-sub">{Math.round((pct ?? 1) * run.totalProps)} / {run.totalProps}</span> : null}
+ </span>
+ )}
+ {status === "running" && (
+ <>
+ <Stamp tilt={-5}>ROLLING</Stamp>
+ <span className="st-sub">
+ {fmtTime(dur)}
+ {counts && run.totalProps && pct !== undefined ? ` ${Math.round(pct * run.totalProps)} / ${run.totalProps}` : ""}
+ </span>
+ </>
+ )}
+ {status === "failed" && <Stamp tilt={3}>HOLD</Stamp>}
+ {status === "pending" && <span className="standby">STANDBY</span>}
+ {status === "skipped" && <span className="standby">N/A</span>}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ {run.status === "failed" && run.error && <p className="error-note">{run.error}</p>}
+ </section>
+ );
+}
diff --git a/web/components/Stamp.tsx b/web/components/Stamp.tsx
new file mode 100644
index 0000000..40db81c
--- /dev/null
+++ b/web/components/Stamp.tsx
@@ -0,0 +1,8 @@
+/** A red rubber stamp. Thunks in (scale + rotate) the first time it renders. */
+export default function Stamp({ children, tilt = -4, big = false, ink = false }: { children: React.ReactNode; tilt?: number; big?: boolean; ink?: boolean }) {
+ return (
+ <span className={`stamp ${big ? "big" : ""} ${ink ? "ink" : ""}`} style={{ ["--tilt" as string]: `${tilt}deg` } as React.CSSProperties}>
+ {children}
+ </span>
+ );
+}
diff --git a/web/components/Studio.tsx b/web/components/Studio.tsx
new file mode 100644
index 0000000..6ed3937
--- /dev/null
+++ b/web/components/Studio.tsx
@@ -0,0 +1,332 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
+import { useSearchParams } from "next/navigation";
+import { initialRun, runReducer, type RunState } from "@/lib/run";
+import { APP_ID, LiveSource, ReplaySource, type Source } from "@/lib/sources";
+import type { BuildResponse, PlanResponse, StageEvent } from "@/lib/types";
+import Inputs, { type InputsState } from "./Inputs";
+import Stages from "./Stages";
+import Viewport, { type TabId } from "./Viewport";
+import PropShelf from "./PropShelf";
+import PlanPanel from "./PlanPanel";
+import Stamp from "./Stamp";
+
+export default function Studio() {
+ const params = useSearchParams();
+ const replayName = params.get("replay");
+ const auto = params.get("auto") === "1";
+ const initialSpeed = Math.max(0.25, Math.min(64, Number(params.get("speed")) || 1));
+
+ const [source, setSource] = useState<Source | null>(null);
+ const [sourceError, setSourceError] = useState<string>("");
+ const [speed, setSpeed] = useState(initialSpeed);
+
+ const [inputs, setInputs] = useState<InputsState>({
+ file: null,
+ previewUrl: "",
+ prompt: "",
+ dials: {},
+ effort: "medium",
+ tier: "draft",
+ });
+
+ const [planRun, dispatchPlan] = useReducer(runReducer, undefined, () => initialRun(null));
+ const [buildRun, dispatchBuild] = useReducer(runReducer, undefined, () => initialRun(null));
+ const [planRes, setPlanRes] = useState<PlanResponse | null>(null);
+ const [buildRes, setBuildRes] = useState<BuildResponse | null>(null);
+ const [planEnd, setPlanEnd] = useState<number | null>(null);
+ const [buildEnd, setBuildEnd] = useState<number | null>(null);
+ const [tab, setTab] = useState<TabId>("floor");
+ const [take, setTake] = useState(0);
+ const [follow, setFollow] = useState(true);
+ const followRef = useRef(true);
+ followRef.current = follow;
+ const [selected, setSelected] = useState<string | null>(null);
+ const [rightOpen, setRightOpen] = useState(true);
+ const [, setTick] = useState(0);
+ const refUrlRef = useRef<string>("");
+
+ // ---- source: live through the proxy, or a recorded run
+ useEffect(() => {
+ let cancelled = false;
+ if (replayName) {
+ ReplaySource.load(replayName, initialSpeed)
+ .then((s) => {
+ if (cancelled) return;
+ setSource(s);
+ setInputs((i) => ({ ...i, previewUrl: s.referenceUrl, prompt: "" }));
+ refUrlRef.current = s.referenceUrl;
+ })
+ .catch((e) => setSourceError(String(e.message || e)));
+ } else {
+ setSource(new LiveSource());
+ }
+ return () => {
+ cancelled = true;
+ };
+ }, [replayName, initialSpeed]);
+
+ useEffect(() => {
+ if (source instanceof ReplaySource) source.speed = speed;
+ }, [source, speed]);
+
+ const activeKind: "plan" | "build" = buildRun.kind ? "build" : "plan";
+ const run: RunState = activeKind === "build" ? buildRun : planRun;
+ const running = planRun.status === "running" || buildRun.status === "running";
+
+ // timer tick while anything runs
+ useEffect(() => {
+ if (!running) return;
+ const id = setInterval(() => setTick((n) => n + 1), 250);
+ return () => clearInterval(id);
+ }, [running]);
+
+ const clock = source ? source.clock() : 0;
+ const now = activeKind === "build" ? (buildEnd ?? clock) : (planEnd ?? (planRun.status === "idle" ? 0 : clock));
+
+ const choose = useCallback((t: TabId, user = true) => {
+ setTab(t);
+ if (user) setFollow(false);
+ }, []);
+
+ // ---- follow mode: move the viewport to whatever just arrived
+ const lastPreview = run.previews[run.previews.length - 1];
+ useEffect(() => {
+ if (!follow || !lastPreview) return;
+ if (activeKind === "plan") {
+ if (lastPreview.stage === "drawing_floor_plan") setTab("floor");
+ else if (lastPreview.stage === "blockout") setTab("greybox");
+ } else setTab("live");
+ }, [follow, lastPreview, activeKind]);
+
+ // ---- requests
+ const doPlan = useCallback(
+ async (edit?: string) => {
+ if (!source) return;
+ setFollow(true);
+ setPlanEnd(null);
+ dispatchPlan({ type: "start", kind: "plan" });
+ if (!edit) {
+ dispatchBuild({ type: "reset" });
+ setBuildRes(null);
+ setBuildEnd(null);
+ setPlanRes(null);
+ setSelected(null);
+ setTab("floor");
+ }
+ const sink = { onEvent: (ev: StageEvent, t: number) => dispatchPlan({ type: "event", ev, t }) };
+ try {
+ let res: PlanResponse;
+ if (edit && planRes) {
+ res = await source.plan({ plan_id: planRes.plan_id, edit, effort: inputs.effort }, sink);
+ } else {
+ let url = refUrlRef.current;
+ if (inputs.file && source.mode === "live") {
+ url = await source.uploadReference(inputs.file);
+ refUrlRef.current = url;
+ }
+ if (!url) throw new Error("Add a reference image first.");
+ const dials = Object.fromEntries(Object.entries(inputs.dials).filter(([, v]) => v !== undefined && v !== null)) as Record<string, number | string>;
+ res = await source.plan(
+ { reference_image_urls: [url], prompt: inputs.prompt, effort: inputs.effort, ...(Object.keys(dials).length ? { dials } : {}) },
+ sink,
+ );
+ }
+ setPlanRes(res);
+ dispatchPlan({ type: "finish", t: source.clock() });
+ setPlanEnd(source.clock());
+ if (followRef.current) setTab("greybox");
+ } catch (e) {
+ const msg = errorMessage(e);
+ dispatchPlan({ type: "fail", message: msg, t: source.clock() });
+ setPlanEnd(source.clock());
+ }
+ },
+ [source, inputs, planRes],
+ );
+
+ const doBuild = useCallback(async () => {
+ if (!source || !planRes) return;
+ setFollow(true);
+ setBuildEnd(null);
+ setBuildRes(null);
+ setTab("floor");
+ setTake((n) => n + 1);
+ dispatchBuild({ type: "start", kind: "build" });
+ const sink = { onEvent: (ev: StageEvent, t: number) => dispatchBuild({ type: "event", ev, t }) };
+ try {
+ const res = await source.build({ plan_id: planRes.plan_id, tier: inputs.tier }, sink);
+ setBuildRes(res);
+ dispatchBuild({ type: "finish", t: source.clock() });
+ setBuildEnd(source.clock());
+ if (followRef.current) setTab("result");
+ } catch (e) {
+ dispatchBuild({ type: "fail", message: errorMessage(e), t: source.clock() });
+ setBuildEnd(source.clock());
+ }
+ }, [source, planRes, inputs.tier]);
+
+ // ---- auto mode for screen recordings: plan, pause on the result, build
+ const autoState = useRef(0);
+ useEffect(() => {
+ if (!auto || !source) return;
+ if (autoState.current === 0) {
+ autoState.current = 1;
+ setTimeout(() => doPlan(), 1200);
+ } else if (autoState.current === 1 && planRes && planRun.status === "done") {
+ autoState.current = 2;
+ setTimeout(() => doBuild(), 3500);
+ }
+ }, [auto, source, planRes, planRun.status, doPlan, doBuild]);
+
+ const selectProp = useCallback(
+ (id: string) => {
+ setSelected(id);
+ choose("3d");
+ },
+ [choose],
+ );
+
+ const replay = source instanceof ReplaySource ? source : null;
+ const stagesMeta = useMemo(
+ () =>
+ activeKind === "build" && planRun.status === "done"
+ ? { label: "Plan approved", time: planEnd ?? undefined }
+ : null,
+ [activeKind, planRun.status, planEnd],
+ );
+
+ return (
+ <div className={`studio ${rightOpen ? "" : "right-closed"}`}>
+ <header className="topbar">
+ <div className="slate" role="group" aria-label="Slate">
+ <div className="slate-cell">
+ <small>Production</small>
+ <b>AnyScene</b>
+ </div>
+ <div className="slate-cell">
+ <small>Scene</small>
+ <b>{sceneCode(planRes?.plan?.name, planRes?.plan?.objects.length)}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Take</small>
+ <b>{String(take).padStart(2, "0")}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Roll</small>
+ <b>{inputs.tier === "full" ? "FULL" : "DRAFT"}</b>
+ </div>
+ <div className="slate-cell">
+ <small>Clock</small>
+ <b className="clock">{clockText(now)}</b>
+ </div>
+ <div className="slate-stripe" aria-hidden />
+ {buildRun.status === "done" && (
+ <span className="slate-wrap">
+ <Stamp big tilt={-6}>WRAPPED</Stamp>
+ </span>
+ )}
+ </div>
+ <div className="toolbar">
+ {replay ? (
+ <div className="replay-ctl" title="Replaying a recorded run">
+ <span>Replay: {replay.manifest.name}</span>
+ <div className="speeds" role="group" aria-label="Replay speed">
+ {[1, 2, 4, 8, 16].map((s) => (
+ <button key={s} className={speed === s ? "on" : ""} onClick={() => setSpeed(s)} aria-pressed={speed === s}>
+ {s}x
+ </button>
+ ))}
+ </div>
+ </div>
+ ) : (
+ source && <span className="live-pill">Live: {APP_ID || "no app set (NEXT_PUBLIC_ANYSCENE_APP)"}</span>
+ )}
+ <span className="mode-switch">
+ <a href="/" className="text-btn">
+ builder
+ </a>{" "}
+ <span aria-hidden>/</span> Plan + build pipeline
+ </span>
+ {planRes?.plan?.name && <span className="scene-name">{planRes.plan.name.replace(/-/g, " ")}</span>}
+ <button className="text-btn" onClick={() => setRightOpen((o) => !o)} aria-expanded={rightOpen}>
+ {rightOpen ? "Hide breakdown" : "Show breakdown"}
+ </button>
+ </div>
+ </header>
+
+ <aside className="left">
+ <Inputs
+ value={inputs}
+ onChange={(v) => {
+ setInputs(v);
+ if (v.file !== inputs.file) refUrlRef.current = v.file ? "" : refUrlRef.current;
+ }}
+ disabled={running}
+ onPlan={() => doPlan()}
+ canPlan={!!(inputs.file || refUrlRef.current) && !running}
+ planning={planRun.status === "running"}
+ />
+ <Stages run={run} now={now} kind={activeKind} previous={stagesMeta} />
+ {sourceError && <p className="error-note">{sourceError}</p>}
+ </aside>
+
+ <main className="center">
+ <Viewport
+ tab={tab}
+ onTab={(t) => choose(t)}
+ follow={follow}
+ onFollow={() => setFollow(true)}
+ planRun={planRun}
+ buildRun={buildRun}
+ planRes={planRes}
+ buildRes={buildRes}
+ referenceUrl={inputs.previewUrl}
+ selected={selected}
+ onSelect={selectProp}
+ now={now}
+ activeKind={activeKind}
+ />
+ </main>
+
+ <section className="shelf-wrap">
+ <PropShelf run={buildRun} plan={planRes?.plan ?? null} selected={selected} onSelect={selectProp} />
+ </section>
+
+ <aside className="right" aria-hidden={!rightOpen}>
+ <PlanPanel
+ planRes={planRes}
+ planRun={planRun}
+ buildRun={buildRun}
+ buildRes={buildRes}
+ onEdit={(t) => doPlan(t)}
+ onBuild={doBuild}
+ tier={inputs.tier}
+ busy={running}
+ />
+ </aside>
+ </div>
+ );
+}
+
+/** A short slate code from the plan name and object count: apollo-era-mission-control-night, 70 -> AEM-70. */
+function sceneCode(name?: string, n?: number) {
+ if (!name) return "--";
+ const words = name.split(/[-_\s]+/).filter((w) => w && !/^(the|a|an|of|and|at|in)$/i.test(w));
+ return `${words.slice(0, 3).map((w) => w[0].toUpperCase()).join("")}${n ? "-" + n : ""}`;
+}
+
+function clockText(s: number) {
+ s = Math.max(0, Math.floor(s));
+ return `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
+}
+
+function errorMessage(e: unknown): string {
+ if (!e) return "Request failed";
+ const anyE = e as { body?: { detail?: unknown }; message?: string };
+ const d = anyE.body?.detail;
+ if (typeof d === "string") return d;
+ if (Array.isArray(d) && d[0]?.msg) return String(d[0].msg);
+ return anyE.message || String(e);
+}
diff --git a/web/components/Viewer3D.tsx b/web/components/Viewer3D.tsx
new file mode 100644
index 0000000..70029a2
--- /dev/null
+++ b/web/components/Viewer3D.tsx
@@ -0,0 +1,203 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import * as THREE from "three";
+import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
+import { disposeObject, envFor, loadEquirect, loadGlb, pmremFrom } from "@/lib/three-util";
+
+export const modelName = (m?: string | null) => (!m ? "" : m.startsWith("tripo") ? "Tripo" : m.startsWith("meshy") ? "Meshy" : m);
+
+interface Props {
+ url: string;
+ label: string;
+ model?: string | null;
+ refUrl?: string | null;
+ /** The plan's size for this prop in metres (w, d, h); the mesh is scaled so its largest side matches. */
+ size?: { w: number; d: number; h: number } | null;
+ /** Equirectangular HDR/PNG of the scene's lighting; a neutral studio environment until there is one. */
+ envUrl?: string | null;
+ no?: number;
+}
+
+/** Orbitable view of one prop GLB at real scale, with its bounds, a ground shadow and the scene's light if known. */
+export default function Viewer3D({ url, label, model, refUrl, size, envUrl, no }: Props) {
+ const host = useRef<HTMLDivElement>(null);
+ const sceneRef = useRef<{ renderer: THREE.WebGLRenderer; scene: THREE.Scene; studio: THREE.Texture } | null>(null);
+ const [progress, setProgress] = useState(0);
+ const [state, setState] = useState<"loading" | "ready" | "error">("loading");
+ const [dims, setDims] = useState<THREE.Vector3 | null>(null);
+ const [envState, setEnvState] = useState<"studio" | "scene">("studio");
+
+ useEffect(() => {
+ const el = host.current!;
+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
+ renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ el.appendChild(renderer.domElement);
+ const scene = new THREE.Scene();
+ const studio = envFor(renderer);
+ scene.environment = studio;
+ sceneRef.current = { renderer, scene, studio };
+ const cam = new THREE.PerspectiveCamera(32, 1, 0.01, 200);
+ const controls = new OrbitControls(cam, renderer.domElement);
+ controls.enableDamping = true;
+ controls.autoRotate = true;
+ controls.autoRotateSpeed = 1.0;
+ controls.addEventListener("start", () => (controls.autoRotate = false));
+ const key = new THREE.DirectionalLight(0xfff4e6, 1.4);
+ key.castShadow = true;
+ key.shadow.mapSize.set(2048, 2048);
+ key.shadow.radius = 5;
+ scene.add(key, key.target);
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.ShadowMaterial({ opacity: 0.32 }));
+ ground.rotation.x = -Math.PI / 2;
+ ground.receiveShadow = true;
+ scene.add(ground);
+
+ let model: THREE.Object3D | null = null;
+ let disposed = false;
+ setState("loading");
+ setProgress(0);
+ setDims(null);
+ loadGlb(url, setProgress)
+ .then((g) => {
+ if (disposed) return disposeObject(g);
+ g.traverse((o) => {
+ if ((o as THREE.Mesh).isMesh) o.castShadow = true;
+ });
+ // real scale: largest side = the plan's largest side (Tripo/Meshy meshes come in arbitrary units)
+ const box = new THREE.Box3().setFromObject(g);
+ const raw = box.getSize(new THREE.Vector3());
+ const target = size ? Math.max(size.w, size.d, size.h) : Math.max(raw.x, raw.y, raw.z);
+ const s = target / Math.max(raw.x, raw.y, raw.z, 1e-6);
+ const c = box.getCenter(new THREE.Vector3());
+ g.scale.setScalar(s);
+ g.position.set(-c.x * s, -box.min.y * s, -c.z * s);
+ const pivot = new THREE.Group();
+ pivot.add(g);
+ scene.add(pivot);
+ model = pivot;
+ const d = raw.clone().multiplyScalar(s);
+ setDims(d);
+ // dashed bounding box in ink
+ const edges = new THREE.LineSegments(
+ new THREE.EdgesGeometry(new THREE.BoxGeometry(d.x, d.y, d.z)),
+ new THREE.LineDashedMaterial({ color: 0x1f1d1a, dashSize: Math.max(d.x, d.y, d.z) * 0.03, gapSize: Math.max(d.x, d.y, d.z) * 0.02, transparent: true, opacity: 0.55 }),
+ );
+ edges.position.y = d.y / 2;
+ edges.computeLineDistances();
+ scene.add(edges);
+ const r = Math.max(d.x, d.y, d.z);
+ ground.scale.setScalar(r * 6);
+ key.position.set(r * 1.5, r * 3, r * 1.8);
+ const sc = key.shadow.camera as THREE.OrthographicCamera;
+ sc.left = sc.bottom = -r * 1.5;
+ sc.right = sc.top = r * 1.5;
+ sc.near = 0.01;
+ sc.far = r * 10;
+ sc.updateProjectionMatrix();
+ controls.target.set(0, d.y * 0.45, 0);
+ cam.position.set(r * 1.4, r * 0.9, r * 1.9);
+ cam.near = r / 200;
+ cam.far = r * 50;
+ cam.updateProjectionMatrix();
+ controls.minDistance = r * 0.4;
+ controls.maxDistance = r * 8;
+ setState("ready");
+ })
+ .catch(() => !disposed && setState("error"));
+
+ const resize = () => {
+ renderer.setSize(el.clientWidth, el.clientHeight);
+ cam.aspect = el.clientWidth / Math.max(1, el.clientHeight);
+ cam.updateProjectionMatrix();
+ };
+ const ro = new ResizeObserver(resize);
+ ro.observe(el);
+ resize();
+ let raf = 0;
+ const loop = () => {
+ raf = requestAnimationFrame(loop);
+ controls.update();
+ renderer.render(scene, cam);
+ };
+ loop();
+ return () => {
+ disposed = true;
+ cancelAnimationFrame(raf);
+ ro.disconnect();
+ controls.dispose();
+ if (model) disposeObject(model);
+ studio.dispose();
+ renderer.dispose();
+ el.removeChild(renderer.domElement);
+ sceneRef.current = null;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [url, size?.w, size?.d, size?.h]);
+
+ // the scene's own lighting, when the endpoint provides it
+ useEffect(() => {
+ const ctx = sceneRef.current;
+ if (!ctx) return;
+ if (!envUrl) {
+ ctx.scene.environment = ctx.studio;
+ setEnvState("studio");
+ return;
+ }
+ let live = true;
+ let env: THREE.Texture | null = null;
+ loadEquirect(envUrl)
+ .then((tex) => {
+ if (!live || !sceneRef.current) return tex.dispose();
+ env = pmremFrom(ctx.renderer, tex);
+ tex.dispose();
+ ctx.scene.environment = env;
+ setEnvState("scene");
+ })
+ .catch(() => setEnvState("studio"));
+ return () => {
+ live = false;
+ if (sceneRef.current) sceneRef.current.scene.environment = sceneRef.current.studio;
+ env?.dispose();
+ };
+ }, [envUrl, url]);
+
+ return (
+ <div className="viewer3d">
+ <div className="viewer3d-canvas" ref={host} />
+ {state === "loading" && (
+ <div className="viewer3d-load">
+ <div className="tick">
+ <span style={{ width: `${Math.max(2, progress * 100)}%` }} />
+ </div>
+ <span>Loading mesh {Math.round(progress * 100)}%</span>
+ </div>
+ )}
+ {state === "error" && <div className="viewer3d-load">This mesh couldn&apos;t be loaded.</div>}
+ <div className="viewer3d-info">
+ {refUrl && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={refUrl} alt={`${label} reference`} />
+ )}
+ <div>
+ {no ? <div className="v3-no">P-{String(no).padStart(3, "0")}</div> : null}
+ <div className="v3-label">{label}</div>
+ {dims && (
+ <div className="v3-dims">
+ {dims.x.toFixed(2)} x {dims.z.toFixed(2)} x {dims.y.toFixed(2)} m
+ </div>
+ )}
+ <div className="v3-meta">
+ {model && <span className={`badge ${modelName(model).toLowerCase()}`}>{modelName(model)}</span>}
+ <span className="v3-env">{envState === "scene" ? "lit by the scene" : "studio light"}</span>
+ </div>
+ </div>
+ </div>
+ <p className="viewer-hint">drag to orbit, scroll to zoom</p>
+ </div>
+ );
+}
diff --git a/web/components/Viewport.tsx b/web/components/Viewport.tsx
new file mode 100644
index 0000000..ef550e8
--- /dev/null
+++ b/web/components/Viewport.tsx
@@ -0,0 +1,247 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { fmtTime, type RunState } from "@/lib/run";
+import { STAGE_LABELS, type BuildResponse, type PlanResponse } from "@/lib/types";
+import LiveMap from "./LiveMap";
+import Compare from "./Compare";
+import Viewer3D from "./Viewer3D";
+import Result from "./Result";
+import Fade from "./Fade";
+import Pano360 from "./Pano360";
+import SceneView from "./SceneView";
+import { assetKey } from "@/lib/run";
+
+export type TabId = "floor" | "greybox" | "live" | "compare" | "3d" | "360" | "result";
+
+interface Props {
+ tab: TabId;
+ onTab: (t: TabId) => void;
+ follow: boolean;
+ onFollow: () => void;
+ planRun: RunState;
+ buildRun: RunState;
+ planRes: PlanResponse | null;
+ buildRes: BuildResponse | null;
+ referenceUrl: string;
+ selected: string | null;
+ onSelect: (id: string) => void;
+ now: number;
+ activeKind: "plan" | "build";
+}
+
+export default function Viewport(p: Props) {
+ const { tab, planRun, buildRun, planRes, buildRes } = p;
+ const run = p.activeKind === "build" ? buildRun : planRun;
+ const building = buildRun.kind !== null;
+ const [floorMode, setFloorMode] = useState<"drawing" | "map">("drawing");
+ const [greyView, setGreyView] = useState<"reference" | "overview">("reference");
+ const [view360, setView360] = useState<number>(0); // index into panoramas, or -1 for the set model
+ useEffect(() => {
+ setFloorMode(building ? "map" : "drawing");
+ }, [building]);
+
+ const floorUrl = planRes?.floor_plan_url ?? planRun.previews.find((x) => x.stage === "drawing_floor_plan")?.url;
+ const allPreviews = [...planRun.previews, ...buildRun.previews];
+ const latest = allPreviews[allPreviews.length - 1];
+ const stills = buildRes?.stills ?? buildRun.previews.filter((x) => x.stage === "rendering").map((x) => x.url);
+ const compareRender = stills[0] ?? planRes?.blockout_reference_url;
+ const sel = p.selected ? buildRun.props[p.selected] : null;
+ // 360: panoramas and the scene glTF from events, or from the response
+ const panoramas = buildRun.panoramas.length
+ ? buildRun.panoramas
+ : (buildRes?.panorama_urls ?? []).map((url, i) => ({ url, label: i === 0 ? "reference camera" : `viewpoint ${i + 1}` }));
+ const sceneGlb = buildRun.sceneGlbUrl ?? buildRes?.scene_glb_url;
+ const has360 = panoramas.length > 0 || !!sceneGlb;
+ const refPano = panoramas[0]?.url;
+ // scene lighting for the prop viewer: an explicit environment map, else the reference-camera panorama
+ const envUrl = buildRun.envUrl ?? buildRes?.environment_url ?? refPano ?? null;
+ const selSize = (() => {
+ if (!p.selected || !planRes) return null;
+ const obs = planRes.plan.objects.filter((o) => assetKey(o) === p.selected);
+ if (!obs.length) return null;
+ return { w: Math.max(...obs.map((o) => o.w)), d: Math.max(...obs.map((o) => o.d)), h: Math.max(...obs.map((o) => o.h)) };
+ })();
+ const v360 = view360 >= 0 && view360 < panoramas.length ? view360 : sceneGlb ? -1 : 0;
+
+ const tabs: { id: TabId; label: string; ready: boolean }[] = [
+ { id: "floor", label: "Floor plan", ready: !!floorUrl || !!planRes },
+ { id: "greybox", label: "Grey-box", ready: !!planRes },
+ { id: "live", label: "Live", ready: !!latest },
+ { id: "compare", label: "Compare", ready: !!(p.referenceUrl && compareRender) },
+ { id: "3d", label: "3D", ready: !!sel?.mesh_url },
+ ...(has360 ? [{ id: "360" as TabId, label: "360", ready: true }] : []),
+ ...(buildRun.status === "done" ? [{ id: "result" as TabId, label: "Result", ready: true }] : []),
+ ];
+
+ const lens = planRes?.plan.reference_camera ? `${Math.round(planRes.plan.reference_camera.lens_mm)}MM` : "";
+ const room = planRes?.plan.room;
+ const selNo = p.selected ? buildRun.propOrder.indexOf(p.selected) + 1 : 0;
+ const title =
+ tab === "floor"
+ ? `Floor plan${room ? ` · ${room.width} x ${room.depth} M` : ""}${floorMode === "map" && planRes ? " · prop map" : ""}`
+ : tab === "greybox"
+ ? greyView === "reference"
+ ? `Camera A · grey-box · reference angle${lens ? " · " + lens : ""}`
+ : "Camera B · grey-box · overview"
+ : tab === "live"
+ ? `Camera A · live${lens ? " · " + lens : ""}`
+ : tab === "compare"
+ ? `Plate vs camera A${lens ? " · " + lens : ""}`
+ : tab === "3d"
+ ? `Prop ${selNo ? "P-" + String(selNo).padStart(3, "0") : ""} · turntable${selSize ? " · real scale" : ""}`
+ : tab === "360"
+ ? v360 >= 0
+ ? `Camera B · 360 plate · ${panoramas[v360]?.label ?? ""}`
+ : "Set model · glTF · free camera"
+ : "Dailies";
+ const props = Object.values(buildRun.props);
+ const meshed = props.filter((x) => x.mesh_url).length;
+ const standins = props.filter((x) => !x.mesh_url && x.status !== "failed").length;
+ const meshPhaseOver = buildRun.stages.generating_meshes?.status === "done" || buildRun.status === "done";
+ const note = building
+ ? buildRun.status === "done"
+ ? buildRes?.standins_left.length
+ ? `${buildRes.standins_left.length} props stood in`
+ : "all props in"
+ : meshPhaseOver && standins
+ ? `${standins} props stood in`
+ : buildRun.totalProps
+ ? `${meshed} of ${buildRun.totalProps} props in`
+ : "calling props"
+ : planRun.status === "done"
+ ? "plan ready for approval"
+ : planRun.status === "running"
+ ? "planning"
+ : "";
+
+ return (
+ <div className="viewport">
+ <h3 className="sheet-h frame-title">{title}</h3>
+ <div className="vp-tabs" role="tablist">
+ {tabs.map((t) => (
+ <button
+ key={t.id}
+ role="tab"
+ aria-selected={tab === t.id}
+ className={`vp-tab ${tab === t.id ? "on" : ""} ${t.ready ? "ready" : ""}`}
+ onClick={() => p.onTab(t.id)}
+ >
+ {t.label}
+ </button>
+ ))}
+ <span className="vp-spacer" />
+ {tab === "floor" && planRes && (
+ <div className="seg small" role="group" aria-label="Floor plan view">
+ <button className={floorMode === "drawing" ? "on" : ""} onClick={() => setFloorMode("drawing")}>
+ Drawing
+ </button>
+ <button className={floorMode === "map" ? "on" : ""} onClick={() => setFloorMode("map")}>
+ Prop map
+ </button>
+ </div>
+ )}
+ {tab === "greybox" && planRes && (
+ <div className="seg small" role="group" aria-label="Grey-box view">
+ <button className={greyView === "reference" ? "on" : ""} onClick={() => setGreyView("reference")}>
+ Reference camera
+ </button>
+ <button className={greyView === "overview" ? "on" : ""} onClick={() => setGreyView("overview")}>
+ Overview
+ </button>
+ </div>
+ )}
+ {tab === "360" && has360 && (
+ <div className="seg small" role="group" aria-label="360 viewpoint">
+ {panoramas.map((pn, i) => (
+ <button key={pn.url} className={v360 === i ? "on" : ""} onClick={() => setView360(i)} title={pn.label}>
+ {i === 0 ? "Ref angle" : `Spot ${i + 1}`}
+ </button>
+ ))}
+ {sceneGlb && (
+ <button className={v360 === -1 ? "on" : ""} onClick={() => setView360(-1)}>
+ Set model
+ </button>
+ )}
+ </div>
+ )}
+ <button className={`follow ${p.follow ? "on" : ""}`} onClick={p.onFollow} title="Switch views as new results arrive">
+ <span className="follow-dot" aria-hidden /> Follow
+ </button>
+ </div>
+
+ <div className="vp-stage">
+ {note && <span className="frame-note">{note}</span>}
+ {tab === "floor" &&
+ (floorMode === "map" && planRes ? (
+ <LiveMap plan={planRes.plan} run={buildRun} selected={p.selected} onSelect={p.onSelect} />
+ ) : floorUrl ? (
+ <Fade src={floorUrl} alt="Floor plan" className="paper" />
+ ) : (
+ <Empty run={planRun} text="The floor plan is drawn once the layout is planned." />
+ ))}
+ {tab === "greybox" &&
+ (planRes ? (
+ <Fade
+ src={greyView === "reference" ? planRes.blockout_reference_url : planRes.blockout_overview_url}
+ alt={greyView === "reference" ? "Grey-box from the reference camera" : "Grey-box overview"}
+ />
+ ) : (
+ <Empty run={planRun} text="Grey-box renders from the reference camera and an overview land here." />
+ ))}
+ {tab === "live" &&
+ (latest ? (
+ <div className="live-frame">
+ <Fade src={latest.url} alt={latest.message || latest.stage} />
+ <span className="live-tag">
+ {STAGE_LABELS[latest.stage] ?? latest.stage}
+ {latest.message ? `: ${latest.message}` : ""}
+ </span>
+ </div>
+ ) : (
+ <Empty run={run} text="Each render the endpoint makes shows up here as it lands." />
+ ))}
+ {tab === "compare" &&
+ (p.referenceUrl && compareRender ? (
+ <Compare left={p.referenceUrl} right={compareRender} rightLabel={stills[0] ? "Render" : "Grey-box"} />
+ ) : (
+ <Empty run={run} text="Compare the reference with the matching render once there is one." />
+ ))}
+ {tab === "3d" &&
+ (sel?.mesh_url ? (
+ <Viewer3D url={sel.mesh_url} label={sel.label} model={sel.model} refUrl={sel.ref_url} size={selSize} envUrl={envUrl} no={selNo} />
+ ) : (
+ <Empty run={run} text={sel ? "This prop has no mesh yet." : "Pick a prop on the shelf to inspect its mesh."} />
+ ))}
+ {tab === "360" &&
+ has360 &&
+ (v360 >= 0 && panoramas[v360] ? <Pano360 url={panoramas[v360].url} /> : sceneGlb ? <SceneView url={sceneGlb} envUrl={refPano} camera={planRes?.plan.reference_camera} /> : null)}
+ {tab === "result" && buildRes && <Result res={buildRes} run={buildRun} planRun={planRun} />}
+ </div>
+
+ <div className="caption" aria-live="polite">
+ <span className="caption-text" key={run.caption.message}>
+ {run.status === "idle"
+ ? "Drop a reference, plan the space, then build it."
+ : run.status === "failed"
+ ? run.error
+ : run.status === "done" && p.activeKind === "plan"
+ ? "Plan ready. Revise it in words or approve it to build."
+ : run.status === "done"
+ ? "Scene built. Download the package or look through the stills."
+ : run.caption.message || STAGE_LABELS[run.caption.stage] || "Starting"}
+ </span>
+ <span className="caption-time">{run.status === "idle" ? "" : fmtTime(p.now)}</span>
+ </div>
+ </div>
+ );
+}
+
+function Empty({ run, text }: { run: RunState; text: string }) {
+ return (
+ <div className="empty">
+ {run.status === "running" && <span className="empty-pulse" />}
+ <p>{text}</p>
+ </div>
+ );
+}
diff --git a/web/fixtures/blockout_overview.png b/web/fixtures/blockout_overview.png
new file mode 100644
index 0000000..77b2608
Binary files /dev/null and b/web/fixtures/blockout_overview.png differ
diff --git a/web/fixtures/blockout_reference.png b/web/fixtures/blockout_reference.png
new file mode 100644
index 0000000..33a4bd2
Binary files /dev/null and b/web/fixtures/blockout_reference.png differ
diff --git a/web/fixtures/build.json b/web/fixtures/build.json
new file mode 100644
index 0000000..fa6d4c3
--- /dev/null
+++ b/web/fixtures/build.json
@@ -0,0 +1,255 @@
+{
+ "scene_id": "s_0e36d5fbec",
+ "package_url": "https://v3b.fal.media/files/b/0ab08e00/m4GTss3UapWdQmO9PaFiw_scene_package.zip",
+ "scene_blend_url": "https://v3b.fal.media/files/b/0ab08e03/9dTPt9JkZPUcpvIhhvq04_scene.blend",
+ "stills": [
+ "https://v3b.fal.media/files/b/0ab08dfe/nr0jS7nyXO8vBaTgSbGf3_0001.png",
+ "https://v3b.fal.media/files/b/0ab08dfe/AZ-FM3r8isnUvUr9oI83Z_0001.png",
+ "https://v3b.fal.media/files/b/0ab08dff/0B6ziyyAYbMjAMS7KCOq2_0001.png"
+ ],
+ "props": [
+ {
+ "id": "big_wall_display",
+ "label": "Giant orbit tracking wall display with world map and telemetry readouts",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/31vjhG9AK00OrMV-5GLix_RpsYE5df.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db6/Qf9DLRoeVAt2NMOXnCndy_model.glb"
+ },
+ "placements": [
+ "big_wall_display"
+ ]
+ },
+ {
+ "id": "wall_clock",
+ "label": "Round analogue wall clock",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/_w9HD3HRlKsXmerwMJx4Y_kMhIJ8GC.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08dbb/rc_p2lvty5IGPDjXAPy_j_model.glb"
+ },
+ "placements": [
+ "wall_clock"
+ ]
+ },
+ {
+ "id": "console_orbital_hero",
+ "label": "Hero orbital analysis console with CRT scopes and switch panels",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/_qulAvYn4R_vYNyLjdeDk_bvN3g9dh.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db9/Wkyw9krivg2gYuP7PxYwe_model.glb"
+ },
+ "placements": [
+ "console_orbital_analysis"
+ ]
+ },
+ {
+ "id": "index_cabinet",
+ "label": "Tall indexed reference cabinet labelled flight data, trajectory, systems, anomalies",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/5AW4-anXrXZRyAnlbtduh_p0Fo2o8P.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08ddc/JgTo3h2uNhmFe1YXViq7J_model.glb"
+ },
+ "placements": [
+ "console_flight_data_stack"
+ ]
+ },
+ {
+ "id": "teleprinter",
+ "label": "Chrome teleprinter spooling paper",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/6y06wKMHDZwc6zGoqYn3O_qBp4FbPT.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08dbf/wvCkHArGNGiBv2mvxH3sW_model.glb"
+ },
+ "placements": [
+ "teleprinter"
+ ]
+ },
+ {
+ "id": "console_bank",
+ "label": "Second-row console with CRT monitors",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/c8f1tOnsIyvFn3AswWi6J_l1XLxiPT.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08dbc/O0do4w3w_kTq9q5O-rGhw_model.glb"
+ },
+ "placements": [
+ "console_mission_control",
+ "console_telemetry",
+ "console_guidance",
+ "console_back_row",
+ "console_left_back"
+ ]
+ },
+ {
+ "id": "swivel_chair",
+ "label": "Black swivel chair",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/L5eyJU1KNrpAE-Y1knsCx_MngHigV5.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08dbb/OypRNzm5EteHD9eJpU41Z_model.glb"
+ },
+ "placements": [
+ "chair_fg_left",
+ "chair_fg_right",
+ "chair_row2_a",
+ "chair_row2_b",
+ "chair_telemetry_a",
+ "chair_telemetry_b",
+ "chair_guidance",
+ "chair_back_a",
+ "chair_back_b"
+ ]
+ },
+ {
+ "id": "binder_open",
+ "label": "Open ring binder of flight procedures",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/Ojx7X-ST4DqvwJBMAhk3g_t36nkBOi.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db9/fcwdszH3Goze2F8n2RnMV_model.glb"
+ },
+ "placements": [
+ "binder_fg_1",
+ "binder_fg_2",
+ "binder_mission"
+ ]
+ },
+ {
+ "id": "mug_white",
+ "label": "White coffee mug",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/HljuXiw1Oa3ryNL02KPgw_C3MuGMST.png",
+ "mesh_urls": {
+ "meshy": "https://v3b.fal.media/files/b/0ab08dc9/L72eOrBb-8bRjuqHHt6rE_model.glb"
+ },
+ "placements": [
+ "mug_white_fg",
+ "mug_white_fg_2",
+ "mug_guidance",
+ "mug_telemetry",
+ "mug_back"
+ ]
+ },
+ {
+ "id": "mug_black",
+ "label": "Black coffee mug",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/g3Xjkv8D0hhVjSU5LwvMY_OKIbtfhA.png",
+ "mesh_urls": {
+ "meshy": "https://v3b.fal.media/files/b/0ab08dc6/2nhr62QF94Su-l2zJY_2U_model.glb"
+ },
+ "placements": [
+ "mug_black_fg",
+ "mug_mission"
+ ]
+ },
+ {
+ "id": "ashtray_full",
+ "label": "Glass ashtray with cigarette butts",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/J9b6fXQB1kN7s62dWlp5P_zSi18VN2.png",
+ "mesh_urls": {
+ "meshy": "https://v3b.fal.media/files/b/0ab08dce/OcFAljrdjTGYgrMrW1GwA_model.glb"
+ },
+ "placements": [
+ "ashtray_fg_1",
+ "ashtray_fg_2",
+ "ashtray_guidance",
+ "ashtray_mission"
+ ]
+ },
+ {
+ "id": "cigarette_pack",
+ "label": "Red and white cigarette pack",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/plMTmiC7ebEMxlq-MIL5I_KjvNflol.png",
+ "mesh_urls": {
+ "meshy": "https://v3b.fal.media/files/b/0ab08dc7/ell8qpZK7Rq84aReULhVy_model.glb"
+ },
+ "placements": [
+ "cigarette_pack_fg"
+ ]
+ },
+ {
+ "id": "desk_intercom",
+ "label": "Desk intercom unit with push buttons and microphone",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/DmGzQxgiE1BVtEP8vdIbb_WpURLbUh.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db9/1J_7g3n5MKLX6NOOqihQn_model.glb"
+ },
+ "placements": [
+ "comm_box_fg"
+ ]
+ },
+ {
+ "id": "desk_lamp",
+ "label": "Brass desk lamp on console top",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da3/tOWraIMiw1qfD7FDf4Brz_GCTShC1R.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db8/PH1cmkhj6nu9ke9oCehoW_model.glb"
+ },
+ "placements": [
+ "desk_lamp_guidance",
+ "desk_lamp_window",
+ "desk_lamp_right"
+ ]
+ },
+ {
+ "id": "filing_cabinet",
+ "label": "Grey four-drawer filing cabinet",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/2cCylhD6Iovmj6nBBxHSn_1CqFOvFh.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db8/e-syzKvbc7pwy7EQvHXEV_model.glb"
+ },
+ "placements": [
+ "filing_cabinet_1",
+ "filing_cabinet_2"
+ ]
+ },
+ {
+ "id": "wastebasket",
+ "label": "Metal wastebasket with crumpled paper",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/BOUdvCxKQsqq4viOMVHEq_tliJiqKp.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08dc4/6ofddR2gi7rsE-fxcSler_model.glb"
+ },
+ "placements": [
+ "wastebasket_1",
+ "wastebasket_2"
+ ]
+ },
+ {
+ "id": "coat_rack",
+ "label": "Coat stand with jacket",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/VxfAul4Ml4cD7XhitSwLU_cLGuvmwi.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db2/VInLnUPqVwX8HiT7w74HO_model.glb"
+ },
+ "placements": [
+ "coat_rack"
+ ]
+ },
+ {
+ "id": "water_cooler",
+ "label": "Office water cooler",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/eIx9Y9z-uor3zqn87R7F9_9aWSSyyo.png",
+ "mesh_urls": {
+ "tripo-h31": "https://v3b.fal.media/files/b/0ab08db5/240g5RCEZusrYrnebtcmc_model.glb"
+ },
+ "placements": [
+ "water_cooler"
+ ]
+ },
+ {
+ "id": "rotary_phone",
+ "label": "Black rotary phone",
+ "ref_url": "https://v3b.fal.media/files/b/0ab08da2/kCAE737iDxdjqeaPe_7nz_RSri3jFJ.png",
+ "mesh_urls": {
+ "meshy": "https://v3b.fal.media/files/b/0ab08dc2/cRxfLp_tN0K5RNHP1Yt9Y_model.glb"
+ },
+ "placements": [
+ "rotary_phone"
+ ]
+ }
+ ],
+ "standins_left": [],
+ "timings": {
+ "meshes_s": 481.3,
+ "assemble_s": 249.6,
+ "render_s": 71.5,
+ "package_s": 54.1,
+ "total_s": 984.8
+ }
+}
\ No newline at end of file
diff --git a/web/fixtures/build_events.jsonl b/web/fixtures/build_events.jsonl
new file mode 100644
index 0000000..9bc5f7d
--- /dev/null
+++ b/web/fixtures/build_events.jsonl
@@ -0,0 +1,54 @@
+{"t": 12.7, "stage": "received", "status": "running", "message": "build p_4f46c795ea (draft)", "elapsed_s": 0.0}
+{"t": 12.7, "stage": "prop_references", "status": "running", "message": "19 unique props (45 placements)", "elapsed_s": 1.2, "progress": 0.0}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "water_cooler reference ready", "elapsed_s": 35.1, "prop": {"id": "water_cooler", "label": "Office water cooler", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/eIx9Y9z-uor3zqn87R7F9_9aWSSyyo.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "coat_rack reference ready", "elapsed_s": 35.4, "prop": {"id": "coat_rack", "label": "Coat stand with jacket", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/VxfAul4Ml4cD7XhitSwLU_cLGuvmwi.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "mug_black reference ready", "elapsed_s": 35.9, "prop": {"id": "mug_black", "label": "Black coffee mug", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/g3Xjkv8D0hhVjSU5LwvMY_OKIbtfhA.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "swivel_chair reference ready", "elapsed_s": 36.6, "prop": {"id": "swivel_chair", "label": "Black swivel chair", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/L5eyJU1KNrpAE-Y1knsCx_MngHigV5.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "wastebasket reference ready", "elapsed_s": 37.3, "prop": {"id": "wastebasket", "label": "Metal wastebasket with crumpled paper", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/BOUdvCxKQsqq4viOMVHEq_tliJiqKp.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "filing_cabinet reference ready", "elapsed_s": 37.6, "prop": {"id": "filing_cabinet", "label": "Grey four-drawer filing cabinet", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/2cCylhD6Iovmj6nBBxHSn_1CqFOvFh.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "rotary_phone reference ready", "elapsed_s": 38.5, "prop": {"id": "rotary_phone", "label": "Black rotary phone", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/kCAE737iDxdjqeaPe_7nz_RSri3jFJ.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "desk_intercom reference ready", "elapsed_s": 38.7, "prop": {"id": "desk_intercom", "label": "Desk intercom unit with push buttons and microphone", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/DmGzQxgiE1BVtEP8vdIbb_WpURLbUh.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "desk_lamp reference ready", "elapsed_s": 40.7, "prop": {"id": "desk_lamp", "label": "Brass desk lamp on console top", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/tOWraIMiw1qfD7FDf4Brz_GCTShC1R.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "wall_clock reference ready", "elapsed_s": 41.2, "prop": {"id": "wall_clock", "label": "Round analogue wall clock", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/_w9HD3HRlKsXmerwMJx4Y_kMhIJ8GC.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "mug_white reference ready", "elapsed_s": 41.3, "prop": {"id": "mug_white", "label": "White coffee mug", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/HljuXiw1Oa3ryNL02KPgw_C3MuGMST.png", "status": "meshing"}}
+{"t": 52.9, "stage": "prop_references", "status": "running", "message": "index_cabinet reference ready", "elapsed_s": 41.6, "prop": {"id": "index_cabinet", "label": "Tall indexed reference cabinet labelled flight data, trajectory, systems, anomalies", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/5AW4-anXrXZRyAnlbtduh_p0Fo2o8P.png", "status": "meshing"}}
+{"t": 57.5, "stage": "prop_references", "status": "running", "message": "big_wall_display reference ready", "elapsed_s": 44.9, "prop": {"id": "big_wall_display", "label": "Giant orbit tracking wall display with world map and telemetry readouts", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/31vjhG9AK00OrMV-5GLix_RpsYE5df.png", "status": "meshing"}}
+{"t": 57.5, "stage": "prop_references", "status": "running", "message": "cigarette_pack reference ready", "elapsed_s": 45.5, "prop": {"id": "cigarette_pack", "label": "Red and white cigarette pack", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/plMTmiC7ebEMxlq-MIL5I_KjvNflol.png", "status": "meshing"}}
+{"t": 58.0, "stage": "prop_references", "status": "running", "message": "binder_open reference ready", "elapsed_s": 46.9, "prop": {"id": "binder_open", "label": "Open ring binder of flight procedures", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/Ojx7X-ST4DqvwJBMAhk3g_t36nkBOi.png", "status": "meshing"}}
+{"t": 58.0, "stage": "prop_references", "status": "running", "message": "ashtray_full reference ready", "elapsed_s": 47.0, "prop": {"id": "ashtray_full", "label": "Glass ashtray with cigarette butts", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/J9b6fXQB1kN7s62dWlp5P_zSi18VN2.png", "status": "meshing"}}
+{"t": 59.1, "stage": "prop_references", "status": "running", "message": "console_bank reference ready", "elapsed_s": 47.4, "prop": {"id": "console_bank", "label": "Second-row console with CRT monitors", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/c8f1tOnsIyvFn3AswWi6J_l1XLxiPT.png", "status": "meshing"}}
+{"t": 59.1, "stage": "prop_references", "status": "running", "message": "teleprinter reference ready", "elapsed_s": 48.0, "prop": {"id": "teleprinter", "label": "Chrome teleprinter spooling paper", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/6y06wKMHDZwc6zGoqYn3O_qBp4FbPT.png", "status": "meshing"}}
+{"t": 59.1, "stage": "prop_references", "status": "running", "message": "console_orbital_hero reference ready", "elapsed_s": 48.4, "prop": {"id": "console_orbital_hero", "label": "Hero orbital analysis console with CRT scopes and switch panels", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/_qulAvYn4R_vYNyLjdeDk_bvN3g9dh.png", "status": "meshing"}}
+{"t": 190.5, "stage": "generating_meshes", "status": "running", "message": "1 of 19 props have meshes", "elapsed_s": 168.9, "progress": 0.053, "prop": {"id": "coat_rack", "label": "Coat stand with jacket", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/VxfAul4Ml4cD7XhitSwLU_cLGuvmwi.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db2/VInLnUPqVwX8HiT7w74HO_model.glb", "status": "done"}}
+{"t": 218.3, "stage": "generating_meshes", "status": "running", "message": "2 of 19 props have meshes", "elapsed_s": 199.4, "progress": 0.105, "prop": {"id": "water_cooler", "label": "Office water cooler", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/eIx9Y9z-uor3zqn87R7F9_9aWSSyyo.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db5/240g5RCEZusrYrnebtcmc_model.glb", "status": "done"}}
+{"t": 218.3, "stage": "generating_meshes", "status": "running", "message": "3 of 19 props have meshes", "elapsed_s": 207.7, "progress": 0.158, "prop": {"id": "big_wall_display", "label": "Giant orbit tracking wall display with world map and telemetry readouts", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/31vjhG9AK00OrMV-5GLix_RpsYE5df.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db6/Qf9DLRoeVAt2NMOXnCndy_model.glb", "status": "done"}}
+{"t": 249.5, "stage": "generating_meshes", "status": "running", "message": "4 of 19 props have meshes", "elapsed_s": 233.6, "progress": 0.211, "prop": {"id": "desk_lamp", "label": "Brass desk lamp on console top", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/tOWraIMiw1qfD7FDf4Brz_GCTShC1R.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db8/PH1cmkhj6nu9ke9oCehoW_model.glb", "status": "done"}}
+{"t": 249.5, "stage": "generating_meshes", "status": "running", "message": "5 of 19 props have meshes", "elapsed_s": 236.8, "progress": 0.263, "prop": {"id": "filing_cabinet", "label": "Grey four-drawer filing cabinet", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/2cCylhD6Iovmj6nBBxHSn_1CqFOvFh.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db8/e-syzKvbc7pwy7EQvHXEV_model.glb", "status": "done"}}
+{"t": 253.7, "stage": "generating_meshes", "status": "running", "message": "6 of 19 props have meshes", "elapsed_s": 242.1, "progress": 0.316, "prop": {"id": "console_orbital_hero", "label": "Hero orbital analysis console with CRT scopes and switch panels", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/_qulAvYn4R_vYNyLjdeDk_bvN3g9dh.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db9/Wkyw9krivg2gYuP7PxYwe_model.glb", "status": "done"}}
+{"t": 253.7, "stage": "generating_meshes", "status": "running", "message": "7 of 19 props have meshes", "elapsed_s": 242.4, "progress": 0.368, "prop": {"id": "binder_open", "label": "Open ring binder of flight procedures", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/Ojx7X-ST4DqvwJBMAhk3g_t36nkBOi.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db9/fcwdszH3Goze2F8n2RnMV_model.glb", "status": "done"}}
+{"t": 257.7, "stage": "generating_meshes", "status": "running", "message": "8 of 19 props have meshes", "elapsed_s": 245.4, "progress": 0.421, "prop": {"id": "desk_intercom", "label": "Desk intercom unit with push buttons and microphone", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/DmGzQxgiE1BVtEP8vdIbb_WpURLbUh.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08db9/1J_7g3n5MKLX6NOOqihQn_model.glb", "status": "done"}}
+{"t": 277.8, "stage": "generating_meshes", "status": "running", "message": "9 of 19 props have meshes", "elapsed_s": 265.7, "progress": 0.474, "prop": {"id": "wall_clock", "label": "Round analogue wall clock", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/_w9HD3HRlKsXmerwMJx4Y_kMhIJ8GC.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08dbb/rc_p2lvty5IGPDjXAPy_j_model.glb", "status": "done"}}
+{"t": 278.6, "stage": "generating_meshes", "status": "running", "message": "10 of 19 props have meshes", "elapsed_s": 268.1, "progress": 0.526, "prop": {"id": "swivel_chair", "label": "Black swivel chair", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/L5eyJU1KNrpAE-Y1knsCx_MngHigV5.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08dbb/OypRNzm5EteHD9eJpU41Z_model.glb", "status": "done"}}
+{"t": 285.3, "stage": "generating_meshes", "status": "running", "message": "11 of 19 props have meshes", "elapsed_s": 272.7, "progress": 0.579, "prop": {"id": "console_bank", "label": "Second-row console with CRT monitors", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/c8f1tOnsIyvFn3AswWi6J_l1XLxiPT.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08dbc/O0do4w3w_kTq9q5O-rGhw_model.glb", "status": "done"}}
+{"t": 316.0, "stage": "generating_meshes", "status": "running", "message": "12 of 19 props have meshes", "elapsed_s": 301.7, "progress": 0.632, "prop": {"id": "teleprinter", "label": "Chrome teleprinter spooling paper", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/6y06wKMHDZwc6zGoqYn3O_qBp4FbPT.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08dbf/wvCkHArGNGiBv2mvxH3sW_model.glb", "status": "done"}}
+{"t": 377.2, "stage": "generating_meshes", "status": "running", "message": "13 of 19 props have meshes", "elapsed_s": 359.1, "progress": 0.684, "prop": {"id": "wastebasket", "label": "Metal wastebasket with crumpled paper", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/BOUdvCxKQsqq4viOMVHEq_tliJiqKp.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08dc4/6ofddR2gi7rsE-fxcSler_model.glb", "status": "done"}}
+{"t": 377.2, "stage": "generating_meshes", "status": "running", "message": "14 of 19 props have meshes", "elapsed_s": 366.3, "progress": 0.737, "prop": {"id": "rotary_phone", "label": "Black rotary phone", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/kCAE737iDxdjqeaPe_7nz_RSri3jFJ.png", "model": "meshy", "mesh_url": "https://v3b.fal.media/files/b/0ab08dc2/cRxfLp_tN0K5RNHP1Yt9Y_model.glb", "status": "done"}}
+{"t": 488.1, "stage": "generating_meshes", "status": "running", "message": "15 of 19 props have meshes", "elapsed_s": 476.5, "progress": 0.789, "prop": {"id": "mug_black", "label": "Black coffee mug", "ref_url": "https://v3b.fal.media/files/b/0ab08da2/g3Xjkv8D0hhVjSU5LwvMY_OKIbtfhA.png", "model": "meshy", "mesh_url": "https://v3b.fal.media/files/b/0ab08dc6/2nhr62QF94Su-l2zJY_2U_model.glb", "status": "done"}}
+{"t": 491.5, "stage": "generating_meshes", "status": "running", "message": "15 of 19 done after 480 s, 4 still running (stand-ins for now)", "elapsed_s": 481.3, "progress": 0.789}
+{"t": 491.5, "stage": "generating_meshes", "status": "done", "message": "15 of 19 props ready, 4 still running", "elapsed_s": 481.3}
+{"t": 491.5, "stage": "layout", "status": "running", "message": "building the scene from the plan", "elapsed_s": 481.3}
+{"t": 493.0, "stage": "generating_meshes", "status": "running", "message": "16 of 19 props have meshes", "elapsed_s": 481.8, "progress": 0.842, "prop": {"id": "cigarette_pack", "label": "Red and white cigarette pack", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/plMTmiC7ebEMxlq-MIL5I_KjvNflol.png", "model": "meshy", "mesh_url": "https://v3b.fal.media/files/b/0ab08dc7/ell8qpZK7Rq84aReULhVy_model.glb", "status": "done"}}
+{"t": 503.0, "stage": "generating_meshes", "status": "running", "message": "17 of 19 props have meshes", "elapsed_s": 490.8, "progress": 0.895, "prop": {"id": "mug_white", "label": "White coffee mug", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/HljuXiw1Oa3ryNL02KPgw_C3MuGMST.png", "model": "meshy", "mesh_url": "https://v3b.fal.media/files/b/0ab08dc9/L72eOrBb-8bRjuqHHt6rE_model.glb", "status": "done"}}
+{"t": 612.2, "stage": "generating_meshes", "status": "running", "message": "18 of 19 props have meshes", "elapsed_s": 594.7, "progress": 0.947, "prop": {"id": "index_cabinet", "label": "Tall indexed reference cabinet labelled flight data, trajectory, systems, anomalies", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/5AW4-anXrXZRyAnlbtduh_p0Fo2o8P.png", "model": "tripo-h31", "mesh_url": "https://v3b.fal.media/files/b/0ab08ddc/JgTo3h2uNhmFe1YXViq7J_model.glb", "status": "done"}}
+{"t": 641.5, "stage": "generating_meshes", "status": "running", "message": "19 of 19 props have meshes", "elapsed_s": 622.5, "progress": 1.0, "prop": {"id": "ashtray_full", "label": "Glass ashtray with cigarette butts", "ref_url": "https://v3b.fal.media/files/b/0ab08da3/J9b6fXQB1kN7s62dWlp5P_zSi18VN2.png", "model": "meshy", "mesh_url": "https://v3b.fal.media/files/b/0ab08dce/OcFAljrdjTGYgrMrW1GwA_model.glb", "status": "done"}}
+{"t": 772.2, "stage": "layout", "status": "done", "message": "70 objects placed, 4 stand-ins", "elapsed_s": 753.3, "preview_url": "https://v3b.fal.media/files/b/0ab08ded/4D56g-JZtrjm9g2ElyEml_0001.png"}
+{"t": 772.2, "stage": "dressing", "status": "running", "message": "waiting up to 240 s for 4 late meshes", "elapsed_s": 753.3}
+{"t": 772.2, "stage": "generating_meshes", "status": "running", "message": "19 of 19 done after 752 s", "elapsed_s": 753.3, "progress": 1.0}
+{"t": 878.1, "stage": "dressing", "status": "done", "message": "swapped in 10 meshes, 0 stand-ins left, 1 dropped onto their support", "elapsed_s": 859.2, "preview_url": "https://v3b.fal.media/files/b/0ab08df7/jQQ2vHPFNHpNlUC_bgakY_0001.png"}
+{"t": 878.1, "stage": "rendering", "status": "running", "message": "stills from the reference camera and two open views", "elapsed_s": 859.2}
+{"t": 939.8, "stage": "rendering", "status": "running", "message": "ref_view done", "elapsed_s": 928.5, "preview_url": "https://v3b.fal.media/files/b/0ab08dfe/nr0jS7nyXO8vBaTgSbGf3_0001.png"}
+{"t": 939.8, "stage": "rendering", "status": "running", "message": "view_1 done", "elapsed_s": 929.4, "preview_url": "https://v3b.fal.media/files/b/0ab08dfe/AZ-FM3r8isnUvUr9oI83Z_0001.png"}
+{"t": 942.4, "stage": "rendering", "status": "running", "message": "view_2 done", "elapsed_s": 930.7, "preview_url": "https://v3b.fal.media/files/b/0ab08dff/0B6ziyyAYbMjAMS7KCOq2_0001.png"}
+{"t": 942.4, "stage": "rendering", "status": "done", "message": "3 stills", "elapsed_s": 930.7}
+{"t": 942.4, "stage": "packaging", "status": "running", "message": "", "elapsed_s": 930.7}
+{"t": 996.5, "stage": "done", "status": "done", "message": "scene s_0e36d5fbec in 985 s", "elapsed_s": 984.8, "package_url": "https://v3b.fal.media/files/b/0ab08e00/m4GTss3UapWdQmO9PaFiw_scene_package.zip", "synthetic": true}
diff --git a/web/fixtures/builder/build.json b/web/fixtures/builder/build.json
new file mode 100644
index 0000000..bf087fa
--- /dev/null
+++ b/web/fixtures/builder/build.json
@@ -0,0 +1,82 @@
+{
+ "build_id": "b_synthetic01",
+ "stills": [
+ "/replay/demo/still_0.png",
+ "/replay/demo/still_1.png",
+ "/replay/demo/still_2.png"
+ ],
+ "scene_blend_url": null,
+ "scene_glb_url": "/replay/demo/scene.glb",
+ "panorama_urls": [
+ "/replay/demo/panorama_ref.png",
+ "/replay/demo/panorama_mid.png"
+ ],
+ "package_url": "https://v3b.fal.media/files/b/0ab08e00/m4GTss3UapWdQmO9PaFiw_scene_package.zip",
+ "critiques": [
+ {
+ "round": 1,
+ "scores": {
+ "layout": 7,
+ "props": 6,
+ "screens_signage": 5,
+ "materials": 6,
+ "lighting": 7,
+ "atmosphere": 6,
+ "plausibility": 8,
+ "composition": 7
+ },
+ "fixes": [
+ "Console CRTs: all 14 scopes show the same sine trace; the reference has varied content (polar plots, columns of telemetry, a radar sweep). Give each scope its own texture.",
+ "Wall display: the world map is too bright and flat; it should glow from behind with darker ocean areas and thin orbit ground tracks.",
+ "Desk clutter: binders and teleprinter paper read as clean grey boxes; add page edges, curl and print.",
+ "Haze is too uniform; the reference has denser smoke near the ceiling lit by the screens.",
+ "Chairs: three swivel chairs intersect the console fronts in the second row."
+ ],
+ "summary": "Right room, right layout and camera. It falls down on the screens, which carry this reference, and on generic clutter.",
+ "passed": false
+ },
+ {
+ "round": 2,
+ "scores": {
+ "layout": 7,
+ "props": 7,
+ "screens_signage": 6,
+ "materials": 7,
+ "lighting": 8,
+ "atmosphere": 7,
+ "plausibility": 8,
+ "composition": 7
+ },
+ "fixes": [
+ "Wall display: ground tracks are there but the telemetry panels either side are blank; the reference has columns of stencilled data.",
+ "Two scopes on the hero console are out of focus compared with the rest; sharpen or raise their emission.",
+ "Window reflections: the glass shows no reflection of the room; add a faint reflection so it reads as glass at night."
+ ],
+ "summary": "Big improvement on the screens and the haze. The side panels of the wall display are the last thing that reads as unfinished.",
+ "passed": false
+ },
+ {
+ "round": 3,
+ "scores": {
+ "layout": 8,
+ "props": 7,
+ "screens_signage": 7,
+ "materials": 7,
+ "lighting": 8,
+ "atmosphere": 8,
+ "plausibility": 8,
+ "composition": 8
+ },
+ "fixes": [
+ "Optional: a little more variation in console paint wear between rows.",
+ "Optional: one or two lit cigarettes in the ashtrays would add life to the haze."
+ ],
+ "summary": "Passes. A faithful, photoreal version of the reference; the screens and the wall display now carry it.",
+ "passed": true
+ }
+ ],
+ "missing": [],
+ "agent_cost_usd": 27.4,
+ "minutes": 28.2,
+ "_synthetic": "made by scripts/make-builder-fixture.mjs; images and package are from the earlier pipeline run"
+}
\ No newline at end of file
diff --git a/web/fixtures/builder/events.jsonl b/web/fixtures/builder/events.jsonl
new file mode 100644
index 0000000..23ed34e
--- /dev/null
+++ b/web/fixtures/builder/events.jsonl
@@ -0,0 +1,89 @@
+{"t":0.2,"stage":"received","status":"running","message":"build b_synthetic01: 1 reference image(s)"}
+{"t":0.3,"stage":"received","status":"running","message":"scene builder starting"}
+{"t":3.1,"stage":"thinking","status":"running","message":"I'll start by reading the skill docs and the inputs."}
+{"t":3.3,"stage":"log","status":"running","message":"ls && cat SKILL.md && ls input && cat input/brief.md","tool":"Bash"}
+{"t":4.4,"stage":"log","status":"running","message":"cat CRAFT.md; ls docs endpoint camera pipeline generate","tool":"Bash"}
+{"t":4.5,"stage":"log","status":"running","message":"looking at input/reference_1.png","tool":"Read"}
+{"t":13.5,"stage":"thinking","status":"running","message":"A 1960s mission control room at night: tiered console rows, a giant orbit-tracking wall display, tall windows on the left onto a floodlit pad. Lots of desk clutter. The screens are the hero; they need to read as green CRT phosphor, not flat emissive cards."}
+{"t":19.5,"stage":"log","status":"running","message":"sed -n 80,400p generate/fal.mjs; which blender; blender --version","tool":"Bash"}
+{"t":23.5,"stage":"log","status":"running","message":"writing scenes/scene/plan.json","tool":"Write"}
+{"t":45.5,"stage":"log","status":"running","message":"python pipeline/floorplan.py scenes/scene/plan.json out/floor_plan.png","tool":"Bash"}
+{"t":50.5,"stage":"log","status":"running","message":"looking at out/floor_plan.png","tool":"Read"}
+{"t":53.5,"stage":"plan","status":"running","message":"70 objects (18 invented), 16 lights, 16 x 14 m interior; consoles in three tiers facing the wall display","preview_url":"/replay/demo/floor_plan.png"}
+{"t":61.5,"stage":"log","status":"running","message":"writing scenes/scene/scripts/shell.py","tool":"Write"}
+{"t":64.5,"stage":"log","status":"running","message":"blender -b --factory-startup --python scenes/scene/scripts/shell.py -- out/scene.blend","tool":"Bash"}
+{"t":105.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --preview","tool":"Bash"}
+{"t":141.5,"stage":"log","status":"running","message":"looking at out/preview/ref_view.png","tool":"Read"}
+{"t":145.5,"stage":"thinking","status":"running","message":"Proportions are right but the camera is a little high; the reference is shot from seated eye level, about 1.25 m."}
+{"t":148.5,"stage":"log","status":"running","message":"editing scenes/scene/shots.json","tool":"Edit"}
+{"t":178.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --preview","tool":"Bash"}
+{"t":212.5,"stage":"log","status":"running","message":"looking at out/preview/overview.png","tool":"Read"}
+{"t":214.5,"stage":"layout","status":"running","message":"shell, tiers and console rows blocked out; reference camera matched at 28 mm","preview_url":"/replay/demo/blockout_overview.png"}
+{"t":219.5,"stage":"thinking","status":"running","message":"Props next. 19 unique assets cover 45 placements: references cropped from the plate and cleaned, then meshes from Tripo H3.1, Meshy for the small items."}
+{"t":222.5,"stage":"log","status":"running","message":"node generate/fal.mjs refs scenes/scene/props.json --out scenes/scene/props","tool":"Bash"}
+{"t":270.5,"stage":"log","status":"running","message":"looking at scenes/scene/props/console_bank_ref.png","tool":"Read"}
+{"t":273.5,"stage":"log","status":"running","message":"looking at scenes/scene/props/teleprinter_ref.png","tool":"Read"}
+{"t":275.5,"stage":"log","status":"running","message":"looking at scenes/scene/props/rotary_phone_ref.png","tool":"Read"}
+{"t":279.5,"stage":"props","status":"running","message":"19 prop references in; meshes generating (15 Tripo H3.1, 4 Meshy)","preview_url":"https://v3b.fal.media/files/b/0ab08da2/eIx9Y9z-uor3zqn87R7F9_9aWSSyyo.png"}
+{"t":284.5,"stage":"log","status":"running","message":"node generate/fal.mjs meshes scenes/scene/props.json --wait","tool":"Bash"}
+{"t":464.5,"stage":"thinking","status":"running","message":"Meshes are landing. Swapping them in as they arrive and checking scale against the plan."}
+{"t":467.5,"stage":"log","status":"running","message":"writing scenes/scene/scripts/dress.py","tool":"Write"}
+{"t":473.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python scenes/scene/scripts/dress.py","tool":"Bash"}
+{"t":525.5,"stage":"log","status":"running","message":"python pipeline/collide.py out/scene.blend --drop","tool":"Bash"}
+{"t":539.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --preview","tool":"Bash"}
+{"t":577.5,"stage":"log","status":"running","message":"looking at out/preview/ref_view.png","tool":"Read"}
+{"t":579.5,"stage":"dressing","status":"running","message":"45 placements dressed; 1 ashtray dropped onto its desk, nothing floating","preview_url":"https://v3b.fal.media/files/b/0ab08ded/4D56g-JZtrjm9g2ElyEml_0001.png"}
+{"t":583.5,"stage":"thinking","status":"running","message":"The consoles' CRTs are blank. Each scope needs its own phosphor content: sine traces, polar plots, telemetry columns."}
+{"t":586.5,"stage":"log","status":"running","message":"writing scenes/scene/scripts/screens.py","tool":"Write"}
+{"t":591.5,"stage":"log","status":"running","message":"python scenes/scene/scripts/screens.py --make-textures out/screens","tool":"Bash"}
+{"t":617.5,"stage":"log","status":"running","message":"looking at out/screens/scope_04.png","tool":"Read"}
+{"t":621.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python scenes/scene/scripts/screens.py -- --apply","tool":"Bash"}
+{"t":639.5,"stage":"screens","status":"running","message":"14 CRT textures and the wall map with ground tracks; no repeated text","preview_url":"https://v3b.fal.media/files/b/0ab08df7/jQQ2vHPFNHpNlUC_bgakY_0001.png"}
+{"t":644.5,"stage":"log","status":"running","message":"writing scenes/scene/scripts/materials.py","tool":"Write"}
+{"t":652.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python scenes/scene/scripts/materials.py","tool":"Bash"}
+{"t":692.5,"stage":"log","status":"running","message":"looking at out/preview/close_console.png","tool":"Read"}
+{"t":695.5,"stage":"materials","status":"running","message":"grey-green enamel with edge wear, linoleum floor, acoustic ceiling tiles, smoked glass","preview_url":"https://v3b.fal.media/files/b/0ab08df7/jQQ2vHPFNHpNlUC_bgakY_0001.png"}
+{"t":700.5,"stage":"log","status":"running","message":"writing scenes/scene/scripts/lighting.py","tool":"Write"}
+{"t":707.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python scenes/scene/scripts/lighting.py","tool":"Bash"}
+{"t":751.5,"stage":"log","status":"running","message":"looking at out/preview/ref_view.png","tool":"Read"}
+{"t":754.5,"stage":"thinking","status":"running","message":"Too bright overall; the reference is lit mostly by the screens and the wall display. Dropping the ceiling panels by 60%."}
+{"t":757.5,"stage":"log","status":"running","message":"editing scenes/scene/scripts/lighting.py","tool":"Edit"}
+{"t":798.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python scenes/scene/scripts/lighting.py","tool":"Bash"}
+{"t":800.5,"stage":"lighting","status":"running","message":"screens and wall display carry the room; ceiling panels at 40%; sodium floods outside","preview_url":"/replay/demo/still_2.png"}
+{"t":805.5,"stage":"log","status":"running","message":"editing scenes/scene/scripts/lighting.py","tool":"Edit"}
+{"t":841.5,"stage":"atmosphere","status":"running","message":"cigarette haze (volume density 0.012), slight bloom, Kodak 5219-style grade","preview_url":"/replay/demo/still_2.png"}
+{"t":845.5,"stage":"log","status":"running","message":"writing scenes/scene/shots.json","tool":"Write"}
+{"t":875.5,"stage":"cameras","status":"running","message":"reference angle plus two open views down the console rows","preview_url":"/replay/demo/still_1.png"}
+{"t":878.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --finals --samples 256","tool":"Bash"}
+{"t":974.5,"stage":"log","status":"running","message":"looking at out/stills/ref.png","tool":"Read"}
+{"t":977.5,"stage":"finals","status":"running","message":"3 stills at 1920 x 804, 256 samples","preview_url":"/replay/demo/still_0.png"}
+{"t":981.5,"stage":"critique","status":"running","message":"critic is looking at 3 stills"}
+{"t":1039.5,"stage":"critique","status":"running","message":"round 1: not yet - layout 7, props 6, screens_signage 5, materials 6, lighting 7, atmosphere 6, plausibility 8, composition 7","preview_url":"/replay/demo/still_0.png","critique":{"round":1,"scores":{"layout":7,"props":6,"screens_signage":5,"materials":6,"lighting":7,"atmosphere":6,"plausibility":8,"composition":7},"fixes":["Console CRTs: all 14 scopes show the same sine trace; the reference has varied content (polar plots, columns of telemetry, a radar sweep). Give each scope its own texture.","Wall display: the world map is too bright and flat; it should glow from behind with darker ocean areas and thin orbit ground tracks.","Desk clutter: binders and teleprinter paper read as clean grey boxes; add page edges, curl and print.","Haze is too uniform; the reference has denser smoke near the ceiling lit by the screens.","Chairs: three swivel chairs intersect the console fronts in the second row."],"summary":"Right room, right layout and camera. It falls down on the screens, which carry this reference, and on generic clutter.","passed":false,"stills":["out/stills/ref.png","out/stills/view_1.png","out/stills/view_2.png"]}}
+{"t":1043.5,"stage":"thinking","status":"running","message":"Screens first, they cost the most points. Then the clutter and the chairs."}
+{"t":1046.5,"stage":"log","status":"running","message":"editing scenes/scene/scripts/screens.py","tool":"Edit"}
+{"t":1052.5,"stage":"log","status":"running","message":"python scenes/scene/scripts/screens.py --make-textures out/screens --vary 14","tool":"Bash"}
+{"t":1082.5,"stage":"log","status":"running","message":"looking at out/screens/contact_sheet.png","tool":"Read"}
+{"t":1086.5,"stage":"screens","status":"running","message":"14 distinct scope textures: polar plots, telemetry columns, radar sweep; wall map darkened","preview_url":"https://v3b.fal.media/files/b/0ab08df7/jQQ2vHPFNHpNlUC_bgakY_0001.png"}
+{"t":1091.5,"stage":"log","status":"running","message":"editing scenes/scene/scripts/dress.py","tool":"Edit"}
+{"t":1122.5,"stage":"log","status":"running","message":"python pipeline/collide.py out/scene.blend --fix chairs","tool":"Bash"}
+{"t":1125.5,"stage":"dressing","status":"running","message":"chairs pulled back from the consoles; binders and printouts swapped for detailed meshes","preview_url":"https://v3b.fal.media/files/b/0ab08ded/4D56g-JZtrjm9g2ElyEml_0001.png"}
+{"t":1129.5,"stage":"log","status":"running","message":"editing scenes/scene/scripts/lighting.py","tool":"Edit"}
+{"t":1169.5,"stage":"atmosphere","status":"running","message":"haze layered: denser under the ceiling, lit by the scopes","preview_url":"/replay/demo/still_2.png"}
+{"t":1172.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --finals --samples 256","tool":"Bash"}
+{"t":1270.5,"stage":"log","status":"running","message":"looking at out/stills/ref.png","tool":"Read"}
+{"t":1272.5,"stage":"finals","status":"running","message":"3 stills re-rendered after round 1 fixes","preview_url":"/replay/demo/still_0.png"}
+{"t":1276.5,"stage":"critique","status":"running","message":"critic is looking at 3 stills"}
+{"t":1334.5,"stage":"critique","status":"running","message":"round 2: not yet - layout 7, props 7, screens_signage 6, materials 7, lighting 8, atmosphere 7, plausibility 8, composition 7","preview_url":"/replay/demo/still_0.png","critique":{"round":2,"scores":{"layout":7,"props":7,"screens_signage":6,"materials":7,"lighting":8,"atmosphere":7,"plausibility":8,"composition":7},"fixes":["Wall display: ground tracks are there but the telemetry panels either side are blank; the reference has columns of stencilled data.","Two scopes on the hero console are out of focus compared with the rest; sharpen or raise their emission.","Window reflections: the glass shows no reflection of the room; add a faint reflection so it reads as glass at night."],"summary":"Big improvement on the screens and the haze. The side panels of the wall display are the last thing that reads as unfinished.","passed":false,"stills":["out/stills/ref.png","out/stills/view_1.png","out/stills/view_2.png"]}}
+{"t":1338.5,"stage":"thinking","status":"running","message":"Filling the wall display's side panels with stencilled data columns and adding reflection to the window glass."}
+{"t":1341.5,"stage":"log","status":"running","message":"editing scenes/scene/scripts/screens.py","tool":"Edit"}
+{"t":1363.5,"stage":"log","status":"running","message":"python scenes/scene/scripts/screens.py --wall-panels out/screens","tool":"Bash"}
+{"t":1367.5,"stage":"log","status":"running","message":"editing scenes/scene/scripts/materials.py","tool":"Edit"}
+{"t":1370.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --finals --samples 256","tool":"Bash"}
+{"t":1467.5,"stage":"log","status":"running","message":"looking at out/stills/view_1.png","tool":"Read"}
+{"t":1469.5,"stage":"finals","status":"running","message":"3 stills with the wall panels and window glass fixed","preview_url":"/replay/demo/still_0.png"}
+{"t":1473.5,"stage":"critique","status":"running","message":"critic is looking at 3 stills"}
+{"t":1531.5,"stage":"critique","status":"done","message":"round 3: PASS - layout 8, props 7, screens_signage 7, materials 7, lighting 8, atmosphere 8, plausibility 8, composition 8","preview_url":"/replay/demo/still_0.png","critique":{"round":3,"scores":{"layout":8,"props":7,"screens_signage":7,"materials":7,"lighting":8,"atmosphere":8,"plausibility":8,"composition":8},"fixes":["Optional: a little more variation in console paint wear between rows.","Optional: one or two lit cigarettes in the ashtrays would add life to the haze."],"summary":"Passes. A faithful, photoreal version of the reference; the screens and the wall display now carry it.","passed":true,"stills":["out/stills/ref.png","out/stills/view_1.png","out/stills/view_2.png"]}}
+{"t":1536.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python pipeline/export_glb.py -- out/scene.glb --decimate 0.25","tool":"Bash"}
+{"t":1576.5,"stage":"log","status":"running","message":"blender -b out/scene.blend --python camera/panorama.py -- --at ref_view,room_centre --out out/panoramas","tool":"Bash"}
+{"t":1646.5,"stage":"done","status":"done","message":"scene builder finished after 33 min, agent cost $27.40","missing":[],"critiques":3}
+{"t":1694.5,"stage":"packaged","status":"done","message":"package ready after 34 min","package_url":"https://v3b.fal.media/files/b/0ab08e00/m4GTss3UapWdQmO9PaFiw_scene_package.zip"}
diff --git a/web/fixtures/comparison.png b/web/fixtures/comparison.png
new file mode 100644
index 0000000..7f085a0
Binary files /dev/null and b/web/fixtures/comparison.png differ
diff --git a/web/fixtures/floor_plan.png b/web/fixtures/floor_plan.png
new file mode 100644
index 0000000..301a341
Binary files /dev/null and b/web/fixtures/floor_plan.png differ
diff --git a/web/fixtures/panorama_mid.png b/web/fixtures/panorama_mid.png
new file mode 100644
index 0000000..a897d9c
Binary files /dev/null and b/web/fixtures/panorama_mid.png differ
diff --git a/web/fixtures/panorama_ref.png b/web/fixtures/panorama_ref.png
new file mode 100644
index 0000000..439df3f
Binary files /dev/null and b/web/fixtures/panorama_ref.png differ
diff --git a/web/fixtures/plan.json b/web/fixtures/plan.json
new file mode 100644
index 0000000..da37179
--- /dev/null
+++ b/web/fixtures/plan.json
@@ -0,0 +1,1702 @@
+{
+ "name": "apollo-era-mission-control-night",
+ "summary": "A 1960s-style mission control room at night: tiered rows of grey-green steel consoles with glowing green CRT scopes and amber indicator lamps face a giant world-map orbit tracking display on the back wall, while tall windows on the left look out across a dark field to a floodlit rocket on its launch pad. Desks are littered with ring binders, teleprinter paper, coffee mugs and overflowing ashtrays.",
+ "setting": "interior",
+ "time_of_day": "night",
+ "mood": [
+ "tense",
+ "focused",
+ "retro-futurist",
+ "smoky",
+ "late-shift"
+ ],
+ "palette": [
+ "#1b1f1c",
+ "#5d6658",
+ "#39ff8a",
+ "#ffb46b",
+ "#c9c4b0",
+ "#0c1418"
+ ],
+ "room": {
+ "width": 16.0,
+ "depth": 14.0,
+ "height": 3.6
+ },
+ "openings": [
+ {
+ "wall": "left",
+ "kind": "window",
+ "center": 7.5,
+ "width": 11.0,
+ "height": 2.2,
+ "sill": 0.9
+ },
+ {
+ "wall": "front",
+ "kind": "door",
+ "center": 14.5,
+ "width": 1.0,
+ "height": 2.1,
+ "sill": 0.0
+ },
+ {
+ "wall": "right",
+ "kind": "door",
+ "center": 11.5,
+ "width": 0.9,
+ "height": 2.1,
+ "sill": 0.0
+ }
+ ],
+ "objects": [
+ {
+ "id": "big_wall_display",
+ "label": "Giant orbit tracking wall display with world map and telemetry readouts",
+ "asset": "big_wall_display",
+ "category": "fixture",
+ "x": 8.2,
+ "y": 13.9,
+ "z": 1.6,
+ "w": 8.5,
+ "d": 0.15,
+ "h": 2.3,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Huge back-lit wall display panel for a 1960s mission control room, dark glass with a glowing green world map grid and sine-wave orbit ground tracks, flanked by panels of white stencilled orbital data text, black steel frame",
+ "crop": [
+ 0.358,
+ 0.066,
+ 0.846,
+ 0.329
+ ]
+ },
+ {
+ "id": "poster_further",
+ "label": "Framed moon poster 'Further Higher Safer'",
+ "asset": "poster_moon_motto",
+ "category": "decal",
+ "x": 13.3,
+ "y": 13.95,
+ "z": 1.7,
+ "w": 1.2,
+ "d": 0.04,
+ "h": 1.8,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.865,
+ 0.06,
+ 0.94,
+ 0.29
+ ]
+ },
+ {
+ "id": "wall_clock",
+ "label": "Round analogue wall clock",
+ "asset": "wall_clock",
+ "category": "fixture",
+ "x": 15.0,
+ "y": 13.93,
+ "z": 2.4,
+ "w": 0.4,
+ "d": 0.06,
+ "h": 0.4,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Round 1960s institutional wall clock, white face with black numerals, black metal rim, slightly yellowed glass",
+ "crop": [
+ 0.96,
+ 0.13,
+ 0.995,
+ 0.21
+ ]
+ },
+ {
+ "id": "ceiling_panel_1",
+ "label": "Recessed fluorescent ceiling panel",
+ "asset": "ceiling_fluoro_panel",
+ "category": "fixture",
+ "x": 5.0,
+ "y": 4.0,
+ "z": 3.52,
+ "w": 1.2,
+ "d": 0.6,
+ "h": 0.08,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.51,
+ 0.02,
+ 0.56,
+ 0.05
+ ]
+ },
+ {
+ "id": "ceiling_panel_2",
+ "label": "Recessed fluorescent ceiling panel",
+ "asset": "ceiling_fluoro_panel",
+ "category": "fixture",
+ "x": 11.0,
+ "y": 4.0,
+ "z": 3.52,
+ "w": 1.2,
+ "d": 0.6,
+ "h": 0.08,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.75,
+ 0.0,
+ 0.8,
+ 0.03
+ ]
+ },
+ {
+ "id": "ceiling_panel_3",
+ "label": "Recessed fluorescent ceiling panel",
+ "asset": "ceiling_fluoro_panel",
+ "category": "fixture",
+ "x": 5.0,
+ "y": 9.0,
+ "z": 3.52,
+ "w": 1.2,
+ "d": 0.6,
+ "h": 0.08,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": false,
+ "prompt": "",
+ "crop": null
+ },
+ {
+ "id": "ceiling_panel_4",
+ "label": "Recessed fluorescent ceiling panel",
+ "asset": "ceiling_fluoro_panel",
+ "category": "fixture",
+ "x": 11.0,
+ "y": 9.0,
+ "z": 3.52,
+ "w": 1.2,
+ "d": 0.6,
+ "h": 0.08,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": false,
+ "prompt": "",
+ "crop": null
+ },
+ {
+ "id": "console_orbital_analysis",
+ "label": "Hero orbital analysis console with CRT scopes and switch panels",
+ "asset": "console_orbital_hero",
+ "category": "furniture",
+ "x": 8.6,
+ "y": 3.6,
+ "z": 0.0,
+ "w": 4.6,
+ "d": 0.9,
+ "h": 1.3,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Long 1960s mission control console, grey-green painted steel with sloped front, two green-glowing round-cornered CRT scopes showing orbital plots, banks of toggle switches, rotary knobs and amber push-button indicator lamps, worn paint at edges",
+ "crop": [
+ 0.27,
+ 0.52,
+ 0.83,
+ 0.87
+ ]
+ },
+ {
+ "id": "desk_orbital",
+ "label": "Writing ledge in front of orbital console",
+ "asset": "console_desk_ledge",
+ "category": "furniture",
+ "x": 8.6,
+ "y": 2.85,
+ "z": 0.0,
+ "w": 4.6,
+ "d": 0.6,
+ "h": 0.76,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.07,
+ 0.72,
+ 0.83,
+ 1.0
+ ]
+ },
+ {
+ "id": "console_flight_data_stack",
+ "label": "Tall indexed reference cabinet labelled flight data, trajectory, systems, anomalies",
+ "asset": "index_cabinet",
+ "category": "furniture",
+ "x": 12.4,
+ "y": 3.5,
+ "z": 0.0,
+ "w": 1.1,
+ "d": 0.9,
+ "h": 1.6,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Tall grey steel 1960s console cabinet with a stack of pull-out labelled drawers reading FLIGHT DATA, TRAJECTORY, SYSTEMS, ANOMALIES in stencilled black letters, chrome handles",
+ "crop": [
+ 0.89,
+ 0.5,
+ 1.0,
+ 0.73
+ ]
+ },
+ {
+ "id": "desk_right",
+ "label": "Desk ledge under teleprinter",
+ "asset": "console_desk_ledge",
+ "category": "furniture",
+ "x": 12.4,
+ "y": 2.55,
+ "z": 0.0,
+ "w": 1.6,
+ "d": 0.7,
+ "h": 0.76,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.8,
+ 0.85,
+ 1.0,
+ 1.0
+ ]
+ },
+ {
+ "id": "teleprinter",
+ "label": "Chrome teleprinter spooling paper",
+ "asset": "teleprinter",
+ "category": "prop",
+ "x": 12.4,
+ "y": 2.55,
+ "z": 0.76,
+ "w": 0.6,
+ "d": 0.45,
+ "h": 0.45,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "1960s chrome and grey metal teleprinter printer with a roll of continuous fan-fold paper spilling out covered in printed columns of numbers",
+ "crop": [
+ 0.79,
+ 0.68,
+ 1.0,
+ 1.0
+ ]
+ },
+ {
+ "id": "console_mission_control",
+ "label": "Second-row console with CRT monitors",
+ "asset": "console_bank",
+ "category": "furniture",
+ "x": 7.2,
+ "y": 7.2,
+ "z": 0.0,
+ "w": 5.0,
+ "d": 0.9,
+ "h": 1.3,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Row of 1960s mission control consoles in grey-green painted steel, several green-glowing CRT monitors with data text and radar plots, amber indicator lamps, toggle switches, slightly scuffed",
+ "crop": [
+ 0.2,
+ 0.36,
+ 0.6,
+ 0.5
+ ]
+ },
+ {
+ "id": "desk_mission_control",
+ "label": "Writing ledge for second row",
+ "asset": "console_desk_ledge",
+ "category": "furniture",
+ "x": 7.2,
+ "y": 6.45,
+ "z": 0.0,
+ "w": 5.0,
+ "d": 0.6,
+ "h": 0.76,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.2,
+ 0.46,
+ 0.58,
+ 0.52
+ ]
+ },
+ {
+ "id": "console_telemetry",
+ "label": "Telemetry console with radar scope",
+ "asset": "console_bank",
+ "category": "furniture",
+ "x": 12.9,
+ "y": 7.8,
+ "z": 0.0,
+ "w": 4.0,
+ "d": 0.9,
+ "h": 1.3,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Row of 1960s mission control consoles in grey-green painted steel, several green-glowing CRT monitors with data text and radar plots, amber indicator lamps, toggle switches, slightly scuffed",
+ "crop": [
+ 0.68,
+ 0.38,
+ 1.0,
+ 0.53
+ ]
+ },
+ {
+ "id": "desk_telemetry",
+ "label": "Writing ledge for telemetry",
+ "asset": "console_desk_ledge",
+ "category": "furniture",
+ "x": 12.9,
+ "y": 7.05,
+ "z": 0.0,
+ "w": 4.0,
+ "d": 0.6,
+ "h": 0.76,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.73,
+ 0.52,
+ 1.0,
+ 0.56
+ ]
+ },
+ {
+ "id": "console_guidance",
+ "label": "Guidance console by the windows",
+ "asset": "console_bank",
+ "category": "furniture",
+ "x": 1.6,
+ "y": 5.5,
+ "z": 0.0,
+ "w": 2.6,
+ "d": 0.9,
+ "h": 1.3,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Row of 1960s mission control consoles in grey-green painted steel, several green-glowing CRT monitors with data text and radar plots, amber indicator lamps, toggle switches, slightly scuffed",
+ "crop": [
+ 0.0,
+ 0.4,
+ 0.2,
+ 0.75
+ ]
+ },
+ {
+ "id": "desk_guidance",
+ "label": "Writing ledge for guidance",
+ "asset": "console_desk_ledge",
+ "category": "furniture",
+ "x": 1.6,
+ "y": 4.75,
+ "z": 0.0,
+ "w": 2.6,
+ "d": 0.6,
+ "h": 0.76,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.0,
+ 0.55,
+ 0.15,
+ 0.62
+ ]
+ },
+ {
+ "id": "console_back_row",
+ "label": "Back row of consoles beneath wall display",
+ "asset": "console_bank",
+ "category": "furniture",
+ "x": 8.5,
+ "y": 10.8,
+ "z": 0.0,
+ "w": 9.0,
+ "d": 0.9,
+ "h": 1.3,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Row of 1960s mission control consoles in grey-green painted steel, several green-glowing CRT monitors with data text and radar plots, amber indicator lamps, toggle switches, slightly scuffed",
+ "crop": [
+ 0.4,
+ 0.33,
+ 0.95,
+ 0.4
+ ]
+ },
+ {
+ "id": "desk_back_row",
+ "label": "Writing ledge for back row",
+ "asset": "console_desk_ledge",
+ "category": "furniture",
+ "x": 8.5,
+ "y": 10.05,
+ "z": 0.0,
+ "w": 9.0,
+ "d": 0.6,
+ "h": 0.76,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": false,
+ "prompt": "",
+ "crop": null
+ },
+ {
+ "id": "console_left_back",
+ "label": "Left back console by windows",
+ "asset": "console_bank",
+ "category": "furniture",
+ "x": 1.8,
+ "y": 9.5,
+ "z": 0.0,
+ "w": 3.0,
+ "d": 0.9,
+ "h": 1.3,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Row of 1960s mission control consoles in grey-green painted steel, several green-glowing CRT monitors with data text and radar plots, amber indicator lamps, toggle switches, slightly scuffed",
+ "crop": [
+ 0.18,
+ 0.36,
+ 0.33,
+ 0.45
+ ]
+ },
+ {
+ "id": "placard_orbital",
+ "label": "Placard ORBITAL ANALYSIS",
+ "asset": "console_placard",
+ "category": "signage",
+ "x": 8.0,
+ "y": 3.4,
+ "z": 1.3,
+ "w": 1.0,
+ "d": 0.05,
+ "h": 0.15,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.46,
+ 0.51,
+ 0.57,
+ 0.57
+ ]
+ },
+ {
+ "id": "placard_mission_control",
+ "label": "Placard MISSION CONTROL",
+ "asset": "console_placard",
+ "category": "signage",
+ "x": 7.5,
+ "y": 7.0,
+ "z": 1.3,
+ "w": 1.0,
+ "d": 0.05,
+ "h": 0.15,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.42,
+ 0.355,
+ 0.49,
+ 0.38
+ ]
+ },
+ {
+ "id": "placard_telemetry",
+ "label": "Placard TELEMETRY",
+ "asset": "console_placard",
+ "category": "signage",
+ "x": 12.6,
+ "y": 7.6,
+ "z": 1.3,
+ "w": 1.0,
+ "d": 0.05,
+ "h": 0.15,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.79,
+ 0.37,
+ 0.87,
+ 0.4
+ ]
+ },
+ {
+ "id": "placard_guidance",
+ "label": "Placard GUIDANCE",
+ "asset": "console_placard",
+ "category": "signage",
+ "x": 0.8,
+ "y": 5.3,
+ "z": 1.3,
+ "w": 0.8,
+ "d": 0.05,
+ "h": 0.15,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.01,
+ 0.39,
+ 0.07,
+ 0.42
+ ]
+ },
+ {
+ "id": "chair_fg_left",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 6.6,
+ "y": 1.9,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 180.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": [
+ 0.0,
+ 0.75,
+ 0.27,
+ 1.0
+ ]
+ },
+ {
+ "id": "chair_fg_right",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 9.8,
+ "y": 1.9,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 170.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": null
+ },
+ {
+ "id": "chair_row2_a",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 5.8,
+ "y": 5.8,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 200.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": [
+ 0.28,
+ 0.45,
+ 0.38,
+ 0.55
+ ]
+ },
+ {
+ "id": "chair_row2_b",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 8.6,
+ "y": 5.8,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 175.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": null
+ },
+ {
+ "id": "chair_telemetry_a",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 11.6,
+ "y": 6.4,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 185.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": [
+ 0.66,
+ 0.5,
+ 0.74,
+ 0.58
+ ]
+ },
+ {
+ "id": "chair_telemetry_b",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 13.8,
+ "y": 6.4,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 160.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": null
+ },
+ {
+ "id": "chair_guidance",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 1.6,
+ "y": 4.0,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 190.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": null
+ },
+ {
+ "id": "chair_back_a",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 6.5,
+ "y": 9.4,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 180.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": [
+ 0.63,
+ 0.4,
+ 0.67,
+ 0.5
+ ]
+ },
+ {
+ "id": "chair_back_b",
+ "label": "Black swivel chair",
+ "asset": "swivel_chair",
+ "category": "furniture",
+ "x": 10.5,
+ "y": 9.4,
+ "z": 0.0,
+ "w": 0.6,
+ "d": 0.6,
+ "h": 1.05,
+ "rot": 165.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s office swivel chair with black vinyl padded seat and high back, chrome armrests and five-star chrome base on casters, slightly worn",
+ "crop": null
+ },
+ {
+ "id": "binder_fg_1",
+ "label": "Open ring binder of flight procedures",
+ "asset": "binder_open",
+ "category": "prop",
+ "x": 6.9,
+ "y": 2.8,
+ "z": 0.76,
+ "w": 0.6,
+ "d": 0.32,
+ "h": 0.06,
+ "rot": -5.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Open three-ring binder with dark grey cloth cover and dense typed procedure pages, chrome rings, dog-eared corners",
+ "crop": [
+ 0.14,
+ 0.75,
+ 0.33,
+ 0.86
+ ]
+ },
+ {
+ "id": "binder_fg_2",
+ "label": "Open ring binder",
+ "asset": "binder_open",
+ "category": "prop",
+ "x": 7.9,
+ "y": 2.75,
+ "z": 0.76,
+ "w": 0.6,
+ "d": 0.32,
+ "h": 0.06,
+ "rot": -12.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Open three-ring binder with dark grey cloth cover and dense typed procedure pages, chrome rings, dog-eared corners",
+ "crop": [
+ 0.24,
+ 0.8,
+ 0.46,
+ 0.92
+ ]
+ },
+ {
+ "id": "papers_fg",
+ "label": "Loose typed flight plan sheets",
+ "asset": "paper_sheets",
+ "category": "clutter",
+ "x": 9.0,
+ "y": 2.7,
+ "z": 0.76,
+ "w": 0.45,
+ "d": 0.35,
+ "h": 0.01,
+ "rot": 8.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.39,
+ 0.85,
+ 0.62,
+ 1.0
+ ]
+ },
+ {
+ "id": "papers_fg_2",
+ "label": "Loose typed sheets",
+ "asset": "paper_sheets",
+ "category": "clutter",
+ "x": 10.3,
+ "y": 2.65,
+ "z": 0.76,
+ "w": 0.45,
+ "d": 0.35,
+ "h": 0.01,
+ "rot": -6.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.58,
+ 0.92,
+ 0.79,
+ 1.0
+ ]
+ },
+ {
+ "id": "pencil_fg",
+ "label": "Pencil",
+ "asset": "pencil",
+ "category": "clutter",
+ "x": 8.4,
+ "y": 2.62,
+ "z": 0.77,
+ "w": 0.18,
+ "d": 0.01,
+ "h": 0.01,
+ "rot": 20.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.38,
+ 0.9,
+ 0.45,
+ 0.94
+ ]
+ },
+ {
+ "id": "mug_white_fg",
+ "label": "White coffee mug",
+ "asset": "mug_white",
+ "category": "prop",
+ "x": 6.5,
+ "y": 3.0,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.09,
+ "h": 0.1,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Plain white ceramic coffee mug with handle, faint coffee stain at the rim",
+ "crop": [
+ 0.21,
+ 0.66,
+ 0.26,
+ 0.75
+ ]
+ },
+ {
+ "id": "mug_white_fg_2",
+ "label": "White coffee mug",
+ "asset": "mug_white",
+ "category": "prop",
+ "x": 10.1,
+ "y": 3.0,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.09,
+ "h": 0.1,
+ "rot": 40.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Plain white ceramic coffee mug with handle, faint coffee stain at the rim",
+ "crop": [
+ 0.69,
+ 0.77,
+ 0.73,
+ 0.83
+ ]
+ },
+ {
+ "id": "mug_black_fg",
+ "label": "Black coffee mug",
+ "asset": "mug_black",
+ "category": "prop",
+ "x": 7.6,
+ "y": 3.05,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.09,
+ "h": 0.1,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Glossy black ceramic coffee mug with handle, half full of black coffee",
+ "crop": [
+ 0.33,
+ 0.71,
+ 0.38,
+ 0.8
+ ]
+ },
+ {
+ "id": "ashtray_fg_1",
+ "label": "Glass ashtray with cigarette butts",
+ "asset": "ashtray_full",
+ "category": "prop",
+ "x": 6.2,
+ "y": 2.85,
+ "z": 0.76,
+ "w": 0.16,
+ "d": 0.16,
+ "h": 0.05,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Heavy round glass ashtray overflowing with crushed cigarette butts and grey ash",
+ "crop": [
+ 0.16,
+ 0.72,
+ 0.23,
+ 0.78
+ ]
+ },
+ {
+ "id": "ashtray_fg_2",
+ "label": "Glass ashtray overflowing",
+ "asset": "ashtray_full",
+ "category": "prop",
+ "x": 9.8,
+ "y": 2.85,
+ "z": 0.76,
+ "w": 0.16,
+ "d": 0.16,
+ "h": 0.05,
+ "rot": 30.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Heavy round glass ashtray overflowing with crushed cigarette butts and grey ash",
+ "crop": [
+ 0.62,
+ 0.79,
+ 0.72,
+ 0.9
+ ]
+ },
+ {
+ "id": "cigarette_pack_fg",
+ "label": "Red and white cigarette pack",
+ "asset": "cigarette_pack",
+ "category": "prop",
+ "x": 10.6,
+ "y": 2.7,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.05,
+ "h": 0.06,
+ "rot": 15.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Crumpled soft cigarette pack, red and white cardboard with unbranded generic label, a few cigarettes poking out",
+ "crop": [
+ 0.71,
+ 0.88,
+ 0.78,
+ 0.95
+ ]
+ },
+ {
+ "id": "comm_box_fg",
+ "label": "Desk intercom unit with push buttons and microphone",
+ "asset": "desk_intercom",
+ "category": "prop",
+ "x": 8.8,
+ "y": 3.0,
+ "z": 0.76,
+ "w": 0.3,
+ "d": 0.2,
+ "h": 0.18,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "1960s black desk intercom box with chrome toggle switches, small round speaker grille and a short gooseneck microphone",
+ "crop": [
+ 0.43,
+ 0.73,
+ 0.55,
+ 0.87
+ ]
+ },
+ {
+ "id": "small_box_fg",
+ "label": "Small white instruction card stand",
+ "asset": "card_box",
+ "category": "clutter",
+ "x": 8.3,
+ "y": 3.05,
+ "z": 0.76,
+ "w": 0.12,
+ "d": 0.08,
+ "h": 0.06,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.38,
+ 0.76,
+ 0.43,
+ 0.8
+ ]
+ },
+ {
+ "id": "printout_guidance",
+ "label": "Fan-fold printout trailing over desk edge",
+ "asset": "printout_trail",
+ "category": "clutter",
+ "x": 1.0,
+ "y": 4.6,
+ "z": 0.3,
+ "w": 0.35,
+ "d": 0.05,
+ "h": 0.46,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.04,
+ 0.58,
+ 0.11,
+ 0.72
+ ]
+ },
+ {
+ "id": "mug_guidance",
+ "label": "White coffee mug",
+ "asset": "mug_white",
+ "category": "prop",
+ "x": 0.5,
+ "y": 4.85,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.09,
+ "h": 0.1,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Plain white ceramic coffee mug with handle, faint coffee stain at the rim",
+ "crop": [
+ 0.03,
+ 0.53,
+ 0.06,
+ 0.57
+ ]
+ },
+ {
+ "id": "ashtray_guidance",
+ "label": "Glass ashtray",
+ "asset": "ashtray_full",
+ "category": "prop",
+ "x": 2.1,
+ "y": 4.8,
+ "z": 0.76,
+ "w": 0.16,
+ "d": 0.16,
+ "h": 0.05,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Heavy round glass ashtray overflowing with crushed cigarette butts and grey ash",
+ "crop": [
+ 0.09,
+ 0.55,
+ 0.14,
+ 0.58
+ ]
+ },
+ {
+ "id": "desk_lamp_guidance",
+ "label": "Brass desk lamp on console top",
+ "asset": "desk_lamp",
+ "category": "prop",
+ "x": 2.5,
+ "y": 5.6,
+ "z": 1.3,
+ "w": 0.2,
+ "d": 0.25,
+ "h": 0.4,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Small 1960s articulated desk lamp with brass arm and dome shade, warm bulb glowing",
+ "crop": [
+ 0.08,
+ 0.36,
+ 0.11,
+ 0.42
+ ]
+ },
+ {
+ "id": "desk_lamp_window",
+ "label": "Desk lamp by window",
+ "asset": "desk_lamp",
+ "category": "prop",
+ "x": 3.2,
+ "y": 9.6,
+ "z": 1.3,
+ "w": 0.2,
+ "d": 0.25,
+ "h": 0.4,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Small 1960s articulated desk lamp with brass arm and dome shade, warm bulb glowing",
+ "crop": [
+ 0.31,
+ 0.32,
+ 0.33,
+ 0.36
+ ]
+ },
+ {
+ "id": "desk_lamp_right",
+ "label": "Desk lamp on right console",
+ "asset": "desk_lamp",
+ "category": "prop",
+ "x": 14.6,
+ "y": 8.0,
+ "z": 1.3,
+ "w": 0.2,
+ "d": 0.25,
+ "h": 0.4,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Small 1960s articulated desk lamp with brass arm and dome shade, warm bulb glowing",
+ "crop": [
+ 0.92,
+ 0.34,
+ 0.94,
+ 0.38
+ ]
+ },
+ {
+ "id": "mug_telemetry",
+ "label": "White coffee mug",
+ "asset": "mug_white",
+ "category": "prop",
+ "x": 11.9,
+ "y": 7.05,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.09,
+ "h": 0.1,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Plain white ceramic coffee mug with handle, faint coffee stain at the rim",
+ "crop": [
+ 0.78,
+ 0.49,
+ 0.8,
+ 0.53
+ ]
+ },
+ {
+ "id": "papers_telemetry",
+ "label": "Stack of typed sheets",
+ "asset": "paper_sheets",
+ "category": "clutter",
+ "x": 13.6,
+ "y": 7.0,
+ "z": 0.76,
+ "w": 0.45,
+ "d": 0.35,
+ "h": 0.01,
+ "rot": 10.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.84,
+ 0.51,
+ 0.89,
+ 0.54
+ ]
+ },
+ {
+ "id": "binder_mission",
+ "label": "Open ring binder",
+ "asset": "binder_open",
+ "category": "prop",
+ "x": 6.6,
+ "y": 6.45,
+ "z": 0.76,
+ "w": 0.6,
+ "d": 0.32,
+ "h": 0.06,
+ "rot": 5.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Open three-ring binder with dark grey cloth cover and dense typed procedure pages, chrome rings, dog-eared corners",
+ "crop": [
+ 0.39,
+ 0.47,
+ 0.44,
+ 0.5
+ ]
+ },
+ {
+ "id": "mug_mission",
+ "label": "Black coffee mug",
+ "asset": "mug_black",
+ "category": "prop",
+ "x": 8.2,
+ "y": 6.5,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.09,
+ "h": 0.1,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Glossy black ceramic coffee mug with handle, half full of black coffee",
+ "crop": [
+ 0.5,
+ 0.46,
+ 0.52,
+ 0.49
+ ]
+ },
+ {
+ "id": "ashtray_mission",
+ "label": "Glass ashtray",
+ "asset": "ashtray_full",
+ "category": "prop",
+ "x": 9.0,
+ "y": 6.4,
+ "z": 0.76,
+ "w": 0.16,
+ "d": 0.16,
+ "h": 0.05,
+ "rot": 0.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "Heavy round glass ashtray overflowing with crushed cigarette butts and grey ash",
+ "crop": [
+ 0.53,
+ 0.47,
+ 0.56,
+ 0.5
+ ]
+ },
+ {
+ "id": "papers_back",
+ "label": "Loose typed sheets",
+ "asset": "paper_sheets",
+ "category": "clutter",
+ "x": 7.0,
+ "y": 10.0,
+ "z": 0.76,
+ "w": 0.45,
+ "d": 0.35,
+ "h": 0.01,
+ "rot": -4.0,
+ "source": "invented",
+ "generate": false,
+ "prompt": "",
+ "crop": null
+ },
+ {
+ "id": "mug_back",
+ "label": "White coffee mug",
+ "asset": "mug_white",
+ "category": "prop",
+ "x": 10.0,
+ "y": 10.1,
+ "z": 0.76,
+ "w": 0.09,
+ "d": 0.09,
+ "h": 0.1,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "Plain white ceramic coffee mug with handle, faint coffee stain at the rim",
+ "crop": null
+ },
+ {
+ "id": "cardboard_box_floor",
+ "label": "Cardboard box of printouts",
+ "asset": "cardboard_box",
+ "category": "clutter",
+ "x": 10.9,
+ "y": 5.9,
+ "z": 0.0,
+ "w": 0.4,
+ "d": 0.3,
+ "h": 0.3,
+ "rot": 5.0,
+ "source": "reference",
+ "generate": false,
+ "prompt": "",
+ "crop": [
+ 0.59,
+ 0.51,
+ 0.63,
+ 0.56
+ ]
+ },
+ {
+ "id": "filing_cabinet_1",
+ "label": "Grey four-drawer filing cabinet",
+ "asset": "filing_cabinet",
+ "category": "furniture",
+ "x": 15.6,
+ "y": 12.8,
+ "z": 0.0,
+ "w": 0.5,
+ "d": 0.65,
+ "h": 1.35,
+ "rot": -90.0,
+ "source": "reference",
+ "generate": true,
+ "prompt": "1960s grey steel four-drawer filing cabinet with chrome pull handles and paper label slots, scuffed paint",
+ "crop": [
+ 0.95,
+ 0.28,
+ 1.0,
+ 0.4
+ ]
+ },
+ {
+ "id": "filing_cabinet_2",
+ "label": "Grey four-drawer filing cabinet",
+ "asset": "filing_cabinet",
+ "category": "furniture",
+ "x": 15.6,
+ "y": 10.0,
+ "z": 0.0,
+ "w": 0.5,
+ "d": 0.65,
+ "h": 1.35,
+ "rot": -90.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s grey steel four-drawer filing cabinet with chrome pull handles and paper label slots, scuffed paint",
+ "crop": null
+ },
+ {
+ "id": "wastebasket_1",
+ "label": "Metal wastebasket with crumpled paper",
+ "asset": "wastebasket",
+ "category": "clutter",
+ "x": 5.5,
+ "y": 2.4,
+ "z": 0.0,
+ "w": 0.3,
+ "d": 0.3,
+ "h": 0.36,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "Round grey metal office wastebasket half filled with crumpled paper and printout strips",
+ "crop": null
+ },
+ {
+ "id": "wastebasket_2",
+ "label": "Metal wastebasket",
+ "asset": "wastebasket",
+ "category": "clutter",
+ "x": 10.2,
+ "y": 6.2,
+ "z": 0.0,
+ "w": 0.3,
+ "d": 0.3,
+ "h": 0.36,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "Round grey metal office wastebasket half filled with crumpled paper and printout strips",
+ "crop": null
+ },
+ {
+ "id": "coat_rack",
+ "label": "Coat stand with jacket",
+ "asset": "coat_rack",
+ "category": "furniture",
+ "x": 15.4,
+ "y": 0.6,
+ "z": 0.0,
+ "w": 0.5,
+ "d": 0.5,
+ "h": 1.8,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "Chrome 1960s coat stand with a grey suit jacket and a fedora hanging from the hooks",
+ "crop": null
+ },
+ {
+ "id": "water_cooler",
+ "label": "Office water cooler",
+ "asset": "water_cooler",
+ "category": "fixture",
+ "x": 15.6,
+ "y": 4.5,
+ "z": 0.0,
+ "w": 0.35,
+ "d": 0.35,
+ "h": 1.25,
+ "rot": -90.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s office water cooler with glass bottle on top, cream enamel cabinet and chrome tap, paper cup dispenser on the side",
+ "crop": null
+ },
+ {
+ "id": "briefing_table",
+ "label": "Plain side table with flight plan folders",
+ "asset": "side_table",
+ "category": "furniture",
+ "x": 3.0,
+ "y": 1.2,
+ "z": 0.0,
+ "w": 1.6,
+ "d": 0.7,
+ "h": 0.74,
+ "rot": 0.0,
+ "source": "invented",
+ "generate": false,
+ "prompt": "",
+ "crop": null
+ },
+ {
+ "id": "folders_side_table",
+ "label": "Stack of manila folders",
+ "asset": "folder_stack",
+ "category": "clutter",
+ "x": 3.0,
+ "y": 1.2,
+ "z": 0.74,
+ "w": 0.35,
+ "d": 0.27,
+ "h": 0.08,
+ "rot": 10.0,
+ "source": "invented",
+ "generate": false,
+ "prompt": "",
+ "crop": null
+ },
+ {
+ "id": "rotary_phone",
+ "label": "Black rotary phone",
+ "asset": "rotary_phone",
+ "category": "prop",
+ "x": 11.0,
+ "y": 2.75,
+ "z": 0.76,
+ "w": 0.22,
+ "d": 0.24,
+ "h": 0.12,
+ "rot": -10.0,
+ "source": "invented",
+ "generate": true,
+ "prompt": "1960s black bakelite rotary dial desk telephone with coiled cord, slightly glossy",
+ "crop": null
+ }
+ ],
+ "lights": [
+ {
+ "id": "ceiling_1",
+ "kind": "practical",
+ "x": 5.0,
+ "y": 4.0,
+ "z": 3.5,
+ "color": "#e8f0ff",
+ "power": "low",
+ "attached_to": "ceiling_panel_1",
+ "source": "reference"
+ },
+ {
+ "id": "ceiling_2",
+ "kind": "practical",
+ "x": 11.0,
+ "y": 4.0,
+ "z": 3.5,
+ "color": "#e8f0ff",
+ "power": "low",
+ "attached_to": "ceiling_panel_2",
+ "source": "reference"
+ },
+ {
+ "id": "ceiling_3",
+ "kind": "practical",
+ "x": 5.0,
+ "y": 9.0,
+ "z": 3.5,
+ "color": "#e8f0ff",
+ "power": "low",
+ "attached_to": "ceiling_panel_3",
+ "source": "invented"
+ },
+ {
+ "id": "ceiling_4",
+ "kind": "practical",
+ "x": 11.0,
+ "y": 9.0,
+ "z": 3.5,
+ "color": "#e8f0ff",
+ "power": "low",
+ "attached_to": "ceiling_panel_4",
+ "source": "invented"
+ },
+ {
+ "id": "wall_display_glow",
+ "kind": "screen",
+ "x": 8.2,
+ "y": 13.6,
+ "z": 2.7,
+ "color": "#7fe0b0",
+ "power": "medium",
+ "attached_to": "big_wall_display",
+ "source": "reference"
+ },
+ {
+ "id": "crt_orbital",
+ "kind": "screen",
+ "x": 8.6,
+ "y": 3.1,
+ "z": 1.0,
+ "color": "#39ff8a",
+ "power": "low",
+ "attached_to": "console_orbital_analysis",
+ "source": "reference"
+ },
+ {
+ "id": "crt_mission",
+ "kind": "screen",
+ "x": 7.2,
+ "y": 6.7,
+ "z": 1.0,
+ "color": "#39ff8a",
+ "power": "low",
+ "attached_to": "console_mission_control",
+ "source": "reference"
+ },
+ {
+ "id": "crt_telemetry",
+ "kind": "screen",
+ "x": 12.9,
+ "y": 7.3,
+ "z": 1.0,
+ "color": "#39ff8a",
+ "power": "low",
+ "attached_to": "console_telemetry",
+ "source": "reference"
+ },
+ {
+ "id": "crt_guidance",
+ "kind": "screen",
+ "x": 1.6,
+ "y": 5.0,
+ "z": 1.0,
+ "color": "#39ff8a",
+ "power": "low",
+ "attached_to": "console_guidance",
+ "source": "reference"
+ },
+ {
+ "id": "crt_back",
+ "kind": "screen",
+ "x": 8.5,
+ "y": 10.3,
+ "z": 1.0,
+ "color": "#39ff8a",
+ "power": "low",
+ "attached_to": "console_back_row",
+ "source": "reference"
+ },
+ {
+ "id": "lamp_guidance",
+ "kind": "practical",
+ "x": 2.5,
+ "y": 5.6,
+ "z": 1.65,
+ "color": "#ffb46b",
+ "power": "low",
+ "attached_to": "desk_lamp_guidance",
+ "source": "reference"
+ },
+ {
+ "id": "lamp_window",
+ "kind": "practical",
+ "x": 3.2,
+ "y": 9.6,
+ "z": 1.65,
+ "color": "#ffb46b",
+ "power": "low",
+ "attached_to": "desk_lamp_window",
+ "source": "reference"
+ },
+ {
+ "id": "lamp_right",
+ "kind": "practical",
+ "x": 14.6,
+ "y": 8.0,
+ "z": 1.65,
+ "color": "#ffb46b",
+ "power": "low",
+ "attached_to": "desk_lamp_right",
+ "source": "reference"
+ },
+ {
+ "id": "window_night",
+ "kind": "window",
+ "x": 0.05,
+ "y": 7.5,
+ "z": 2.0,
+ "color": "#2a3a5a",
+ "power": "low",
+ "attached_to": "",
+ "source": "reference"
+ },
+ {
+ "id": "amber_indicators",
+ "kind": "practical",
+ "x": 7.4,
+ "y": 3.15,
+ "z": 1.1,
+ "color": "#ffa040",
+ "power": "low",
+ "attached_to": "console_orbital_analysis",
+ "source": "reference"
+ },
+ {
+ "id": "fill_room",
+ "kind": "fill",
+ "x": 8.0,
+ "y": 0.5,
+ "z": 2.5,
+ "color": "#9aa6a0",
+ "power": "low",
+ "attached_to": "",
+ "source": "invented"
+ }
+ ],
+ "reference_camera": {
+ "position": [
+ 7.6,
+ 0.9,
+ 1.3
+ ],
+ "look_at": [
+ 8.6,
+ 13.0,
+ 1.6
+ ],
+ "lens_mm": 26.0
+ },
+ "notes": [
+ "Exterior beyond the left windows (floodlit rocket on launch pad, distant lights) should be a night backplate/HDRI card, not modelled.",
+ "Invented: front area behind camera (side table with folders, coat stand, water cooler, wastebaskets, second filing cabinet, rotary phone), the entry doors on the front and right walls, and the rear chairs and desk clutter not visible.",
+ "Console banks share one asset scaled to different widths; the foreground Orbital Analysis console is a distinct hero asset.",
+ "Placards and poster text are fictional; screen contents are emissive textures.",
+ "Add light haze/cigarette smoke volume for atmosphere; consoles assumed on a flat floor without tiers."
+ ]
+}
\ No newline at end of file
diff --git a/web/fixtures/plan_events.jsonl b/web/fixtures/plan_events.jsonl
new file mode 100644
index 0000000..372ad45
--- /dev/null
+++ b/web/fixtures/plan_events.jsonl
@@ -0,0 +1,9 @@
+{"t": 35.9, "stage": "received", "status": "running", "message": "plan request", "elapsed_s": 0.0}
+{"t": 35.9, "stage": "reading_reference", "status": "running", "message": "1 reference image(s)", "elapsed_s": 0.0}
+{"t": 35.9, "stage": "planning", "status": "running", "message": "laying out the whole space (effort medium)", "elapsed_s": 0.0}
+{"t": 96.7, "stage": "planning", "status": "done", "message": "70 objects (18 invented), 16 lights, 16 x 14 m interior", "elapsed_s": 50.6}
+{"t": 96.7, "stage": "drawing_floor_plan", "status": "running", "message": "", "elapsed_s": 50.8}
+{"t": 96.7, "stage": "drawing_floor_plan", "status": "done", "message": "", "elapsed_s": 51.5, "preview_url": "https://v3b.fal.media/files/b/0ab08d9a/ITwcWiHrIg3HudA4h-1Wb_floor_plan.png"}
+{"t": 96.7, "stage": "blockout", "status": "running", "message": "grey-box renders from the reference camera and an overview", "elapsed_s": 51.5}
+{"t": 131.4, "stage": "blockout", "status": "done", "message": "", "elapsed_s": 86.2, "preview_url": "comparison.png", "synthetic": true}
+{"t": 131.4, "stage": "done", "status": "done", "message": "plan p_4f46c795ea", "elapsed_s": 86.2, "synthetic": true}
diff --git a/web/fixtures/reference.png b/web/fixtures/reference.png
new file mode 100644
index 0000000..41c75b4
Binary files /dev/null and b/web/fixtures/reference.png differ
diff --git a/web/fixtures/scene.glb b/web/fixtures/scene.glb
new file mode 100644
index 0000000..b899f20
Binary files /dev/null and b/web/fixtures/scene.glb differ
diff --git a/web/fixtures/still_0.png b/web/fixtures/still_0.png
new file mode 100644
index 0000000..08208a8
Binary files /dev/null and b/web/fixtures/still_0.png differ
diff --git a/web/fixtures/still_1.png b/web/fixtures/still_1.png
new file mode 100644
index 0000000..42d4676
Binary files /dev/null and b/web/fixtures/still_1.png differ
diff --git a/web/fixtures/still_2.png b/web/fixtures/still_2.png
new file mode 100644
index 0000000..60abbf6
Binary files /dev/null and b/web/fixtures/still_2.png differ
diff --git a/web/lib/apps.ts b/web/lib/apps.ts
new file mode 100644
index 0000000..145396b
--- /dev/null
+++ b/web/lib/apps.ts
@@ -0,0 +1,30 @@
+// The fal apps the UI calls, as <owner>/<app>, from NEXT_PUBLIC_* env vars (web/.env.local; see web/.env.example).
+// No defaults: an unset app fails with a message naming the variable instead of calling someone else's app.
+// Each process.env.NEXT_PUBLIC_* is written out in full so Next inlines it into the client bundle.
+
+const clean = (v: string | undefined) => (v || "").trim().replace(/^\/+|\/+$/g, "");
+
+/** The scene builder (builder/app.py): /ref2scene, /shots, /builds, /build_events. */
+export const BUILDER_APP = clean(process.env.NEXT_PUBLIC_ANYSCENE_APP);
+/** The older plan + build pipeline (endpoint/app.py) behind ?mode=pipeline. Falls back to the builder app's id. */
+export const PIPELINE_APP = clean(process.env.NEXT_PUBLIC_ANYSCENE_PIPELINE_APP) || BUILDER_APP;
+/** AnyKit (kit/app.py): /kits, /kit_events. */
+export const KIT_APP = clean(process.env.NEXT_PUBLIC_ANYKIT_APP);
+/** Optional second builder deployment (e.g. a private test copy) that ?gallery_app=<id> may point the gallery at. */
+export const TEST_APP = clean(process.env.NEXT_PUBLIC_ANYSCENE_TEST_APP);
+
+/** Every app the proxy may forward to (the server-side allowlist is built from this). */
+export const ALL_APPS = [...new Set([BUILDER_APP, PIPELINE_APP, KIT_APP, TEST_APP].filter(Boolean))];
+
+const ENV_OF: [string, string, string][] = [
+ [BUILDER_APP, "NEXT_PUBLIC_ANYSCENE_APP", "anyscene"],
+ [PIPELINE_APP, "NEXT_PUBLIC_ANYSCENE_PIPELINE_APP", "anyscene"],
+ [KIT_APP, "NEXT_PUBLIC_ANYKIT_APP", "anykit"],
+];
+
+/** The app id, or a clear error naming the env var to set. */
+export function requireApp(app: string, which: "builder" | "pipeline" | "kit"): string {
+ if (app) return app;
+ const [, env, name] = ENV_OF[which === "builder" ? 0 : which === "pipeline" ? 1 : 2];
+ throw new Error(`No fal app configured: set ${env}=<your-fal-username>/${name} in web/.env.local and restart the dev server.`);
+}
diff --git a/web/lib/builder.ts b/web/lib/builder.ts
new file mode 100644
index 0000000..20fd156
--- /dev/null
+++ b/web/lib/builder.ts
@@ -0,0 +1,316 @@
+// Contract with the AnyScene builder app, NEXT_PUBLIC_ANYSCENE_APP (builder/app.py, builder/scene_builder.py) and the UI state folded from its
+// stage events. One request runs the whole build: an agent works, reports milestones, and loops with a critic.
+
+export { BUILDER_APP } from "./apps";
+
+export interface BuilderRequest {
+ reference_image_urls: string[];
+ prompt: string;
+ effort: string;
+ scene: string;
+ /** Only the dials the user set; the builder reads the rest from the reference. */
+ dials?: Record<string, number | string>;
+ floor_plan_url?: string;
+}
+
+/** /shots: scene to images or scene to video, on a finished build. */
+export interface ShotsRequest {
+ build_id: string;
+ mode: "images" | "video";
+ shots: { name?: string; description?: string }[];
+ settings?: { seconds?: number; handheld?: "none" | "walk" | "subtle"; lens_mm?: number; look?: string; res?: [number, number] };
+ dials?: Record<string, number | string>;
+ effort?: string;
+}
+
+export interface ShotsResponse {
+ job_id: string;
+ stills: string[];
+ videos: string[];
+ result: Record<string, unknown>;
+ missing: string[];
+ agent_cost_usd: number | null;
+ minutes: number;
+}
+
+export const SCORE_KEYS = [
+ "layout",
+ "props",
+ "screens_signage",
+ "materials",
+ "lighting",
+ "atmosphere",
+ "plausibility",
+ "composition",
+] as const;
+export type ScoreKey = (typeof SCORE_KEYS)[number];
+export const SCORE_LABELS: Record<ScoreKey, string> = {
+ layout: "Layout",
+ props: "Props",
+ screens_signage: "Screens + signs",
+ materials: "Materials",
+ lighting: "Lighting",
+ atmosphere: "Atmosphere",
+ plausibility: "Plausibility",
+ composition: "Composition",
+};
+export const PASS_MARK = 7;
+
+export interface Critique {
+ round: number;
+ scores: Record<ScoreKey, number>;
+ fixes: string[];
+ summary: string;
+ passed: boolean;
+ stills?: string[];
+}
+
+export interface BuilderEvent {
+ t: number; // seconds since the builder started (server clock)
+ stage: string;
+ status: "running" | "done" | "failed";
+ message: string;
+ preview_url?: string;
+ tool?: string;
+ critique?: Critique;
+ package_url?: string;
+ missing?: string[];
+ critiques?: number;
+ // heartbeat (every 20 s): the tool call in progress and every milestone so far
+ working?: string | null;
+ working_s?: number | null;
+ milestones?: { t: number; stage: string; status: string; message: string; preview_url?: string }[];
+}
+
+export interface BuilderResponse {
+ build_id: string;
+ stills: string[];
+ scene_blend_url: string | null;
+ scene_glb_url: string | null;
+ panorama_urls: string[];
+ /** The scouting previews; each name is a camera usable in a /shots order. */
+ previews?: { name: string; url: string }[];
+ package_url: string | null;
+ critiques: Critique[];
+ missing: string[];
+ /** Every dial as built (out/dials.json); the agent decides each entry's shape. */
+ dials?: Record<string, unknown>;
+ agent_cost_usd: number | null;
+ minutes: number;
+}
+
+/** The milestones the agent usually reports (it picks its own; unknown ones are added in arrival order). */
+export const MILESTONES = ["plan", "props", "layout", "dressing", "screens", "materials", "lighting", "atmosphere", "cameras", "finals"];
+export const MILESTONE_LABELS: Record<string, string> = {
+ plan: "Plan",
+ props: "Props",
+ layout: "Layout",
+ dressing: "Set dressing",
+ screens: "Screens",
+ materials: "Materials",
+ lighting: "Lighting",
+ atmosphere: "Atmosphere",
+ cameras: "Cameras",
+ finals: "Finals",
+};
+const NON_MILESTONES = new Set(["received", "log", "thinking", "critique", "done", "packaged", "heartbeat", "error"]);
+
+export interface LogLine {
+ id: number;
+ t: number;
+ kind: "tool" | "note" | "milestone" | "critic" | "system";
+ tool?: string;
+ stage: string;
+ text: string;
+ image?: string;
+}
+
+export interface Milestone {
+ stage: string;
+ start: number;
+ end?: number;
+ message: string;
+ takes: number;
+ preview?: string;
+}
+
+export interface BuilderState {
+ status: "idle" | "running" | "done" | "failed" | "ended"; // ended: a replay recording that stops mid-run
+ buildId?: string;
+ lines: LogLine[];
+ milestones: Record<string, Milestone>;
+ order: string[]; // MILESTONES plus extras the agent picked, in display order
+ current?: string; // milestone being worked on
+ previews: { url: string; stage: string; message: string; t: number }[];
+ critiques: Critique[];
+ criticBusy: boolean;
+ received?: number;
+ doneAt?: number;
+ packagedAt?: number;
+ packageUrl?: string;
+ missing?: string[];
+ lastT: number;
+ error?: string;
+ thought?: string; // the agent's latest note, for the caption
+ working?: { what: string; since: number }; // the tool call in progress (heartbeat), what a long render looks like
+}
+
+export function initialBuilder(status: BuilderState["status"] = "idle"): BuilderState {
+ return { status, lines: [], milestones: {}, order: [...MILESTONES], previews: [], critiques: [], criticBusy: false, lastT: 0 };
+}
+
+export type BuilderAction =
+ | { type: "start" }
+ | { type: "event"; ev: BuilderEvent }
+ | { type: "result"; res: BuilderResponse }
+ | { type: "fail"; message: string }
+ | { type: "ended" }
+ | { type: "reset" };
+
+let lineId = 0;
+
+export function builderReducer(s: BuilderState, a: BuilderAction): BuilderState {
+ switch (a.type) {
+ case "reset":
+ return initialBuilder();
+ case "start":
+ return initialBuilder("running");
+ case "fail":
+ return {
+ ...s,
+ status: "failed",
+ error: a.message,
+ lines: [...s.lines, { id: ++lineId, t: s.lastT, kind: "system", stage: "failed", text: a.message }],
+ };
+ case "ended":
+ return { ...s, status: "ended", criticBusy: false };
+ case "result": {
+ // the response is authoritative for critiques (the events can miss the last ones)
+ const critiques = a.res.critiques?.length ? a.res.critiques : s.critiques;
+ return {
+ ...s,
+ status: s.status === "failed" ? "failed" : "done",
+ buildId: a.res.build_id || s.buildId,
+ critiques,
+ criticBusy: false,
+ packageUrl: a.res.package_url ?? s.packageUrl,
+ missing: a.res.missing ?? s.missing,
+ doneAt: s.doneAt ?? s.lastT,
+ milestones: closeAll(s, s.lastT),
+ current: undefined,
+ };
+ }
+ case "event":
+ return applyEvent(s, a.ev);
+ }
+}
+
+function closeAll(s: BuilderState, t: number) {
+ const ms = { ...s.milestones };
+ for (const k of Object.keys(ms)) if (ms[k].end === undefined) ms[k] = { ...ms[k], end: t };
+ return ms;
+}
+
+function applyEvent(s: BuilderState, ev: BuilderEvent): BuilderState {
+ const t = typeof ev.t === "number" ? ev.t : s.lastT;
+ const next: BuilderState = { ...s, lastT: Math.max(s.lastT, t) };
+ const line = (kind: LogLine["kind"], text: string, extra: Partial<LogLine> = {}) =>
+ (next.lines = [...next.lines, { id: ++lineId, t, kind, stage: ev.stage, text, ...extra }]);
+
+ if (ev.preview_url && !s.previews.some((p) => p.url === ev.preview_url)) {
+ next.previews = [...s.previews, { url: ev.preview_url, stage: ev.stage, message: ev.message, t }];
+ }
+ if (ev.status === "failed") {
+ next.status = "failed";
+ next.error = ev.message;
+ }
+
+ switch (ev.stage) {
+ case "received": {
+ next.received = next.received ?? t;
+ const id = /build ([bk]_\w+)/.exec(ev.message)?.[1]; // b_ scene builds, k_ kits
+ if (id) next.buildId = id;
+ line("system", ev.message);
+ break;
+ }
+ case "log":
+ next.working = undefined;
+ line("tool", ev.message, { tool: ev.tool || "Tool" });
+ break;
+ case "heartbeat": {
+ next.working = ev.working ? { what: ev.working, since: t - (ev.working_s ?? 0) } : undefined;
+ // a page that attached late missed the early milestones: the heartbeat carries them all
+ let filled: BuilderState = next;
+ for (const m of ev.milestones ?? []) {
+ if (!filled.milestones[m.stage]) filled = applyEvent(filled, { ...m, status: "running" } as BuilderEvent);
+ }
+ if (filled !== next) return { ...filled, current: filled.current, working: next.working, lastT: next.lastT };
+ break;
+ }
+ case "error":
+ line("system", ev.message);
+ break;
+ case "thinking":
+ next.thought = ev.message;
+ line("note", ev.message);
+ break;
+ case "critique":
+ if (ev.critique) {
+ const c = ev.critique;
+ next.critiques = [...s.critiques.filter((x) => x.round !== c.round), c].sort((a, b) => a.round - b.round);
+ next.criticBusy = false;
+ line("critic", `round ${c.round}: ${c.passed ? "PASS" : "not yet"}. ${c.summary || ""}`.trim(), { image: ev.preview_url });
+ } else {
+ next.criticBusy = true;
+ line("critic", ev.message);
+ }
+ break;
+ case "done":
+ next.doneAt = t;
+ next.missing = ev.missing ?? s.missing;
+ next.milestones = closeAll(next, t);
+ next.current = undefined;
+ line("system", ev.message);
+ break;
+ case "packaged":
+ next.packagedAt = t;
+ next.packageUrl = ev.package_url ?? s.packageUrl;
+ if (next.status !== "failed") next.status = "done";
+ line("system", ev.message);
+ break;
+ default: {
+ if (NON_MILESTONES.has(ev.stage)) break;
+ // a milestone the agent reported: it is now the current one; the previous one wraps
+ const ms = { ...s.milestones };
+ if (s.current && s.current !== ev.stage && ms[s.current] && ms[s.current].end === undefined) {
+ ms[s.current] = { ...ms[s.current], end: t };
+ }
+ const old = ms[ev.stage];
+ const retake = !!old && s.current !== ev.stage;
+ ms[ev.stage] = {
+ stage: ev.stage,
+ start: old && !retake ? old.start : t,
+ end: undefined,
+ message: ev.message || old?.message || "",
+ takes: (old?.takes ?? 0) + (retake || !old ? 1 : 0),
+ preview: ev.preview_url ?? old?.preview,
+ };
+ next.milestones = ms;
+ next.current = ev.stage;
+ if (!s.order.includes(ev.stage)) next.order = [...s.order, ev.stage];
+ line("milestone", ev.message, { image: ev.preview_url });
+ }
+ }
+ return next;
+}
+
+export const clock = (s: number | undefined) => {
+ if (s === undefined || !isFinite(s)) return "";
+ s = Math.max(0, Math.floor(s));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ const mm = String(m).padStart(2, "0");
+ const ss = String(sec).padStart(2, "0");
+ return h ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
+};
diff --git a/web/lib/gallery.ts b/web/lib/gallery.ts
new file mode 100644
index 0000000..0220a15
--- /dev/null
+++ b/web/lib/gallery.ts
@@ -0,0 +1,166 @@
+// The shared gallery: every build anyone ran on the fal apps, read from their storage (/builds, /build_events on the
+// builder app; /kits, /kit_events on the AnyKit app; see builder/gallery.py and lib/apps.ts). Unlike ?watch, this does
+// not need the submitter's key: the fal queue only shows a request to the key that started it, storage shows everyone's.
+import { fal } from "@fal-ai/client";
+import { type BuilderEvent, type BuilderResponse, type Critique } from "./builder";
+import { BUILDER_APP, KIT_APP, TEST_APP, requireApp } from "./apps";
+import { configureFal } from "./sources";
+
+export type GalleryKind = "scene" | "kit";
+export { KIT_APP };
+
+/** ?gallery_app=<id> points the scene gallery at NEXT_PUBLIC_ANYSCENE_TEST_APP (e.g. a private test copy).
+ * Empty when the app isn't configured; the calls below then fail with a message naming the env var. */
+export function galleryApp(kind: GalleryKind, override?: string | null): string {
+ if (kind === "kit") return KIT_APP;
+ return override && (override === BUILDER_APP || override === TEST_APP) ? override : BUILDER_APP;
+}
+
+export interface GalleryItem {
+ id: string;
+ kind: GalleryKind;
+ started: number; // unix seconds
+ updated: number;
+ status: "done" | "running" | "stopped" | "capped";
+ passed: boolean;
+ reference_urls: string[];
+ prompt: string;
+ dials: Record<string, number | string>;
+ effort?: string | null;
+ floor_plan_url?: string | null;
+ items?: string[] | null;
+ name?: string | null;
+ critic_rounds: number;
+ last_scores?: Record<string, number> | null;
+ last_summary?: string | null;
+ minutes: number;
+ cover?: string | null;
+ stills: string[];
+ previews: { url: string; message: string }[];
+ n_stills: number;
+ n_previews: number;
+ frames: number;
+ milestone?: { stage: string; message: string; t: number } | null;
+ attempts: number;
+ has_response: boolean;
+ agent_cost_usd?: number | null;
+ error?: string | null;
+}
+
+export interface GalleryList {
+ builds: GalleryItem[];
+ total: number;
+ now: number;
+}
+
+export interface GalleryEventsPage {
+ id: string;
+ events: BuilderEvent[];
+ next: number;
+ size: number;
+ more: boolean;
+ summary: GalleryItem;
+ response?: Record<string, unknown>;
+}
+
+async function call<O>(endpoint: string, input: object): Promise<O> {
+ configureFal();
+ // through the queue, not a sync call: a cold GPU worker can take minutes to come up
+ const r = await fal.subscribe(endpoint, { input, pollInterval: 700 });
+ return r.data as O;
+}
+
+function needApp(kind: GalleryKind, app: string) {
+ return requireApp(app, kind === "kit" ? "kit" : "builder");
+}
+
+export function listGallery(kind: GalleryKind, app: string, limit = 300): Promise<GalleryList> {
+ app = needApp(kind, app);
+ return call<GalleryList>(`${app}/${kind === "kit" ? "kits" : "builds"}`, { limit });
+}
+
+export function galleryEvents(kind: GalleryKind, app: string, id: string, after: number): Promise<GalleryEventsPage> {
+ app = needApp(kind, app);
+ return kind === "kit"
+ ? call<GalleryEventsPage>(`${app}/kit_events`, { kit_id: id, after })
+ : call<GalleryEventsPage>(`${app}/build_events`, { build_id: id, after });
+}
+
+/** The last listing, per kind, so the grid paints at once while a (possibly cold) worker answers. Per viewer only. */
+const CACHE_KEY = (kind: GalleryKind, app: string) => `anyscene.gallery.${app}.${kind}`;
+export function cachedList(kind: GalleryKind, app: string): GalleryList | null {
+ try {
+ const s = localStorage.getItem(CACHE_KEY(kind, app));
+ return s ? (JSON.parse(s) as GalleryList) : null;
+ } catch {
+ return null;
+ }
+}
+export function storeList(kind: GalleryKind, app: string, list: GalleryList) {
+ try {
+ localStorage.setItem(CACHE_KEY(kind, app), JSON.stringify(list));
+ } catch {
+ /* full or blocked: the grid just loads without a head start */
+ }
+}
+
+interface KitItemResp {
+ id: string;
+ label?: string;
+ thumb_url?: string | null;
+ glb_url?: string | null;
+}
+
+/** A finished build's response, as the results view expects it. Kits map onto it: the lineup is the still, each item
+ * thumbnail a named preview. */
+export function toBuilderResponse(kind: GalleryKind, r: Record<string, unknown> | undefined, id: string): BuilderResponse | null {
+ if (!r) return null;
+ if (kind === "scene") {
+ const b = r as unknown as BuilderResponse;
+ return {
+ ...b,
+ build_id: b.build_id || id,
+ stills: b.stills ?? [],
+ panorama_urls: b.panorama_urls ?? [],
+ previews: b.previews ?? [],
+ critiques: b.critiques ?? [],
+ missing: b.missing ?? [],
+ scene_blend_url: b.scene_blend_url ?? null,
+ scene_glb_url: b.scene_glb_url ?? null,
+ package_url: b.package_url ?? null,
+ agent_cost_usd: b.agent_cost_usd ?? null,
+ minutes: b.minutes as number,
+ };
+ }
+ const items = ((r.items as KitItemResp[]) ?? []).filter((x) => x.thumb_url);
+ const lineup = r.lineup_url as string | null;
+ return {
+ build_id: (r.kit_id as string) || id,
+ stills: lineup ? [lineup] : [],
+ previews: items.map((x) => ({ name: x.label || x.id, url: x.thumb_url! })),
+ panorama_urls: [],
+ scene_blend_url: (r.kit_blend_url as string | null) ?? null,
+ scene_glb_url: null,
+ package_url: (r.package_url as string | null) ?? null,
+ critiques: (r.critiques as Critique[]) ?? [],
+ missing: (r.missing as string[]) ?? [],
+ dials: (r.dials as Record<string, unknown>) ?? {},
+ agent_cost_usd: (r.agent_cost_usd as number | null) ?? null,
+ minutes: r.minutes as number,
+ };
+}
+
+export const ago = (unixS: number, now = Date.now() / 1000) => {
+ const s = Math.max(0, now - unixS);
+ if (s < 90) return "just now";
+ if (s < 3600) return `${Math.round(s / 60)} min ago`;
+ if (s < 86400 * 2) return `${Math.round(s / 3600)} h ago`;
+ return `${Math.round(s / 86400)} days ago`;
+};
+
+export const STATUS_LABEL: Record<GalleryItem["status"], string> = {
+ done: "Wrapped",
+ running: "Rolling",
+ stopped: "Stopped",
+ capped: "Capped",
+};
diff --git a/web/lib/run.ts b/web/lib/run.ts
new file mode 100644
index 0000000..527d63d
--- /dev/null
+++ b/web/lib/run.ts
@@ -0,0 +1,249 @@
+// Folds the stage-event stream of one /plan or /build request into UI state.
+import { BUILD_STAGES, PLAN_STAGES, type RunKind, type StageEvent } from "./types";
+
+export type StageUiStatus = "pending" | "running" | "done" | "failed" | "skipped";
+
+export interface StageState {
+ status: StageUiStatus;
+ start?: number; // run seconds
+ end?: number;
+ message: string;
+ progress?: number;
+}
+
+export interface PropTile {
+ id: string;
+ label: string;
+ ref_url?: string | null;
+ model?: string | null;
+ mesh_url?: string | null;
+ status: "meshing" | "done" | "failed";
+ arrivedAt: number;
+ meshAt?: number;
+}
+
+export interface Preview {
+ url: string;
+ stage: string;
+ message: string;
+ at: number;
+}
+
+export interface RunState {
+ kind: RunKind | null;
+ status: "idle" | "running" | "done" | "failed";
+ order: string[];
+ stages: Record<string, StageState>;
+ caption: { stage: string; message: string };
+ previews: Preview[];
+ props: Record<string, PropTile>;
+ propOrder: string[];
+ totalProps?: number;
+ totalPlacements?: number;
+ packageUrl?: string;
+ panoramas: { url: string; label: string }[];
+ sceneGlbUrl?: string;
+ envUrl?: string;
+ error?: string;
+ lastAt: number;
+ events: number;
+}
+
+export function initialRun(kind: RunKind | null = null): RunState {
+ const order = kind === "build" ? [...BUILD_STAGES] : [...PLAN_STAGES];
+ return {
+ kind,
+ status: kind ? "running" : "idle",
+ order,
+ stages: Object.fromEntries(order.map((s) => [s, { status: "pending", message: "" } as StageState])),
+ caption: { stage: "", message: "" },
+ previews: [],
+ panoramas: [],
+ props: {},
+ propOrder: [],
+ lastAt: 0,
+ events: 0,
+ };
+}
+
+export type RunAction =
+ | { type: "start"; kind: RunKind }
+ | { type: "event"; ev: StageEvent; t: number }
+ | { type: "fail"; message: string; t: number }
+ | { type: "finish"; t: number }
+ | { type: "reset" };
+
+const closed = (s: StageState) => s.status === "done" || s.status === "failed" || s.status === "skipped";
+
+export function runReducer(state: RunState, action: RunAction): RunState {
+ switch (action.type) {
+ case "reset":
+ return initialRun(null);
+ case "start":
+ return initialRun(action.kind);
+ case "fail": {
+ const stages = { ...state.stages };
+ const cur = state.order.find((s) => stages[s].status === "running");
+ if (cur) stages[cur] = { ...stages[cur], status: "failed", end: action.t, message: action.message };
+ return { ...state, stages, status: "failed", error: action.message, caption: { stage: cur ?? "", message: action.message } };
+ }
+ case "finish": {
+ if (state.status !== "running") return state;
+ const stages = { ...state.stages };
+ for (const s of state.order) {
+ if (stages[s].status === "running") stages[s] = { ...stages[s], status: "done", end: action.t };
+ else if (stages[s].status === "pending") stages[s] = { ...stages[s], status: "skipped" };
+ }
+ return { ...state, stages, status: "done" };
+ }
+ case "event":
+ return applyEvent(state, action.ev, action.t);
+ }
+}
+
+function applyEvent(state: RunState, ev: StageEvent, t: number): RunState {
+ const stages = { ...state.stages };
+ const order = state.order.includes(ev.stage) ? state.order : [...state.order.slice(0, -1), ev.stage, "done"];
+ if (!stages[ev.stage]) stages[ev.stage] = { status: "pending", message: "" };
+ const idx = order.indexOf(ev.stage);
+ const isPropRefs = (s: string) => s === "prop_references";
+
+ // A stage that starts implies the ones before it are finished (the endpoint doesn't emit "done" for every stage).
+ // prop_references overlaps generating_meshes, so it closes on its own count or when layout starts.
+ if (ev.status !== "failed") {
+ order.slice(0, idx).forEach((s) => {
+ const st = stages[s];
+ if (isPropRefs(s) && order.indexOf("layout") > idx) return;
+ if (st.status === "running") stages[s] = { ...st, status: "done", end: t, progress: st.progress !== undefined ? 1 : undefined };
+ else if (st.status === "pending") stages[s] = { ...st, status: "skipped" };
+ });
+ }
+
+ const cur = stages[ev.stage];
+ const next: StageState = { ...cur };
+ if (cur.start === undefined) next.start = t;
+ const msg = ev.message || cur.message;
+ if (ev.status === "failed") {
+ next.status = "failed";
+ next.end = t;
+ next.message = ev.message;
+ } else if (ev.status === "done") {
+ if (!closed(cur) || cur.status === "done") {
+ next.status = "done";
+ next.end = cur.end ?? t;
+ }
+ next.message = msg;
+ if (cur.progress !== undefined || ev.progress !== undefined) next.progress = ev.progress ?? 1;
+ } else {
+ // running: an already-closed stage (late meshes after generating_meshes "done") only updates its numbers
+ if (!closed(cur)) next.status = "running";
+ next.message = msg;
+ if (ev.progress !== undefined) next.progress = ev.progress;
+ }
+ stages[ev.stage] = next;
+
+ // props
+ let { props, propOrder, totalProps, totalPlacements } = state;
+ const m = ev.stage === "prop_references" && /(\d+) unique props \((\d+) placements\)/.exec(ev.message || "");
+ if (m) {
+ totalProps = +m[1];
+ totalPlacements = +m[2];
+ }
+ if (ev.prop) {
+ const p = ev.prop;
+ const old = props[p.id];
+ const tile: PropTile = {
+ id: p.id,
+ label: p.label || old?.label || p.id,
+ ref_url: p.ref_url ?? old?.ref_url,
+ model: p.model ?? old?.model,
+ mesh_url: p.mesh_url ?? old?.mesh_url,
+ status: p.status,
+ arrivedAt: old?.arrivedAt ?? t,
+ meshAt: p.mesh_url ? (old?.meshAt ?? t) : old?.meshAt,
+ };
+ props = { ...props, [p.id]: tile };
+ if (!old) propOrder = [...propOrder, p.id];
+ }
+ if (totalProps && stages.prop_references && stages.prop_references.status !== "done") {
+ const n = propOrder.length;
+ const pr = stages.prop_references;
+ stages.prop_references = { ...pr, progress: Math.min(1, n / totalProps) };
+ if (n >= totalProps) stages.prop_references = { ...stages.prop_references, status: "done", end: t };
+ }
+
+ let status = state.status;
+ if (ev.status === "failed") status = "failed";
+ if (ev.stage === "done" && ev.status === "done") {
+ status = "done";
+ for (const s of order) {
+ if (stages[s].status === "running") stages[s] = { ...stages[s], status: "done", end: t };
+ if (stages[s].status === "pending") stages[s] = { ...stages[s], status: "skipped" };
+ }
+ }
+
+ const previews = ev.preview_url
+ ? [...state.previews.filter((p) => p.url !== ev.preview_url), { url: ev.preview_url, stage: ev.stage, message: ev.message, at: t }]
+ : state.previews;
+
+ // The caption follows the newest non-prop message (prop events are many and quick; they read on the shelf).
+ const caption =
+ ev.message && !(ev.prop && ev.prop.status === "meshing")
+ ? { stage: ev.stage, message: ev.message }
+ : state.caption.stage
+ ? state.caption
+ : { stage: ev.stage, message: ev.message };
+
+ return {
+ ...state,
+ order,
+ stages,
+ props,
+ propOrder,
+ totalProps,
+ totalPlacements,
+ previews,
+ caption,
+ status,
+ packageUrl: ev.package_url ?? state.packageUrl,
+ panoramas:
+ ev.panorama_url && !state.panoramas.some((p) => p.url === ev.panorama_url)
+ ? [...state.panoramas, { url: ev.panorama_url, label: ev.viewpoint || `viewpoint ${state.panoramas.length + 1}` }]
+ : state.panoramas,
+ sceneGlbUrl: ev.scene_glb_url ?? state.sceneGlbUrl,
+ envUrl: ev.environment_url ?? state.envUrl,
+ error: ev.status === "failed" ? ev.message : state.error,
+ lastAt: t,
+ events: state.events + 1,
+ };
+}
+
+/** Parse every stage event out of fal queue log lines. `seen` dedupes across polls (fal resends all logs). */
+export function parseLogs(logs: { message?: string }[] | undefined, seen: Set<string>, prefix: string): StageEvent[] {
+ const out: StageEvent[] = [];
+ for (const log of logs ?? []) {
+ const msg = log.message ?? "";
+ const i = msg.indexOf(prefix);
+ if (i < 0 || seen.has(msg)) continue;
+ seen.add(msg);
+ try {
+ out.push(JSON.parse(msg.slice(i + prefix.length)));
+ } catch {
+ /* partial line */
+ }
+ }
+ return out;
+}
+
+/** Which plan objects a prop asset stands for (props.py assets_for: the `asset` key, or the id's stem). */
+export function assetKey(o: { id: string; asset?: string }) {
+ return o.asset || o.id.replace(/(_(\d+|left|right|fg|bg|front|back|[a-z]))+$/, "");
+}
+
+export function fmtTime(s: number | undefined) {
+ if (s === undefined || !isFinite(s)) return "";
+ s = Math.max(0, s);
+ const m = Math.floor(s / 60);
+ const sec = Math.floor(s % 60);
+ return `${m}:${sec.toString().padStart(2, "0")}`;
+}
diff --git a/web/lib/sources.ts b/web/lib/sources.ts
new file mode 100644
index 0000000..5dcf61c
--- /dev/null
+++ b/web/lib/sources.ts
@@ -0,0 +1,425 @@
+// Where stage events come from: the live fal app (through the Next.js proxy) or a recorded run in public/replay/.
+import { fal } from "@fal-ai/client";
+import {
+ STAGE_PREFIX,
+ type BuildRequest,
+ type BuildResponse,
+ type Plan,
+ type PlanRequest,
+ type PlanResponse,
+ type StageEvent,
+} from "./types";
+import { assetKey, parseLogs } from "./run";
+import { type BuilderEvent, type BuilderRequest, type BuilderResponse, type ShotsRequest, type ShotsResponse } from "./builder";
+
+import { BUILDER_APP, PIPELINE_APP, requireApp } from "./apps";
+
+export const APP_ID = PIPELINE_APP;
+
+export interface Sink {
+ onEvent: (ev: StageEvent, t: number) => void;
+}
+
+export interface BuilderSink {
+ onEvent: (ev: BuilderEvent) => void;
+}
+
+export interface Source {
+ readonly mode: "live" | "replay";
+ /** Seconds since the current request was submitted (replay: virtual seconds at the replay speed). */
+ clock(): number;
+ uploadReference(file: File): Promise<string>;
+ plan(req: PlanRequest, sink: Sink): Promise<PlanResponse>;
+ build(req: BuildRequest, sink: Sink): Promise<BuildResponse>;
+ builder(req: BuilderRequest, sink: BuilderSink): Promise<BuilderResponse>;
+}
+
+// ---------------------------------------------------------------- live
+
+// The proxy can require a shared access key (ANYSCENE_ACCESS_KEY on the server). The viewer types it once; it is kept
+// in this browser's localStorage and sent as x-anyscene-key to our own proxy only (the proxy never forwards it to fal).
+export const ACCESS_KEY_STORAGE = "anyscene.access-key";
+export function getAccessKey(): string {
+ try {
+ return localStorage.getItem(ACCESS_KEY_STORAGE) || "";
+ } catch {
+ return "";
+ }
+}
+export function setAccessKey(k: string) {
+ try {
+ if (k) localStorage.setItem(ACCESS_KEY_STORAGE, k);
+ else localStorage.removeItem(ACCESS_KEY_STORAGE);
+ } catch {
+ /* private window: the key lasts for this page only */
+ }
+ sessionKey = k;
+}
+let sessionKey = "";
+
+let falConfigured = false;
+export function configureFal() {
+ if (falConfigured) return;
+ fal.config({
+ proxyUrl: "/api/fal/proxy",
+ requestMiddleware: async (req) => {
+ const key = sessionKey || getAccessKey();
+ return key ? { ...req, headers: { ...(req.headers || {}), "x-anyscene-key": key } } : req;
+ },
+ });
+ falConfigured = true;
+}
+
+export class LiveSource implements Source {
+ readonly mode = "live" as const;
+ private t0 = performance.now();
+
+ clock() {
+ return (performance.now() - this.t0) / 1000;
+ }
+
+ async uploadReference(file: File) {
+ configureFal();
+ return fal.storage.upload(file);
+ }
+
+ private async call<O>(endpoint: string, input: object, onEvent: (ev: StageEvent) => void, pollInterval = 1000): Promise<O> {
+ configureFal();
+ this.t0 = performance.now();
+ const seen = new Set<string>();
+ const take = (logs: unknown) => {
+ for (const ev of parseLogs(logs as { message?: string }[] | undefined, seen, STAGE_PREFIX)) onEvent(ev);
+ };
+ const res = await fal.subscribe(endpoint, {
+ input,
+ logs: true,
+ pollInterval,
+ onQueueUpdate: (update) => take("logs" in update ? update.logs : undefined),
+ });
+ // The last poll that sees COMPLETED usually carries no logs, so the closing events ("blockout done" with the
+ // comparison, "done" with package_url) would be lost. Ask for the logs once more.
+ try {
+ const st = await fal.queue.status(endpoint, { requestId: res.requestId, logs: true });
+ take("logs" in st ? st.logs : undefined);
+ } catch {
+ /* the response itself still has everything the UI needs */
+ }
+ return res.data as O;
+ }
+
+ plan(req: PlanRequest, sink: Sink) {
+ return this.call<PlanResponse>(`${requireApp(APP_ID, "pipeline")}/plan`, req, (ev) => sink.onEvent(ev, this.clock()));
+ }
+
+ build(req: BuildRequest, sink: Sink) {
+ return this.call<BuildResponse>(`${requireApp(APP_ID, "pipeline")}/build`, req, (ev) => sink.onEvent(ev, this.clock()));
+ }
+
+ /** The agent builder: one request, up to fal's 2 h cap. Logs grow with every tool call, so poll every 2 s. */
+ builder(req: BuilderRequest, sink: BuilderSink) {
+ return this.call<BuilderResponse>(`${requireApp(BUILDER_APP, "builder")}/ref2scene`, req, (ev) => sink.onEvent(ev as unknown as BuilderEvent), 2000);
+ }
+
+ /** Scene to images / video on a finished build: same event stream as a build (the shots agent reports blocking,
+ * farm progress and finals). */
+ shots(req: ShotsRequest, sink: BuilderSink) {
+ return this.call<ShotsResponse>(`${requireApp(BUILDER_APP, "builder")}/shots`, req, (ev) => sink.onEvent(ev as unknown as BuilderEvent), 2000);
+ }
+
+ /** Attach to a build that is already running (started elsewhere: the CLI client, another tab) by its fal request id.
+ * The queue keeps the request's whole log, so the page catches up from the start and then follows it live. */
+ async watchBuilder(requestId: string, sink: BuilderSink): Promise<BuilderResponse> {
+ configureFal();
+ this.t0 = performance.now();
+ const endpoint = `${requireApp(BUILDER_APP, "builder")}/ref2scene`;
+ const seen = new Set<string>();
+ const take = (logs: unknown) => {
+ for (const ev of parseLogs(logs as { message?: string }[] | undefined, seen, STAGE_PREFIX))
+ sink.onEvent(ev as unknown as BuilderEvent);
+ };
+ for (;;) {
+ const st = await fal.queue.status(endpoint, { requestId, logs: true });
+ take("logs" in st ? st.logs : undefined);
+ if (st.status === "COMPLETED") break;
+ await new Promise((r) => setTimeout(r, 3000));
+ }
+ const res = await fal.queue.result(endpoint, { requestId });
+ return res.data as BuilderResponse;
+ }
+}
+
+// ---------------------------------------------------------------- replay
+
+export interface ReplayManifest {
+ name: string;
+ plan_events: boolean;
+ plan: boolean;
+ reference: string | null;
+ floor_plan: string | null;
+ blockout_reference: string | null;
+ blockout_overview: string | null;
+ comparison: string | null;
+ build_events: boolean;
+ build: boolean;
+ stills: string[];
+ panoramas?: string[];
+ scene_glb?: string | null;
+ kind?: "pipeline" | "builder";
+ events?: boolean; // builder: events.jsonl
+}
+
+type Recorded = StageEvent & { t: number };
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+export class ReplaySource implements Source {
+ readonly mode = "replay" as const;
+ speed: number;
+ paused = false;
+ private vt = 0;
+ private last = performance.now();
+ private base: string;
+ private planCache?: Plan;
+
+ constructor(
+ readonly manifest: ReplayManifest,
+ speed = 1,
+ ) {
+ this.speed = speed;
+ this.base = `/replay/${manifest.name}/`;
+ }
+
+ static async load(name: string, speed: number): Promise<ReplaySource> {
+ let res = await fetch(`/replay/${encodeURIComponent(name)}/manifest.json`);
+ if (!res.ok) res = await fetch(`/replay/demo/manifest.json`);
+ if (!res.ok) throw new Error(`No replay named "${name}" in web/fixtures (run npm run fixtures).`);
+ return new ReplaySource(await res.json(), speed);
+ }
+
+ url(file: string | null | undefined) {
+ if (!file) return "";
+ return /^(https?:|data:|blob:|\/)/.test(file) ? file : this.base + file;
+ }
+
+ get referenceUrl() {
+ return this.url(this.manifest.reference);
+ }
+
+ clock() {
+ this.tick();
+ return this.vt;
+ }
+
+ private tick() {
+ const now = performance.now();
+ if (!this.paused) this.vt += ((now - this.last) / 1000) * this.speed;
+ this.last = now;
+ }
+
+ private reset() {
+ this.vt = 0;
+ this.last = performance.now();
+ }
+
+ private async lines(file: string): Promise<Recorded[]> {
+ const txt = await (await fetch(this.base + file)).text();
+ return txt
+ .split(/\r?\n/)
+ .filter((l) => l.trim())
+ .map((l) => JSON.parse(l));
+ }
+
+ /** Play recorded events on the virtual clock, starting the first one at ~0.6 s. */
+ private async play(events: Recorded[], sink: Sink, remap: (ev: Recorded) => Recorded) {
+ const t0 = (events[0]?.t ?? 0) - 0.6;
+ this.reset();
+ for (const ev of events) {
+ const at = ev.t - t0;
+ while (this.clock() < at) await sleep(Math.min(100, Math.max(16, ((at - this.vt) * 1000) / this.speed)));
+ const { t: _t, ...rest } = remap(ev);
+ sink.onEvent(rest as StageEvent, at);
+ }
+ }
+
+ async uploadReference(file: File) {
+ return URL.createObjectURL(file);
+ }
+
+ /** Builder replay: events.jsonl on its own server clock (t), build.json as the response. Recorded still URLs are
+ * swapped for local still_*.png copies when the fixture has them. */
+ async builder(_req: BuilderRequest, sink: BuilderSink): Promise<BuilderResponse> {
+ const events = (await this.lines("events.jsonl")) as unknown as BuilderEvent[];
+ const res: BuilderResponse = this.manifest.build
+ ? await (await fetch(this.base + "build.json")).json()
+ : { build_id: "", stills: [], scene_blend_url: null, scene_glb_url: null, panorama_urls: [], package_url: null, critiques: [], missing: [], agent_cost_usd: null, minutes: 0 };
+ const local = new Map<string, string>();
+ (res.stills ?? []).forEach((u, i) => this.manifest.stills[i] && local.set(u, this.url(this.manifest.stills[i])));
+ const fix = (u?: string | null) => (u ? (local.get(u) ?? this.url(u)) : (u ?? undefined));
+ this.reset();
+ const t0 = (events[0]?.t ?? 0) - 0.6;
+ for (const ev of events) {
+ const at = ev.t - t0;
+ while (this.clock() < at) await sleep(Math.min(100, Math.max(16, ((at - this.vt) * 1000) / this.speed)));
+ sink.onEvent({ ...ev, preview_url: fix(ev.preview_url) ?? undefined, package_url: fix(ev.package_url) ?? undefined });
+ }
+ if (!this.manifest.build) return { ...res, _partial: true } as BuilderResponse;
+ return {
+ ...res,
+ stills: (res.stills ?? []).map((u) => fix(u)!),
+ panorama_urls: (res.panorama_urls ?? []).map((u) => fix(u)!),
+ scene_glb_url: fix(res.scene_glb_url) ?? null,
+ scene_blend_url: fix(res.scene_blend_url) ?? null,
+ package_url: fix(res.package_url) ?? null,
+ };
+ }
+
+ async loadPlan(): Promise<Plan> {
+ if (!this.planCache) this.planCache = await (await fetch(this.base + "plan.json")).json();
+ return this.planCache!;
+ }
+
+ async plan(req: PlanRequest, sink: Sink): Promise<PlanResponse> {
+ const plan = await this.loadPlan();
+ const m = this.manifest;
+ let recordedId: string | undefined;
+ if (req.plan_id && req.edit) {
+ // A recorded edit isn't available: play a short revision and return the same plan.
+ const n = plan.objects.length;
+ const inv = plan.objects.filter((o) => o.source === "invented").length;
+ const fake: Recorded[] = [
+ { t: 0, stage: "received", status: "running", message: "plan request", elapsed_s: 0 },
+ { t: 0.2, stage: "planning", status: "running", message: "revising the plan", elapsed_s: 0.2 },
+ { t: 24, stage: "planning", status: "done", message: `${n} objects (${inv} invented), ${plan.lights.length} lights, ${plan.room.width} x ${plan.room.depth} m ${plan.setting}`, elapsed_s: 24 },
+ { t: 24.3, stage: "drawing_floor_plan", status: "running", message: "", elapsed_s: 24.3 },
+ { t: 25, stage: "drawing_floor_plan", status: "done", message: "", elapsed_s: 25, preview_url: m.floor_plan ?? undefined },
+ { t: 25, stage: "blockout", status: "running", message: "grey-box renders from the reference camera and an overview", elapsed_s: 25 },
+ { t: 58, stage: "blockout", status: "done", message: "", elapsed_s: 58, preview_url: m.comparison ?? undefined },
+ { t: 58, stage: "done", status: "done", message: `plan ${req.plan_id}`, elapsed_s: 58 },
+ ];
+ await this.play(fake, sink, (ev) => ({ ...ev, preview_url: ev.preview_url ? this.url(ev.preview_url) : undefined }));
+ } else {
+ const events = m.plan_events ? await this.lines("plan_events.jsonl") : [];
+ recordedId = events.map((e) => /plan (p_\w+)/.exec(e.message || "")?.[1]).find(Boolean);
+ await this.play(events, sink, (ev) => {
+ let p = ev.preview_url;
+ if (ev.stage === "drawing_floor_plan" && p && m.floor_plan) p = m.floor_plan;
+ return { ...ev, preview_url: p ? this.url(p) : undefined };
+ });
+ }
+ const done = /plan (p_\w+)/.exec(JSON.stringify(m)) ?? null;
+ return {
+ plan_id: req.plan_id || (done ? done[1] : "p_4f46c795ea"),
+ plan,
+ floor_plan_url: this.url(m.floor_plan),
+ blockout_reference_url: this.url(m.blockout_reference),
+ blockout_overview_url: this.url(m.blockout_overview),
+ comparison_url: this.url(m.comparison),
+ timings: {},
+ };
+ }
+
+ async build(req: BuildRequest, sink: Sink): Promise<BuildResponse> {
+ const m = this.manifest;
+ const plan = await this.loadPlan();
+ const recorded = m.build_events ? await this.lines("build_events.jsonl") : synthesizeBuild(plan, req.plan_id);
+ const result: Partial<BuildResponse> = m.build ? await (await fetch(this.base + "build.json")).json() : {};
+ // Stills recorded with the run are served locally; map the remote still URLs onto them in order.
+ const remoteStills = result.stills ?? [];
+ const localStills = m.stills.map((s) => this.url(s));
+ const stillMap = new Map(remoteStills.map((u, i) => [u, localStills[i] ?? u]));
+ const local = (u?: string) => (u ? (stillMap.get(u) ?? this.url(u)) : undefined);
+ await this.play(withPlaceholder360(recorded, m.panoramas ?? [], m.scene_glb ?? null), sink, (ev) => ({
+ ...ev,
+ preview_url: local(ev.preview_url),
+ panorama_url: ev.panorama_url ? this.url(ev.panorama_url) : undefined,
+ scene_glb_url: ev.scene_glb_url ? this.url(ev.scene_glb_url) : undefined,
+ }));
+ const last = recorded.findLast?.((e) => e.package_url) ?? [...recorded].reverse().find((e) => e.package_url);
+ return {
+ scene_id: result.scene_id ?? "s_replay",
+ package_url: result.package_url ?? last?.package_url ?? "",
+ scene_blend_url: result.scene_blend_url ?? "",
+ stills: remoteStills.length ? remoteStills.map((u) => local(u)!) : localStills,
+ props: result.props ?? [],
+ standins_left: result.standins_left ?? [],
+ timings: result.timings ?? {},
+ };
+ }
+}
+
+// ---------------------------------------------------------------- placeholder 360
+
+/** The endpoint doesn't emit panoramas or a scene glTF yet: when a recording has none but fixtures/ has the
+ * placeholders, add them where the endpoint will (rendering: one panorama per viewpoint; packaging: the scene). */
+function withPlaceholder360(events: Recorded[], panoramas: string[], sceneGlb: string | null): Recorded[] {
+ const out = [...events];
+ const hasPano = events.some((e) => e.panorama_url);
+ const hasGlb = events.some((e) => e.scene_glb_url);
+ const lastRender = [...events].reverse().find((e) => e.stage === "rendering" && e.status === "running");
+ if (!hasPano && panoramas.length && lastRender) {
+ panoramas.forEach((p, i) => {
+ const vp = p.replace(/^panorama_|\.\w+$/g, "");
+ const label = vp === "ref" ? "reference camera" : vp === "mid" ? "room centre" : vp;
+ out.push({ t: lastRender.t + 0.2 + i * 0.2, stage: "rendering", status: "running", message: `360 plate: ${label} (placeholder)`, elapsed_s: lastRender.elapsed_s, panorama_url: p, viewpoint: `${label} (placeholder)` });
+ });
+ }
+ const pack = events.find((e) => e.stage === "packaging");
+ if (!hasGlb && sceneGlb && pack) {
+ out.push({ t: pack.t + 0.5, stage: "packaging", status: "running", message: "scene glTF exported (placeholder)", elapsed_s: pack.elapsed_s, scene_glb_url: sceneGlb });
+ }
+ return out.sort((a, b) => a.t - b.t);
+}
+
+// ---------------------------------------------------------------- synthesized build
+
+// Used only when no recorded /build run is in fixtures/: one tile per unique generated asset (as props.py groups
+// them), references at 30-60 s, meshes at 3-9 min, a failure and two stand-ins, like a real draft build.
+export const SAMPLE_GLB = "https://threejs.org/examples/models/gltf/DamagedHelmet/glTF-Binary/DamagedHelmet.glb";
+
+function synthesizeBuild(plan: Plan, planId: string): Recorded[] {
+ let seed = 7;
+ const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
+ const assets = new Map<string, { id: string; label: string; n: number; small: boolean }>();
+ for (const o of plan.objects) {
+ if (!o.generate) continue;
+ const k = assetKey(o);
+ const a = assets.get(k) ?? { id: k, label: o.label, n: 0, small: (o.category === "prop" || o.category === "clutter") && Math.max(o.w, o.d, o.h) < 0.3 };
+ a.n++;
+ assets.set(k, a);
+ }
+ const list = [...assets.values()];
+ const N = list.length;
+ const ev: Recorded[] = [
+ { t: 0, stage: "received", status: "running", message: `build ${planId} (draft)`, elapsed_s: 0 },
+ { t: 1.2, stage: "prop_references", status: "running", message: `${N} unique props (${list.reduce((s, a) => s + a.n, 0)} placements)`, elapsed_s: 1.2, progress: 0 },
+ ];
+ const meshes: { t: number; a: (typeof list)[0]; fail: boolean; model: string }[] = [];
+ list.forEach((a, i) => {
+ const tr = 30 + rnd() * 30;
+ ev.push({ t: tr, stage: "prop_references", status: "running", message: `${a.id} reference ready`, elapsed_s: tr, prop: { id: a.id, label: a.label, ref_url: null, status: "meshing" } });
+ const model = a.small ? "meshy" : "tripo-h31";
+ const tm = i === 3 || i === 9 ? 1e9 : tr + (a.small ? 300 + rnd() * 240 : 150 + rnd() * 240);
+ meshes.push({ t: tm, a, fail: i === 6, model });
+ });
+ meshes.sort((x, y) => x.t - y.t);
+ let done = 0;
+ for (const mm of meshes) {
+ if (mm.t > 480) break;
+ done++;
+ ev.push({
+ t: mm.t, stage: "generating_meshes", status: "running", message: `${done} of ${N} props have meshes`, elapsed_s: mm.t, progress: done / N,
+ prop: { id: mm.a.id, label: mm.a.label, ref_url: null, model: mm.fail ? null : mm.model, mesh_url: mm.fail ? null : SAMPLE_GLB, status: mm.fail ? "failed" : "done" },
+ });
+ }
+ const left = N - done;
+ ev.push({ t: 481, stage: "generating_meshes", status: "done", message: `${done} of ${N} props ready, ${left} still running`, elapsed_s: 481 });
+ ev.push({ t: 481, stage: "layout", status: "running", message: "building the scene from the plan", elapsed_s: 481 });
+ ev.push({ t: 540, stage: "layout", status: "done", message: `${plan.objects.length} objects placed, ${left} stand-ins`, elapsed_s: 540 });
+ ev.push({ t: 540, stage: "dressing", status: "running", message: `waiting up to 240 s for ${left} late meshes`, elapsed_s: 540 });
+ ev.push({ t: 780, stage: "dressing", status: "done", message: `swapped ${done} props, ${left} stand-ins kept`, elapsed_s: 780 });
+ ev.push({ t: 781, stage: "rendering", status: "running", message: "stills from the reference camera and two open views", elapsed_s: 781 });
+ ev.push({ t: 900, stage: "rendering", status: "done", message: "3 stills", elapsed_s: 900 });
+ ev.push({ t: 901, stage: "packaging", status: "running", message: "", elapsed_s: 901 });
+ ev.push({ t: 930, stage: "done", status: "done", message: "scene s_synthetic in 930 s", elapsed_s: 930 });
+ return ev.sort((a, b) => a.t - b.t);
+}
diff --git a/web/lib/three-util.ts b/web/lib/three-util.ts
new file mode 100644
index 0000000..36741e8
--- /dev/null
+++ b/web/lib/three-util.ts
@@ -0,0 +1,163 @@
+// three.js helpers: a shared GLB cache, the 3D-tab viewer setup, and the prop shelf's turntable sprites.
+//
+// Prop GLBs from Tripo/Meshy are 10-60 MB each with 4K PBR textures, so the shelf can't keep 20 live WebGL scenes.
+// Each prop is loaded once, rendered into a 48-frame turntable strip on one shared offscreen renderer, then freed;
+// tiles animate the strip with CSS. Only the 3D tab keeps a live model.
+import * as THREE from "three";
+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
+
+export const SPRITE_FRAMES = 48;
+export const SPRITE_SIZE = 176;
+
+const loader = new GLTFLoader();
+
+export function loadGlb(url: string, onProgress?: (f: number) => void): Promise<THREE.Group> {
+ return new Promise((resolve, reject) => {
+ loader.load(
+ url,
+ (g) => resolve(g.scene),
+ (e) => onProgress && e.total && onProgress(e.loaded / e.total),
+ (err) => reject(err),
+ );
+ });
+}
+
+/** Centre on the ground and scale so the largest side is 1 unit; returns the bounding size. */
+export function normalize(obj: THREE.Object3D) {
+ const box = new THREE.Box3().setFromObject(obj);
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ const s = 1 / Math.max(size.x, size.y, size.z, 1e-6);
+ obj.position.set(-center.x * s, -box.min.y * s, -center.z * s);
+ obj.scale.setScalar(s);
+ const pivot = new THREE.Group();
+ pivot.add(obj);
+ return { pivot, size: size.multiplyScalar(s) };
+}
+
+export function disposeObject(obj: THREE.Object3D) {
+ obj.traverse((o) => {
+ const m = o as THREE.Mesh;
+ if (m.geometry) m.geometry.dispose();
+ const mats = Array.isArray(m.material) ? m.material : m.material ? [m.material] : [];
+ for (const mat of mats) {
+ for (const v of Object.values(mat)) if (v instanceof THREE.Texture) v.dispose();
+ mat.dispose();
+ }
+ });
+}
+
+export function envFor(renderer: THREE.WebGLRenderer) {
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ pmrem.dispose();
+ return env;
+}
+
+// ---------------------------------------------------------------- turntable sprites
+
+let shared: { renderer: THREE.WebGLRenderer; env: THREE.Texture } | null = null;
+function sharedRenderer() {
+ if (!shared) {
+ const canvas = document.createElement("canvas");
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });
+ renderer.setPixelRatio(1);
+ renderer.setSize(SPRITE_SIZE, SPRITE_SIZE, false);
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.05;
+ shared = { renderer, env: envFor(renderer) };
+ }
+ return shared;
+}
+
+const spriteCache = new Map<string, Promise<string>>();
+const queue: (() => Promise<void>)[] = [];
+let active = 0;
+const MAX_CONCURRENT = 2;
+
+function pump() {
+ while (active < MAX_CONCURRENT && queue.length) {
+ const job = queue.shift()!;
+ active++;
+ job().finally(() => {
+ active--;
+ pump();
+ });
+ }
+}
+
+/** A blob URL of a horizontal strip of SPRITE_FRAMES turntable frames for this GLB (queued, cached). */
+export function turntableSprite(url: string): Promise<string> {
+ let p = spriteCache.get(url);
+ if (!p) {
+ p = new Promise<string>((resolve, reject) => {
+ queue.push(async () => {
+ try {
+ resolve(await renderSprite(url));
+ } catch (e) {
+ reject(e);
+ }
+ });
+ pump();
+ });
+ spriteCache.set(url, p);
+ }
+ return p;
+}
+
+async function renderSprite(url: string): Promise<string> {
+ const model = await loadGlb(url);
+ const { renderer, env } = sharedRenderer();
+ const scene = new THREE.Scene();
+ scene.environment = env;
+ const { pivot, size } = normalize(model);
+ scene.add(pivot);
+ const key = new THREE.DirectionalLight(0xfff1e0, 1.6);
+ key.position.set(2, 3, 2);
+ scene.add(key, new THREE.HemisphereLight(0xdfe6ff, 0x1a1712, 0.5));
+ const cam = new THREE.PerspectiveCamera(30, 1, 0.01, 50);
+ const h = size.y;
+ const dist = 2.35;
+ const strip = document.createElement("canvas");
+ strip.width = SPRITE_SIZE * SPRITE_FRAMES;
+ strip.height = SPRITE_SIZE;
+ const ctx = strip.getContext("2d")!;
+ for (let i = 0; i < SPRITE_FRAMES; i++) {
+ const a = (i / SPRITE_FRAMES) * Math.PI * 2 + Math.PI * 0.25;
+ cam.position.set(Math.sin(a) * dist, h * 0.5 + 0.55, Math.cos(a) * dist);
+ cam.lookAt(0, h * 0.45, 0);
+ renderer.render(scene, cam);
+ ctx.drawImage(renderer.domElement, i * SPRITE_SIZE, 0);
+ if (i % 12 === 11) await new Promise((r) => requestAnimationFrame(r));
+ }
+ disposeObject(model);
+ renderer.renderLists.dispose();
+ const blob: Blob = await new Promise((r) => strip.toBlob((b) => r(b!), "image/webp", 0.9));
+ return URL.createObjectURL(blob);
+}
+
+// ---------------------------------------------------------------- equirectangular environments
+
+/** Load an equirectangular image (.hdr, or PNG/JPG) as a texture three can use as background or environment. */
+export async function loadEquirect(url: string): Promise<THREE.Texture> {
+ let tex: THREE.Texture;
+ if (/\.hdr(\?|$)/i.test(url)) {
+ const { HDRLoader } = await import("three/examples/jsm/loaders/HDRLoader.js");
+ tex = await new HDRLoader().loadAsync(url);
+ } else {
+ tex = await new THREE.TextureLoader().loadAsync(url);
+ tex.colorSpace = THREE.SRGBColorSpace;
+ }
+ tex.mapping = THREE.EquirectangularReflectionMapping;
+ return tex;
+}
+
+/** Prefiltered environment for PBR lighting from an equirect texture. */
+export function pmremFrom(renderer: THREE.WebGLRenderer, tex: THREE.Texture) {
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const env = pmrem.fromEquirectangular(tex).texture;
+ pmrem.dispose();
+ return env;
+}
diff --git a/web/lib/types.ts b/web/lib/types.ts
new file mode 100644
index 0000000..75052e3
--- /dev/null
+++ b/web/lib/types.ts
@@ -0,0 +1,169 @@
+// Data contract with the AnyScene pipeline fal app, NEXT_PUBLIC_ANYSCENE_PIPELINE_APP (endpoint/app.py, endpoint/stages.py, docs/ENDPOINT.md).
+
+export const STAGE_PREFIX = "ANYSCENE_STAGE ";
+
+export type StageStatus = "running" | "done" | "failed";
+
+export interface PropEvent {
+ id: string;
+ label: string;
+ ref_url?: string | null;
+ model?: string | null;
+ mesh_url?: string | null;
+ status: "meshing" | "done" | "failed";
+}
+
+export interface StageEvent {
+ stage: string;
+ status: StageStatus;
+ message: string;
+ elapsed_s: number;
+ progress?: number;
+ preview_url?: string;
+ prop?: PropEvent;
+ package_url?: string;
+ // 360 (expected from the endpoint soon; all optional)
+ panorama_url?: string; // rendering: one equirectangular Cycles render per viewpoint
+ viewpoint?: string; // rendering: which viewpoint the panorama is from
+ scene_glb_url?: string; // packaging: decimated scene glTF with KHR_lights_punctual
+ environment_url?: string; // any stage: equirect HDR/PNG of the scene's lighting for the prop viewer
+}
+
+export type RunKind = "plan" | "build";
+
+export const PLAN_STAGES = ["received", "reading_reference", "planning", "drawing_floor_plan", "blockout", "done"] as const;
+export const BUILD_STAGES = [
+ "received",
+ "prop_references",
+ "generating_meshes",
+ "layout",
+ "dressing",
+ "rendering",
+ "packaging",
+ "done",
+] as const;
+
+export const STAGE_LABELS: Record<string, string> = {
+ received: "Call received",
+ reading_reference: "Reading the plate",
+ planning: "Layout plan",
+ drawing_floor_plan: "Floor plan",
+ blockout: "Grey-box",
+ prop_references: "Prop refs",
+ generating_meshes: "Prop build",
+ layout: "Layout + stand-ins",
+ dressing: "Set dressing",
+ rendering: "Camera: stills",
+ packaging: "Package",
+ done: "Wrap",
+};
+
+// ---- Plan (schema.py) ----
+export interface PlanObject {
+ id: string;
+ label: string;
+ asset?: string;
+ category: string;
+ x: number;
+ y: number;
+ z: number;
+ w: number;
+ d: number;
+ h: number;
+ rot: number;
+ source: "reference" | "invented";
+ generate: boolean;
+ prompt?: string;
+ crop?: number[] | null;
+}
+export interface PlanLight {
+ id: string;
+ kind: string;
+ x: number;
+ y: number;
+ z: number;
+ color: string;
+ power: string;
+ source?: string;
+}
+export interface PlanOpening {
+ wall: "front" | "back" | "left" | "right";
+ kind: string;
+ center: number;
+ width: number;
+ height: number;
+ sill: number;
+}
+export interface Plan {
+ name: string;
+ summary: string;
+ setting: string;
+ time_of_day?: string;
+ mood?: string[];
+ palette?: string[];
+ room: { width: number; depth: number; height: number };
+ openings: PlanOpening[];
+ objects: PlanObject[];
+ lights: PlanLight[];
+ reference_camera?: { position: number[]; look_at: number[]; lens_mm: number };
+ notes?: string[];
+ dials?: Record<string, { value: number | string; means: string }>;
+}
+
+// ---- Requests / responses (app.py) ----
+export interface PlanRequest {
+ reference_image_urls?: string[];
+ floor_plan_url?: string | null;
+ prompt?: string;
+ plan_id?: string;
+ edit?: string;
+ effort?: string;
+ dials?: Record<string, number | string>;
+}
+export interface PlanResponse {
+ plan_id: string;
+ plan: Plan;
+ floor_plan_url: string;
+ blockout_reference_url: string;
+ blockout_overview_url: string;
+ comparison_url: string;
+ timings: Record<string, number>;
+}
+export interface BuildRequest {
+ plan_id: string;
+ tier: "draft" | "full";
+ mesh_deadline_s?: number;
+ late_mesh_wait_s?: number;
+ still_samples?: number;
+ include_glbs?: boolean;
+}
+export interface BuildResponse {
+ scene_id: string;
+ package_url: string;
+ scene_blend_url: string;
+ stills: string[];
+ props: { id: string; label: string; ref_url?: string; mesh_urls?: Record<string, string>; placements?: string[] }[];
+ standins_left: string[];
+ timings: Record<string, number>;
+ panorama_urls?: string[];
+ scene_glb_url?: string;
+ environment_url?: string;
+}
+
+// ---- Dials (docs/ENDPOINT.md) ----
+export type DialSpec =
+ | { key: string; label: string; kind: "range"; min: number; max: number; lo: string; hi: string; group: string }
+ | { key: string; label: string; kind: "select"; options: string[]; group: string };
+
+export const DIALS: DialSpec[] = [
+ { key: "density", label: "Density", kind: "range", min: 0, max: 1, lo: "sparse", hi: "packed", group: "Stuff" },
+ { key: "tidiness", label: "Tidiness", kind: "range", min: 0, max: 1, lo: "messy", hi: "tidy", group: "Stuff" },
+ { key: "wear", label: "Wear", kind: "range", min: 0, max: 1, lo: "pristine", hi: "decayed", group: "Surfaces" },
+ { key: "wetness", label: "Wetness", kind: "range", min: 0, max: 1, lo: "dry", hi: "soaked", group: "Surfaces" },
+ { key: "atmosphere", label: "Atmosphere", kind: "range", min: 0, max: 1, lo: "clear", hi: "thick", group: "Environment" },
+ { key: "power", label: "Power", kind: "range", min: 0, max: 1, lo: "dormant", hi: "live", group: "Energy" },
+ { key: "warmth", label: "Warmth", kind: "range", min: -1, max: 1, lo: "cold", hi: "warm", group: "Look" },
+ { key: "time_of_day", label: "Time of day", kind: "select", options: ["dawn", "day", "dusk", "night"], group: "Environment" },
+ { key: "weather", label: "Weather", kind: "select", options: ["clear", "overcast", "rain", "fog", "snow"], group: "Environment" },
+ { key: "look", label: "Look", kind: "select", options: ["clean", "cinematic", "gritty", "vintage"], group: "Look" },
+];
diff --git a/web/next.config.ts b/web/next.config.ts
new file mode 100644
index 0000000..5b316aa
--- /dev/null
+++ b/web/next.config.ts
@@ -0,0 +1,13 @@
+import type { NextConfig } from "next";
+
+// Dev server opened from other devices on the LAN (Next blocks dev assets from non-localhost origins otherwise):
+// DEV_ORIGINS=192.168.1.20,other-host in web/.env.local, comma-separated.
+const devOrigins = (process.env.DEV_ORIGINS || "").split(",").map((s) => s.trim()).filter(Boolean);
+
+const nextConfig: NextConfig = {
+ reactStrictMode: true,
+ images: { unoptimized: true },
+ allowedDevOrigins: [...devOrigins, "*.local"],
+};
+
+export default nextConfig;
diff --git a/web/package-lock.json b/web/package-lock.json
new file mode 100644
index 0000000..cedd3bd
--- /dev/null
+++ b/web/package-lock.json
@@ -0,0 +1,1188 @@
+{
+ "name": "anyscene-web",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "anyscene-web",
+ "version": "0.1.0",
+ "dependencies": {
+ "@fal-ai/client": "^1.10.1",
+ "@fal-ai/server-proxy": "^1.2.1",
+ "next": "^16.4.3",
+ "react": "^19.3.1",
+ "react-dom": "^19.3.1",
+ "three": "^0.187.0"
+ },
+ "devDependencies": {
+ "@types/node": "^26.6.6",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "@types/three": "^0.187.0",
+ "playwright-core": "^1.64.1",
+ "typescript": "^5.9.3"
+ }
+ },
+ "node_modules/@dimforge/rapier3d-compat": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@fal-ai/client": {
+ "version": "1.10.1",
+ "resolved": "https://registry.npmjs.org/@fal-ai/client/-/client-1.10.1.tgz",
+ "integrity": "sha512-c3AVeH31OioiI2J1BfW8Cryi1DhUYldnY3X35nv6xLMq3fU2NQOo+eYaR5mL2O8MoHHh+HzXdQuIyanIyeq+ug==",
+ "license": "MIT",
+ "dependencies": {
+ "@msgpack/msgpack": "^3.0.0-beta2",
+ "eventsource-parser": "^1.1.2",
+ "robot3": "^0.4.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@fal-ai/server-proxy": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@fal-ai/server-proxy/-/server-proxy-1.2.1.tgz",
+ "integrity": "sha512-A2HT3ppvdK0rmULPWQ4ipEDb5LkUtcn8q72N6jwlhpSNIn50/2d68kaNxDqpE/re7ExyzS7SM3z0D1+Uo7H3bA==",
+ "license": "MIT",
+ "dependencies": {
+ "picomatch": "^4.0.0"
+ },
+ "peerDependencies": {
+ "@remix-run/dev": "^2.0.0",
+ "@sveltejs/kit": "^2.0.0",
+ "express": "^4.0.0",
+ "hono": "^4.0.0",
+ "next": "13.4 - 14 || >=15.0.0-0",
+ "react": "^18.0.0 || >=19.0.0-0",
+ "react-dom": "^18.0.0 || >=19.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "@remix-run/dev": {
+ "optional": true
+ },
+ "@sveltejs/kit": {
+ "optional": true
+ },
+ "express": {
+ "optional": true
+ },
+ "hono": {
+ "optional": true
+ },
+ "next": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@img/colour": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
+ "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
+ "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-freebsd-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
+ "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
+ "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
+ "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
+ "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
+ "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-riscv64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
+ "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
+ "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
+ "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
+ "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
+ "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
+ "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
+ "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
+ "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
+ "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-riscv64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
+ "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
+ "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
+ "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
+ "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.11.3"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-webcontainers-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
+ "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
+ "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
+ "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
+ "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@msgpack/msgpack": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz",
+ "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/@next/env": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.3.tgz",
+ "integrity": "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==",
+ "license": "MIT"
+ },
+ "node_modules/@next/swc-darwin-arm64": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.3.tgz",
+ "integrity": "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-darwin-x64": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.3.tgz",
+ "integrity": "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-gnu": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.3.tgz",
+ "integrity": "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-musl": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.3.tgz",
+ "integrity": "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-gnu": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.3.tgz",
+ "integrity": "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-musl": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.3.tgz",
+ "integrity": "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-arm64-msvc": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.3.tgz",
+ "integrity": "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-x64-msvc": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.3.tgz",
+ "integrity": "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@swc/helpers": {
+ "version": "0.5.23",
+ "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
+ "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "tslib": "^2.8.0"
+ }
+ },
+ "node_modules/@tweenjs/tween.js": {
+ "version": "23.1.3",
+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@types/react": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "csstype": "^3.2.2"
+ }
+ },
+ "node_modules/@types/react-dom": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
+ "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "^19.3.0"
+ }
+ },
+ "node_modules/@types/stats.js": {
+ "version": "0.17.4",
+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/three": {
+ "version": "0.187.0",
+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.187.0.tgz",
+ "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "~0.12.0",
+ "@tweenjs/tween.js": "~23.1.3",
+ "@types/stats.js": "*",
+ "@types/webxr": ">=0.5.17",
+ "fflate": "~0.8.3",
+ "meshoptimizer": "~1.1.1"
+ }
+ },
+ "node_modules/@types/webxr": {
+ "version": "0.5.24",
+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/baseline-browser-mapping": {
+ "version": "2.11.34",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz",
+ "integrity": "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA==",
+ "license": "Apache-2.0",
+ "bin": {
+ "baseline-browser-mapping": "dist/cli.cjs"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001820",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001820.tgz",
+ "integrity": "sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "CC-BY-4.0"
+ },
+ "node_modules/client-only": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
+ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
+ "license": "MIT"
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-1.1.2.tgz",
+ "integrity": "sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.18"
+ }
+ },
+ "node_modules/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/meshoptimizer": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.20",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/next": {
+ "version": "16.4.3",
+ "resolved": "https://registry.npmjs.org/next/-/next-16.4.3.tgz",
+ "integrity": "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==",
+ "license": "MIT",
+ "dependencies": {
+ "@next/env": "16.4.3",
+ "@swc/helpers": "0.5.23",
+ "baseline-browser-mapping": "^2.9.19",
+ "caniuse-lite": "^1.0.30001579",
+ "postcss": "8.5.23",
+ "styled-jsx": "5.1.6"
+ },
+ "bin": {
+ "next": "dist/bin/next"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "optionalDependencies": {
+ "@next/swc-darwin-arm64": "16.4.3",
+ "@next/swc-darwin-x64": "16.4.3",
+ "@next/swc-linux-arm64-gnu": "16.4.3",
+ "@next/swc-linux-arm64-musl": "16.4.3",
+ "@next/swc-linux-x64-gnu": "16.4.3",
+ "@next/swc-linux-x64-musl": "16.4.3",
+ "@next/swc-win32-arm64-msvc": "16.4.3",
+ "@next/swc-win32-x64-msvc": "16.4.3",
+ "sharp": "^0.35.5"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.1.0",
+ "@playwright/test": "^1.51.1",
+ "babel-plugin-react-compiler": "*",
+ "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",
+ "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",
+ "sass": "^1.3.0"
+ },
+ "peerDependenciesMeta": {
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@playwright/test": {
+ "optional": true
+ },
+ "babel-plugin-react-compiler": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.64.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
+ "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.23",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz",
+ "integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.16",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/react": {
+ "version": "19.3.1",
+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz",
+ "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "19.3.1",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz",
+ "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.28.0"
+ },
+ "peerDependencies": {
+ "react": "^19.3.1"
+ }
+ },
+ "node_modules/robot3": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/robot3/-/robot3-0.4.1.tgz",
+ "integrity": "sha512-hzjy826lrxzx8eRgv80idkf8ua1JAepRc9Efdtj03N3KNJuznQCPlyCJ7gnUmDFwZCLQjxy567mQVKmdv2BsXQ==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/scheduler": {
+ "version": "0.28.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
+ "license": "MIT"
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "license": "ISC",
+ "optional": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
+ "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/colour": "^1.1.0",
+ "detect-libc": "^2.1.2",
+ "semver": "^7.8.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.35.5",
+ "@img/sharp-darwin-x64": "0.35.5",
+ "@img/sharp-freebsd-wasm32": "0.35.5",
+ "@img/sharp-libvips-darwin-arm64": "1.3.4",
+ "@img/sharp-libvips-darwin-x64": "1.3.4",
+ "@img/sharp-libvips-linux-arm": "1.3.4",
+ "@img/sharp-libvips-linux-arm64": "1.3.4",
+ "@img/sharp-libvips-linux-ppc64": "1.3.4",
+ "@img/sharp-libvips-linux-riscv64": "1.3.4",
+ "@img/sharp-libvips-linux-s390x": "1.3.4",
+ "@img/sharp-libvips-linux-x64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4",
+ "@img/sharp-linux-arm": "0.35.5",
+ "@img/sharp-linux-arm64": "0.35.5",
+ "@img/sharp-linux-ppc64": "0.35.5",
+ "@img/sharp-linux-riscv64": "0.35.5",
+ "@img/sharp-linux-s390x": "0.35.5",
+ "@img/sharp-linux-x64": "0.35.5",
+ "@img/sharp-linuxmusl-arm64": "0.35.5",
+ "@img/sharp-linuxmusl-x64": "0.35.5",
+ "@img/sharp-webcontainers-wasm32": "0.35.5",
+ "@img/sharp-win32-arm64": "0.35.5",
+ "@img/sharp-win32-ia32": "0.35.5",
+ "@img/sharp-win32-x64": "0.35.5"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/styled-jsx": {
+ "version": "5.1.6",
+ "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz",
+ "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==",
+ "license": "MIT",
+ "dependencies": {
+ "client-only": "0.0.1"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "peerDependencies": {
+ "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "@babel/core": {
+ "optional": true
+ },
+ "babel-plugin-macros": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/three": {
+ "version": "0.187.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz",
+ "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==",
+ "license": "MIT"
+ },
+ "node_modules/tslib": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
+ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
+ "license": "0BSD"
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/web/package.json b/web/package.json
new file mode 100644
index 0000000..5a7e906
--- /dev/null
+++ b/web/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "anyscene-web",
+ "private": true,
+ "version": "0.1.0",
+ "scripts": {
+ "fixtures": "node scripts/sync-fixtures.mjs",
+ "predev": "node scripts/sync-fixtures.mjs",
+ "dev": "next dev -p 3210",
+ "prebuild": "node scripts/sync-fixtures.mjs",
+ "build": "next build",
+ "start": "next start -p 3210",
+ "env:local": "node scripts/write-env-local.mjs",
+ "screenshots": "node scripts/screenshots.mjs",
+ "screenshots:builder": "node scripts/screenshots-builder.mjs",
+ "fixture:builder": "node scripts/make-builder-fixture.mjs",
+ "import:builder": "node scripts/import-builder-run.mjs"
+ },
+ "dependencies": {
+ "@fal-ai/client": "^1.10.1",
+ "@fal-ai/server-proxy": "^1.2.1",
+ "next": "^16.4.3",
+ "react": "^19.3.1",
+ "react-dom": "^19.3.1",
+ "three": "^0.187.0"
+ },
+ "devDependencies": {
+ "@types/node": "^26.6.6",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "@types/three": "^0.187.0",
+ "playwright-core": "^1.64.1",
+ "typescript": "^5.9.3"
+ }
+}
diff --git a/web/screenshots/01-idle.png b/web/screenshots/01-idle.png
new file mode 100644
index 0000000..23c8243
Binary files /dev/null and b/web/screenshots/01-idle.png differ
diff --git a/web/screenshots/02-planning.png b/web/screenshots/02-planning.png
new file mode 100644
index 0000000..8d85699
Binary files /dev/null and b/web/screenshots/02-planning.png differ
diff --git a/web/screenshots/03-plan-ready-greybox.png b/web/screenshots/03-plan-ready-greybox.png
new file mode 100644
index 0000000..9565703
Binary files /dev/null and b/web/screenshots/03-plan-ready-greybox.png differ
diff --git a/web/screenshots/04-floor-plan.png b/web/screenshots/04-floor-plan.png
new file mode 100644
index 0000000..69ad177
Binary files /dev/null and b/web/screenshots/04-floor-plan.png differ
diff --git a/web/screenshots/05-compare-greybox.png b/web/screenshots/05-compare-greybox.png
new file mode 100644
index 0000000..036a2be
Binary files /dev/null and b/web/screenshots/05-compare-greybox.png differ
diff --git a/web/screenshots/06-build-references.png b/web/screenshots/06-build-references.png
new file mode 100644
index 0000000..1d7bf58
Binary files /dev/null and b/web/screenshots/06-build-references.png differ
diff --git a/web/screenshots/07-build-meshes-prop-map.png b/web/screenshots/07-build-meshes-prop-map.png
new file mode 100644
index 0000000..62b5c2d
Binary files /dev/null and b/web/screenshots/07-build-meshes-prop-map.png differ
diff --git a/web/screenshots/08-live-layout.png b/web/screenshots/08-live-layout.png
new file mode 100644
index 0000000..ff5c240
Binary files /dev/null and b/web/screenshots/08-live-layout.png differ
diff --git a/web/screenshots/09-prop-3d.png b/web/screenshots/09-prop-3d.png
new file mode 100644
index 0000000..ee004a7
Binary files /dev/null and b/web/screenshots/09-prop-3d.png differ
diff --git a/web/screenshots/10-wrapped-result.png b/web/screenshots/10-wrapped-result.png
new file mode 100644
index 0000000..6bce4ed
Binary files /dev/null and b/web/screenshots/10-wrapped-result.png differ
diff --git a/web/screenshots/11-compare-final.png b/web/screenshots/11-compare-final.png
new file mode 100644
index 0000000..e3c5562
Binary files /dev/null and b/web/screenshots/11-compare-final.png differ
diff --git a/web/screenshots/12-360-plate.png b/web/screenshots/12-360-plate.png
new file mode 100644
index 0000000..c03de21
Binary files /dev/null and b/web/screenshots/12-360-plate.png differ
diff --git a/web/screenshots/13-360-set-model.png b/web/screenshots/13-360-set-model.png
new file mode 100644
index 0000000..2b401bb
Binary files /dev/null and b/web/screenshots/13-360-set-model.png differ
diff --git a/web/screenshots/14-prop-3d-scene-light.png b/web/screenshots/14-prop-3d-scene-light.png
new file mode 100644
index 0000000..3a6e65f
Binary files /dev/null and b/web/screenshots/14-prop-3d-scene-light.png differ
diff --git a/web/screenshots/15-mobile.png b/web/screenshots/15-mobile.png
new file mode 100644
index 0000000..7b1552c
Binary files /dev/null and b/web/screenshots/15-mobile.png differ
diff --git a/web/screenshots/builder-01-idle.png b/web/screenshots/builder-01-idle.png
new file mode 100644
index 0000000..546249a
Binary files /dev/null and b/web/screenshots/builder-01-idle.png differ
diff --git a/web/screenshots/builder-02-plan-milestone.png b/web/screenshots/builder-02-plan-milestone.png
new file mode 100644
index 0000000..ed820c1
Binary files /dev/null and b/web/screenshots/builder-02-plan-milestone.png differ
diff --git a/web/screenshots/builder-03-props-dressing.png b/web/screenshots/builder-03-props-dressing.png
new file mode 100644
index 0000000..44a261c
Binary files /dev/null and b/web/screenshots/builder-03-props-dressing.png differ
diff --git a/web/screenshots/builder-04-critic-round-1.png b/web/screenshots/builder-04-critic-round-1.png
new file mode 100644
index 0000000..637853d
Binary files /dev/null and b/web/screenshots/builder-04-critic-round-1.png differ
diff --git a/web/screenshots/builder-05-contact-sheet-round-2.png b/web/screenshots/builder-05-contact-sheet-round-2.png
new file mode 100644
index 0000000..fe37353
Binary files /dev/null and b/web/screenshots/builder-05-contact-sheet-round-2.png differ
diff --git a/web/screenshots/builder-06-log-notes-filter.png b/web/screenshots/builder-06-log-notes-filter.png
new file mode 100644
index 0000000..6405d7e
Binary files /dev/null and b/web/screenshots/builder-06-log-notes-filter.png differ
diff --git a/web/screenshots/builder-07-wrapped-stills.png b/web/screenshots/builder-07-wrapped-stills.png
new file mode 100644
index 0000000..24dd4cb
Binary files /dev/null and b/web/screenshots/builder-07-wrapped-stills.png differ
diff --git a/web/screenshots/builder-08-compare.png b/web/screenshots/builder-08-compare.png
new file mode 100644
index 0000000..e9039d7
Binary files /dev/null and b/web/screenshots/builder-08-compare.png differ
diff --git a/web/screenshots/builder-09-360-plate.png b/web/screenshots/builder-09-360-plate.png
new file mode 100644
index 0000000..168c6b6
Binary files /dev/null and b/web/screenshots/builder-09-360-plate.png differ
diff --git a/web/screenshots/builder-10-360-set-model.png b/web/screenshots/builder-10-360-set-model.png
new file mode 100644
index 0000000..5fae401
Binary files /dev/null and b/web/screenshots/builder-10-360-set-model.png differ
diff --git a/web/screenshots/builder-11-mobile.png b/web/screenshots/builder-11-mobile.png
new file mode 100644
index 0000000..28ef693
Binary files /dev/null and b/web/screenshots/builder-11-mobile.png differ
diff --git a/web/screenshots/builder-12-pipeline-toggle.png b/web/screenshots/builder-12-pipeline-toggle.png
new file mode 100644
index 0000000..9f974d5
Binary files /dev/null and b/web/screenshots/builder-12-pipeline-toggle.png differ
diff --git a/web/scripts/import-builder-run.mjs b/web/scripts/import-builder-run.mjs
new file mode 100644
index 0000000..8da09e1
--- /dev/null
+++ b/web/scripts/import-builder-run.mjs
@@ -0,0 +1,23 @@
+// Drop a real builder run (builder/app.py) into the replay fixtures.
+// node scripts/import-builder-run.mjs <run dir> [name=builder] [reference image]
+// <run dir> is what builder/client.py writes: events.jsonl, build.json and still_*.png (e.g. anyscene-runs/fal_mc_1).
+// The result replaces fixtures/<name>/ and is served at ?replay=<name>.
+import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const [run, name = "builder", ref] = process.argv.slice(2);
+if (!run || !existsSync(path.join(run, "events.jsonl"))) {
+ console.error("usage: node scripts/import-builder-run.mjs <run dir with events.jsonl> [name] [reference image]");
+ process.exit(1);
+}
+const out = path.join(root, "fixtures", name);
+rmSync(out, { recursive: true, force: true });
+mkdirSync(out, { recursive: true });
+const files = readdirSync(run).filter((f) => f === "events.jsonl" || f === "build.json" || /^still_\d+\.(png|jpg)$/i.test(f));
+for (const f of files) copyFileSync(path.join(run, f), path.join(out, f));
+const refSrc = ref || [path.join(run, "reference.png"), path.join(root, "fixtures", "reference.png")].find((p) => existsSync(p));
+if (refSrc) copyFileSync(refSrc, path.join(out, "reference.png"));
+if (!files.includes("build.json")) console.warn("no build.json yet: the replay ends after the last event (run still going?)");
+console.log(`fixtures/${name}: ${files.join(", ")}${refSrc ? ", reference.png" : ""}. Run npm run fixtures (or restart dev).`);
diff --git a/web/scripts/make-builder-fixture.mjs b/web/scripts/make-builder-fixture.mjs
new file mode 100644
index 0000000..0a8b364
--- /dev/null
+++ b/web/scripts/make-builder-fixture.mjs
@@ -0,0 +1,168 @@
+// A short synthetic builder recording (fixtures/builder/) that follows the real schema, for building
+// and demoing the UI until a real run is dropped in with scripts/import-builder-run.mjs.
+// Images reuse the pipeline recording in fixtures/ (served at /replay/demo/...), so nothing is copied.
+// node scripts/make-builder-fixture.mjs
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const dir = path.join(root, "fixtures", "builder");
+mkdirSync(dir, { recursive: true });
+
+const D = "/replay/demo/";
+const img = {
+ floor: D + "floor_plan.png",
+ overview: D + "blockout_overview.png",
+ greyRef: D + "blockout_reference.png",
+ layout: "https://v3b.fal.media/files/b/0ab08ded/4D56g-JZtrjm9g2ElyEml_0001.png",
+ dressed: "https://v3b.fal.media/files/b/0ab08df7/jQQ2vHPFNHpNlUC_bgakY_0001.png",
+ prop: "https://v3b.fal.media/files/b/0ab08da2/eIx9Y9z-uor3zqn87R7F9_9aWSSyyo.png",
+ s0: D + "still_0.png",
+ s1: D + "still_1.png",
+ s2: D + "still_2.png",
+};
+
+const ev = [];
+let t = 0;
+const at = (dt) => (t = Math.round((t + dt) * 10) / 10);
+const e = (stage, message, extra = {}) => ev.push({ t, stage, status: "running", message, ...extra });
+const log = (dt, tool, message) => (at(dt), e("log", message, { tool }));
+const say = (dt, message) => (at(dt), e("thinking", message));
+const report = (dt, stage, message, preview_url) => (at(dt), e(stage, message, preview_url ? { preview_url } : {}));
+
+at(0.2); e("received", "build b_synthetic01: 1 reference image(s)");
+at(0.1); e("received", "scene builder starting");
+say(2.8, "I'll start by reading the skill docs and the inputs.");
+log(0.2, "Bash", "ls && cat SKILL.md && ls input && cat input/brief.md");
+log(1.1, "Bash", "cat CRAFT.md; ls docs endpoint camera pipeline generate");
+log(0.1, "Read", "looking at input/reference_1.png");
+say(9, "A 1960s mission control room at night: tiered console rows, a giant orbit-tracking wall display, tall windows on the left onto a floodlit pad. Lots of desk clutter. The screens are the hero; they need to read as green CRT phosphor, not flat emissive cards.");
+log(6, "Bash", "sed -n 80,400p generate/fal.mjs; which blender; blender --version");
+log(4, "Write", "writing scenes/scene/plan.json");
+log(22, "Bash", "python pipeline/floorplan.py scenes/scene/plan.json out/floor_plan.png");
+log(5, "Read", "looking at out/floor_plan.png");
+report(3, "plan", "70 objects (18 invented), 16 lights, 16 x 14 m interior; consoles in three tiers facing the wall display", img.floor);
+log(8, "Write", "writing scenes/scene/scripts/shell.py");
+log(3, "Bash", "blender -b --factory-startup --python scenes/scene/scripts/shell.py -- out/scene.blend");
+log(41, "Bash", "blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --preview");
+log(36, "Read", "looking at out/preview/ref_view.png");
+say(4, "Proportions are right but the camera is a little high; the reference is shot from seated eye level, about 1.25 m.");
+log(3, "Edit", "editing scenes/scene/shots.json");
+log(30, "Bash", "blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --preview");
+log(34, "Read", "looking at out/preview/overview.png");
+report(2, "layout", "shell, tiers and console rows blocked out; reference camera matched at 28 mm", img.overview);
+say(5, "Props next. 19 unique assets cover 45 placements: references cropped from the plate and cleaned, then meshes from Tripo H3.1, Meshy for the small items.");
+log(3, "Bash", "node generate/fal.mjs refs scenes/scene/props.json --out scenes/scene/props");
+log(48, "Read", "looking at scenes/scene/props/console_bank_ref.png");
+log(3, "Read", "looking at scenes/scene/props/teleprinter_ref.png");
+log(2, "Read", "looking at scenes/scene/props/rotary_phone_ref.png");
+report(4, "props", "19 prop references in; meshes generating (15 Tripo H3.1, 4 Meshy)", img.prop);
+log(5, "Bash", "node generate/fal.mjs meshes scenes/scene/props.json --wait");
+say(180, "Meshes are landing. Swapping them in as they arrive and checking scale against the plan.");
+log(3, "Write", "writing scenes/scene/scripts/dress.py");
+log(6, "Bash", "blender -b out/scene.blend --python scenes/scene/scripts/dress.py");
+log(52, "Bash", "python pipeline/collide.py out/scene.blend --drop");
+log(14, "Bash", "blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --preview");
+log(38, "Read", "looking at out/preview/ref_view.png");
+report(2, "dressing", "45 placements dressed; 1 ashtray dropped onto its desk, nothing floating", img.layout);
+say(4, "The consoles' CRTs are blank. Each scope needs its own phosphor content: sine traces, polar plots, telemetry columns.");
+log(3, "Write", "writing scenes/scene/scripts/screens.py");
+log(5, "Bash", "python scenes/scene/scripts/screens.py --make-textures out/screens");
+log(26, "Read", "looking at out/screens/scope_04.png");
+log(4, "Bash", "blender -b out/scene.blend --python scenes/scene/scripts/screens.py -- --apply");
+report(18, "screens", "14 CRT textures and the wall map with ground tracks; no repeated text", img.dressed);
+log(5, "Write", "writing scenes/scene/scripts/materials.py");
+log(8, "Bash", "blender -b out/scene.blend --python scenes/scene/scripts/materials.py");
+log(40, "Read", "looking at out/preview/close_console.png");
+report(3, "materials", "grey-green enamel with edge wear, linoleum floor, acoustic ceiling tiles, smoked glass", img.dressed);
+log(5, "Write", "writing scenes/scene/scripts/lighting.py");
+log(7, "Bash", "blender -b out/scene.blend --python scenes/scene/scripts/lighting.py");
+log(44, "Read", "looking at out/preview/ref_view.png");
+say(3, "Too bright overall; the reference is lit mostly by the screens and the wall display. Dropping the ceiling panels by 60%.");
+log(3, "Edit", "editing scenes/scene/scripts/lighting.py");
+log(41, "Bash", "blender -b out/scene.blend --python scenes/scene/scripts/lighting.py");
+report(2, "lighting", "screens and wall display carry the room; ceiling panels at 40%; sodium floods outside", img.s2);
+log(5, "Edit", "editing scenes/scene/scripts/lighting.py");
+report(36, "atmosphere", "cigarette haze (volume density 0.012), slight bloom, Kodak 5219-style grade", img.s2);
+log(4, "Write", "writing scenes/scene/shots.json");
+report(30, "cameras", "reference angle plus two open views down the console rows", img.s1);
+log(3, "Bash", "blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --finals --samples 256");
+log(96, "Read", "looking at out/stills/ref.png");
+report(3, "finals", "3 stills at 1920 x 804, 256 samples", img.s0);
+
+const crit = (round, scores, fixes, summary, preview) => {
+ at(4);
+ e("critique", "critic is looking at 3 stills");
+ at(58);
+ const passed = Object.values(scores).every((v) => v >= 7);
+ ev.push({
+ t, stage: "critique", status: passed ? "done" : "running",
+ message: `round ${round}: ${passed ? "PASS" : "not yet"} - ` + Object.entries(scores).map(([k, v]) => `${k} ${v}`).join(", "),
+ preview_url: preview,
+ critique: { round, scores, fixes, summary, passed, stills: ["out/stills/ref.png", "out/stills/view_1.png", "out/stills/view_2.png"] },
+ });
+};
+crit(1, { layout: 7, props: 6, screens_signage: 5, materials: 6, lighting: 7, atmosphere: 6, plausibility: 8, composition: 7 }, [
+ "Console CRTs: all 14 scopes show the same sine trace; the reference has varied content (polar plots, columns of telemetry, a radar sweep). Give each scope its own texture.",
+ "Wall display: the world map is too bright and flat; it should glow from behind with darker ocean areas and thin orbit ground tracks.",
+ "Desk clutter: binders and teleprinter paper read as clean grey boxes; add page edges, curl and print.",
+ "Haze is too uniform; the reference has denser smoke near the ceiling lit by the screens.",
+ "Chairs: three swivel chairs intersect the console fronts in the second row.",
+], "Right room, right layout and camera. It falls down on the screens, which carry this reference, and on generic clutter.", img.s0);
+say(4, "Screens first, they cost the most points. Then the clutter and the chairs.");
+log(3, "Edit", "editing scenes/scene/scripts/screens.py");
+log(6, "Bash", "python scenes/scene/scripts/screens.py --make-textures out/screens --vary 14");
+log(30, "Read", "looking at out/screens/contact_sheet.png");
+report(4, "screens", "14 distinct scope textures: polar plots, telemetry columns, radar sweep; wall map darkened", img.dressed);
+log(5, "Edit", "editing scenes/scene/scripts/dress.py");
+log(31, "Bash", "python pipeline/collide.py out/scene.blend --fix chairs");
+report(3, "dressing", "chairs pulled back from the consoles; binders and printouts swapped for detailed meshes", img.layout);
+log(4, "Edit", "editing scenes/scene/scripts/lighting.py");
+report(40, "atmosphere", "haze layered: denser under the ceiling, lit by the scopes", img.s2);
+log(3, "Bash", "blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --finals --samples 256");
+log(98, "Read", "looking at out/stills/ref.png");
+report(2, "finals", "3 stills re-rendered after round 1 fixes", img.s0);
+crit(2, { layout: 7, props: 7, screens_signage: 6, materials: 7, lighting: 8, atmosphere: 7, plausibility: 8, composition: 7 }, [
+ "Wall display: ground tracks are there but the telemetry panels either side are blank; the reference has columns of stencilled data.",
+ "Two scopes on the hero console are out of focus compared with the rest; sharpen or raise their emission.",
+ "Window reflections: the glass shows no reflection of the room; add a faint reflection so it reads as glass at night.",
+], "Big improvement on the screens and the haze. The side panels of the wall display are the last thing that reads as unfinished.", img.s0);
+say(4, "Filling the wall display's side panels with stencilled data columns and adding reflection to the window glass.");
+log(3, "Edit", "editing scenes/scene/scripts/screens.py");
+log(22, "Bash", "python scenes/scene/scripts/screens.py --wall-panels out/screens");
+log(4, "Edit", "editing scenes/scene/scripts/materials.py");
+log(3, "Bash", "blender -b out/scene.blend --python camera/shoot.py -- --shots out/shots.json --finals --samples 256");
+log(97, "Read", "looking at out/stills/view_1.png");
+report(2, "finals", "3 stills with the wall panels and window glass fixed", img.s0);
+crit(3, { layout: 8, props: 7, screens_signage: 7, materials: 7, lighting: 8, atmosphere: 8, plausibility: 8, composition: 8 }, [
+ "Optional: a little more variation in console paint wear between rows.",
+ "Optional: one or two lit cigarettes in the ashtrays would add life to the haze.",
+], "Passes. A faithful, photoreal version of the reference; the screens and the wall display now carry it.", img.s0);
+log(5, "Bash", "blender -b out/scene.blend --python pipeline/export_glb.py -- out/scene.glb --decimate 0.25");
+log(40, "Bash", "blender -b out/scene.blend --python camera/panorama.py -- --at ref_view,room_centre --out out/panoramas");
+at(70);
+ev.push({ t, stage: "done", status: "done", message: "scene builder finished after 33 min, agent cost $27.40", missing: [], critiques: 3 });
+at(48);
+ev.push({ t, stage: "packaged", status: "done", message: "package ready after 34 min", package_url: "https://v3b.fal.media/files/b/0ab08e00/m4GTss3UapWdQmO9PaFiw_scene_package.zip" });
+
+writeFileSync(path.join(dir, "events.jsonl"), ev.map((x) => JSON.stringify(x)).join("\n") + "\n");
+const critiques = ev.filter((x) => x.critique).map((x) => {
+ const { stills, ...c } = x.critique;
+ return c;
+});
+const build = {
+ build_id: "b_synthetic01",
+ stills: [img.s0, img.s1, img.s2],
+ scene_blend_url: null,
+ scene_glb_url: D + "scene.glb",
+ panorama_urls: [D + "panorama_ref.png", D + "panorama_mid.png"],
+ package_url: ev[ev.length - 1].package_url,
+ critiques,
+ missing: [],
+ agent_cost_usd: 27.4,
+ minutes: Math.round((t / 60) * 10) / 10,
+ _synthetic: "made by scripts/make-builder-fixture.mjs; images and package are from the earlier pipeline run",
+};
+writeFileSync(path.join(dir, "build.json"), JSON.stringify(build, null, 1));
+console.log(`fixtures/builder: ${ev.length} events over ${(t / 60).toFixed(1)} min`);
diff --git a/web/scripts/make-placeholders.mjs b/web/scripts/make-placeholders.mjs
new file mode 100644
index 0000000..c6b4d5a
--- /dev/null
+++ b/web/scripts/make-placeholders.mjs
@@ -0,0 +1,211 @@
+// Placeholder 360 assets for replay, until the endpoint emits real ones (see README):
+// fixtures/panorama_ref.png, fixtures/panorama_mid.png procedural equirectangular "grey room" renders (2:1)
+// fixtures/scene.glb the plan as boxes + KHR_lights_punctual lights
+// Both are built from fixtures/plan.json so they line up with the recorded scene's layout. No dependencies.
+// node scripts/make-placeholders.mjs [fixturesDir]
+import { readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import zlib from "node:zlib";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const dir = process.argv[2] || path.join(root, "fixtures");
+const plan = JSON.parse(readFileSync(path.join(dir, "plan.json"), "utf8"));
+const { width: W, depth: D, height: H } = plan.room;
+
+// ---------------------------------------------------------------- PNG
+const crcTable = new Uint32Array(256).map((_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+});
+const crc32 = (buf) => {
+ let c = 0xffffffff;
+ for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+};
+function chunk(type, data) {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length);
+ const td = Buffer.concat([Buffer.from(type), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(td));
+ return Buffer.concat([len, td, crc]);
+}
+function png(w, h, rgb) {
+ const raw = Buffer.alloc((w * 3 + 1) * h);
+ for (let y = 0; y < h; y++) rgb.copy(raw, y * (w * 3 + 1) + 1, y * w * 3, (y + 1) * w * 3);
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(w, 0);
+ ihdr.writeUInt32BE(h, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 2;
+ return Buffer.concat([
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
+ chunk("IHDR", ihdr),
+ chunk("IDAT", zlib.deflateSync(raw, { level: 6 })),
+ chunk("IEND", Buffer.alloc(0)),
+ ]);
+}
+
+// ---------------------------------------------------------------- equirectangular grey room
+const hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16) / 255);
+const lights = plan.lights.map((l) => ({ p: [l.x, l.y, l.z], c: hex(l.color), k: l.power === "high" ? 2.2 : l.power === "medium" ? 1.2 : 0.6 }));
+const objects = plan.objects.filter((o) => o.h > 0.05);
+
+function shade(o, d) {
+ // ray from o (plan coords, Z up) along d against the room box and object footprints (as axis-aligned boxes)
+ let tBest = Infinity, n = null, kind = "";
+ for (let a = 0; a < 3; a++) {
+ if (Math.abs(d[a]) < 1e-9) continue;
+ const lim = [W, D, H][a];
+ const t = d[a] > 0 ? (lim - o[a]) / d[a] : -o[a] / d[a];
+ if (t > 0 && t < tBest) { tBest = t; n = a; kind = a === 2 ? (d[2] > 0 ? "ceiling" : "floor") : "wall"; }
+ }
+ for (const ob of objects) {
+ const hw = Math.max(ob.w, ob.d) / 2;
+ const lo = [ob.x - hw, ob.y - hw, ob.z], hi = [ob.x + hw, ob.y + hw, ob.z + ob.h];
+ let t0 = 0, t1 = tBest, axis = -1;
+ for (let a = 0; a < 3; a++) {
+ const inv = 1 / (d[a] || 1e-9);
+ let ta = (lo[a] - o[a]) * inv, tb = (hi[a] - o[a]) * inv;
+ if (ta > tb) [ta, tb] = [tb, ta];
+ if (ta > t0) { t0 = ta; axis = a; }
+ t1 = Math.min(t1, tb);
+ if (t0 > t1) { axis = -2; break; }
+ }
+ if (axis >= 0 && t0 < tBest) { tBest = t0; n = axis; kind = "object"; }
+ }
+ const p = [o[0] + d[0] * tBest, o[1] + d[1] * tBest, o[2] + d[2] * tBest];
+ let base = kind === "floor" ? [0.23, 0.22, 0.2] : kind === "ceiling" ? [0.32, 0.32, 0.3] : kind === "object" ? [0.42, 0.44, 0.4] : [0.36, 0.38, 0.35];
+ // window openings glow (night: deep blue)
+ if (kind === "wall") {
+ for (const op of plan.openings) {
+ const along = op.wall === "front" || op.wall === "back" ? p[0] : p[1];
+ const onWall = (op.wall === "left" && p[0] < 0.01) || (op.wall === "right" && p[0] > W - 0.01) || (op.wall === "front" && p[1] < 0.01) || (op.wall === "back" && p[1] > D - 0.01);
+ if (onWall && Math.abs(along - op.center) < op.width / 2 && p[2] > op.sill && p[2] < op.sill + op.height)
+ base = op.kind === "window" ? [0.08, 0.12, 0.22] : [0.05, 0.05, 0.05];
+ }
+ // 1 m grid lines, like a set under construction
+ const u = n === 0 ? p[1] : p[0];
+ if (Math.abs(u - Math.round(u)) < 0.012 || Math.abs(p[2] - Math.round(p[2])) < 0.012) base = base.map((c) => c * 0.8);
+ }
+ if (kind === "floor" && (Math.abs(p[0] - Math.round(p[0])) < 0.01 || Math.abs(p[1] - Math.round(p[1])) < 0.01)) base = base.map((c) => c * 0.75);
+ let col = base.map((c) => c * 0.25);
+ for (const l of lights) {
+ const v = [l.p[0] - p[0], l.p[1] - p[1], l.p[2] - p[2]];
+ const dist2 = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + 0.4;
+ const f = (l.k * 2.2) / dist2;
+ col = col.map((c, i) => c + base[i] * l.c[i] * f);
+ }
+ // practical bulbs seen directly
+ for (const l of lights) {
+ const v = [l.p[0] - o[0], l.p[1] - o[1], l.p[2] - o[2]];
+ const len = Math.hypot(...v);
+ const cos = (v[0] * d[0] + v[1] * d[1] + v[2] * d[2]) / len;
+ if (len < tBest + 0.1 && cos > 0.99985) col = l.c.map((c) => c * 1.4);
+ }
+ return col.map((c) => Math.min(1, Math.pow(c / (1 + c), 1 / 2.2) * 0.95));
+}
+
+function panorama(origin, w = 2048) {
+ const h = w / 2;
+ const rgb = Buffer.alloc(w * h * 3);
+ for (let y = 0; y < h; y++) {
+ const lat = Math.PI / 2 - ((y + 0.5) / h) * Math.PI;
+ for (let x = 0; x < w; x++) {
+ // u = 0.5 looks along +Y (into the room), the way three.js maps an equirect onto a sphere
+ const lon = ((x + 0.5) / w - 0.5) * 2 * Math.PI;
+ const d = [Math.sin(lon) * Math.cos(lat), Math.cos(lon) * Math.cos(lat), Math.sin(lat)];
+ const c = shade(origin, d);
+ const i = (y * w + x) * 3;
+ rgb[i] = c[0] * 255;
+ rgb[i + 1] = c[1] * 255;
+ rgb[i + 2] = c[2] * 255;
+ }
+ }
+ return png(w, h, rgb);
+}
+
+const cam = plan.reference_camera?.position ?? [W / 2, 1, 1.6];
+const refPos = [Math.min(W - 0.2, Math.max(0.2, cam[0])), Math.min(D - 0.2, Math.max(1.0, cam[1])), Math.min(H - 0.2, Math.max(0.3, cam[2]))];
+writeFileSync(path.join(dir, "panorama_ref.png"), panorama(refPos));
+writeFileSync(path.join(dir, "panorama_mid.png"), panorama([W / 2, D / 2, 1.6]));
+console.log("wrote panorama_ref.png, panorama_mid.png");
+
+// ---------------------------------------------------------------- scene.glb
+// glTF is Y up, -Z forward: plan (x, y, z) -> (x, z, -y). Plan rotation about Z -> rotation about Y.
+const pos = [], nor = [], idx = [];
+const faces = [
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[-1, 0, 0], [0, 1, 0], [0, 0, -1]],
+ [[0, 1, 0], [0, 0, 1], [1, 0, 0]], [[0, -1, 0], [0, 0, -1], [1, 0, 0]],
+ [[0, 0, 1], [1, 0, 0], [0, 1, 0]], [[0, 0, -1], [-1, 0, 0], [0, 1, 0]],
+];
+for (const [nrm, u, v] of faces) {
+ const b = pos.length / 3;
+ for (const [su, sv] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
+ pos.push(...[0, 1, 2].map((i) => 0.5 * nrm[i] + 0.5 * su * u[i] + 0.5 * sv * v[i]));
+ nor.push(...nrm);
+ }
+ idx.push(b, b + 1, b + 2, b, b + 2, b + 3);
+}
+const posBuf = Buffer.from(new Float32Array(pos).buffer);
+const norBuf = Buffer.from(new Float32Array(nor).buffer);
+const idxBuf = Buffer.from(new Uint16Array(idx).buffer);
+const bin = Buffer.concat([posBuf, norBuf, idxBuf, Buffer.alloc((4 - (idxBuf.length % 4)) % 4)]);
+
+const catColor = { furniture: [0.36, 0.4, 0.35], fixture: [0.3, 0.33, 0.3], prop: [0.6, 0.56, 0.48], clutter: [0.66, 0.6, 0.5], structure: [0.45, 0.45, 0.43] };
+const cats = [...new Set(plan.objects.map((o) => o.category))];
+const materials = [
+ { name: "shell", pbrMetallicRoughness: { baseColorFactor: [0.4, 0.41, 0.39, 1], metallicFactor: 0, roughnessFactor: 0.9 }, doubleSided: true },
+ ...cats.map((c) => ({ name: c, pbrMetallicRoughness: { baseColorFactor: [...(catColor[c] ?? [0.5, 0.5, 0.5]), 1], metallicFactor: 0.1, roughnessFactor: 0.6 } })),
+];
+const meshes = materials.map((_, m) => ({ primitives: [{ attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, material: m }] }));
+const nodes = [];
+const q = (deg) => [0, Math.sin((deg * Math.PI) / 360), 0, Math.cos((deg * Math.PI) / 360)];
+const box = (name, mesh, x, y, z, w, d, h, rot = 0) =>
+ nodes.push({ name, mesh, translation: [x, z + h / 2, -y], rotation: q(rot), scale: [Math.max(w, 0.02), Math.max(h, 0.02), Math.max(d, 0.02)] });
+box("floor", 0, W / 2, D / 2, -0.05, W, D, 0.05);
+box("ceiling", 0, W / 2, D / 2, H, W, D, 0.05);
+box("wall_back", 0, W / 2, D + 0.05, 0, W, 0.1, H);
+box("wall_left", 0, -0.05, D / 2, 0, 0.1, D, H);
+box("wall_right", 0, W + 0.05, D / 2, 0, 0.1, D, H);
+for (const o of plan.objects) box(o.id, 1 + cats.indexOf(o.category), o.x, o.y, o.z, o.w, o.d, o.h, o.rot);
+const power = { low: 15, medium: 40, high: 120 };
+const lightsExt = plan.lights.map((l) => ({ type: "point", color: hex(l.color), intensity: power[l.power] ?? 30, range: 12, name: l.id }));
+plan.lights.forEach((l, i) => nodes.push({ name: l.id, translation: [l.x, l.z, -l.y], extensions: { KHR_lights_punctual: { light: i } } }));
+const gltf = {
+ asset: { version: "2.0", generator: "anyscene web placeholder" },
+ extensionsUsed: ["KHR_lights_punctual"],
+ extensions: { KHR_lights_punctual: { lights: lightsExt } },
+ scene: 0,
+ scenes: [{ nodes: nodes.map((_, i) => i) }],
+ nodes,
+ meshes,
+ materials,
+ buffers: [{ byteLength: bin.length }],
+ bufferViews: [
+ { buffer: 0, byteOffset: 0, byteLength: posBuf.length, target: 34962 },
+ { buffer: 0, byteOffset: posBuf.length, byteLength: norBuf.length, target: 34962 },
+ { buffer: 0, byteOffset: posBuf.length + norBuf.length, byteLength: idxBuf.length, target: 34963 },
+ ],
+ accessors: [
+ { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.5, -0.5, -0.5], max: [0.5, 0.5, 0.5] },
+ { bufferView: 1, componentType: 5126, count: nor.length / 3, type: "VEC3" },
+ { bufferView: 2, componentType: 5123, count: idx.length, type: "SCALAR" },
+ ],
+};
+let json = Buffer.from(JSON.stringify(gltf));
+json = Buffer.concat([json, Buffer.alloc((4 - (json.length % 4)) % 4, 0x20)]);
+const header = Buffer.alloc(12);
+header.writeUInt32LE(0x46546c67, 0);
+header.writeUInt32LE(2, 4);
+header.writeUInt32LE(12 + 8 + json.length + 8 + bin.length, 8);
+const ch = (len, type) => {
+ const b = Buffer.alloc(8);
+ b.writeUInt32LE(len, 0);
+ b.writeUInt32LE(type, 4);
+ return b;
+};
+writeFileSync(path.join(dir, "scene.glb"), Buffer.concat([header, ch(json.length, 0x4e4f534a), json, ch(bin.length, 0x004e4942), bin]));
+console.log(`wrote scene.glb (${nodes.length} nodes, ${lightsExt.length} lights)`);
diff --git a/web/scripts/screenshots-builder.mjs b/web/scripts/screenshots-builder.mjs
new file mode 100644
index 0000000..074f16e
--- /dev/null
+++ b/web/scripts/screenshots-builder.mjs
@@ -0,0 +1,66 @@
+// Captures the builder UI from the builder replay into web/screenshots/builder-*.png. Needs `npm run dev` running.
+// node scripts/screenshots-builder.mjs [baseUrl] [replayName=builder]
+import { chromium } from "playwright-core";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { mkdirSync } from "node:fs";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const out = path.join(root, "screenshots");
+mkdirSync(out, { recursive: true });
+const base = process.argv[2] || "http://localhost:3210";
+const name = process.argv[3] || "builder";
+
+let browser;
+for (const channel of ["msedge", "chrome"]) {
+ try {
+ browser = await chromium.launch({ channel, args: ["--enable-gpu", "--ignore-gpu-blocklist"] });
+ break;
+ } catch {}
+}
+if (!browser) throw new Error("No Edge or Chrome found");
+const page = await browser.newPage({ viewport: { width: 1600, height: 940 } });
+page.on("pageerror", (e) => console.error("page error:", e.message));
+const shot = async (file) => {
+ await page.waitForTimeout(700);
+ await page.screenshot({ path: path.join(out, file) });
+ console.log("saved", file);
+};
+const tab = (label) => page.getByRole("tab", { name: label, exact: true }).click();
+const until = (fn, arg, timeout = 300000) => page.waitForFunction(fn, arg, { timeout });
+
+await page.goto(`${base}/?replay=${name}&speed=32`, { waitUntil: "networkidle" });
+await page.waitForSelector(".drop img");
+await shot("builder-01-idle.png");
+
+await page.getByRole("button", { name: "Build the scene" }).click();
+await until(() => document.querySelectorAll(".ll.milestone").length >= 1);
+await shot("builder-02-plan-milestone.png");
+await until(() => document.querySelectorAll(".ll.milestone").length >= 4);
+await shot("builder-03-props-dressing.png");
+await until(() => document.querySelectorAll(".scores tbody tr").length > 0);
+await shot("builder-04-critic-round-1.png");
+await until(() => [...document.querySelectorAll(".scores thead th")].length >= 3);
+await tab("Contact sheet");
+await shot("builder-05-contact-sheet-round-2.png");
+await page.getByRole("button", { name: "Notes", exact: true }).click();
+await shot("builder-06-log-notes-filter.png");
+await page.getByRole("button", { name: "All", exact: true }).click();
+await page.getByRole("button", { name: "Follow" }).click();
+await until(() => !!document.querySelector(".slate-wrap .stamp"));
+await page.waitForTimeout(1500);
+await shot("builder-07-wrapped-stills.png");
+await tab("Compare");
+await shot("builder-08-compare.png");
+await tab("360");
+await page.waitForTimeout(2500);
+await shot("builder-09-360-plate.png");
+await page.getByRole("button", { name: "Set model" }).click();
+await page.waitForTimeout(3000);
+await shot("builder-10-360-set-model.png");
+await page.setViewportSize({ width: 390, height: 844 });
+await shot("builder-11-mobile.png");
+await page.setViewportSize({ width: 1600, height: 940 });
+await page.goto(`${base}/?mode=pipeline`, { waitUntil: "networkidle" });
+await shot("builder-12-pipeline-toggle.png");
+await browser.close();
diff --git a/web/scripts/screenshots.mjs b/web/scripts/screenshots.mjs
new file mode 100644
index 0000000..51e4b15
--- /dev/null
+++ b/web/scripts/screenshots.mjs
@@ -0,0 +1,88 @@
+// Captures the major UI states from a replay into web/screenshots/. Needs `npm run dev` running.
+// node scripts/screenshots.mjs [baseUrl] [replayName]
+// Uses the installed Microsoft Edge (or Chrome) through playwright-core; no browser download.
+import { chromium } from "playwright-core";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { mkdirSync } from "node:fs";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const out = path.join(root, "screenshots");
+mkdirSync(out, { recursive: true });
+const base = process.argv[2] || "http://localhost:3210";
+const name = process.argv[3] || "demo";
+const speed = 16;
+
+let browser;
+for (const channel of ["msedge", "chrome"]) {
+ try {
+ browser = await chromium.launch({ channel, args: ["--enable-gpu", "--ignore-gpu-blocklist"] });
+ break;
+ } catch {}
+}
+if (!browser) throw new Error("No Edge or Chrome found");
+
+const page = await browser.newPage({ viewport: { width: 1600, height: 940 }, deviceScaleFactor: 1 });
+page.on("pageerror", (e) => console.error("page error:", e.message));
+const shot = async (file) => {
+ await page.waitForTimeout(700);
+ await page.screenshot({ path: path.join(out, file) });
+ console.log("saved", file);
+};
+const tab = (label) => page.getByRole("tab", { name: label, exact: true }).click();
+
+await page.goto(`${base}/?replay=${name}&speed=${speed}`, { waitUntil: "networkidle" });
+await page.waitForSelector(".drop img");
+await shot("01-idle.png");
+
+await page.getByRole("button", { name: "Plan the scene" }).click();
+await page.waitForTimeout(1500);
+await shot("02-planning.png");
+
+await page.waitForSelector(".plan-title", { timeout: 120000 });
+await shot("03-plan-ready-greybox.png");
+await tab("Floor plan");
+await shot("04-floor-plan.png");
+await tab("Compare");
+await shot("05-compare-greybox.png");
+
+await page.getByRole("button", { name: /Approve and build/ }).click();
+await page.waitForFunction(() => document.querySelectorAll(".tile:not(.ghost)").length >= 10, null, { timeout: 120000 });
+await shot("06-build-references.png");
+await page.waitForFunction(() => document.querySelectorAll(".tile.spinning").length >= 6, null, { timeout: 120000 }).catch(() => console.log("(few turntables ready yet)"));
+await shot("07-build-meshes-prop-map.png");
+
+await page.waitForFunction(() => [...document.querySelectorAll(".sched tr.running .dept")].some((d) => /Set dressing|Camera/.test(d.textContent || "")), null, { timeout: 300000 });
+await tab("Live");
+await shot("08-live-layout.png");
+
+await page.locator(".tile:not(.ghost):not(:disabled)").first().click();
+await page.waitForSelector(".viewer3d canvas");
+await page.waitForFunction(() => !document.querySelector(".viewer3d-load"), null, { timeout: 180000 }).catch(() => {});
+await page.waitForTimeout(1500);
+await shot("09-prop-3d.png");
+
+await page.waitForSelector(".slate-wrap .stamp", { timeout: 400000 });
+await tab("Result");
+await page.waitForTimeout(1200);
+await shot("10-wrapped-result.png");
+await tab("Compare");
+await shot("11-compare-final.png");
+
+await tab("360");
+await page.waitForTimeout(2500);
+await shot("12-360-plate.png");
+await page.getByRole("button", { name: "Set model" }).click();
+await page.waitForTimeout(3000);
+await shot("13-360-set-model.png");
+
+await page.locator(".tile:not(.ghost):not(:disabled)").nth(2).click();
+await page.waitForFunction(() => !document.querySelector(".viewer3d-load"), null, { timeout: 180000 }).catch(() => {});
+await page.waitForTimeout(2000);
+await shot("14-prop-3d-scene-light.png");
+
+await page.setViewportSize({ width: 390, height: 844 });
+await page.evaluate(() => window.scrollTo(0, 0));
+await shot("15-mobile.png");
+
+await browser.close();
diff --git a/web/scripts/sync-fixtures.mjs b/web/scripts/sync-fixtures.mjs
new file mode 100644
index 0000000..6c4a58e
--- /dev/null
+++ b/web/scripts/sync-fixtures.mjs
@@ -0,0 +1,53 @@
+// Copies recorded runs from web/fixtures/ into public/replay/ so `?replay=<name>` can stream them.
+// web/fixtures/* -> public/replay/demo/
+// web/fixtures/<name>/* -> public/replay/<name>/
+// Each copy gets a manifest.json saying which pieces exist (plan events, plan, images, build events, stills).
+import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const src = path.join(root, "fixtures");
+const dst = path.join(root, "public", "replay");
+rmSync(dst, { recursive: true, force: true });
+mkdirSync(dst, { recursive: true });
+
+function copyRun(from, name) {
+ const to = path.join(dst, name);
+ mkdirSync(to, { recursive: true });
+ const files = readdirSync(from).filter((f) => statSync(path.join(from, f)).isFile());
+ for (const f of files) cpSync(path.join(from, f), path.join(to, f));
+ const has = (f) => files.includes(f);
+ const manifest = {
+ name,
+ // a builder recording (builder/app.py) is events.jsonl + build.json; the old pipeline has plan/build events
+ kind: has("events.jsonl") ? "builder" : "pipeline",
+ events: has("events.jsonl"),
+ plan_events: has("plan_events.jsonl"),
+ plan: has("plan.json"),
+ // a recording without its own reference borrows the root one (both demo runs use the same plate)
+ reference: has("reference.png") ? "reference.png" : name !== "demo" && existsSync(path.join(src, "reference.png")) ? "/replay/demo/reference.png" : null,
+ floor_plan: has("floor_plan.png") ? "floor_plan.png" : null,
+ blockout_reference: has("blockout_reference.png") ? "blockout_reference.png" : null,
+ blockout_overview: has("blockout_overview.png") ? "blockout_overview.png" : null,
+ comparison: has("comparison.png") ? "comparison.png" : null,
+ build_events: has("build_events.jsonl"),
+ build: has("build.json"),
+ // placeholders for the 360 tab (scripts/make-placeholders.mjs) until a recorded build carries real ones
+ panoramas: files.filter((f) => /^panorama_.*\.(png|jpg|hdr)$/i.test(f)).sort((a, b) => (a.includes("ref") ? -1 : b.includes("ref") ? 1 : a.localeCompare(b))),
+ scene_glb: has("scene.glb") ? "scene.glb" : null,
+ stills: files.filter((f) => /^still_.*\.(png|jpg|webp)$/i.test(f)).sort(),
+ };
+ writeFileSync(path.join(to, "manifest.json"), JSON.stringify(manifest, null, 1));
+ return manifest;
+}
+
+const runs = [];
+if (existsSync(src)) {
+ runs.push(copyRun(src, "demo").name);
+ for (const d of readdirSync(src)) {
+ if (statSync(path.join(src, d)).isDirectory()) runs.push(copyRun(path.join(src, d), d).name);
+ }
+}
+writeFileSync(path.join(dst, "index.json"), JSON.stringify({ runs }));
+console.log(`replay fixtures: ${runs.join(", ") || "none"}`);
diff --git a/web/scripts/write-env-local.mjs b/web/scripts/write-env-local.mjs
new file mode 100644
index 0000000..0391704
--- /dev/null
+++ b/web/scripts/write-env-local.mjs
@@ -0,0 +1,25 @@
+// Writes web/.env.local with FAL_KEY taken from the Windows user env var FAL_SERVERLESS_KEY (HKCU\Environment).
+// The key is never printed.
+import { execFileSync } from "node:child_process";
+import { writeFileSync, existsSync, readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import path from "node:path";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const out = path.join(root, ".env.local");
+let key = process.env.FAL_SERVERLESS_KEY;
+if (!key && process.platform === "win32") {
+ try {
+ const txt = execFileSync("reg", ["query", String.raw`HKCU\Environment`, "/v", "FAL_SERVERLESS_KEY"], { encoding: "utf8" });
+ const m = txt.match(/FAL_SERVERLESS_KEY\s+REG_\w+\s+(\S+)/);
+ if (m) key = m[1];
+ } catch {}
+}
+if (!key) {
+ console.error("FAL_SERVERLESS_KEY not found in the environment or HKCU/Environment; .env.local not written.");
+ process.exit(1);
+}
+let lines = existsSync(out) ? readFileSync(out, "utf8").split(/\r?\n/).filter((l) => l && !l.startsWith("FAL_KEY=")) : [];
+lines.push(`FAL_KEY=${key}`);
+writeFileSync(out, lines.join("\n") + "\n");
+console.log(`wrote FAL_KEY (${key.length} chars) to .env.local`);
diff --git a/web/tsconfig.json b/web/tsconfig.json
new file mode 100644
index 0000000..469c297
--- /dev/null
+++ b/web/tsconfig.json
@@ -0,0 +1,42 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "lib": [
+ "dom",
+ "dom.iterable",
+ "esnext"
+ ],
+ "allowJs": false,
+ "skipLibCheck": true,
+ "strict": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "jsx": "react-jsx",
+ "incremental": true,
+ "plugins": [
+ {
+ "name": "next"
+ }
+ ],
+ "paths": {
+ "@/*": [
+ "./*"
+ ]
+ }
+ },
+ "include": [
+ "next-env.d.ts",
+ "**/*.ts",
+ "**/*.tsx",
+ ".next/types/**/*.ts",
+ ".next/dev/types/**/*.ts"
+ ],
+ "exclude": [
+ "node_modules",
+ "scripts"
+ ]
+}