Eight agent skills for 3D and animated websites: three.js scenes from code, scroll films, transparent video, cursor rigs, exploded views, AI motion assets, browser checks and 60 fps recording. Claude Code, Codex, Cursor, Gemini CLI.
Open 3D Skills 1.0.0: eight skills for 3D and animated websites
Moh4696475b8d9c4644
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 0000000..c43b462--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,12 @@+{+ "name": "open-3d-skills",+ "interface": { "displayName": "Open 3D Skills" },+ "plugins": [+ {+ "name": "open-3d-skills",+ "source": { "source": "url", "url": "https://github.com/Moh4696/open-3d-skills.git", "ref": "main" },+ "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" },+ "category": "Design"+ }+ ]+}diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 0000000..16c5733--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,19 @@+{+ "name": "open-3d-skills",+ "description": "Eight agent skills for 3D and animated websites: three.js scenes built from code, scroll-scrubbed films, transparent video, cursor-following characters, exploded views, AI motion assets, real-browser checks and frame-exact recording.",+ "owner": { "name": "exploraX", "url": "https://x.com/exploraX_" },+ "plugins": [+ {+ "name": "open-3d-skills",+ "description": "Eight agent skills for 3D and animated websites: three.js scenes built from code, scroll-scrubbed films, transparent video, cursor-following characters, exploded views, AI motion assets, real-browser checks and frame-exact recording.",+ "version": "1.0.0",+ "source": "./",+ "skills": ["./skills/threejs-scene", "./skills/scroll-film", "./skills/motion-assets", "./skills/alpha-cutout", "./skills/cursor-rig", "./skills/exploded-view", "./skills/site-check", "./skills/frame-capture"],+ "author": { "name": "exploraX", "url": "https://x.com/exploraX_" },+ "homepage": "https://github.com/Moh4696/open-3d-skills",+ "repository": "https://github.com/Moh4696/open-3d-skills",+ "license": "MIT",+ "keywords": ["skills", "3d", "threejs", "webgl", "animation", "scroll", "frontend", "video"]+ }+ ]+}diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonnew file mode 100644index 0000000..296fc7b--- /dev/null+++ b/.codex-plugin/plugin.json@@ -0,0 +1,25 @@+{+ "name": "open-3d-skills",+ "version": "1.0.0",+ "description": "Eight agent skills for 3D and animated websites: three.js scenes built from code, scroll-scrubbed films, transparent video, cursor-following characters, exploded views, AI motion assets, real-browser checks and frame-exact recording.",+ "author": { "name": "exploraX", "url": "https://x.com/exploraX_" },+ "homepage": "https://github.com/Moh4696/open-3d-skills",+ "repository": "https://github.com/Moh4696/open-3d-skills",+ "license": "MIT",+ "keywords": ["skills", "3d", "threejs", "webgl", "animation", "scroll", "frontend", "video"],+ "skills": "./skills/",+ "interface": {+ "displayName": "Open 3D Skills",+ "shortDescription": "3D and animated websites: three.js, scroll films, transparent video, recording.",+ "longDescription": "Eight agent skills for 3D and animated websites: three.js scenes built from code, scroll-scrubbed films, transparent video, cursor-following characters, exploded views, AI motion assets, real-browser checks and frame-exact recording.",+ "developerName": "exploraX",+ "category": "Design",+ "capabilities": [],+ "websiteURL": "https://github.com/Moh4696/open-3d-skills",+ "defaultPrompt": [+ "Build a 3D website of this building in three.js, lit at golden hour.",+ "Turn these generated clips into a scroll-scrubbed film section.",+ "Record this page as a smooth 60 fps video for X."+ ]+ }+}diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.jsonnew file mode 100644index 0000000..142db58--- /dev/null+++ b/.cursor-plugin/plugin.json@@ -0,0 +1,11 @@+{+ "name": "open-3d-skills",+ "version": "1.0.0",+ "description": "Eight agent skills for 3D and animated websites: three.js scenes built from code, scroll-scrubbed films, transparent video, cursor-following characters, exploded views, AI motion assets, real-browser checks and frame-exact recording.",+ "author": { "name": "exploraX" },+ "homepage": "https://github.com/Moh4696/open-3d-skills",+ "repository": "https://github.com/Moh4696/open-3d-skills",+ "license": "MIT",+ "keywords": ["skills", "3d", "threejs", "webgl", "animation", "scroll", "frontend", "video"],+ "logo": "assets/icon.png"+}diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..1bbd695--- /dev/null+++ b/.gitattributes@@ -0,0 +1,2 @@+*.sh text eol=lf+*.py text eol=lfdiff --git a/.github/workflows/check.yml b/.github/workflows/check.ymlnew file mode 100644index 0000000..7769540--- /dev/null+++ b/.github/workflows/check.yml@@ -0,0 +1,29 @@+name: Check skills++on:+ push:+ branches: [main]+ pull_request:++jobs:+ check:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ - uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ - name: Skills load in every agent, manifests agree, scripts parse+ run: |+ npm install --no-save --no-package-lock [email protected]+ node tests/check.mjs+ - name: Installer works in a clean home+ run: |+ export HOME="$RUNNER_TEMP/home" && mkdir -p "$HOME/.claude" "$HOME/.codex"+ bash install.sh+ test -L "$HOME/.claude/skills/threejs-scene" && test -L "$HOME/.codex/skills/frame-capture"+ bash install.sh --uninstall --claude --codex+ test ! -e "$HOME/.claude/skills/threejs-scene"diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..9cf123a--- /dev/null+++ b/.gitignore@@ -0,0 +1,5 @@+node_modules/+.DS_Store+__pycache__/+*.pyc+shots/diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..aac13ac--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,15 @@+# Changelog++## 1.0.0 (2026-10-31)++First release: eight skills for 3D and animated websites.++- `threejs-scene`: code-built three.js scenes with a 60 fps starter (sky and sun presets, fitted shadows, GTAO, bloom, instancing kit, profile sweeps, quality tiers, recording hooks).+- `scroll-film`: scroll-scrubbed films from frame sequences or scrub-ready video, with holds, smoothing and reduced motion; prep and seam tools.+- `motion-assets`: planning and generating AI assets; loop checker and outpaint paste-back.+- `alpha-cutout`: per-frame chroma keying with edge unmixing; stacked-alpha MP4 player for Safari.+- `cursor-rig`: cursor-following head rigs from head-turn clips; builder and player.+- `exploded-view`: staged explode, x-ray, section, labels and picking; motor demo.+- `site-check`: Chromium and WebKit checks at three sizes with a contact sheet.+- `frame-capture`: virtual-clock recorder, comparison builder, Range-capable server.+- Install for Claude Code, Codex, Cursor, Gemini CLI and OpenCode with one command.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..bb43009--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 exploraX++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..88d6c55--- /dev/null+++ b/README.md@@ -0,0 +1,165 @@+<p align="center">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="assets/cover-dark.webp" />+ <img src="assets/cover-light.webp" alt="Open 3D Skills, for coding agents. three.js worlds, scroll films, transparent video, cursor rigs, exploded views. One command." width="100%" />+ </picture>+</p>++<p align="center">+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-24292f?style=flat" alt="MIT License" /></a>+ + <img src="https://img.shields.io/badge/skills-8-e8642c?style=flat" alt="8 skills" />+ + <img src="https://img.shields.io/badge/agents-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20Cursor%20%C2%B7%20Gemini%20%C2%B7%20OpenCode-24292f?style=flat" alt="Works with Claude Code, Codex, Cursor, Gemini CLI and OpenCode" />+ + <a href="https://github.com/Moh4696/open-3d-skills/actions/workflows/check.yml"><img src="https://github.com/Moh4696/open-3d-skills/actions/workflows/check.yml/badge.svg" alt="Checks" /></a>+</p>++**Open 3D Skills** are eight agent skills for building 3D and animated websites: real-time three.js scenes built from code, scroll-scrubbed films, transparent video that plays in Safari, characters that follow the cursor, exploded views of machines, and the AI image and video work behind them. They also teach the agent to check its work in real browsers and to record it as a smooth 60 fps video.++Every technique here was used to build a real site first, and every script was run on real footage before it went in.++<p align="center">+ <img src="examples/motor-take-apart.webp" alt="A code-built electric motor taking itself apart: the housing lifts, the end shields, fan and rotor slide out along the shaft, the casing turns to x-ray, then it all goes back together. Recorded frame by frame with frame-capture." width="100%" />+</p>++<table>+ <tr>+ <td width="50%"><img src="examples/pavilion-golden.webp" alt="A round classical pavilion on a lawn at golden hour, with long shadows and trees" /></td>+ <td width="50%"><img src="examples/pavilion-night.webp" alt="The same pavilion at night under stars, lit from within by a lantern, with lamp posts glowing along the path" /></td>+ </tr>+ <tr>+ <td width="50%"><img src="examples/motor-exploded.webp" alt="The motor fully exploded, each part labelled at the side of the screen with leader lines" /></td>+ <td width="50%"><img src="examples/motor-section.webp" alt="The motor assembled with its casing cut away, showing copper windings and the rotor inside" /></td>+ </tr>+</table>++<sub>The pavilion is the starter scene in <code>threejs-scene</code>; the motor is the demo in <code>exploded-view</code>. Both are built entirely from code: no model files, no textures to download.</sub>++## Install++```bash+curl -fsSL https://raw.githubusercontent.com/Moh4696/open-3d-skills/main/install.sh | bash+```++One command installs all eight skills for every coding agent it finds on your machine: Claude Code, Codex, Cursor, Gemini CLI and OpenCode (which also reads Claude Code's skills folder). It clones the repo to `~/.open-3d-skills` and links the skills from there, so running it again updates them. Start a new agent session afterwards.++<details>+<summary>Claude Code plugin</summary>++Inside Claude Code:++```+/plugin marketplace add Moh4696/open-3d-skills+/plugin install open-3d-skills@open-3d-skills+```++The skills are namespaced as `open-3d-skills:threejs-scene` and so on, so they never collide with other skills. `/plugin update` upgrades them.++</details>++<details>+<summary>Codex plugin</summary>++```bash+codex plugin marketplace add Moh4696/open-3d-skills+codex plugin add open-3d-skills@open-3d-skills+```++Start a new Codex session afterwards.++</details>++<details>+<summary>Cursor</summary>++The one-line installer links the skills into `~/.cursor/skills`, where Cursor finds personal skills. To use the repo as a Cursor plugin instead, clone it into `~/.cursor/plugins/local/open-3d-skills` and run **Developer: Reload Window**. Teams can import the repo URL as a marketplace under **Dashboard → Plugins & MCPs → Add Marketplace**.++</details>++<details>+<summary>Gemini CLI</summary>++```bash+gemini extensions install https://github.com/Moh4696/open-3d-skills+```++`gemini extensions update` pulls new versions.++</details>++<details>+<summary>Other agents, one skill, or a copy instead of links</summary>++```bash+git clone https://github.com/Moh4696/open-3d-skills && cd open-3d-skills+./install.sh --claude --codex # only these agents (also --cursor --gemini --opencode --agents)+./install.sh --dir path/to/skills # any agent that reads a skills folder+./install.sh threejs-scene frame-capture # only some skills+./install.sh --copy # copy instead of symlink (Windows, synced folders)+./install.sh --uninstall # remove what it installed+```++Each skill is a plain folder with a `SKILL.md`, so any agent that supports Agent Skills can load it.++</details>++## The skills++| Skill | What it does | Ships with |+| --- | --- | --- |+| [`threejs-scene`](skills/threejs-scene) | Real-time 3D sites built from code: buildings, vehicles, machines, landscapes. Sky and sun presets that blend, soft fitted shadows, ambient occlusion, bloom, instancing, profile sweeps, shader patches, camera flights, quality tiers | A complete 60 fps starter scene, and notes on lighting, geometry, shaders and performance |+| [`scroll-film`](skills/scroll-film) | Scroll-scrubbed films from generated clips: chained with start and end frames, holds for captions, phone versions, loading order, reduced motion | `scroll-film.js` engine, a prep script for frames or scrub-ready video, a seam checker |+| [`motion-assets`](skills/motion-assets) | Planning and generating AI images and clips without wasting money: asset lists with prompts and costs up front, one look across assets, model choice by capability, rate limits, logging | A loop checker that finds and fixes loop points, and a paste-back tool for outpainted images |+| [`alpha-cutout`](skills/alpha-cutout) | Transparent video from clips shot on a key plate: per-frame plate measurement, edge unmixing, outputs for every browser including Safari | Plate builder, keyer (stacked-alpha MP4, VP9 alpha, WebP frames), WebGL alpha video player |+| [`cursor-rig`](skills/cursor-rig) | A painted character whose head follows the cursor, built as a grid of poses on one fixed body, with live blinks | Rig builder (alignment, even steps, flow in-betweens) and a spring-driven canvas player |+| [`exploded-view`](skills/exploded-view) | Interactive explainers of how machines work: staged explode, x-ray, section cut, labels with leader lines, picking | `explode.js` and the motor demo above |+| [`site-check`](skills/site-check) | Checks a 3D or animated page in headless Chromium and WebKit at three sizes: frame time, draw calls, errors, blank canvases, overflow, reduced motion | A checker that writes a report and a contact sheet, and a Range-capable local server |+| [`frame-capture`](skills/frame-capture) | Frame-exact 60 fps video of any page by running it on a virtual clock; labelled side-by-side or stacked comparisons | Recorder, comparison builder, local server |++## How they work together++1. **Plan.** `motion-assets` writes the concept, the asset list, every prompt and the cost, and waits for a yes before spending anything.+2. **Make.** `threejs-scene` builds what should be real-time. `scroll-film`, `alpha-cutout` and `cursor-rig` turn generated clips into page motion. `exploded-view` takes a machine apart.+3. **Check.** `site-check` shoots every state in real browsers and fails on errors, blank canvases and broken phone layouts.+4. **Show it.** `frame-capture` records the result as a smooth video for X, YouTube or a client, and builds before-and-after comparisons.++## Requirements++The skills are instructions; their scripts need:++- **Node 22+** only to run the repo's own checks (`node tests/check.mjs`). The browser code has no build step.+- **Python 3.9+** with `pip install -r requirements.txt` (Playwright, Pillow, NumPy, OpenCV), then `python3 -m playwright install chromium webkit`.+- **ffmpeg** on your PATH.+- An image and video generation service (any) for `motion-assets`, `alpha-cutout`, `cursor-rig` and `scroll-film`. `threejs-scene`, `exploded-view`, `site-check` and `frame-capture` need none.++Nothing is installed behind your back and no API keys are stored by the skills.++## Common questions++**Do I need a particular AI video service?**+No. The skills describe what a model must be able to do (start and end frames, image editing that holds framing) and how to check its output. They were built with Higgsfield, MiniMax, Kling, Seedance and Nano Banana, and say so where a behaviour was observed.++**Why build 3D from code instead of loading models?**+Code-built scenes are small, sharp at any size, free of licensing questions and easy for an agent to change. `exploded-view` works on loaded GLB files too.++**Does it work with React, Vue or Svelte?**+Yes. The modules are plain ES modules and the techniques are framework-free.++**Can I install just one skill?**+Yes: `./install.sh scroll-film`. Skills mention each other by name where they work together, but each one works alone.++## Works well with++- [Taste Skill](https://github.com/Leonxlnx/taste-skill) by Leonxlnx: art direction for the page around your 3D. It also inspired the layout of this repo.+- [scroll-world](https://github.com/oso95/scroll-world) by oso95: Higgsfield fly-through worlds.+- [Anatomy](https://github.com/wheresryan22/anatomy) by wheresryan22: isometric SVG explainer figures.+- [Interfaces skills](https://github.com/jakubkrehel/skills) by Jakub Krehel: typography, layout, colour, accessibility and UI polish.++## Feedback++Open an issue or a pull request, or find me on X at [@exploraX_](https://x.com/exploraX_).++## License++[MIT License](LICENSE) · Copyright (c) 2026 exploraXdiff --git a/assets/cover-dark.webp b/assets/cover-dark.webpnew file mode 100644index 0000000..5bfd53dBinary files /dev/null and b/assets/cover-dark.webp differdiff --git a/assets/cover-light.webp b/assets/cover-light.webpnew file mode 100644index 0000000..4bdcb12Binary files /dev/null and b/assets/cover-light.webp differdiff --git a/assets/icon.png b/assets/icon.pngnew file mode 100644index 0000000..ad98455Binary files /dev/null and b/assets/icon.png differdiff --git a/examples/motor-exploded.webp b/examples/motor-exploded.webpnew file mode 100644index 0000000..b39479cBinary files /dev/null and b/examples/motor-exploded.webp differdiff --git a/examples/motor-section.webp b/examples/motor-section.webpnew file mode 100644index 0000000..f114dd4Binary files /dev/null and b/examples/motor-section.webp differdiff --git a/examples/motor-take-apart.webp b/examples/motor-take-apart.webpnew file mode 100644index 0000000..59a06a8Binary files /dev/null and b/examples/motor-take-apart.webp differdiff --git a/examples/pavilion-golden.webp b/examples/pavilion-golden.webpnew file mode 100644index 0000000..ad92afcBinary files /dev/null and b/examples/pavilion-golden.webp differdiff --git a/examples/pavilion-night.webp b/examples/pavilion-night.webpnew file mode 100644index 0000000..46258f5Binary files /dev/null and b/examples/pavilion-night.webp differdiff --git a/gemini-extension.json b/gemini-extension.jsonnew file mode 100644index 0000000..818b698--- /dev/null+++ b/gemini-extension.json@@ -0,0 +1,5 @@+{+ "name": "open-3d-skills",+ "version": "1.0.0",+ "description": "Eight agent skills for 3D and animated websites: three.js scenes built from code, scroll-scrubbed films, transparent video, cursor-following characters, exploded views, AI motion assets, real-browser checks and frame-exact recording."+}diff --git a/install.sh b/install.shnew file mode 100755index 0000000..23bfa84--- /dev/null+++ b/install.sh@@ -0,0 +1,138 @@+#!/usr/bin/env bash+# Install Open 3D Skills for every coding agent on this machine.+#+# curl -fsSL https://raw.githubusercontent.com/Moh4696/open-3d-skills/main/install.sh | bash+#+# Run from the internet, it clones the repo to ~/.open-3d-skills (or updates it) and links the+# skills from there, so `bash ~/.open-3d-skills/install.sh` again (or a git pull) updates them.+# Run from a clone, it links from that clone.+#+# ./install.sh every agent found: Claude Code, Codex, Cursor, Gemini CLI, OpenCode+# ./install.sh --claude --codex only these (also --cursor --gemini --opencode --agents)+# ./install.sh --dir PATH into any skills folder+# ./install.sh --copy copy instead of symlink (Windows, synced folders)+# ./install.sh threejs-scene only these skills, by name+# ./install.sh --list show the skills+# ./install.sh --uninstall remove links and copies this script made+#+# Needs bash and git. Nothing else is installed; the skills' own scripts list what they use.++set -euo pipefail++REPO_URL="https://github.com/Moh4696/open-3d-skills.git"+HOME_CLONE="${OPEN3D_HOME:-$HOME/.open-3d-skills}"+MARK=".open-3d-skills"++SELF="${BASH_SOURCE[0]:-}"+REPO=""+if [[ -n $SELF && -f $SELF ]]; then REPO="$(cd "$(dirname "$SELF")" && pwd)"; fi++# piped from curl (or run outside a clone): fetch the repo, then run the copy inside it+if [[ -z $REPO || ! -d $REPO/skills ]]; then+ command -v git >/dev/null || { echo "git is required" >&2; exit 1; }+ if [[ -d $HOME_CLONE/.git ]]; then+ echo "updating $HOME_CLONE"+ git -C "$HOME_CLONE" pull --ff-only --quiet+ else+ echo "cloning to $HOME_CLONE"+ git clone --depth 1 --quiet "$REPO_URL" "$HOME_CLONE"+ fi+ exec bash "$HOME_CLONE/install.sh" "$@"+fi++SKILLS_DIR="$REPO/skills"+targets=()+mode=install+copy=0+wanted=()++add_target() { targets+=("$1"); }+while [[ $# -gt 0 ]]; do+ case "$1" in+ --claude) add_target "$HOME/.claude/skills" ;;+ --codex) add_target "${CODEX_HOME:-$HOME/.codex}/skills" ;;+ --cursor) add_target "$HOME/.cursor/skills" ;;+ --gemini) add_target "$HOME/.gemini/skills" ;;+ --opencode) add_target "$HOME/.config/opencode/skills" ;;+ --agents) add_target "$HOME/.agents/skills" ;;+ --dir) shift; add_target "${1:?--dir needs a path}" ;;+ --copy) copy=1 ;;+ --list) mode=list ;;+ --uninstall) mode=uninstall ;;+ -h|--help) awk 'NR>1 { if ($0 !~ /^#/) exit; sub(/^# ?/, ""); print }' "$REPO/install.sh"; exit 0 ;;+ -*) echo "unknown flag: $1" >&2; exit 2 ;;+ *) wanted+=("$1") ;;+ esac+ shift+done++# no agent named: every agent whose home folder exists+if [[ ${#targets[@]} -eq 0 ]]; then+ [[ -d $HOME/.claude ]] && add_target "$HOME/.claude/skills"+ [[ -d ${CODEX_HOME:-$HOME/.codex} ]] && add_target "${CODEX_HOME:-$HOME/.codex}/skills"+ [[ -d $HOME/.cursor ]] && add_target "$HOME/.cursor/skills"+ [[ -d $HOME/.gemini ]] && add_target "$HOME/.gemini/skills"+ # OpenCode also reads ~/.claude/skills; linking both would list every skill twice+ [[ -d $HOME/.config/opencode && ! -d $HOME/.claude ]] && add_target "$HOME/.config/opencode/skills"+ if [[ ${#targets[@]} -eq 0 ]]; then+ echo "no coding agent found; installing to ~/.claude/skills (use --dir for another place)"+ add_target "$HOME/.claude/skills"+ fi+fi++# frontmatter name: of a SKILL.md, falling back to the folder name+skill_name() {+ awk 'NR==1 && $0!="---" { exit } NR>1 && /^---[[:space:]]*$/ { exit }+ NR>1 && /^name:/ { sub(/^name:[[:space:]]*/, ""); gsub(/^["'\'']|["'\'']$/, ""); print; exit }' "$1"+}+wants() {+ [[ ${#wanted[@]} -eq 0 ]] && return 0+ local w; for w in "${wanted[@]}"; do [[ $w == "$1" ]] && return 0; done+ return 1+}+# true if PATH is a link into this repo, or a copy this script made+ours() {+ local p="$1"+ if [[ -L $p ]]; then [[ "$(readlink "$p")" == "$SKILLS_DIR"/* ]]; return; fi+ [[ -f $p/$MARK ]]+}++if [[ $mode == uninstall ]]; then+ for t in "${targets[@]}"; do+ [[ -d $t ]] || continue+ for d in "$SKILLS_DIR"/*/; do+ n="$(skill_name "$d/SKILL.md")"; n="${n:-$(basename "$d")}"+ p="$t/$n"+ if [[ -e $p || -L $p ]] && ours "$p"; then rm -rf "$p"; echo "removed $p"; fi+ done+ done+ exit 0+fi++names=()+for d in "$SKILLS_DIR"/*/; do+ d="${d%/}"+ [[ -f $d/SKILL.md ]] || continue+ n="$(skill_name "$d/SKILL.md")"; n="${n:-$(basename "$d")}"+ names+=("$n")+ wants "$n" || continue+ if [[ $mode == list ]]; then printf '%-16s %s\n' "$n" "skills/$(basename "$d")"; continue; fi+ for t in "${targets[@]}"; do+ mkdir -p "$t"+ p="$t/$n"+ if [[ -e $p || -L $p ]]; then+ if ours "$p"; then rm -rf "$p"+ else echo "skip $p (something else is installed there; move it aside first)" >&2; continue; fi+ fi+ if [[ $copy == 1 ]]; then cp -R "$d" "$p"; touch "$p/$MARK"; echo "copied $p"+ else ln -s "$d" "$p"; echo "linked $p"; fi+ done+done++if [[ ${#wanted[@]} -gt 0 ]]; then+ for w in "${wanted[@]}"; do+ found=0; for n in "${names[@]}"; do [[ $n == "$w" ]] && found=1; done+ [[ $found == 1 ]] || { echo "no skill named '$w'; available: ${names[*]}" >&2; exit 1; }+ done+fi+[[ $mode == list ]] || echo "done. Start a new agent session to load the skills."diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..eddf21b--- /dev/null+++ b/requirements.txt@@ -0,0 +1,7 @@+# Python packages the skills' scripts use. Install what you need:+# pip install -r requirements.txt && python3 -m playwright install chromium webkit+# ffmpeg and ffprobe must be on PATH as well.+playwright>=1.45 # frame-capture, site-check+pillow>=10 # frame-capture, scroll-film, site-check, alpha-cutout+numpy>=1.24 # alpha-cutout, cursor-rig, motion-assets, scroll-film+opencv-python-headless>=4.8 # alpha-cutout, cursor-rig, motion-assetsdiff --git a/skills/alpha-cutout/SKILL.md b/skills/alpha-cutout/SKILL.mdnew file mode 100644index 0000000..96a355a--- /dev/null+++ b/skills/alpha-cutout/SKILL.md@@ -0,0 +1,89 @@+---+name: alpha-cutout+description: Turns an AI-generated (or filmed) clip of a character or product into a transparent, web-ready animation by shooting it on a flat chroma plate and keying it with per-frame plate measurement and edge unmixing. Delivers stacked-alpha MP4 that plays with transparency in every browser including Safari, VP9 alpha WebM, or keyed WebP frame sequences for scroll scrubbing. Use when an animated subject has to sit over page content, between layers of type, or over a 3D scene, when someone asks for "transparent video", "video with alpha", "remove the background from this clip", or when a generated video has a background that should not be there.+---++# Alpha cutout++Image-to-video models never return alpha. A character that should stand between a giant headline and a sun disc, or a bottle that should float over a page, needs its background removed from every frame, cleanly enough that no fringe shows on any page colour. This skill does it the way a film studio does: shoot the subject on a flat key colour, then pull a matte per frame.++## Tools++| File | What it does |+| --- | --- |+| `scripts/plate.py` | Places a cut-out subject on a key plate with headroom; picks the key colour the subject clashes with least |+| `scripts/key.py` | Keys a clip or still into stacked MP4, VP9 alpha WebM, RGBA WebP frames or PNGs |+| `assets/alpha-video.js` | Plays a stacked-alpha MP4 with transparency on a canvas (WebGL), with `seek()` for scrubbing |++Needs Python 3.9+, `pip install numpy opencv-python-headless pillow`, and ffmpeg on PATH.++## Pipeline++1. **Cut the subject out of the still.** Any background remover works. Check what it dropped: thin objects (a ball in the air, racket strings, hair) often go missing. Put them back by hand.++2. **Make the plate.**++ ```bash+ python3 scripts/plate.py subject.png plate.png --size 1350x1800 --fit 0.8+ ```++ The script reports, for magenta, green and blue, how much of the subject sits close to that key, and picks the cleanest. Magenta is usually right: almost nothing in skin, clothing, product or foliage is pure magenta. Green fails on plants and green products; blue fails on denim and sky. The subject is pasted with a hard edge on purpose: a soft edge pre-mixed with the plate colour teaches the model to draw a fringe.++ Leave room for the motion. A serve needs space above the head; a turn needs space to the side. Match the plate's aspect to the video model's output aspect so nothing gets cropped.++3. **Generate on the plate.** Use the plate as the start frame (and as the end frame for a seamless loop; see `motion-assets`). The prompt must name the plate, or the model invents a background:++ > The background must remain a completely flat, uniform, pure chroma-key magenta (exact RGB 255, 0, 255) filling the entire frame, with no shadows, no floor, no gradient, no vignette and no scenery. Locked-off camera.++ **The prompt wins over the image.** A leftover "on a white background" in the prompt gets you a white background whatever the plate was. Re-read the prompt after every edit.++4. **Key it.**++ ```bash+ python3 scripts/key.py clip.mp4 --png check/ --frame-list 0,40,80,120 # inspect first+ python3 scripts/key.py clip.mp4 --stacked hero-1080.mp4 --width 1080+ python3 scripts/key.py clip.mp4 --stacked hero-720.mp4 --width 720 # phones+ python3 scripts/key.py clip.mp4 --frames serve/lg --width 960 --start 0 --end 78+ ```++ `--png` prints the plate colour it measured in each frame. Models drift the plate: a pure magenta can come back pale pink (250, 178, 243) halfway through while the subject keeps its colours. That is why the key colour is measured per frame from the frame's own border instead of being set once. If the subject touches the top edge, the measurement breaks and the script says so.++ Then, per pixel: alpha comes from how far the pixel's key excess is from the plate's, edge pixels are unmixed against the plate (`F = (C - (1 - a) K) / a`), and surviving spill is clamped. Unmixing matters. A plain colour-key or a clamp toward neutral turns magenta edge blends tan, which reads as a salmon outline on a white shirt; unmixing returns the real edge colour.++5. **Check on three backgrounds**: near-black, the page's light colour, and its loudest brand colour. Composite the `--png` output and look at the edges at 100% and 400%. Look hardest at hair, fingers, thin props, motion blur and the frame where the plate drifted most.++## Fixes++| You see | Do |+| --- | --- |+| A thin outline that follows the subject | `--erode 1` (rarely 2). The model copied a fringe into the artwork |+| Holes in light or shiny parts | That colour is too close to the key. Regenerate on a different key (`plate.py --key`) |+| Pink or green wash over the whole background | The plate gradient is stronger than usual; check the measured plate colours and raise `--solid` slightly |+| A detail changed colour mid-clip (a cap turned green) | Model drift, not a keying fault. Recolour that hue in those frames, or regenerate |+| Coloured line round the subject after compression | Already handled: colour under transparent pixels is the subject's own edge colour pushed outward, so chroma subsampling has nothing foreign to bleed in. `--fill` only sets the colour far from the subject |++## Which output++| Output | Plays in | Use for |+| --- | --- | --- |+| `--stacked` MP4 + `assets/alpha-video.js` | Every browser, Safari and iOS included | Looping heroes, characters, anything that plays |+| `--webm` VP9 alpha | Chrome, Edge, Firefox. Not Safari | A plain `<video>` tag where Safari support is not needed |+| `--frames` WebP sequence | Everywhere | Scroll-scrubbed motion (see `scroll-film`): exact frame per scroll position, no seeking lag |++Stacked alpha doubles the frame height (colour on top, matte below) and a shader recombines them, so it is plain H.264: it decodes in hardware everywhere and costs about 1.3 times the bytes of the colour alone. Ship two widths (1080 and 720) and choose by viewport.++```js+import { AlphaVideo } from "./alpha-video.js";+const hero = new AlphaVideo(document.querySelector("canvas.hero"), innerWidth > 900 ? "hero-1080.mp4" : "hero-720.mp4");+hero.onready = () => document.body.classList.add("hero-ready");+function frame() { hero.draw(); requestAnimationFrame(frame); }+requestAnimationFrame(frame);+```++The player pauses itself off screen and uploads a texture only when the video has moved on. For scrubbing, create it with `{ loop: false, autoplay: false }` and call `hero.seek(seconds)` from your scroll handler.++Serve videos from a server that answers HTTP Range requests (the `frame-capture` skill's serve.py does; `python3 -m http.server` does not), or seeking will not work.++## Reduced motion++With `prefers-reduced-motion: reduce`, show one keyed still (`--png` a good frame, convert to WebP) instead of the loop.diff --git a/skills/alpha-cutout/agents/openai.yaml b/skills/alpha-cutout/agents/openai.yamlnew file mode 100644index 0000000..69b5830--- /dev/null+++ b/skills/alpha-cutout/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Alpha Cutout"+ short_description: "Key generated clips into transparent video that plays in every browser"diff --git a/skills/alpha-cutout/assets/alpha-video.js b/skills/alpha-cutout/assets/alpha-video.jsnew file mode 100644index 0000000..d5a355f--- /dev/null+++ b/skills/alpha-cutout/assets/alpha-video.js@@ -0,0 +1,120 @@+// Plays a "stacked alpha" MP4 (colour in the top half, matte as grey in the bottom half) with+// real transparency on a <canvas>. Plain H.264 plus a two-line shader works in every browser,+// Safari included, where VP9 alpha does not.+//+// import { AlphaVideo } from "./alpha-video.js";+// const hero = new AlphaVideo(document.querySelector("canvas.hero"), "hero-1080.mp4");+// function frame() { hero.draw(); requestAnimationFrame(frame); } // or call draw() from your loop+//+// For scroll scrubbing, pass { loop: false, autoplay: false } and call hero.seek(seconds).+// Give the canvas its size with CSS; resize() matches the backing store to it (DPR capped at 2).++const VERT = `+attribute vec2 p;+varying vec2 uv;+void main() {+ uv = vec2(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5);+ gl_Position = vec4(p, 0.0, 1.0);+}`;+const FRAG = `+precision mediump float;+uniform sampler2D tex;+varying vec2 uv;+void main() {+ vec3 c = texture2D(tex, vec2(uv.x, uv.y * 0.5)).rgb;+ float a = texture2D(tex, vec2(uv.x, 0.5 + uv.y * 0.5)).g;+ gl_FragColor = vec4(c * a, a);+}`;++export class AlphaVideo {+ constructor(canvas, src, { loop = true, autoplay = true } = {}) {+ this.canvas = canvas;+ this.ready = false;+ this.visible = true;+ const gl = canvas.getContext("webgl", { premultipliedAlpha: true, alpha: true, antialias: false });+ this.gl = gl;+ if (!gl) return;++ const sh = (type, source) => {+ const s = gl.createShader(type);+ gl.shaderSource(s, source);+ gl.compileShader(s);+ return s;+ };+ const prog = gl.createProgram();+ gl.attachShader(prog, sh(gl.VERTEX_SHADER, VERT));+ gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FRAG));+ gl.linkProgram(prog);+ gl.useProgram(prog);++ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);+ const loc = gl.getAttribLocation(prog, "p");+ gl.enableVertexAttribArray(loc);+ gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);++ this.tex = gl.createTexture();+ gl.bindTexture(gl.TEXTURE_2D, this.tex);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);++ const v = document.createElement("video");+ Object.assign(v, { muted: true, loop, playsInline: true, autoplay, preload: "auto", crossOrigin: "anonymous" });+ v.setAttribute("muted", "");+ v.setAttribute("playsinline", "");+ v.src = src;+ this.video = v;+ this.lastTime = -1;+ v.addEventListener("loadeddata", () => {+ this.ready = true;+ this.onready && this.onready();+ }, { once: true });+ if (autoplay) v.play().catch(() => {});++ this.resize();+ new ResizeObserver(() => this.resize()).observe(canvas);+ // a looping hero off screen still decodes every frame; pause it+ new IntersectionObserver(([e]) => {+ this.visible = e.isIntersecting;+ if (!autoplay) return;+ this.visible ? this.play() : this.pause();+ }, { rootMargin: "100px" }).observe(canvas);+ }++ resize() {+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ const w = Math.round(this.canvas.clientWidth * dpr), h = Math.round(this.canvas.clientHeight * dpr);+ if (w && h && (this.canvas.width !== w || this.canvas.height !== h)) {+ this.canvas.width = w;+ this.canvas.height = h;+ this.lastTime = -1;+ }+ }++ play() { this.video && this.video.paused && this.video.play().catch(() => {}); }+ pause() { this.video && !this.video.paused && this.video.pause(); }++ // scrubbing: seconds into the clip; draw() picks the new frame up once it has decoded+ seek(t) {+ const v = this.video;+ if (!v || !v.duration) return;+ const target = Math.min(Math.max(t, 0), v.duration - 0.001);+ if (Math.abs(v.currentTime - target) > 0.001 && !v.seeking) v.currentTime = target;+ }++ draw() {+ const gl = this.gl;+ if (!gl || !this.ready || !this.visible || this.video.readyState < 2) return;+ // upload only when the video moved on: texImage2D from video is the expensive part+ if (this.video.currentTime === this.lastTime && this.video.paused) return;+ this.lastTime = this.video.currentTime;+ gl.viewport(0, 0, this.canvas.width, this.canvas.height);+ gl.bindTexture(gl.TEXTURE_2D, this.tex);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, this.video);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ }+}diff --git a/skills/alpha-cutout/scripts/key.py b/skills/alpha-cutout/scripts/key.pynew file mode 100644index 0000000..63ef7f0--- /dev/null+++ b/skills/alpha-cutout/scripts/key.py@@ -0,0 +1,236 @@+#!/usr/bin/env python3+"""Key a generated clip shot on a flat colour plate into real alpha, frame by frame.++ python3 key.py clip.mp4 --stacked out.mp4 [--width 1080] # H.264 colour over matte, any browser+ python3 key.py clip.mp4 --webm out.webm [--width 720] # VP9 with alpha (Chrome, Firefox, Edge)+ python3 key.py clip.mp4 --frames out_dir [--width 960 --step 2] # RGBA WebP sequence + manifest.json+ python3 key.py clip.mp4 --png out_dir --frame-list 0,30,60 # full-size RGBA PNGs to inspect+ python3 key.py image.png --png out_dir # stills work too++--key magenta (default) | green | blue. The plate colour is measured per frame from the+frame's own border (top band and upper side columns, where the subject rarely reaches),+because video models drift it: a #FF00FF plate can come back pale pink halfway through.++Matte: the key's "excess" e (magenta: min(R,B) - G; green: G - max(R,B); blue: B - max(R,G))+is high on the plate and low on the subject. With K the frame's plate colour:+ a = (0.97 e_K - e) / (0.97 e_K - solid) clipped to 0..1+Edges are then unmixed against K, F = (C - (1 - a) K) / a, which recovers the real edge+colour instead of a tinted fringe; whatever spill survives is clamped.++Colour under fully transparent pixels is the subject's own edge colour pushed outward. Video+and lossy WebP subsample chroma, so whatever sits next to an edge bleeds into it: a flat fill+there draws a coloured line round the subject.++Needs: pip install numpy opencv-python-headless pillow; ffmpeg on PATH.+"""+import argparse+import json+import subprocess+from pathlib import Path++import cv2+import numpy as np+from PIL import Image++EXCESS = {+ "magenta": lambda f: np.minimum(f[..., 0], f[..., 2]) - f[..., 1],+ "green": lambda f: f[..., 1] - np.maximum(f[..., 0], f[..., 2]),+ "blue": lambda f: f[..., 2] - np.maximum(f[..., 0], f[..., 1]),+}+# channel a surviving spill shows up in, and the channels whose max caps it at the edge+SPILL = {"magenta": (2, (1, 1)), "green": (1, (0, 2)), "blue": (2, (0, 1))}+++def frames(path):+ if Path(path).suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"):+ yield np.array(Image.open(path).convert("RGB"))+ return+ cap = cv2.VideoCapture(str(path))+ while True:+ ok, bgr = cap.read()+ if not ok:+ break+ yield cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)+ cap.release()+++def fps_of(path):+ cap = cv2.VideoCapture(str(path))+ fps = cap.get(cv2.CAP_PROP_FPS) or 24+ cap.release()+ return fps+++def plate_colour(rgb):+ h, w, _ = rgb.shape+ b = max(4, w // 100)+ ring = np.concatenate([rgb[:b].reshape(-1, 3), rgb[: int(h * 0.7), :b].reshape(-1, 3),+ rgb[: int(h * 0.7), -b:].reshape(-1, 3)])+ return np.median(ring, axis=0)+++def key(rgb, opts):+ excess = EXCESS[opts.key]+ k = plate_colour(rgb)+ k_ex = float(excess(k[None, None].astype(np.float32))[0, 0])+ if k_ex < opts.solid + 8:+ raise SystemExit(f"plate colour {k.round().tolist()} is not a {opts.key} plate (excess {k_ex:.0f}); "+ f"check --key, or the subject touches the top edge")+ high = 0.97 * k_ex+ f = rgb.astype(np.float32)+ a = np.clip((high - excess(f)) / max(high - opts.solid, 1.0), 0.0, 1.0)+ ka = np.maximum(a, 0.25)[..., None] # floor keeps compression noise from exploding+ f = np.where((a < 0.999)[..., None], (f - (1 - ka) * k.astype(np.float32)) / ka, f)+ f = np.clip(f, 0, 255)+ a8 = (a * 255).astype(np.uint8)+ a8 = cv2.morphologyEx(a8, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))+ a8 = cv2.morphologyEx(a8, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))+ if opts.erode:+ a8 = cv2.erode(a8, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=opts.erode)+ a = cv2.GaussianBlur(a8, (0, 0), 0.6).astype(np.float32) / 255.0+ # spill that survives the unmix: magenta shows as excess blue (red is left alone so red+ # subjects keep their edges), green and blue as excess of their own channel+ c, others = SPILL[opts.key]+ cap = np.maximum(f[..., others[0]], f[..., others[1]]) + opts.solid * (2 if opts.key == "magenta" else 1)+ f[..., c] = np.where(a < 0.999, np.minimum(f[..., c], cap), f[..., c])+ return f.astype(np.uint8), a, k+++def under_colour(col, a, fill):+ f = col.astype(np.float32)+ w = a.astype(np.float32)+ out = np.empty_like(f)+ out[:] = np.array(fill, np.float32)+ have = np.zeros(a.shape, bool)+ for sigma in (3, 10):+ den = cv2.GaussianBlur(w, (0, 0), sigma)+ num = cv2.GaussianBlur(f * w[..., None], (0, 0), sigma)+ ok = (den > 1e-3) & ~have+ out[ok] = num[ok] / den[ok][..., None]+ have |= ok+ near = cv2.dilate((a > 0.02).astype(np.uint8), np.ones((33, 33), np.uint8)) > 0+ out[~near] = np.array(fill, np.float32)+ return np.where((a > 0.02)[..., None], f, out).astype(np.uint8)+++def resize(img, width):+ if not width or img.shape[1] == width:+ return img+ h = round(img.shape[0] * width / img.shape[1] / 2) * 2+ return cv2.resize(img, (width, h), interpolation=cv2.INTER_AREA)+++def size_for(clip, width):+ first = next(frames(clip))+ w = (width or first.shape[1]) // 2 * 2+ return w, round(first.shape[0] * w / first.shape[1] / 2) * 2+++def pipe(cmd):+ return subprocess.Popen(cmd, stdin=subprocess.PIPE)+++def write_stacked(clip, out, opts):+ w, h = size_for(clip, opts.width)+ fps = opts.fps or fps_of(clip)+ proc = pipe(["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h * 2}",+ "-r", str(fps), "-i", "-", "-c:v", "libx264", "-profile:v", "high", "-pix_fmt", "yuv420p",+ "-crf", str(opts.crf), "-preset", "slow", "-movflags", "+faststart", "-an", str(out)])+ n = 0+ for rgb in frames(clip):+ col, a, _ = key(rgb, opts)+ col = cv2.resize(under_colour(col, a, opts.fill_rgb), (w, h), interpolation=cv2.INTER_AREA)+ m = cv2.resize((a * 255).astype(np.uint8), (w, h), interpolation=cv2.INTER_AREA)+ proc.stdin.write(np.vstack([col, np.repeat(m[..., None], 3, axis=2)]).tobytes())+ n += 1+ proc.stdin.close()+ proc.wait()+ print(json.dumps({"out": str(out), "kind": "stacked", "frames": n, "width": w, "height": h, "fps": fps}))+++def write_webm(clip, out, opts):+ w, h = size_for(clip, opts.width)+ fps = opts.fps or fps_of(clip)+ proc = pipe(["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgba", "-s", f"{w}x{h}",+ "-r", str(fps), "-i", "-", "-c:v", "libvpx-vp9", "-pix_fmt", "yuva420p", "-b:v", "0",+ "-crf", str(opts.crf + 10), "-auto-alt-ref", "0", "-row-mt", "1", "-an", str(out)])+ n = 0+ for rgb in frames(clip):+ col, a, _ = key(rgb, opts)+ rgba = np.dstack([under_colour(col, a, opts.fill_rgb), (a * 255).astype(np.uint8)])+ proc.stdin.write(cv2.resize(rgba, (w, h), interpolation=cv2.INTER_AREA).tobytes())+ n += 1+ proc.stdin.close()+ proc.wait()+ print(json.dumps({"out": str(out), "kind": "webm", "frames": n, "width": w, "height": h, "fps": fps}))+++def write_frames(clip, out_dir, opts):+ out_dir = Path(out_dir)+ out_dir.mkdir(parents=True, exist_ok=True)+ picks = {int(x) for x in opts.picks.split(",")} if opts.picks else None+ picked = []+ for i, rgb in enumerate(frames(clip)):+ if picks is not None:+ if i not in picks:+ continue+ elif i < opts.start or (opts.end is not None and i > opts.end) or (i - opts.start) % opts.step:+ continue+ col, a, _ = key(rgb, opts)+ rgba = resize(np.dstack([under_colour(col, a, opts.fill_rgb), (a * 255).astype(np.uint8)]), opts.width)+ Image.fromarray(rgba).save(out_dir / f"{len(picked):03d}.webp", "WEBP", quality=opts.quality, method=6,+ alpha_quality=90)+ picked.append(i)+ w, h = Image.open(out_dir / "000.webp").size+ (out_dir / "manifest.json").write_text(json.dumps({"count": len(picked), "width": w, "height": h,+ "pattern": "{i:03d}.webp", "source_frames": picked}))+ print(json.dumps({"out": str(out_dir), "kind": "frames", "count": len(picked), "width": w, "height": h}))+++def write_png(clip, out_dir, opts):+ out_dir = Path(out_dir)+ out_dir.mkdir(parents=True, exist_ok=True)+ want = {int(x) for x in opts.frame_list.split(",")}+ for i, rgb in enumerate(frames(clip)):+ if i in want:+ col, a, k = key(rgb, opts)+ Image.fromarray(np.dstack([col, (a * 255).astype(np.uint8)])).save(out_dir / f"f{i:03d}.png")+ print(f"frame {i}: plate {k.round().astype(int).tolist()}, {100 * (a > 0.5).mean():.1f}% subject")+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("clip")+ ap.add_argument("--stacked", help="H.264 mp4, colour on top, matte below")+ ap.add_argument("--webm", help="VP9 webm with an alpha channel")+ ap.add_argument("--frames", help="directory for an RGBA WebP sequence")+ ap.add_argument("--png", help="directory for full-size RGBA PNGs")+ ap.add_argument("--key", choices=list(EXCESS), default="magenta")+ ap.add_argument("--frame-list", default="0")+ ap.add_argument("--width", type=int)+ ap.add_argument("--fps", type=float)+ ap.add_argument("--start", type=int, default=0)+ ap.add_argument("--end", type=int)+ ap.add_argument("--step", type=int, default=1)+ ap.add_argument("--picks", help="comma list of source frames for --frames")+ ap.add_argument("--quality", type=int, default=82, help="WebP quality")+ ap.add_argument("--crf", type=int, default=20)+ ap.add_argument("--solid", type=float, default=12, help="key excess at or below this is solid subject")+ ap.add_argument("--erode", type=int, default=0, help="shave N px off the matte edge")+ ap.add_argument("--fill", default="808080", help="hex colour far from the subject under alpha 0")+ opts = ap.parse_args()+ opts.fill_rgb = [int(opts.fill[i:i + 2], 16) for i in (0, 2, 4)]+ if not any([opts.stacked, opts.webm, opts.frames, opts.png]):+ ap.error("choose at least one of --stacked, --webm, --frames, --png")+ if opts.stacked:+ write_stacked(opts.clip, opts.stacked, opts)+ if opts.webm:+ write_webm(opts.clip, opts.webm, opts)+ if opts.frames:+ write_frames(opts.clip, opts.frames, opts)+ if opts.png:+ write_png(opts.clip, opts.png, opts)+++if __name__ == "__main__":+ main()diff --git a/skills/alpha-cutout/scripts/plate.py b/skills/alpha-cutout/scripts/plate.pynew file mode 100644index 0000000..c45b695--- /dev/null+++ b/skills/alpha-cutout/scripts/plate.py@@ -0,0 +1,79 @@+#!/usr/bin/env python3+"""Put a cut-out subject on a flat key plate, ready to animate with an image-to-video model.++ python3 plate.py subject.png plate.png [--key auto|magenta|green|blue] [--size 1350x1800]+ [--fit 0.82] [--anchor bottom|center] [--margin 0.04]++subject.png must have alpha (cut it out first: rembg, Apple Vision, Photoshop, any tool).+The subject is scaled to --fit of the plate height and placed on a pure key colour with+room to move: a serve, a jump or a head turn needs headroom the still never had.++--key auto picks the key colour the subject collides with least, and every run prints the+collision report: the share of the subject's opaque pixels whose own key excess is close+to the plate's. Above about 0.5% the key will eat into the subject; pick another key or+recolour those details before generating anything.+"""+import argparse++import numpy as np+from PIL import Image++PLATES = {"magenta": (255, 0, 255), "green": (0, 255, 0), "blue": (0, 0, 255)}+EXCESS = {+ "magenta": lambda f: np.minimum(f[..., 0], f[..., 2]) - f[..., 1],+ "green": lambda f: f[..., 1] - np.maximum(f[..., 0], f[..., 2]),+ "blue": lambda f: f[..., 2] - np.maximum(f[..., 0], f[..., 1]),+}+++def collisions(rgba):+ f = rgba[..., :3].astype(np.float32)+ opaque = rgba[..., 3] > 200+ out = {}+ for name, ex in EXCESS.items():+ e = ex(f)[opaque]+ out[name] = (float((e > 60).mean() * 100), float(np.percentile(e, 99.5)) if e.size else 0.0)+ return out+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("subject")+ ap.add_argument("out")+ ap.add_argument("--key", choices=["auto", *PLATES], default="auto")+ ap.add_argument("--size", default="1350x1800", help="plate size WxH; match the video model's aspect")+ ap.add_argument("--fit", type=float, default=0.82, help="subject height as a share of the plate")+ ap.add_argument("--anchor", choices=["bottom", "center"], default="bottom")+ ap.add_argument("--margin", type=float, default=0.04, help="gap below the subject, share of height")+ args = ap.parse_args()++ im = Image.open(args.subject)+ if im.mode != "RGBA" or im.getchannel("A").getextrema()[0] == 255:+ raise SystemExit("subject has no transparency; cut it out first")+ im = im.crop(im.getchannel("A").getbbox())+ rgba = np.array(im)+ report = collisions(rgba)+ for name, (share, p995) in report.items():+ print(f"{name:8s} {share:5.2f}% of the subject would key out (99.5th pct excess {p995:.0f})")+ key = min(report, key=lambda k: report[k][0]) if args.key == "auto" else args.key+ if report[key][0] > 0.5:+ print(f"warning: {report[key][0]:.2f}% of the subject is close to {key}; the key will bite into it")++ W, H = (int(v) for v in args.size.lower().split("x"))+ s = args.fit * H / im.height+ if im.width * s > W * 0.94:+ s = W * 0.94 / im.width+ im = im.resize((round(im.width * s), round(im.height * s)), Image.LANCZOS)+ x = (W - im.width) // 2+ y = H - im.height - round(args.margin * H) if args.anchor == "bottom" else (H - im.height) // 2+ plate = Image.new("RGBA", (W, H), PLATES[key] + (255,))+ # hard-edged alpha: soft edges pre-blended with the plate colour teach the model a fringe+ a = np.array(im.getchannel("A"))+ im.putalpha(Image.fromarray(np.where(a > 127, 255, 0).astype(np.uint8)))+ plate.alpha_composite(im, (x, y))+ plate.convert("RGB").save(args.out)+ print(f"key {key}: wrote {args.out} {W}x{H}, subject {im.width}x{im.height} at ({x},{y})")+++if __name__ == "__main__":+ main()diff --git a/skills/cursor-rig/SKILL.md b/skills/cursor-rig/SKILL.mdnew file mode 100644index 0000000..a8aa83e--- /dev/null+++ b/skills/cursor-rig/SKILL.md@@ -0,0 +1,97 @@+---+name: cursor-rig+description: Makes a painted or illustrated character turn its head to follow the visitor's cursor, looking like one continuous painting that moves, without a 3D model or face tracking. Generates head-pose keyframes with an image-editing model and head-turn clips with an image-to-video model, then builds a pose grid on one fixed body (selected by measured head position, aligned, masked, with optical-flow in-betweens) and plays it with a spring-driven canvas player that also blinks. Use when someone wants a hero character, mascot or portrait whose eyes or face follow the mouse, a "look at the cursor" effect, or an illustration that reacts to the visitor.+---++# Cursor rig++A character who looks at you is the strongest hero a page can have. Building one in 3D means modelling, rigging and matching a painting's style, and the result never quite looks like the painting. This skill keeps the painting. It renders the head in every direction once, as a grid of poses, and at runtime shows the pose that faces the cursor. With 19 yaw steps and 8 pitch rows, the turn reads as continuous.++## Tools++| File | What it does |+| --- | --- |+| `scripts/build_rig.py` | Turns head-turn clips into `row_N.webp` pose strips, `plate.webp` and `rig.json` |+| `assets/rig.js` | Loads the rig, places a canvas over the head, follows the pointer with a spring, blinks, glances about when idle |++Needs Python 3.9+, `pip install numpy opencv-python-headless`, ffmpeg, an image-editing model and an image-to-video model that accepts start and end frames (see `motion-assets`).++## Pipeline++### 1. The plate++The plate is the character facing forward: the one image every pose is built on. Upscale the source illustration to at least 1440 px tall. If the hero needs to be wider than the character, outpaint the sides for the page, but build the rig on the square or portrait crop around the character. Outpainting models re-render the whole image, so paste the original pixels back over the middle afterwards.++### 2. Keyframes++With an image-editing model, make the head turned to each extreme from the plate: left, right, up, down, and the four diagonals. The prompt must pin everything except the head:++> Same character, same painting, same framing and crop. Only the head turns to look toward the left edge of the image, about 40 degrees. Hair, face, skin, shirt, hands, body pose, background and brush style stay exactly the same. No new objects.++Flick between the plate and each keyframe at full size. Only the head may change. Models that hold framing almost pixel-exact are worth paying for here; a keyframe with a shifted shoulder costs a whole row.++### 3. Head-turn clips++Image-to-video, start frame = the plate, end frame = a keyframe, 5 seconds, camera locked off:++> Locked-off camera. The character slowly turns only his head and neck from facing forward to [the end pose]. The body, shirt, arms and background stay perfectly still. Smooth, even motion, no blinking, no talking.++Name the clips by row and side: `L.mp4` and `R.mp4` for the level row (required), `UL`/`UR` (up), `HL`/`HR` (half down), `DL`/`DR` (down). Eight clips make a full rig. Two make a rig that only turns left and right.++If two rows differ a lot (the model redrew the hair in the down keyframes, say), do not rely on morphing between them: generate a real middle row instead.++### 4. Build++```bash+python3 scripts/build_rig.py clips/ site/rig --box 300,40,840,800 --track dots --debug work/rig-cells+```++- `--box x,y,w,h` (plate pixels): everything the head ever covers, hair included, with a little neck.+- `--track dots` for cartoon dot eyes: finds the two dark round eyes in every frame, and records their positions so blinks can be painted live. `--eye-band y0,y1` and `--dark` tune it.+- `--track template --point x,y` for any other face: follows a patch around a point you give (the bridge of the nose works) from frame to frame. No blinks are painted with this mode.+- `--poly` sets the head mask polygon if the default oval cuts the hair or includes the collar.++What the script does, and why:++- **Aligns every clip on the body** (ECC, rows below `--body-y`). Video models drift the whole frame a few pixels; without alignment the shirt jitters as the head turns. It prints the drift per clip; above 6 px, the clip was not locked off.+- **Picks columns by measured head position, not by time.** Models ease in and out, so evenly spaced timestamps give uneven steps. Even steps of the measure give an even turn.+- **Blends each head onto the one plate body** through a feathered mask, after matching brightness to the plate, so only the head ever changes.+- **Fills missing pitch rows** with optical-flow in-betweens of the neighbouring rows.++Open the `--debug` cells as a contact sheet and look down every column and across every row: no jumps in head size, no hair popping, no collar seams.++### 5. Page++```html+<figure class="hero-rig" style="position: relative; margin: 0">+ <img src="rig/plate.webp" alt="A painted shopkeeper in a loud shirt, looking at you">+ <canvas></canvas>+</figure>+<script type="module">+ import { loadRig, HeadRig, animate } from "./rig.js";+ const head = new HeadRig(document.querySelector(".hero-rig"), await loadRig("rig/"));+ animate([head]);+</script>+```++If the page shows a wider artwork than the plate, pass where the plate sits in it, in artwork pixels: `new HeadRig(el, data, { art: { w: 3898, h: 1440, plateX: 1229, plateY: 0 } })`.++The player:++- loads the level row first (the head can turn left and right at once), then the rows above and below;+- aims with `tanh` of the pointer's offset from the eyes, so far corners do not snap the head to its limit;+- moves through a slightly under-damped spring (a small settle at the end of each turn reads as alive);+- cuts between neighbouring poses instead of cross-fading (a cross-fade shows two pairs of eyes);+- paints blinks, double blinks and winks over the eyes using the eye positions and skin tones in `rig.json` (dot tracking only);+- glances about by itself when the pointer has been still for 3.5 s, and on touch devices;+- pauses when off screen.++## Budget++Eight clips is the full cost; at typical image-to-video prices that is a few dollars. The finished rig (152 poses at 0.6 scale) is about 2 MB of WebP.++## Accessibility++- The plate `<img>` carries the alt text; the canvas is decoration.+- With `prefers-reduced-motion`, the head still answers the pointer (the visitor is causing it) but critically damped, with no idle glancing and no blinks.+- Nothing depends on the rig: it is a portrait that happens to look at you.diff --git a/skills/cursor-rig/agents/openai.yaml b/skills/cursor-rig/agents/openai.yamlnew file mode 100644index 0000000..f785084--- /dev/null+++ b/skills/cursor-rig/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Cursor Rig"+ short_description: "A painted character whose head follows the cursor, no 3D needed"diff --git a/skills/cursor-rig/assets/rig.js b/skills/cursor-rig/assets/rig.jsnew file mode 100644index 0000000..c529ad8--- /dev/null+++ b/skills/cursor-rig/assets/rig.js@@ -0,0 +1,205 @@+// Cursor-following head rig. The page shows a still image (the plate, or a wider artwork the+// plate sits inside); a <canvas> placed exactly over the head paints one cell from a grid of+// pre-rendered head poses (rows = pitch, up -> down; columns = yaw, image-left -> image-right),+// built by scripts/build_rig.py.+//+// <figure class="rig" style="position: relative">+// <img src="rig/plate.webp" alt="..."> <!-- or your wider hero artwork -->+// <canvas class="rig-head" style="position: absolute"></canvas>+// </figure>+//+// import { loadRig, HeadRig, animate } from "./rig.js";+// const data = await loadRig("rig/");+// const head = new HeadRig(document.querySelector(".rig"), data);+// animate([head]);+//+// If the plate sits inside a wider artwork (an outpainted hero), say where, in artwork pixels:+// new HeadRig(el, data, { art: { w: 3898, h: 1440, plateX: 1229, plateY: 0 } })++const rand = (a, b) => a + Math.random() * (b - a);+const clamp = (v, a, b) => Math.min(b, Math.max(a, v));+const REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;++export async function loadRig(base) {+ const rig = await (await fetch(base + "rig.json")).json();+ const imgs = new Array(rig.rows.length).fill(null);+ const load = (i) => new Promise((done) => {+ const im = new Image();+ im.decoding = "async";+ im.onload = () => { imgs[i] = im; done(); };+ im.onerror = done;+ im.src = base + rig.rows[i].src;+ });+ // the level row first so the head can turn left and right at once, then fan out up and down+ const order = rig.pitch.map((_, i) => i).sort((a, b) => Math.abs(rig.pitch[a]) - Math.abs(rig.pitch[b]));+ await load(order[0]);+ (async () => { for (const i of order.slice(1)) await load(i); })();+ return { rig, imgs };+}++export class HeadRig {+ constructor(el, data, { art = null, canvas = null, range = 1 } = {}) {+ this.el = el;+ this.canvas = canvas || el.querySelector("canvas");+ this.ctx = this.canvas.getContext("2d");+ this.rig = data.rig;+ this.imgs = data.imgs;+ this.range = range; // 0..1: how far the head may turn+ [this.fw, this.fh] = this.rig.frame;+ const [pw, ph] = this.rig.plate;+ const A = art || { w: pw, h: ph, plateX: 0, plateY: 0 };+ const [bx, by, bw, bh] = this.rig.box;+ Object.assign(this.canvas.style, {+ position: "absolute", pointerEvents: "none",+ left: ((A.plateX + bx) / A.w) * 100 + "%", top: ((A.plateY + by) / A.h) * 100 + "%",+ width: (bw / A.w) * 100 + "%", height: (bh / A.h) * 100 + "%",+ });++ // where the gaze starts from: the eyes if the rig has them, else the box's upper middle+ const level = this.rig.pitch.indexOf(0) >= 0 ? this.rig.pitch.indexOf(0) : 0;+ const e = this.rig.rows[level].cells[this.rig.center].eyes;+ this.hasEyes = !!e;+ this.eyeFx = e ? (e[0][0] + e[1][0]) / 2 / this.fw : 0.5;+ this.eyeFy = e ? (e[0][1] + e[1][1]) / 2 / this.fh : 0.42;++ this.yaw = this.pitch = this.vYaw = this.vPitch = this.tYaw = this.tPitch = 0;+ this.cur = null;+ this.lids = null; // null | "both" | "wink"+ this.lidsUntil = 0;+ this.nextBlink = performance.now() + rand(1800, 4200);+ this.visible = true;+ this.dirty = true;++ this.resize();+ new ResizeObserver(() => this.resize()).observe(this.canvas);+ new IntersectionObserver(([en]) => { this.visible = en.isIntersecting; }, { rootMargin: "120px" }).observe(el);+ }++ resize() {+ const r = this.canvas.getBoundingClientRect();+ if (!r.width) return;+ const w = Math.round(Math.min(r.width * Math.min(devicePixelRatio || 1, 2), this.fw * 1.6));+ this.canvas.width = w;+ this.canvas.height = Math.round((w * this.fh) / this.fw);+ this.dirty = true;+ }++ eyes() {+ const r = this.canvas.getBoundingClientRect();+ return { x: r.left + r.width * this.eyeFx, y: r.top + r.height * this.eyeFy, w: r.width };+ }++ // aim at a point on screen; tanh keeps far points from saturating the turn instantly+ lookAt(px, py) {+ const e = this.eyes();+ this.tYaw = Math.tanh((px - e.x) / Math.max(innerWidth * 0.3, e.w * 1.1)) * this.range;+ this.tPitch = Math.tanh((py - e.y) / Math.max(innerHeight * 0.3, e.w * 0.9)) * this.range;+ }++ lookToward(yaw, pitch) { this.tYaw = clamp(yaw, -1, 1); this.tPitch = clamp(pitch, -1, 1); }++ blink(kind = "both", ms = 130) {+ if (!this.hasEyes) return;+ this.lids = kind;+ this.lidsUntil = performance.now() + ms;+ this.dirty = true;+ }++ rowFor(p) {+ const P = this.rig.pitch;+ let best = 0;+ for (let i = 1; i < P.length; i++) if (Math.abs(P[i] - p) < Math.abs(P[best] - p)) best = i;+ if (this.imgs[best]) return best;+ let alt = -1; // the nearest row that has finished loading+ for (let i = 0; i < P.length; i++) if (this.imgs[i] && (alt < 0 || Math.abs(P[i] - p) < Math.abs(P[alt] - p))) alt = i;+ return alt;+ }++ update(dt, now) {+ // a slightly under-damped spring: the small settle at the end of a turn reads as alive+ const k = 70, c = 2 * (REDUCED ? 1 : 0.78) * Math.sqrt(k);+ this.vYaw += ((this.tYaw - this.yaw) * k - this.vYaw * c) * dt;+ this.vPitch += ((this.tPitch - this.pitch) * k - this.vPitch * c) * dt;+ this.yaw += this.vYaw * dt;+ this.pitch += this.vPitch * dt;++ if (this.hasEyes && !REDUCED && now > this.nextBlink && !this.lids) {+ this.blink("both", rand(110, 150));+ this.nextBlink = now + (Math.random() < 0.18 ? 260 : rand(2400, 5600)); // sometimes a double blink+ }+ if (this.lids && now > this.lidsUntil) { this.lids = null; this.dirty = true; }++ const half = this.rig.center;+ const col = clamp(Math.round(half + clamp(this.yaw, -1, 1) * half), 0, this.rig.cols - 1);+ const row = this.rowFor(clamp(this.pitch, -1, 1));+ if (row < 0) return;+ const key = row * 1000 + col;+ // hard cuts between neighbouring poses: a cross-fade doubles the eyes+ if (!this.cur || this.cur.key !== key) { this.cur = { key, row, col }; this.dirty = true; }+ if (this.dirty) this.draw();+ }++ draw() {+ this.dirty = false;+ const { ctx, canvas, cur } = this;+ if (!cur || !canvas.width) return;+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ ctx.drawImage(this.imgs[cur.row], cur.col * this.fw, 0, this.fw, this.fh, 0, 0, canvas.width, canvas.height);+ if (this.lids) this.drawLids(this.rig.rows[cur.row].cells[cur.col]);+ }++ // closed eyes: cover each eye with its own skin tone, then draw a soft downward lid line+ drawLids(cell) {+ if (!cell.eyes) return;+ const { ctx, canvas } = this;+ const s = canvas.width / this.fw;+ cell.eyes.forEach(([x, y, r], i) => {+ if (this.lids === "wink" && i === 0) return;+ x *= s; y *= s; r *= s;+ const R = r * 1.75, skin = cell.skin[i];+ const g = ctx.createRadialGradient(x, y, R * 0.45, x, y, R);+ g.addColorStop(0, skin);+ g.addColorStop(1, skin + "00");+ ctx.fillStyle = g;+ ctx.beginPath(); ctx.arc(x, y, R, 0, Math.PI * 2); ctx.fill();+ ctx.strokeStyle = "rgba(42, 26, 20, .92)";+ ctx.lineWidth = Math.max(1.2, r * 0.42);+ ctx.lineCap = "round";+ ctx.beginPath();+ ctx.moveTo(x - r * 1.1, y - r * 0.05);+ ctx.quadraticCurveTo(x, y + r * 0.75, x + r * 1.1, y - r * 0.05);+ ctx.stroke();+ });+ }+}++// One loop drives every rig on the page. Follows the pointer while it moves; when nobody is+// around (no pointer for 3.5 s, or a touch device at rest) the head glances about by itself.+export function animate(rigs, { onIdle } = {}) {+ const ptr = { x: innerWidth / 2, y: innerHeight * 0.3, t: -1e9, inside: true };+ const idle = rigs.map(() => ({ next: 0 }));+ addEventListener("pointermove", (e) => { Object.assign(ptr, { x: e.clientX, y: e.clientY, t: performance.now(), inside: true }); }, { passive: true });+ addEventListener("pointerdown", (e) => { Object.assign(ptr, { x: e.clientX, y: e.clientY, t: performance.now() }); }, { passive: true });+ document.documentElement.addEventListener("pointerleave", () => { ptr.inside = false; });++ let last = performance.now();+ const tick = (now) => {+ const dt = Math.min(0.05, (now - last) / 1000);+ last = now;+ const active = ptr.inside && now - ptr.t < 3500;+ rigs.forEach((r, i) => {+ if (!r.visible) return;+ if (active) r.lookAt(ptr.x, ptr.y);+ else if (!REDUCED && now > idle[i].next) {+ if (Math.random() < 0.35) r.lookToward(0, rand(-0.15, 0.05));+ else r.lookToward(rand(-0.75, 0.75), rand(-0.45, 0.3));+ idle[i].next = now + rand(1400, 3200);+ onIdle && onIdle(r);+ } else if (REDUCED && !active) r.lookToward(0, 0);+ r.update(dt, now);+ });+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ return ptr;+}diff --git a/skills/cursor-rig/scripts/build_rig.py b/skills/cursor-rig/scripts/build_rig.pynew file mode 100644index 0000000..f22deaf--- /dev/null+++ b/skills/cursor-rig/scripts/build_rig.py@@ -0,0 +1,342 @@+#!/usr/bin/env python3+"""Build a cursor-following head rig (a grid of head poses on one fixed body) from head-turn clips.++ python3 build_rig.py CLIPS_DIR OUT_DIR --box X,Y,W,H [--track dots|template] [--point X,Y]+ [--cols 19] [--out-scale 0.6] [--prefix ""] [--poly "x,y;x,y;..."]++CLIPS_DIR holds locked-off clips where only the head and neck move, all starting from the+same forward-facing frame (the plate) and turning to one side:+ L.mp4, R.mp4 level row: forward -> image-left, forward -> image-right (required)+ UL.mp4, UR.mp4 the same with the head tilted up (optional)+ HL.mp4, HR.mp4 half-way down (optional)+ DL.mp4, DR.mp4 tilted down (optional)+(--prefix sw_ reads sw_L.mp4 and so on.) All coordinates are in plate pixels, i.e. pixels of+the clips' frames. --box is the head box the rig repaints: the whole head and hair at every+pose, plus a little neck.++How it works:+ 1. Every clip is aligned to the plate (first frame of L) with ECC on the body region+ (rows below --body-y), so every head lands on one fixed body.+ 2. Each frame's head position is measured: --track dots finds two dark round eyes (cartoon+ dot eyes); --track template follows a patch around --point (the nose bridge works) for+ any face. Columns are picked at evenly spaced positions of that measure, not evenly in+ time, so the steps are even even where the model eased in and out.+ 3. Each picked frame is gain-matched to the plate, blended onto it through a feathered head+ mask (--poly, or an oval in the box) and cropped to the box.+ 4. Missing pitch rows in between are filled by optical-flow morphs of the neighbours.+ 5. Writes row_N.webp strips (one cell per yaw step) and rig.json (geometry, pitch per row,+ and with dot tracking the eye positions and skin tone per cell, for live blinks).++Needs: pip install numpy opencv-python-headless; ffmpeg on PATH.+"""+import argparse+import json+import subprocess+import tempfile+from pathlib import Path++import cv2+import numpy as np++ROWS = [("U", -1.0), ("M", 0.0), ("H", 0.5), ("D", 1.0)] # pitch: -1 up .. +1 down+++def clip_name(row, side):+ return side if row == "M" else row + side+++def extract(clips, prefix, name, tmp):+ src = clips / f"{prefix}{name}.mp4"+ if not src.exists():+ return None+ out = tmp / name+ out.mkdir(parents=True, exist_ok=True)+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(src), str(out / "%04d.png")], check=True)+ return sorted(out.glob("*.png"))+++def ecc_align(plate_g, img_g, body_y):+ """Affine warp mapping plate coords to img coords, fitted on the body only."""+ s = 0.5+ a = cv2.resize(plate_g, None, fx=s, fy=s).astype(np.float32)+ b = cv2.resize(img_g, None, fx=s, fy=s).astype(np.float32)+ mask = np.zeros(a.shape, np.uint8)+ mask[int(body_y * s):, :] = 255+ warp = np.eye(2, 3, dtype=np.float32)+ try:+ _, warp = cv2.findTransformECC(a, b, warp, cv2.MOTION_AFFINE,+ (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 200, 1e-6), mask, 5)+ except cv2.error:+ warp = np.eye(2, 3, dtype=np.float32)+ warp[:, 2] /= s+ return warp+++def to_plate(img, warp, w, h):+ return cv2.warpAffine(img, warp, (w, h), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderMode=cv2.BORDER_REPLICATE)+++class DotEyes:+ """Two dark round dots side by side in the eye band. Sizes are relative to the box."""++ def __init__(self, box, band, dark):+ bx, by, bw, bh = box+ self.x0, self.x1 = bx, bx + bw+ self.y0, self.y1 = band+ a = bw * bh+ self.amin, self.amax = 0.00025 * a, 0.0018 * a+ self.dx = (0.05 * bw, 0.2 * bw)+ self.dy = 0.04 * bh+ self.dark = dark++ def __call__(self, img):+ g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[self.y0:self.y1, self.x0:self.x1]+ n, _, st, cen = cv2.connectedComponentsWithStats((g < self.dark).astype(np.uint8), 8)+ c = []+ for i in range(1, n):+ x, y, w, h, a = st[i]+ if self.amin < a < self.amax and a / (w * h) > 0.6 and 0.5 < w / h < 1.4:+ c.append((cen[i][0] + self.x0, cen[i][1] + self.y0, (a / np.pi) ** 0.5, a))+ best, score = None, 1e9+ for i in range(len(c)):+ for j in range(i + 1, len(c)):+ p, q = c[i], c[j]+ dx, dy = abs(p[0] - q[0]), abs(p[1] - q[1])+ if self.dx[0] < dx < self.dx[1] and dy < self.dy:+ sc = dy + abs(p[3] - q[3]) / 40+ if sc < score:+ best, score = sorted([p, q]), sc+ if best is None:+ return None, None+ eyes = [(float(x), float(y), float(r)) for x, y, r, _ in best]+ return ((eyes[0][0] + eyes[1][0]) / 2, (eyes[0][1] + eyes[1][1]) / 2), eyes+++class Template:+ """Follows a patch around a facial point from frame to frame (frames come in order)."""++ def __init__(self, point, box):+ self.start = np.array(point, float)+ self.half = max(8, int(box[2] * 0.06))+ self.search = int(box[2] * 0.12)+ self.reset()++ def reset(self):+ self.pos, self.tpl = self.start.copy(), None++ def __call__(self, img):+ g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)+ x, y, h = int(self.pos[0]), int(self.pos[1]), self.half+ if self.tpl is None:+ self.tpl = g[y - h:y + h, x - h:x + h].copy()+ return (float(x), float(y)), None+ s = self.search+ y0, x0 = max(0, y - h - s), max(0, x - h - s)+ win = g[y0:y + h + s, x0:x + h + s]+ if win.shape[0] < self.tpl.shape[0] or win.shape[1] < self.tpl.shape[1]:+ return None, None+ r = cv2.matchTemplate(win, self.tpl, cv2.TM_CCOEFF_NORMED)+ _, conf, _, loc = cv2.minMaxLoc(r)+ if conf < 0.4:+ return None, None+ self.pos = np.array([x0 + loc[0] + h, y0 + loc[1] + h], float)+ nx, ny = int(self.pos[0]), int(self.pos[1])+ self.tpl = g[ny - h:ny + h, nx - h:nx + h].copy() # follow the slowly changing view+ return (float(self.pos[0]), float(self.pos[1])), None+++def bg_gain(img, plate):+ pts = [(slice(10, 60), slice(10, 110)), (slice(10, 60), slice(-110, -10))]+ a = np.mean([img[p].reshape(-1, 3).mean(0) for p in pts], 0)+ b = np.mean([plate[p].reshape(-1, 3).mean(0) for p in pts], 0)+ return b / np.maximum(a, 1)+++def head_mask(w, h, box, poly, feather):+ m = np.zeros((h, w), np.float32)+ if poly:+ cv2.fillPoly(m, [np.array(poly, np.int32)], 1.0)+ else:+ bx, by, bw, bh = box+ cv2.ellipse(m, (int(bx + bw / 2), int(by + bh * 0.46)), (int(bw * 0.46), int(bh * 0.46)), 0, 0, 360, 1.0, -1)+ k = feather * 2 + 1+ return cv2.GaussianBlur(m, (k, k), feather / 2.5)+++_DIS = None+++def flow_morph(a, b, t):+ global _DIS+ if _DIS is None:+ _DIS = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)+ _DIS.setFinestScale(0)+ _DIS.setPatchSize(12)+ _DIS.setGradientDescentIterations(25)+ _DIS.setVariationalRefinementIterations(10)+ _DIS.setVariationalRefinementAlpha(40)+ ga, gb = cv2.cvtColor(a, cv2.COLOR_BGR2GRAY), cv2.cvtColor(b, cv2.COLOR_BGR2GRAY)+ fab, fba = _DIS.calc(ga, gb, None), _DIS.calc(gb, ga, None)+ h, w = ga.shape+ gx, gy = np.meshgrid(np.arange(w, dtype=np.float32), np.arange(h, dtype=np.float32))+ at = cv2.remap(a, gx + t * fba[..., 0], gy + t * fba[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)+ bt = cv2.remap(b, gx + (1 - t) * fab[..., 0], gy + (1 - t) * fab[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)+ return cv2.addWeighted(at, 1 - t, bt, t, 0)+++def skin_tone(img, eyes):+ """Skin colour in a ring round each eye (lashes and brows excluded), for painting lids."""+ h, w = img.shape[:2]+ out = []+ for x, y, r in eyes:+ x0, x1, y0, y1 = max(int(x - 3 * r), 0), min(int(x + 3 * r), w), max(int(y - 3 * r), 0), min(int(y + 3 * r), h)+ gy, gx = np.mgrid[y0:y1, x0:x1]+ d = np.hypot(gx - x, gy - y)+ px = img[y0:y1, x0:x1][(d > 1.6 * r) & (d < 2.5 * r)].astype(np.float32)+ if not len(px):+ out.append("#c08070")+ continue+ lum = px.mean(1)+ px = px[(lum > np.percentile(lum, 40)) & (lum < np.percentile(lum, 95))]+ b, g, rr = np.median(px, 0)+ out.append("#%02x%02x%02x" % (int(rr), int(g), int(b)))+ return out+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("clips", type=Path)+ ap.add_argument("out", type=Path)+ ap.add_argument("--box", required=True, help="head box x,y,w,h in plate px")+ ap.add_argument("--prefix", default="")+ ap.add_argument("--track", choices=["dots", "template"], default="dots")+ ap.add_argument("--point", help="template tracking: x,y of a facial point at the forward pose")+ ap.add_argument("--eye-band", help="dots: y0,y1 band where the eyes can be (default: middle of the box)")+ ap.add_argument("--dark", type=int, default=70, help="dots: grey level below which a pixel can be an eye")+ ap.add_argument("--body-y", type=int, help="rows below this are body only, used for alignment (default: box bottom)")+ ap.add_argument("--cols", type=int, default=19, help="yaw steps per row (odd, so the centre is forward)")+ ap.add_argument("--out-scale", type=float, default=0.6)+ ap.add_argument("--between", type=int, default=3, help="rows per pitch unit; gaps are filled with morphs")+ ap.add_argument("--quality", type=int, default=82)+ ap.add_argument("--feather", type=int, default=28)+ ap.add_argument("--poly", default="", help="head mask polygon x,y;x,y;... (default: an oval in the box)")+ ap.add_argument("--debug", type=Path, help="write full-size cells here for inspection")+ a = ap.parse_args()++ bx, by, bw, bh = map(int, a.box.split(","))+ box = (bx, by, bw, bh)+ cols = a.cols if a.cols % 2 else a.cols + 1+ a.out.mkdir(parents=True, exist_ok=True)+ tmp = Path(tempfile.mkdtemp(prefix="rig-"))++ level = extract(a.clips, a.prefix, "L", tmp)+ if not level:+ raise SystemExit(f"need {a.prefix}L.mp4 and {a.prefix}R.mp4 in {a.clips}")+ plate = cv2.imread(str(level[0]))+ H, W = plate.shape[:2]+ plate_g = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)+ body_y = a.body_y or min(H - 20, by + bh)+ if a.track == "dots":+ band = tuple(map(int, a.eye_band.split(","))) if a.eye_band else (by + int(bh * 0.2), by + int(bh * 0.65))+ tracker = DotEyes(box, band, a.dark)+ else:+ if not a.point:+ raise SystemExit("--track template needs --point x,y")+ tracker = Template(tuple(map(float, a.point.split(","))), box)+ poly = [tuple(map(int, p.split(","))) for p in a.poly.split(";")] if a.poly else None+ mask = head_mask(W, H, box, poly, a.feather)[..., None]+ if a.debug:+ a.debug.mkdir(parents=True, exist_ok=True)+ cv2.imwrite(str(a.debug / "plate.png"), plate)+ cv2.imwrite(str(a.debug / "mask.png"), (mask[..., 0] * 255).astype(np.uint8))++ src = {}+ for row, pitch in ROWS:+ fl = level if row == "M" else extract(a.clips, a.prefix, clip_name(row, "L"), tmp)+ fr = extract(a.clips, a.prefix, clip_name(row, "R"), tmp)+ if not fl or not fr:+ if row == "M":+ raise SystemExit(f"need {a.prefix}R.mp4 too")+ continue+ seq = [] # (measure_x, path, warp, eyes)+ centre = None+ for frames, left in ((fl, True), (fr, False)):+ warp = ecc_align(plate_g, cv2.cvtColor(cv2.imread(str(frames[0])), cv2.COLOR_BGR2GRAY), body_y)+ drift = np.abs(warp - ecc_align(plate_g, cv2.cvtColor(cv2.imread(str(frames[-1])), cv2.COLOR_BGR2GRAY), body_y))[:, 2].max()+ print(f"{frames[0].parent.name}: body drift first->last {drift:.1f}px" + (" (high: was the camera locked off?)" if drift > 6 else ""))+ if isinstance(tracker, Template):+ tracker.reset()+ for p in frames:+ m, eyes = tracker(to_plate(cv2.imread(str(p)), warp, W, H))+ if m is None:+ continue+ if p == frames[0] and not left:+ centre = m[0]+ if not (left and p == frames[0]):+ seq.append((m[0], p, warp, eyes))+ if len(seq) < cols:+ print(f"row {row}: only {len(seq)} tracked frames, skipped")+ continue+ xs = np.array([s[0] for s in seq])+ cx = centre if centre is not None else float(np.median(xs))+ k = cols // 2+ targets = np.concatenate([np.linspace(xs.min(), cx, k + 1)[:-1], [cx], np.linspace(cx, xs.max(), k + 1)[1:]])+ cells = []+ for t in targets:+ s = seq[int(np.argmin(np.abs(xs - t)))]+ img = to_plate(cv2.imread(str(s[1])), s[2], W, H).astype(np.float32)+ img *= bg_gain(img, plate.astype(np.float32))+ comp = np.clip(img * mask + plate.astype(np.float32) * (1 - mask), 0, 255).astype(np.uint8)+ eyes = [(x - bx, y - by, r) for x, y, r in s[3]] if s[3] else None+ cells.append((comp[by:by + bh, bx:bx + bw].copy(), eyes))+ src[row] = (pitch, cells)+ print(f"row {row}: {len(seq)} tracked frames, swing {xs.min():.0f} .. {cx:.0f} .. {xs.max():.0f}")++ crop_mask = mask[by:by + bh, bx:bx + bw]+ plate_crop = plate[by:by + bh, bx:bx + bw].astype(np.float32)+ order = [r for r, _ in ROWS if r in src]+ grid, pitch = [], []+ for i, r in enumerate(order):+ p0, cells0 = src[r]+ grid.append(cells0)+ pitch.append(p0)+ if i + 1 < len(order):+ p1, cells1 = src[order[i + 1]]+ n = max(0, round(abs(p1 - p0) * a.between) - 1)+ for t in [j / (n + 1) for j in range(1, n + 1)]:+ row = []+ for (ca, ea), (cb, eb) in zip(cells0, cells1):+ m = flow_morph(ca, cb, t).astype(np.float32) * crop_mask + plate_crop * (1 - crop_mask)+ eyes = [tuple((1 - t) * np.array(u) + t * np.array(v)) for u, v in zip(ea, eb)] if ea and eb else None+ row.append((np.clip(m, 0, 255).astype(np.uint8), eyes))+ grid.append(row)+ pitch.append(p0 + (p1 - p0) * t)++ sc = a.out_scale+ ow, oh = int(bw * sc), int(bh * sc)+ rig = {"version": 1, "plate": [W, H], "box": [bx, by, bw, bh], "frame": [ow, oh], "cols": cols, "center": cols // 2,+ "pitch": [round(p, 4) for p in pitch], "rows": []}+ for ri, row in enumerate(grid):+ strip = np.zeros((oh, ow * len(row), 3), np.uint8)+ cells = []+ for ci, (crop, eyes) in enumerate(row):+ strip[:, ci * ow:(ci + 1) * ow] = cv2.resize(crop, (ow, oh), interpolation=cv2.INTER_AREA)+ cell = {}+ if eyes:+ cell = {"eyes": [[round(x * sc, 1), round(y * sc, 1), round(r * sc, 1)] for x, y, r in eyes],+ "skin": skin_tone(crop, eyes)}+ cells.append(cell)+ if a.debug:+ cv2.imwrite(str(a.debug / f"r{ri}_c{ci:02d}.jpg"), crop)+ name = f"row_{ri}.webp"+ cv2.imwrite(str(a.out / name), strip, [cv2.IMWRITE_WEBP_QUALITY, a.quality])+ rig["rows"].append({"src": name, "cells": cells})+ print(f"row {ri} (pitch {pitch[ri]:+.2f}): {len(cells)} cells -> {name}")+ cv2.imwrite(str(a.out / "plate.webp"), plate, [cv2.IMWRITE_WEBP_QUALITY, 88]) # the body the heads sit on+ (a.out / "rig.json").write_text(json.dumps(rig, separators=(",", ":")))+ total = sum(f.stat().st_size for f in a.out.glob("*.webp"))+ print(f"done: {len(grid)} rows x {cols} poses, {total / 1e6:.1f} MB -> {a.out}")+++if __name__ == "__main__":+ main()diff --git a/skills/exploded-view/SKILL.md b/skills/exploded-view/SKILL.mdnew file mode 100644index 0000000..84e05a4--- /dev/null+++ b/skills/exploded-view/SKILL.md@@ -0,0 +1,97 @@+---+name: exploded-view+description: Builds interactive 3D explainers of how a machine or product works, in three.js, with a staged exploded view driven by a slider or scroll, x-ray shells, a section cut through the casing, labels pinned to parts with leader lines that never cover the model, and hover or click to pick parts. Works on code-built models and loaded GLB files. Use for "show how it works", teardown or cutaway pages, product anatomy, engine, motor, gearbox, camera, phone or vehicle internals, technical education pages, or turning a 2D cutaway drawing into an interactive 3D one.+---++# Exploded view++People understand a machine when they see it come apart in the order it was put together, with each part named where it sits. This skill does that in the browser: parts slide apart along sensible lines, outer shells go ghostly or get cut open, and labels follow their parts without ever sitting on top of the model.++## Tools++| File | What it does |+| --- | --- |+| `assets/explode.js` | `Exploder` (staged explode), `Labels` (pinned labels with leader lines), `Xray`, `Section` (clipping plane through shells), `Picker` (hover and click) |+| `assets/demo/` | A complete page: a code-built induction motor taken apart, with sliders, x-ray and section. `?explode=1`, `?cut=1`, `?xray=1` set the state |++Requires three.js (r169 in the demo's import map). Build the model with `threejs-scene` techniques or load a GLB.++## Build++### 1. Structure the model as parts++The unit of an exploded view is a part: a `Group` that moves as one. Make every part a direct child of one assembly group, and give each part **its own materials** (x-ray and hover change materials; shared ones would change every part at once).++For a GLB, regroup on load: walk the scene, and parent meshes into named part groups by their node names. Preserve world transforms when re-parenting (`group.attach(mesh)`).++### 2. Decide how each part moves++Per-part settings live on `userData`:++```js+housing.userData = { shell: true, stage: 0, explode: [0, 0.32, 0] }; // lifts off first+rotor.userData = { stage: 2, explode: [0.42, 0, 0] }; // slides out along the shaft last+```++- `explode: [x, y, z]` is the offset at full explosion. Without it, the part moves away from the assembly centre (along `axis` if you pass one to `Exploder`), scaled by its distance.+- `stage` orders the motion: stage 0 moves first, and each later stage starts when the previous is half done. Take things apart the way a mechanic would: covers and shells, then fasteners and caps, then the inner parts.+- `shell: true` marks casings for x-ray and section cuts.++Lay out the exploded state like a technical illustration: one main axis (the shaft, the stack direction), parts spaced so each is clear of its neighbours, large shells moved off-axis (up) so the core stays visible.++```js+const ex = new Exploder(assembly);+ex.set(t); // 0 assembled .. 1 exploded; ease toward a target each frame for slider input+```++### 3. Label the parts++```js+const labels = new Labels(document.querySelector(".labels"), camera, canvas);+labels.add(rotor, "Rotor", { note: "turns in the magnetic field", anchor: [0.03, 0.07, 0] });+// every frame, after renderer.render():+labels.update();+```++Labels sit in two columns at the screen edges, keep their anchors' vertical order and push apart when they would overlap; a leader line runs from each label to its anchor point. They follow the part as it explodes and hide when the part is hidden or behind the camera. Anchor each label on a point of the part that stays visible from the main view (the top edge, the end of a shaft), in the part's local coordinates.++Style `.label`, `.label b`, `.label span`, `.leader` and their `.focus` variants in CSS. On narrow phones, hide the labels and show the hovered or tapped part's name in one caption instead: two columns of labels do not fit beside a model on a 390 px screen.++### 4. X-ray and section++```js+const xray = new Xray(assembly); xray.set(true); // shells to 14% opacity, no depth write+renderer.localClippingEnabled = true;+const section = new Section(assembly, [0, 0, -1]); section.set(0); // cut the shells' front half away; null = off+```++The section plane cuts only shells, so the interior stays whole inside an opened casing, the way a cutaway drawing shows it. Cut materials are made double-sided so the inside of the casing reads.++### 5. Picking++```js+new Picker(canvas, camera, assembly.children, {+ onHover: (part) => highlightLabelOf(part),+ onPick: (part) => focusOn(part),+});+```++Hover tints the part's emissive slightly and switches the pointer cursor. A click can isolate the part, fly the camera to it, or open its description.++## Camera and framing++- Fit the camera to the assembly for the current screen shape, and let the distance follow the explode amount (the demo's `autoDistance`): close when assembled, pulled back when exploded. Stop doing it once the visitor zooms or orbits.+- Raise `OrbitControls.maxDistance` above the fitted distance, or the controls silently clamp it and phones see a crop.+- A three-quarter view slightly from above (the demo uses direction 0.42, 0.34, 1) shows ends and sides of a cylindrical machine at once.++## Driving it from scroll++Map scroll progress to `ex.set()` through keys with holds, as `scroll-film` does for frames: assembled while the intro reads, explode stage by stage with a caption per stage, hold fully exploded, then section cut. The model is real-time, so the visitor can stop and orbit at any point.++## Rendering++Product-shot lighting suits explainers better than a sky: a `RoomEnvironment` PMREM for reflections, one soft key light with shadows onto a `ShadowMaterial` floor, ACES tone mapping, and the page's own background colour as the clear colour (an opaque canvas defaults to black). Metals read through roughness 0.3 to 0.45 and metalness 0.8 to 0.95; painted parts through a clearcoat.++## Accuracy++If the subject is a real product, use real part names and the real assembly order, and say in the page copy which internal details are illustrative. An explainer that is wrong teaches the wrong thing confidently.diff --git a/skills/exploded-view/agents/openai.yaml b/skills/exploded-view/agents/openai.yamlnew file mode 100644index 0000000..594d354--- /dev/null+++ b/skills/exploded-view/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Exploded View"+ short_description: "Take a 3D machine apart: staged explode, x-ray, section cut, labels"diff --git a/skills/exploded-view/assets/demo/index.html b/skills/exploded-view/assets/demo/index.htmlnew file mode 100644index 0000000..9f37ba1--- /dev/null+++ b/skills/exploded-view/assets/demo/index.html@@ -0,0 +1,50 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <link rel="icon" href="data:,">+ <title>Inside an electric motor</title>+ <script type="importmap">+ { "imports": {+ "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",+ "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"+ } }+ </script>+ <style>+ :root { --paper: #eeeae2; --ink: #1d1c1a; --muted: #6f6a62; --accent: #e8642c; }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; background: var(--paper); color: var(--ink); font: 14px/1.4 ui-sans-serif, system-ui, sans-serif; overflow: hidden; }+ canvas#gl { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; }+ .labels { position: fixed; inset: 0; }+ .label { padding: 2px 0; font-size: 13px; }+ .label b { display: block; font-weight: 600; letter-spacing: .01em; }+ .label span { display: block; color: var(--muted); font-size: 12px; }+ .label.focus b { color: var(--accent); }+ .leader { fill: none; stroke: rgba(29, 28, 26, .45); stroke-width: 1; }+ .leader.focus { stroke: var(--accent); stroke-width: 1.5; }+ header { position: fixed; left: 50%; top: 22px; transform: translateX(-50%); text-align: center; pointer-events: none; }+ header h1 { margin: 0; font-size: clamp(18px, 2.2vw, 26px); font-weight: 650; letter-spacing: -.01em; }+ header p { margin: 4px 0 0; color: var(--muted); }+ .panel { position: fixed; left: 50%; bottom: max(18px, env(safe-area-inset-bottom)); transform: translateX(-50%); display: flex; gap: 18px; align-items: center;+ padding: 10px 16px; border-radius: 14px; background: rgba(255, 255, 255, .72); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);+ box-shadow: 0 0 0 1px rgba(0, 0, 0, .06), 0 8px 24px rgba(0, 0, 0, .06); }+ .panel label { display: flex; gap: 8px; align-items: center; color: var(--muted); font-size: 13px; }+ .panel input[type="range"] { width: 140px; accent-color: var(--accent); }+ .panel button { appearance: none; border: 0; border-radius: 8px; padding: 8px 12px; min-height: 36px; font: inherit; font-size: 13px; background: rgba(0, 0, 0, .06); color: var(--ink); cursor: pointer; }+ .panel button[aria-pressed="true"] { background: var(--ink); color: #fff; }+ @media (max-width: 640px) { .panel { flex-wrap: wrap; width: calc(100% - 24px); justify-content: center; gap: 10px; } .labels { display: none; } }+ </style>+</head>+<body>+ <canvas id="gl" aria-label="An electric motor in 3D. Drag to turn it; use the controls to take it apart."></canvas>+ <div class="labels" aria-hidden="true"></div>+ <header><h1>Inside an electric motor</h1><p>Drag to turn · hover a part</p></header>+ <div class="panel">+ <label>Explode <input id="explode" type="range" min="0" max="1" step="0.001" value="0"></label>+ <label>Section <input id="cut" type="range" min="0" max="1" step="0.001" value="0"></label>+ <button id="xray" aria-pressed="false">X-ray</button>+ </div>+ <script type="module" src="./motor.js"></script>+</body>+</html>diff --git a/skills/exploded-view/assets/demo/motor.js b/skills/exploded-view/assets/demo/motor.jsnew file mode 100644index 0000000..7e102fb--- /dev/null+++ b/skills/exploded-view/assets/demo/motor.js@@ -0,0 +1,225 @@+// A procedural induction motor, built from lathes and instanced parts, taken apart with+// explode.js. ?explode=0..1 ?cut=0..1 ?xray=1 set the state for stills and checks;+// ?transparent=1 renders on a clear background with no UI, for compositing;+// ?record=1 plays a scripted take-apart for the frame-capture skill.+import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { Exploder, Labels, Xray, Section, Picker } from '../explode.js';++const params = new URLSearchParams(location.search);+const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;++const canvas = document.getElementById('gl');+const CLEAR = params.has('transparent');+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: CLEAR, preserveDrawingBuffer: params.has('record') || CLEAR });+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+renderer.setSize(innerWidth, innerHeight, false);+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 1.0;+renderer.shadowMap.enabled = true;+renderer.shadowMap.type = THREE.PCFSoftShadowMap;+renderer.localClippingEnabled = true;+renderer.setClearColor('#eeeae2', CLEAR ? 0 : 1); // the page's paper colour: an opaque canvas is black by default+if (CLEAR) {+ for (const el of document.querySelectorAll('header, .panel, .labels')) el.style.display = 'none';+ document.documentElement.style.background = document.body.style.background = 'transparent';+}++const scene = new THREE.Scene();+scene.environment = new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(), 0.04).texture;+scene.environmentIntensity = 0.9;+const camera = new THREE.PerspectiveCamera(30, innerWidth / innerHeight, 0.01, 50);+const controls = new OrbitControls(camera, canvas);+controls.enableDamping = true; controls.minDistance = 0.6; controls.maxDistance = 5; controls.maxPolarAngle = 1.5;++const key = new THREE.DirectionalLight('#fff6ea', 2.2);+key.position.set(1.2, 2.4, 1.6); key.castShadow = true;+key.shadow.mapSize.set(2048, 2048);+Object.assign(key.shadow.camera, { left: -1.2, right: 1.2, top: 1.2, bottom: -1.2, near: 0.5, far: 6 });+key.shadow.bias = -0.0004; key.shadow.radius = 4;+scene.add(key);+const floor = new THREE.Mesh(new THREE.PlaneGeometry(12, 12), new THREE.ShadowMaterial({ opacity: 0.16 }));+floor.rotation.x = -Math.PI / 2; floor.position.y = -0.163; floor.receiveShadow = true; scene.add(floor);++// ---------------------------------------------------------------- parts+// every part gets its own materials, so x-ray and hover highlight touch only that part+const mat = (o) => new THREE.MeshPhysicalMaterial({ roughness: 0.45, metalness: 0.3, ...o });+const PAINT = { color: '#35556e', roughness: 0.42, metalness: 0.25, clearcoat: 0.6, clearcoatRoughness: 0.3 };+const STEEL = { color: '#b9bdc2', roughness: 0.32, metalness: 0.9 };+const COPPER = { color: '#c26b32', roughness: 0.35, metalness: 0.95 };+const ALU = { color: '#d5d8db', roughness: 0.38, metalness: 0.85 };++// lathe around the X axis (the shaft): profile [[radius, x], ...]+function latheX(points, segs = 64) {+ const g = new THREE.LatheGeometry(points.map(([r, x]) => new THREE.Vector2(r, x)), segs);+ g.rotateZ(-Math.PI / 2);+ return g;+}+const mesh = (g, m) => { const o = new THREE.Mesh(g, m); o.castShadow = o.receiveShadow = true; return o; };+function ring(geometry, material, n, place) {+ const im = new THREE.InstancedMesh(geometry, material, n);+ const m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), p = new THREE.Vector3(), s = new THREE.Vector3(1, 1, 1);+ for (let i = 0; i < n; i++) { place(i, p, q, s); im.setMatrixAt(i, m4.compose(p, q, s)); }+ im.castShadow = im.receiveShadow = true;+ return im;+}+const aroundX = (a) => new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), a);++const motor = new THREE.Group();+scene.add(motor);+const part = (name, opts = {}) => { const g = new THREE.Group(); g.name = name; Object.assign(g.userData, opts); motor.add(g); return g; };++// housing: finned shell, feet and terminal box+const housing = part('housing', { shell: true, stage: 0, explode: [0, 0.32, 0] });+const hMat = mat(PAINT);+housing.add(mesh(latheX([[0.105, -0.15], [0.12, -0.15], [0.12, 0.15], [0.105, 0.15], [0.105, -0.15]]), hMat));+housing.add(ring(new THREE.BoxGeometry(0.27, 0.018, 0.005), hMat, 26, (i, p, q) => {+ const a = (i / 26) * Math.PI * 2; if (Math.abs(Math.sin(a)) > 0.93 && Math.cos(a) < 0) { p.set(0, 99, 0); return; }+ q.copy(aroundX(a)); p.set(0, Math.cos(a) * 0.128, Math.sin(a) * 0.128);+}));+for (const z of [-0.085, 0.085]) { const f = mesh(new THREE.BoxGeometry(0.24, 0.05, 0.05), hMat); f.position.set(0, -0.138, z); housing.add(f); }+const tbox = mesh(new THREE.BoxGeometry(0.09, 0.05, 0.08), hMat); tbox.position.set(0.02, 0.145, 0); housing.add(tbox);+const tlid = mesh(new THREE.BoxGeometry(0.096, 0.008, 0.086), mat(PAINT)); tlid.position.set(0.02, 0.173, 0); housing.add(tlid);++// stator: laminated core and copper windings+const stator = part('stator', { stage: 1, explode: [0, 0, 0] });+stator.add(mesh(latheX([[0.074, -0.1], [0.103, -0.1], [0.103, 0.1], [0.074, 0.1], [0.074, -0.1]]), mat({ color: '#6e737a', roughness: 0.55, metalness: 0.7 })));+const cu = mat(COPPER);+for (const x of [-0.108, 0.108]) stator.add(ring(new THREE.TorusGeometry(0.016, 0.0065, 10, 20), cu, 12, (i, p, q) => {+ const a = (i / 12) * Math.PI * 2; q.copy(aroundX(a)).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 2));+ p.set(x, Math.cos(a) * 0.086, Math.sin(a) * 0.086);+}));++// rotor with skewed bars, on the shaft+const rotor = part('rotor', { stage: 2, explode: [0.42, 0, 0] });+rotor.add(mesh(latheX([[0.001, -0.095], [0.068, -0.095], [0.068, 0.095], [0.001, 0.095]]), mat({ color: '#80868d', roughness: 0.5, metalness: 0.8 })));+rotor.add(ring(new THREE.BoxGeometry(0.19, 0.006, 0.01), mat(ALU), 22, (i, p, q) => {+ const a = (i / 22) * Math.PI * 2; q.copy(aroundX(a)).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), 0.12));+ p.set(0, Math.cos(a) * 0.069, Math.sin(a) * 0.069);+}));+const shaft = mesh(latheX([[0.001, -0.24], [0.014, -0.24], [0.014, 0.3], [0.012, 0.31], [0.012, 0.34], [0.001, 0.34]], 32), mat(STEEL));+rotor.add(shaft);++// bearings: outer race, inner race, balls+function bearing(name, x, explodeX) {+ const b = part(name, { stage: 1, explode: [explodeX, 0, 0] });+ const s = mat(STEEL);+ b.add(mesh(latheX([[0.026, x - 0.008], [0.032, x - 0.008], [0.032, x + 0.008], [0.026, x + 0.008], [0.026, x - 0.008]]), s));+ b.add(mesh(latheX([[0.014, x - 0.008], [0.019, x - 0.008], [0.019, x + 0.008], [0.014, x + 0.008], [0.014, x - 0.008]]), s));+ b.add(ring(new THREE.SphereGeometry(0.0045, 12, 8), s, 9, (i, p) => { const a = (i / 9) * Math.PI * 2; p.set(x, Math.cos(a) * 0.0225, Math.sin(a) * 0.0225); }));+ return b;+}+const frontBearing = bearing('front bearing', 0.16, 0.6);+const rearBearing = bearing('rear bearing', -0.16, -0.22);++// end shields with bolts+function endShield(name, x, dir, explodeX) {+ const e = part(name, { shell: true, stage: 0, explode: [explodeX, 0, 0] });+ const m = mat({ ...PAINT, color: '#3d6079' });+ const prof = [[0.033, x], [0.12, x], [0.12, x + dir * 0.012], [0.06, x + dir * 0.022], [0.045, x + dir * 0.03], [0.033, x + dir * 0.03], [0.033, x]];+ e.add(mesh(latheX(dir > 0 ? prof : prof.reverse()), m)); // keep the winding (and normals) outward on both ends+ e.add(ring(new THREE.CylinderGeometry(0.006, 0.006, 0.012, 6).rotateZ(Math.PI / 2), mat(STEEL), 4, (i, p) => {+ const a = (i / 4) * Math.PI * 2 + Math.PI / 4; p.set(x + dir * 0.012, Math.cos(a) * 0.108, Math.sin(a) * 0.108);+ }));+ return e;+}+const frontShield = endShield('front shield', 0.15, 1, 0.84);+const rearShield = endShield('rear shield', -0.15, -1, -0.32);++// cooling fan and its cover+const fan = part('fan', { stage: 1, explode: [-0.46, 0, 0] });+const fm = mat({ color: '#2b2f33', roughness: 0.6, metalness: 0.1 });+fan.add(mesh(latheX([[0.016, -0.215], [0.03, -0.215], [0.03, -0.195], [0.016, -0.195]]), fm));+fan.add(ring(new THREE.BoxGeometry(0.004, 0.075, 0.03), fm, 10, (i, p, q) => {+ const a = (i / 10) * Math.PI * 2; q.copy(aroundX(a)).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), 0.35));+ p.set(-0.205, Math.cos(a) * 0.065, Math.sin(a) * 0.065);+}));+const cover = part('fan cover', { shell: true, stage: 0, explode: [-0.62, 0, 0] });+const cm = mat({ ...PAINT, color: '#2f4b60' });+cover.add(mesh(latheX([[0.118, -0.16], [0.12, -0.16], [0.12, -0.235], [0.1, -0.25], [0.05, -0.255], [0.048, -0.25], [0.098, -0.245], [0.116, -0.232], [0.118, -0.16]]), cm));++// ---------------------------------------------------------------- explode, x-ray, section, labels+const ex = new Exploder(motor);+const xray = new Xray(motor);+const section = new Section(motor, [0, 0, -1]);+const labels = new Labels(document.querySelector('.labels'), camera, canvas);+const L = [+ [housing, 'Housing', 'cast frame, cooling fins', [0, 0.13, 0.06]],+ [stator, 'Stator', 'fixed copper windings', [0.05, 0.1, 0.03]],+ [rotor, 'Rotor', 'turns in the magnetic field', [0.03, 0.07, 0]],+ [shaft, 'Shaft', 'carries the torque out', [0.3, 0.014, 0]],+ [frontBearing, 'Bearings', 'keep the rotor centred', [0.16, 0.032, 0]],+ [frontShield, 'End shields', 'hold the bearings', [0.16, 0.1, 0.04]],+ [fan, 'Fan', 'pulls air over the fins', [-0.205, 0.1, 0]],+ [cover, 'Fan cover', '', [-0.2, 0.12, 0]],+].map(([o, t, n, a]) => labels.add(o, t, { note: n, anchor: a }));++const parts = motor.children;+new Picker(canvas, camera, parts, {+ onHover: (p) => labels.items.forEach((it) => { let o = it.object; while (o && o.parent !== motor) o = o.parent; it.focus = !!p && o === p; }),+});++// ---------------------------------------------------------------- controls+const exSlider = document.getElementById('explode'), cutSlider = document.getElementById('cut'), xBtn = document.getElementById('xray');+let explodeTarget = +(params.get('explode') ?? 0), explodeNow = explodeTarget;+const setCut = (v) => section.set(v > 0.001 ? 0.14 * (1 - v) : null);+exSlider.value = explodeTarget;+exSlider.addEventListener('input', () => { explodeTarget = +exSlider.value; });+cutSlider.value = params.get('cut') ?? 0; setCut(+cutSlider.value);+cutSlider.addEventListener('input', () => setCut(+cutSlider.value));+const setX = (on) => { xray.set(on); xBtn.setAttribute('aria-pressed', String(on)); };+setX(params.get('xray') === '1');+xBtn.addEventListener('click', () => setX(!xray.on));++// fit the assembly to any screen shape: the camera pulls back as the motor comes apart,+// until the visitor zooms or orbits by hand+const fit = { near: 1, far: 2 }, viewDir = new THREE.Vector3(0.42, 0.34, 1).normalize();+let userMoved = false;+controls.addEventListener('start', () => { userMoved = true; });+function frameView() {+ camera.aspect = innerWidth / innerHeight;+ const t = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));+ const d = (halfW, halfH) => Math.max(halfH / t, halfW / (t * camera.aspect)) * 1.2;+ fit.near = d(0.36, 0.24); fit.far = d(1.05, 0.45);+ controls.maxDistance = Math.max(5, fit.far * 1.4); // or the controls clamp the fitted distance+ controls.target.set(0.1, 0.02, 0);+ camera.updateProjectionMatrix();+ userMoved = false;+}+function autoDistance(k) {+ if (userMoved) return;+ camera.position.copy(controls.target).addScaledVector(viewDir, THREE.MathUtils.lerp(fit.near, fit.far, k));+}+frameView();+autoDistance(explodeNow);+addEventListener('resize', () => { renderer.setSize(innerWidth, innerHeight, false); frameView(); });++window.__app = { renderer, scene, camera, ex, xray, section };++// ?record=1: a scripted take-apart for frame-capture, timed on the page clock+if (params.has('record')) {+ document.querySelector('.panel').style.display = 'none';+ const ease = (k) => { k = Math.min(1, Math.max(0, k)); return k * k * (3 - 2 * k); };+ window.__recordFrame = (t) => {+ explodeTarget = t < 6 ? ease((t - 0.8) / 2.6) : 1 - ease((t - 6) / 2.2);+ const want = t > 3.8 && t < 6;+ if (xray.on !== want) setX(want);+ const a = 0.4 + t * 0.035; // a slow drift round the motor+ viewDir.set(Math.sin(a), 0.34, Math.cos(a)).normalize();+ };+}+let frames = 0, last = performance.now();+function frame(now) {+ const dt = Math.min(0.05, (now - last) / 1000); last = now;+ explodeNow += (explodeTarget - explodeNow) * (REDUCED ? 1 : 1 - Math.pow(0.001, dt));+ ex.set(explodeNow);+ autoDistance(explodeNow);+ if (!REDUCED) rotor.rotation.x += dt * (0.4 + 2.4 * (1 - explodeNow)); // spins while assembled+ controls.update();+ renderer.render(scene, camera);+ labels.update();+ if (++frames === 3) window.__ready = true;+ requestAnimationFrame(frame);+}+requestAnimationFrame(frame);diff --git a/skills/exploded-view/assets/explode.js b/skills/exploded-view/assets/explode.jsnew file mode 100644index 0000000..ba282b4--- /dev/null+++ b/skills/exploded-view/assets/explode.js@@ -0,0 +1,192 @@+// Exploded views for any three.js assembly: staged explode, x-ray, section cut, pinned labels+// with leader lines, and hover/click picking.+//+// import { Exploder, Labels, Xray, Section, Picker } from "./explode.js";+// const ex = new Exploder(motor, { axis: new THREE.Vector3(1, 0, 0) }); // parts = motor.children+// ex.set(0.6); // 0 = assembled, 1 = fully exploded+// const labels = new Labels(document.querySelector(".labels"), camera, canvas);+// labels.add(rotor, "Rotor", { anchor: [0, 0.4, 0] });+// // every frame, after rendering: labels.update();+//+// Per-part options on part.userData:+// explode: [x, y, z] offset at full explosion (overrides the computed direction)+// stage: n parts with lower stages move first (outer shells before inner parts)+// shell: true an outer casing: x-ray makes it ghostly, the section cut opens it+import * as THREE from "three";++const smooth = (t) => t * t * (3 - 2 * t);+const _v = new THREE.Vector3(), _b = new THREE.Box3();++export class Exploder {+ constructor(root, { parts = null, axis = null, spread = 1, center = null } = {}) {+ this.root = root;+ this.parts = parts || [...root.children];+ root.updateMatrixWorld(true);+ const all = new THREE.Box3().setFromObject(root);+ const c = center ? new THREE.Vector3(...center) : all.getCenter(new THREE.Vector3());+ const size = all.getSize(new THREE.Vector3()).length();+ const stages = new Set();+ this.items = this.parts.map((p) => {+ const home = p.position.clone();+ let off;+ if (p.userData.explode) off = new THREE.Vector3(...p.userData.explode);+ else {+ // away from the assembly centre (along `axis` if given), scaled by distance from it+ const pc = _b.setFromObject(p).getCenter(_v).clone();+ const d = pc.sub(c);+ if (axis) d.copy(axis).multiplyScalar(d.dot(axis));+ off = d.lengthSq() < 1e-8 ? new THREE.Vector3(0, size * 0.25, 0) : d.multiplyScalar(spread * 1.2);+ if (p.parent) off.applyQuaternion(p.parent.getWorldQuaternion(new THREE.Quaternion()).invert());+ }+ const stage = p.userData.stage ?? 0;+ stages.add(stage);+ return { p, home, off, stage };+ });+ this.stages = [...stages].sort((a, b) => a - b);+ this.t = 0;+ }++ // staged: each stage gets its own window of t, overlapping by half, so outer parts lead+ set(t) {+ this.t = THREE.MathUtils.clamp(t, 0, 1);+ const n = this.stages.length, w = n > 1 ? 2 / (n + 1) : 1;+ for (const it of this.items) {+ const i = this.stages.indexOf(it.stage), start = n > 1 ? i * w / 2 : 0;+ const k = smooth(THREE.MathUtils.clamp((this.t - start) / w, 0, 1));+ it.p.position.copy(it.home).addScaledVector(it.off, k);+ }+ }+}++// HTML labels pinned to points on parts, laid out in two columns beside the model with+// leader lines, so they never cover the thing they name. Container must overlay the canvas.+export class Labels {+ constructor(container, camera, canvas, { margin = 24, gap = 6 } = {}) {+ Object.assign(this, { container, camera, canvas, margin, gap, items: [] });+ container.style.pointerEvents = "none";+ this.svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");+ Object.assign(this.svg.style, { position: "absolute", inset: "0", width: "100%", height: "100%", overflow: "visible" });+ container.appendChild(this.svg);+ }++ add(object, text, { anchor = [0, 0, 0], note = "" } = {}) {+ const el = document.createElement("div");+ el.className = "label";+ el.innerHTML = `<b></b>${note ? "<span></span>" : ""}`;+ el.querySelector("b").textContent = text;+ if (note) el.querySelector("span").textContent = note;+ Object.assign(el.style, { position: "absolute", left: "0", top: "0", whiteSpace: "nowrap" });+ const line = document.createElementNS("http://www.w3.org/2000/svg", "path");+ line.setAttribute("class", "leader");+ this.container.appendChild(el);+ this.svg.appendChild(line);+ const item = { object, el, line, anchor: new THREE.Vector3(...anchor), focus: false };+ this.items.push(item);+ return item;+ }++ update() {+ const r = this.canvas.getBoundingClientRect();+ const mid = r.width / 2;+ const shown = [];+ for (const it of this.items) {+ _v.copy(it.anchor);+ it.object.localToWorld(_v);+ _v.project(this.camera);+ const visible = it.object.visible && _v.z < 1 && Math.abs(_v.x) < 1.05 && Math.abs(_v.y) < 1.05;+ it.el.style.display = it.line.style.display = visible ? "" : "none";+ if (!visible) continue;+ it.sx = (_v.x * 0.5 + 0.5) * r.width;+ it.sy = (-_v.y * 0.5 + 0.5) * r.height;+ it.h = it.el.offsetHeight || 20;+ it.w = it.el.offsetWidth || 80;+ shown.push(it);+ }+ // two columns; within each, keep the anchors' vertical order and push apart overlaps+ for (const left of [true, false]) {+ const col = shown.filter((it) => (it.sx < mid) === left).sort((a, b) => a.sy - b.sy);+ let y = this.margin;+ for (const it of col) { it.ly = Math.max(it.sy - it.h / 2, y); y = it.ly + it.h + this.gap; }+ const over = y - this.gap - (r.height - this.margin);+ if (over > 0) for (const it of col) it.ly -= over; // shift the column up if it runs off+ for (const it of col) {+ const x = left ? this.margin : r.width - this.margin - it.w;+ it.el.style.transform = `translate(${x}px, ${it.ly}px)`;+ it.el.style.textAlign = left ? "left" : "right";+ const ex = left ? x + it.w + 6 : x - 6, ey = it.ly + it.h / 2;+ const bend = left ? ex + 18 : ex - 18;+ it.line.setAttribute("d", `M${ex},${ey} L${bend},${ey} L${it.sx},${it.sy}`);+ it.el.classList.toggle("focus", it.focus);+ it.line.classList.toggle("focus", it.focus);+ }+ }+ }+}++// X-ray: shells turn into faint, depth-sorted glass so the inside shows; other parts stay solid+export class Xray {+ constructor(root) {+ this.mats = [];+ root.traverse((o) => {+ if (!o.isMesh) return;+ let shell = false;+ for (let p = o; p; p = p.parent) if (p.userData.shell) shell = true;+ if (!shell) return;+ for (const m of [].concat(o.material)) if (!this.mats.find((e) => e.m === m)) this.mats.push({ m, opacity: m.opacity, transparent: m.transparent, depthWrite: m.depthWrite });+ });+ this.on = false;+ }+ set(on, opacity = 0.14) {+ this.on = on;+ for (const e of this.mats) {+ e.m.transparent = on || e.transparent;+ e.m.opacity = on ? opacity : e.opacity;+ e.m.depthWrite = on ? false : e.depthWrite;+ e.m.needsUpdate = true;+ }+ }+}++// Section cut: a clipping plane through the shells. renderer.localClippingEnabled must be true.+export class Section {+ constructor(root, normal = [0, 0, -1]) {+ this.plane = new THREE.Plane(new THREE.Vector3(...normal), 1e6);+ this.mats = new Set();+ root.traverse((o) => {+ if (!o.isMesh) return;+ let shell = false;+ for (let p = o; p; p = p.parent) if (p.userData.shell) shell = true;+ if (shell) for (const m of [].concat(o.material)) { m.clippingPlanes = [this.plane]; m.clipShadows = true; m.side = THREE.DoubleSide; this.mats.add(m); }+ });+ }+ // offset along the normal; Infinity (or null) switches the cut off+ set(offset) { this.plane.constant = offset == null || !isFinite(offset) ? 1e6 : offset; }+}++// Hover highlight and click selection of whole parts+export class Picker {+ constructor(canvas, camera, parts, { onPick = null, onHover = null, color = "#ff8a3d" } = {}) {+ Object.assign(this, { canvas, camera, parts, onPick, onHover });+ this.ray = new THREE.Raycaster();+ this.hot = null;+ this.glow = new THREE.Color(color);+ const pick = (e) => {+ const r = canvas.getBoundingClientRect();+ this.ray.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), camera);+ const hit = this.ray.intersectObjects(parts, true).find((h) => h.object.visible && !(h.object.material?.opacity < 0.3));+ if (!hit) return null;+ let o = hit.object;+ while (o && !parts.includes(o)) o = o.parent;+ return o;+ };+ canvas.addEventListener("pointermove", (e) => { const p = pick(e); if (p !== this.hot) { this.highlight(this.hot, false); this.hot = p; this.highlight(p, true); canvas.style.cursor = p ? "pointer" : ""; onHover && onHover(p); } });+ canvas.addEventListener("click", (e) => { const p = pick(e); onPick && onPick(p); });+ }+ highlight(part, on) {+ part?.traverse((o) => {+ if (!o.isMesh || !o.material.emissive) return;+ if (on) { o.userData._em = o.material.emissive.clone(); o.material.emissive.copy(this.glow).multiplyScalar(0.25); }+ else if (o.userData._em) o.material.emissive.copy(o.userData._em);+ });+ }+}diff --git a/skills/frame-capture/SKILL.md b/skills/frame-capture/SKILL.mdnew file mode 100644index 0000000..d37272a--- /dev/null+++ b/skills/frame-capture/SKILL.md@@ -0,0 +1,96 @@+---+name: frame-capture+description: Records any web page (three.js, WebGL, canvas, GSAP, CSS animation, scroll-driven video) to a perfectly smooth 60 fps MP4 by running the page on a virtual clock, one exact frame at a time, and puts two recordings against each other as a labelled stacked or side-by-side comparison. Use when someone wants a video of a site, a demo clip for X or YouTube, a scroll-through, a showcase reel of a 3D scene, or a "model A vs model B" comparison video. Also use when a screen recording of an animated page stutters or drops frames.+---++# Frame capture++Screen recorders capture whatever the GPU managed to draw in real time, so a heavy scene stutters and a scroll-through looks hand-held. This skill records differently. Before the page's own scripts run, its clock is replaced: `performance.now`, `Date.now` and `requestAnimationFrame` read a virtual time, CSS animations and transitions are pinned to it, and every `<video>` is paused and seeked to it. Each output frame advances the clock by exactly 1/60 s, runs one frame, and takes a screenshot. A frame can take two seconds to render and the video still plays at a perfect 60 fps.++## Tools++| Script | What it does |+| --- | --- |+| `scripts/record.py` | Records a URL to MP4 with scroll keys, pointer motion and a ready condition |+| `scripts/compare.py` | Stacks two clips (or sets them side by side) with labels and rounded panels |+| `scripts/serve.py` | Static server that answers HTTP Range requests, so videos can seek |++Needs Python 3.9+, `pip install playwright pillow`, `python3 -m playwright install chromium webkit`, and ffmpeg on PATH.++## Run++1. **Serve the page with `scripts/serve.py`**, never `python3 -m http.server`. The built-in server ignores Range requests. The browser then cannot seek any video it serves (`video.seekable` is empty) and every recorded video holds its first frame. `record.py` warns when it sees this.++ ```bash+ python3 scripts/serve.py path/to/site --port 8000+ ```++2. **Make a fast timing pass first.** Ten frames a second shows the choreography in seconds instead of minutes:++ ```bash+ python3 scripts/record.py http://127.0.0.1:8000/ /tmp/check.mp4 --seconds 20 --fps 8 \+ --scroll "0:0 2.5:0 9:40% 12:40% 19:100%" --pointer drift+ ```++ Watch it, adjust the keys, repeat. Only then render the full clip.++3. **Render the final.** `--size` is the CSS viewport and `--dpr` multiplies it. `--size 1920x1080 --dpr 1` makes 1080p; `--size 1280x720 --dpr 1.5` makes the same 1920x1080 with a larger layout. Output is H.264, CRF 16, yuv420p, BT.709 tags, faststart, no audio.++ ```bash+ python3 scripts/record.py http://127.0.0.1:8000/ out.mp4 --seconds 20 --fps 60 \+ --scroll "0:0 2.5:0 9:40% 12:40% 19:100%" --pointer drift --ready "window.__ready === true"+ ```++4. **Look at the result** before handing it over. Pull frames at the moments that matter (`ffmpeg -ss 9 -i out.mp4 -frames:v 1 f.png`) and check them: first frame, every scroll stop, the last frame.++### Choreography++- `--scroll` keys are `seconds:position`. Positions are pixels (`1200`), a share of the scroll range (`40%`) or viewport heights (`2.5vh`). Segments ease (half linear, half smootherstep, so a long move never sprints in the middle). Add `~` after the time for a linear segment: `9~:60%`.+- Hold on anything the viewer needs to read: give a pinned section or a counter its own key pair with the same position.+- `--pointer drift` circles the real mouse slowly round the centre, so hover states, parallax and cursor-following rigs come alive. `--pointer 0.7,0.3` parks it.+- For choreography the page knows best (camera flights, a tour), let the page drive itself: define `window.__recordFrame = (t) => { ... }` behind a `?record=1` flag. It is called with the virtual time in seconds before each frame. `window.__recording` is true while recording.+- Smooth-scroll libraries fight a recorder that sets the scroll position. `--kill-lenis` stops Lenis from loading. For others, switch them off under `?record=1`.++## Make the page recordable++- **Time comes from `performance.now()` or the rAF timestamp, never from `setTimeout` or `setInterval`.** Timers keep real time while the clock is virtual, so a `setTimeout(next, 3000)` fires after three real seconds, which might be frame 20 or frame 400. Schedule on the page clock instead:++ ```js+ const pending = [];+ const later = (secs, fn) => pending.push({ at: performance.now() / 1000 + secs, fn });+ // in the frame loop:+ const now = performance.now() / 1000;+ for (let i = pending.length - 1; i >= 0; i--) if (now >= pending[i].at) pending.splice(i, 1)[0].fn();+ ```++- Expose a ready flag (`window.__ready = true` after the first rendered frame, textures decoded, fonts loaded) and pass it as `--ready`. Recording before assets land bakes a loading flash into frame 0.+- In record mode, hide UI that would not be in a film: hints, cursors, loaders, cookie bars.+- If WebGL frames come out black or stale, create the renderer with `preserveDrawingBuffer: true` when recording.++## Browsers++- **Chromium (default)** runs WebGL on the real GPU headless. On macOS the script adds `--use-angle=metal`, which renders at full speed; without it Chromium falls back to SwiftShader, which is correct but many times slower.+- **WebKit** (`--browser webkit`) shows how Safari renders: different font smoothing, colour handling and video decoding. Its screenshots occasionally stall at 1080p (about 1 in 100); the script retries, and because the clock is paused between steps the retry returns the identical frame.+- If Playwright's own Chromium is missing (a version mismatch after an upgrade), the script finds the newest Chromium in the Playwright cache. `CHROME_PATH` overrides it.+- Never record in a visible browser tab you are not looking at, and never in a hidden embedded preview pane. Background tabs throttle or freeze `requestAnimationFrame`. Headless does not.++## Comparisons++```bash+python3 scripts/compare.py a.mp4 b.mp4 versus.mp4 --labels "Model A" "Model B" # stacked, for phones+python3 scripts/compare.py a.mp4 b.mp4 versus.mp4 --labels "Before" "After" --layout side # side by side+```++A fair comparison holds everything equal except the thing being compared:++- Same viewport, same duration, same choreography (`--scroll` keys reused verbatim).+- Crop each source to its content first. Strip watermarks, webcam overlays and UI chrome the other clip does not have.+- Silent output. Two soundtracks fight, and audio steals attention from the picture.+- The shorter clip holds its last frame, so both finish together.+- Name each side honestly in its label. Put the one the audience knows on top.++## Delivery++- Social platforms re-encode everything. 1920x1080 or 1080x1920 at 60 fps, H.264, CRF 14 to 18 survives that best. Higher resolutions are often downscaled anyway.+- Keep the master. Make cut-downs (a 6 s loop, a vertical crop) from it with ffmpeg rather than re-recording.+- Add sound afterwards, timed to the frame numbers the recording printed. Never record audio through the virtual clock.diff --git a/skills/frame-capture/agents/openai.yaml b/skills/frame-capture/agents/openai.yamlnew file mode 100644index 0000000..0e41e3f--- /dev/null+++ b/skills/frame-capture/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Frame Capture"+ short_description: "Record any animated or 3D page to a perfectly smooth 60 fps video"diff --git a/skills/frame-capture/scripts/compare.py b/skills/frame-capture/scripts/compare.pynew file mode 100644index 0000000..206ee63--- /dev/null+++ b/skills/frame-capture/scripts/compare.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3+"""Put two clips against each other, stacked or side by side, each with a label.++ python3 compare.py A.mp4 B.mp4 OUT.mp4 --labels "Model A" "Model B"+ [--layout stack|side] [--width 1080] [--fps 30] [--bg f1ece4] [--ink 1c1a17]+ [--radius 24] [--gap 40] [--margin 56] [--font /path/to/font.ttf]++Both clips are scaled to the same panel width, given rounded corners and laid on a flat+background with a label above each panel. The output runs as long as the longer clip; the+shorter one holds its last frame. Audio is dropped: a comparison should be judged on the+picture, and two soundtracks fight. Labels are drawn with Pillow, so ffmpeg needs no+drawtext/fontconfig build.++Needs: pip install pillow; ffmpeg and ffprobe on PATH.+"""+import argparse+import json+import subprocess+import tempfile+from pathlib import Path++from PIL import Image, ImageDraw, ImageFont++FONT_GUESSES = [+ "/System/Library/Fonts/Supplemental/Arial Bold.ttf",+ "/System/Library/Fonts/Helvetica.ttc",+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",+ "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",+ "C:/Windows/Fonts/arialbd.ttf",+]+++def probe(path):+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",+ "stream=width,height:format=duration", "-of", "json", path],+ check=True, capture_output=True, text=True).stdout+ j = json.loads(out)+ s = j["streams"][0]+ return s["width"], s["height"], float(j["format"]["duration"])+++def font(path, size):+ for p in [path] + FONT_GUESSES:+ if p and Path(p).exists():+ return ImageFont.truetype(p, size)+ return ImageFont.load_default(size)+++def rgb(hexstr):+ return tuple(int(hexstr[i:i + 2], 16) for i in (0, 2, 4))+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("a")+ ap.add_argument("b")+ ap.add_argument("out")+ ap.add_argument("--labels", nargs=2, default=["A", "B"])+ ap.add_argument("--layout", choices=["stack", "side"], default="stack")+ ap.add_argument("--width", type=int, default=1080, help="panel width in px")+ ap.add_argument("--fps", type=float, default=30)+ ap.add_argument("--bg", default="f1ece4")+ ap.add_argument("--ink", default="1c1a17")+ ap.add_argument("--radius", type=int, default=24)+ ap.add_argument("--gap", type=int, default=40)+ ap.add_argument("--margin", type=int, default=56)+ ap.add_argument("--font", default="")+ ap.add_argument("--crf", type=int, default=16)+ args = ap.parse_args()++ clips = [probe(args.a), probe(args.b)]+ pw = args.width // 2 * 2+ ph = [round(pw * h / w / 2) * 2 for w, h, _ in clips]+ label_h = round(pw * 0.075)+ duration = max(d for _, _, d in clips)+ m, g = args.margin, args.gap+ if args.layout == "stack":+ W = pw + 2 * m+ H = m + label_h + ph[0] + g + label_h + ph[1] + m+ slots = [(m, m + label_h), (m, m + label_h + ph[0] + g + label_h)]+ else:+ W = 2 * pw + 2 * m + g+ H = m + label_h + max(ph) + m+ slots = [(m, m + label_h), (m + pw + g, m + label_h)]+ W, H = W // 2 * 2, H // 2 * 2++ with tempfile.TemporaryDirectory() as tmp:+ tmp = Path(tmp)+ base = Image.new("RGB", (W, H), rgb(args.bg))+ draw = ImageDraw.Draw(base)+ f = font(args.font, round(label_h * 0.5))+ for (x, y), text in zip(slots, args.labels):+ draw.text((x + 2, y - label_h * 0.22), text, font=f, fill=rgb(args.ink), anchor="ls")+ base.save(tmp / "base.png")+ masks = []+ for i, hgt in enumerate(ph):+ mk = Image.new("L", (pw, hgt), 0)+ ImageDraw.Draw(mk).rounded_rectangle([0, 0, pw - 1, hgt - 1], radius=args.radius, fill=255)+ mk.save(tmp / f"mask{i}.png")+ masks.append(str(tmp / f"mask{i}.png"))++ fc = []+ for i in range(2):+ fc.append(f"[{i}:v]fps={args.fps},scale={pw}:{ph[i]}:flags=lanczos,format=rgba,"+ f"tpad=stop_mode=clone:stop_duration={duration}[v{i}]")+ fc.append(f"[{i + 3}:v]format=gray,loop=-1:1:0[m{i}]")+ fc.append(f"[v{i}][m{i}]alphamerge[p{i}]")+ fc.append("[2:v]loop=-1:1:0[bg]")+ fc.append(f"[bg][p0]overlay={slots[0][0]}:{slots[0][1]}:shortest=0[t0]")+ fc.append(f"[t0][p1]overlay={slots[1][0]}:{slots[1][1]}:shortest=0,format=yuv420p[out]")+ cmd = ["ffmpeg", "-v", "error", "-y", "-i", args.a, "-i", args.b, "-i", str(tmp / "base.png"),+ "-i", masks[0], "-i", masks[1], "-filter_complex", ";".join(fc), "-map", "[out]",+ "-t", f"{duration:.3f}", "-r", str(args.fps), "-c:v", "libx264", "-preset", "slow",+ "-crf", str(args.crf), "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-an", args.out]+ subprocess.run(cmd, check=True)+ print(f"wrote {args.out}: {W}x{H}, {duration:.2f}s, {args.layout}")+++if __name__ == "__main__":+ main()diff --git a/skills/frame-capture/scripts/record.py b/skills/frame-capture/scripts/record.pynew file mode 100644index 0000000..e65b66b--- /dev/null+++ b/skills/frame-capture/scripts/record.py@@ -0,0 +1,283 @@+#!/usr/bin/env python3+"""Frame-exact video of any web page: WebGL, canvas, requestAnimationFrame, CSS and <video>.++The page's clock is replaced before any of its scripts run. performance.now, Date.now and+requestAnimationFrame read a virtual time; CSS animations and transitions are pinned to it+through the Web Animations API; every <video> is held paused and seeked to it. Each output+frame advances that clock by exactly 1/fps, runs one round of frame callbacks and takes a+screenshot, so the video plays perfectly smoothly however slowly the capture runs.++ python3 record.py URL OUT.mp4 [--seconds 12] [--fps 60] [--size 1920x1080] [--dpr 1]+ [--scroll "0:0 2:0 9:100%"] [--pointer drift] [--ready "window.__ready"]++ python3 record.py http://localhost:8000/ /tmp/check.mp4 --fps 8 # quick timing check++--scroll takes "seconds:position" keys. A position is pixels (1200), a share of the page's+scroll range (35%) or viewport heights (2.5vh). Between keys the scroll eases (smootherstep,+blended half-linear so long moves do not sprint in the middle); "~" after a key's time makes+that segment linear: "4~:100%".+--pointer moves the real mouse, so :hover and pointer-driven rigs react: "drift" circles+slowly around the centre, "x,y" holds a point (fractions of the viewport), "none" leaves it.+--ready is a JS expression polled before frame 0 while pre-roll frames run the page. Pages that need to know+they are being recorded can read window.__recording (true) and the frame clock from+performance.now(). A page may also define window.__recordFrame(t) to choreograph itself:+it is called with the virtual time in seconds before every frame.+--kill-lenis stops Lenis (and similar smooth-scroll libraries that read window.Lenis) from+loading, so the recorder owns the scroll position.++Needs: pip install playwright && python3 -m playwright install chromium webkit; ffmpeg on PATH.+"""+import argparse+import glob+import math+import os+import re+import subprocess+import sys+import time++from playwright.sync_api import TimeoutError as PlaywrightTimeout, sync_playwright++CLOCK = r"""+(() => {+ window.__recording = true;+ if (window.__KILL_LENIS__) Object.defineProperty(window, 'Lenis', { get: () => undefined, set: () => {}, configurable: false });++ // media never runs on the wall clock; it is seeked to virtual time every frame+ const vids = new Set();+ const nativePause = HTMLMediaElement.prototype.pause;+ const nativePlay = HTMLMediaElement.prototype.play;+ HTMLMediaElement.prototype.play = function () {+ if (!vids.has(this)) { this.__t0 = vt; vids.add(this); }+ this.__playing = true;+ nativePause.call(this);+ this.dispatchEvent(new Event('playing'));+ return Promise.resolve();+ };+ HTMLMediaElement.prototype.pause = function () { this.__playing = false; nativePause.call(this); };+ Object.defineProperty(HTMLMediaElement.prototype, 'paused', { get() { return !this.__playing; }, configurable: true });++ const realNow = performance.now.bind(performance);+ let vt = realNow();+ const t0 = vt;+ const dateOffset = Date.now() - vt;+ const queue = new Map();+ let nextId = 1;+ performance.now = () => vt;+ Date.now = () => Math.round(dateOffset + vt);+ window.requestAnimationFrame = cb => { const id = nextId++; queue.set(id, cb); return id; };+ window.cancelAnimationFrame = id => { queue.delete(id); };++ // autoplaying videos never call play(); adopt them as they appear+ const adopt = () => document.querySelectorAll('video').forEach(v => {+ if (!vids.has(v) && (v.autoplay || v.hasAttribute('autoplay'))) { v.__t0 = vt; v.__playing = true; vids.add(v); nativePause.call(v); }+ });++ // pre-roll frames run the page (so a page that renders before it is ready can get ready)+ // without starting its recorded timeline; __arm() marks frame 0 of the recording+ let rec0 = null;+ window.__arm = () => { rec0 = vt; };+ window.__step = async (dtMs, y) => {+ vt += dtMs;+ adopt();+ if (y !== null) window.scrollTo(0, y);+ if (rec0 !== null && typeof window.__recordFrame === 'function') {+ try { window.__recordFrame((vt - rec0) / 1000); } catch (e) { console.error(e); }+ }+ const seeks = [];+ for (const v of vids) {+ if (!v.__playing || !v.duration || v.readyState < 1) continue;+ let t = (vt - v.__t0) / 1000;+ t = v.loop ? t % v.duration : Math.min(t, v.duration);+ t = Math.min(t, v.duration - 0.001);+ if (Math.abs(v.currentTime - t) > 0.002) {+ seeks.push(new Promise(res => { v.addEventListener('seeked', res, { once: true }); setTimeout(res, 1500); }));+ v.currentTime = t;+ }+ }+ await Promise.all(seeks);+ const cbs = [...queue.values()];+ queue.clear();+ for (const cb of cbs) { try { cb(vt); } catch (e) { console.error(e); } }+ for (const a of document.getAnimations()) {+ if (a.__v0 === undefined) { a.__v0 = vt; a.pause(); }+ const t = vt - a.__v0, end = a.effect ? a.effect.getComputedTiming().endTime : 0;+ if (t >= end && end !== Infinity) a.finish(); else a.currentTime = t;+ }+ return rec0 === null ? 0 : (vt - rec0) / 1000;+ };+})();+"""++METRICS = "() => ({ vh: innerHeight, max: Math.max(0, document.documentElement.scrollHeight - innerHeight) })"+++def smooth(t):+ t = min(1.0, max(0.0, t))+ return t * t * t * (t * (6 * t - 15) + 10)+++def soft(t):+ return 0.5 * min(1.0, max(0.0, t)) + 0.5 * smooth(t)+++def parse_scroll(spec, metrics):+ keys = []+ for tok in spec.split():+ m = re.fullmatch(r"([\d.]+)(~?):([\d.]+)(px|%|vh)?", tok)+ if not m:+ sys.exit(f"bad --scroll key {tok!r}; use seconds:position, e.g. 3:50% or 4~:1200")+ t, linear, v, unit = float(m[1]), bool(m[2]), float(m[3]), m[4] or "px"+ y = v * metrics["max"] / 100 if unit == "%" else v * metrics["vh"] if unit == "vh" else v+ keys.append((t, y, linear))+ keys.sort(key=lambda k: k[0])+ return keys+++def scroll_at(keys, t):+ if not keys:+ return None+ if t <= keys[0][0]:+ return keys[0][1]+ for (t0, y0, _), (t1, y1, linear) in zip(keys, keys[1:]):+ if t <= t1:+ k = (t - t0) / (t1 - t0) if t1 > t0 else 1.0+ return y0 + (y1 - y0) * (k if linear else soft(k))+ return keys[-1][1]+++def pointer_at(mode, t, w, h):+ if mode == "none":+ return None+ if mode == "drift":+ return w * (0.5 + 0.22 * math.sin(t * 0.55)), h * (0.5 + 0.14 * math.sin(t * 0.41 + 1.1))+ x, y = (float(v) for v in mode.split(","))+ return w * x, h * y+++def shoot(page, tries=4):+ """Screenshots can stall now and then (WebKit at 1080p, about 1 in 100). The clock is+ paused between steps, so a retry returns the identical frame."""+ for k in range(tries):+ try:+ return page.screenshot(type="png", timeout=30000)+ except PlaywrightTimeout:+ print(f" screenshot stalled, retry {k + 1}", flush=True)+ sys.exit("screenshot kept stalling")+++def cached_chromium():+ """Newest Chromium in the Playwright cache, for when the installed Playwright expects a+ browser build that was never downloaded (a common mismatch after upgrades)."""+ roots = [os.environ.get("PLAYWRIGHT_BROWSERS_PATH", ""), "~/Library/Caches/ms-playwright",+ "~/.cache/ms-playwright", os.path.join(os.environ.get("LOCALAPPDATA", ""), "ms-playwright")]+ pats = ["chromium_headless_shell-*/chrome-headless-shell-*/chrome-headless-shell*",+ "chromium-*/chrome-*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",+ "chromium-*/chrome-*/chrome", "chromium-*/chrome-*/chrome.exe"]+ found = []+ for r in filter(None, roots):+ for pat in pats:+ found += glob.glob(os.path.join(os.path.expanduser(r), pat))+ found = [f for f in found if os.path.isfile(f) and os.access(f, os.X_OK)]+ return sorted(found, key=lambda f: int(re.search(r"-(\d+)/", f).group(1)))[-1] if found else None+++def launch(p, browser):+ if browser == "webkit":+ return p.webkit.launch()+ args = ["--enable-gpu", "--ignore-gpu-blocklist", "--autoplay-policy=no-user-gesture-required"]+ if sys.platform == "darwin":+ args.append("--use-angle=metal") # real GPU headless on macOS: 60 fps WebGL, not SwiftShader+ exe = os.environ.get("CHROME_PATH")+ try:+ return p.chromium.launch(args=args, executable_path=exe) if exe else p.chromium.launch(args=args)+ except Exception as e:+ exe = cached_chromium()+ if "Executable doesn't exist" not in str(e) or not exe:+ raise+ print(f" Playwright's own Chromium is missing; using {exe}", flush=True)+ return p.chromium.launch(args=args, executable_path=exe)+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("url")+ ap.add_argument("out")+ ap.add_argument("--seconds", type=float, default=10)+ ap.add_argument("--fps", type=float, default=60)+ ap.add_argument("--size", default="1920x1080", help="viewport in CSS px, WxH")+ ap.add_argument("--dpr", type=float, default=1, help="device pixel ratio; output is size x dpr")+ ap.add_argument("--browser", choices=["chromium", "webkit"], default="chromium")+ ap.add_argument("--scroll", default="", help='keys "seconds:position", e.g. "0:0 2:0 9:100%%"')+ ap.add_argument("--pointer", default="none", help="none | drift | x,y (fractions)")+ ap.add_argument("--ready", default="document.readyState === 'complete'", help="JS expression to wait for")+ ap.add_argument("--settle", type=float, default=0.5, help="pre-roll after ready: settle x 20 frames, about that many real seconds")+ ap.add_argument("--kill-lenis", action="store_true")+ ap.add_argument("--crf", type=int, default=16)+ ap.add_argument("--preset", default="slow")+ args = ap.parse_args()++ w, h = (int(v) for v in args.size.lower().split("x"))+ total = round(args.seconds * args.fps)+ dt = 1000 / args.fps+ encode = lambda: subprocess.Popen([+ "ffmpeg", "-v", "error", "-y", "-f", "image2pipe", "-framerate", str(args.fps), "-c:v", "png", "-i", "-",+ "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-preset", args.preset, "-crf", str(args.crf),+ "-pix_fmt", "yuv420p", "-profile:v", "high", "-colorspace", "bt709", "-color_primaries", "bt709",+ "-color_trc", "bt709", "-r", str(args.fps), "-movflags", "+faststart", "-an", args.out,+ ], stdin=subprocess.PIPE)++ errors = []+ with sync_playwright() as p:+ browser = launch(p, args.browser)+ page = browser.new_page(viewport={"width": w, "height": h}, device_scale_factor=args.dpr)+ page.on("pageerror", lambda e: errors.append(str(e)))+ page.on("console", lambda m: m.type == "error" and errors.append(m.text))+ if args.kill_lenis:+ page.add_init_script("window.__KILL_LENIS__ = true;")+ page.add_init_script(CLOCK)+ page.goto(args.url, wait_until="load")+ # rAF is virtual, so nothing renders until we step. Pump pre-roll frames (in real time,+ # so network loads land) until the page says it is ready, then let it settle.+ t_wait = time.monotonic()+ while not page.evaluate(f"() => !!({args.ready})"):+ if time.monotonic() - t_wait > 120:+ sys.exit(f"page never satisfied --ready {args.ready!r}")+ page.evaluate("([dt]) => window.__step(dt, null)", [dt])+ time.sleep(0.03)+ page.evaluate("document.fonts.ready")+ for _ in range(max(1, round(args.settle * 20))):+ page.evaluate("([dt]) => window.__step(dt, null)", [dt])+ time.sleep(0.05)+ page.evaluate("window.__arm()")+ keys = parse_scroll(args.scroll, page.evaluate(METRICS)) if args.scroll else []+ stuck = page.evaluate("""() => [...document.querySelectorAll('video')].filter(v =>+ v.duration > 0.1 && !(v.seekable.length && v.seekable.end(v.seekable.length - 1) > 0.1)).map(v => v.currentSrc)""")+ if stuck:+ print(" warning: these videos cannot seek, so they will hold one frame. The server ignores HTTP\n"+ " Range requests (python3 -m http.server does); serve the page with scripts/serve.py:\n "+ + "\n ".join(stuck), flush=True)++ ff = encode()+ started = time.monotonic()+ for n in range(total):+ t = n / args.fps+ pt = pointer_at(args.pointer, t, w, h)+ if pt:+ page.mouse.move(*pt)+ y = scroll_at(keys, t)+ page.evaluate("([dt, y]) => window.__step(dt, y)", [dt, y])+ ff.stdin.write(shoot(page))+ if n % max(1, round(args.fps * 2)) == 0:+ print(f" {t:6.2f}s frame {n}/{total} ({time.monotonic() - started:.0f}s real)", flush=True)+ browser.close()++ ff.stdin.close()+ if ff.wait() != 0:+ sys.exit("ffmpeg failed")+ print(f"wrote {args.out}: {total} frames, {total / args.fps:.2f}s at {args.fps:g} fps, {w * args.dpr:.0f}x{h * args.dpr:.0f}")+ print("page errors:\n " + "\n ".join(sorted(set(errors))) if errors else "no page errors")+++if __name__ == "__main__":+ main()diff --git a/skills/frame-capture/scripts/serve.py b/skills/frame-capture/scripts/serve.pynew file mode 100644index 0000000..9108bb1--- /dev/null+++ b/skills/frame-capture/scripts/serve.py@@ -0,0 +1,90 @@+#!/usr/bin/env python3+"""Static file server with HTTP Range support, for previewing and recording pages.++ python3 serve.py [DIR] [--port 8000]++`python3 -m http.server` ignores Range headers. Browsers then cannot seek a <video> it+serves (video.seekable is empty), so scroll-scrubbed video freezes and recorded videos hold+their first frame. This server answers byte ranges, never caches (edits show on reload) and+sends the right type for .mjs, .wasm, .glb, .webp, .avif and .webm.+"""+import argparse+import http.server+import os+import re+from functools import partial++EXTRA_TYPES = {".mjs": "text/javascript", ".js": "text/javascript", ".wasm": "application/wasm",+ ".glb": "model/gltf-binary", ".gltf": "model/gltf+json", ".webp": "image/webp",+ ".avif": "image/avif", ".webm": "video/webm", ".mp4": "video/mp4", ".json": "application/json"}+++class Handler(http.server.SimpleHTTPRequestHandler):+ extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map, **EXTRA_TYPES}++ def end_headers(self):+ self.send_header("Cache-Control", "no-store")+ self.send_header("Accept-Ranges", "bytes")+ super().end_headers()++ def send_head(self):+ rng = self.headers.get("Range")+ path = self.translate_path(self.path)+ if not rng or os.path.isdir(path) or not os.path.isfile(path):+ return super().send_head()+ m = re.fullmatch(r"bytes=(\d*)-(\d*)", rng.strip())+ size = os.path.getsize(path)+ if not m or (not m[1] and not m[2]):+ return super().send_head()+ if m[1]:+ start, end = int(m[1]), int(m[2]) if m[2] else size - 1+ else:+ start, end = max(0, size - int(m[2])), size - 1+ if start >= size:+ self.send_response(416)+ self.send_header("Content-Range", f"bytes */{size}")+ self.end_headers()+ return None+ end = min(end, size - 1)+ f = open(path, "rb")+ f.seek(start)+ self.send_response(206)+ self.send_header("Content-Type", self.guess_type(path))+ self.send_header("Content-Range", f"bytes {start}-{end}/{size}")+ self.send_header("Content-Length", str(end - start + 1))+ self.end_headers()+ self._remaining = end - start + 1+ return f++ def copyfile(self, source, outputfile):+ left = getattr(self, "_remaining", None)+ if left is None:+ return super().copyfile(source, outputfile)+ while left > 0:+ chunk = source.read(min(65536, left))+ if not chunk:+ break+ outputfile.write(chunk)+ left -= len(chunk)+ self._remaining = None++ def log_message(self, fmt, *args):+ pass+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("dir", nargs="?", default=".")+ ap.add_argument("--port", type=int, default=8000)+ ap.add_argument("--host", default="127.0.0.1")+ args = ap.parse_args()+ httpd = http.server.ThreadingHTTPServer((args.host, args.port), partial(Handler, directory=args.dir))+ print(f"serving {os.path.abspath(args.dir)} at http://{args.host}:{args.port}/", flush=True)+ try:+ httpd.serve_forever()+ except KeyboardInterrupt:+ pass+++if __name__ == "__main__":+ main()diff --git a/skills/motion-assets/SKILL.md b/skills/motion-assets/SKILL.mdnew file mode 100644index 0000000..42b8964--- /dev/null+++ b/skills/motion-assets/SKILL.md@@ -0,0 +1,83 @@+---+name: motion-assets+description: Plans and generates the images and video clips an animated website needs with AI image and video models, without wasting money. Covers proposing the concept and asset list with exact prompts and costs before spending, keeping one style across every asset, start and end frames for clips that chain or loop, choosing a model by what it can do, calibrating cost, staying under rate limits, recovering failed jobs, fixing loops and outpaints, and logging every prompt so the project can be rebuilt. Use whenever a site needs generated heroes, characters, product shots, textures, background loops or camera-move clips, or when someone says "use Higgsfield", "use Runway", "use Kling", "use Veo", "generate the assets" or "animate this image".+---++# Motion assets++Generated assets make or break an animated site, and they cost real money per attempt. This skill is the production discipline around the models: decide everything that can be decided before spending, make every asset in one look, generate in the order that lets later assets anchor on earlier ones, check each one with numbers, and write it all down.++## Tools++| Script | What it does |+| --- | --- |+| `scripts/loop_check.py` | Scores how well a clip loops, finds the best loop point, trims and cross-fades it |+| `scripts/paste_back.py` | Puts the original pixels back into an outpainted image (outpainting re-renders the middle too) |++Related: `alpha-cutout` (clips that need transparency), `scroll-film` (`prep.py seams` scores joins between chained clips), `cursor-rig` (head-turn clips).++Needs Python 3.9+, `pip install numpy opencv-python-headless`, ffmpeg.++## Before spending anything++Write a short plan and show it to the person paying:++1. **The concept in two sentences**, and what moves on the page.+2. **The asset list**: every image and clip, its size and aspect, its role on the page, and its exact prompt.+3. **The model for each**, chosen by capability (table below), and **the cost** of each and in total. Calibrate first: run one still and one short clip, read what was charged, then estimate the rest from that. Plans and prices change; never quote a price from memory.+4. **What the visitor sees with reduced motion** and on a phone.++Get a yes, then generate.++## Choose models by capability++| You need | The model must support | Notes |+| --- | --- | --- |+| A clip that ends on a planned frame | Start frame **and** end frame | Essential for chained scroll films, head turns and loops |+| A seamless loop | Start = end frame | Then check with `loop_check.py`; models rarely land exactly |+| A pose or expression change on the same character | Image editing that holds framing | Compare to the source at full size: only the edited part may change |+| A transparent subject | Nothing special: shoot on a key plate | See `alpha-cutout`. A few image models return real alpha; video models do not |+| Wider artwork | Outpainting | It re-renders the original area: paste it back (`paste_back.py`) |+| Sharpness | Native resolution | Never upscale a clip and call it 1080p; encode what the model returned |++Observed while building with these models in 2026 (check current docs; behaviour changes):++- Video models drift a flat background colour within a single clip (pure magenta came back pale pink); key per frame.+- Models change small details mid-clip (a black cap turned green late in a serve). Watch the whole clip, not the first and last frames.+- Some higher resolutions and quality modes are gated by subscription plan. A rejected submission usually costs nothing: test the cheapest request that proves access.+- Rate limits are tight on many plans: two or three video jobs in flight. Submit in small batches and resubmit only the job that returned 429 once others finish.+- A "server not responding" error does not always mean no job was created. List recent jobs before resubmitting, or you pay twice.+- A request can come back as a suggested preset instead of a job; decline the preset and resubmit.++## One look across every asset++- Write a **style preamble** (medium, palette, light, lens, texture) once and prepend it byte-for-byte to every image prompt.+- Make one **hero still** first, approve it, then pass it as the style reference to every later image.+- Use **one video model for a whole chain** of clips. Each model has its own motion, colour and grain; switching mid-film shows as a style jump at the seam.++## Generation order++1. Stills: hero, then keyframes (every start and end frame of every clip), then supporting images. Review them side by side before any video.+2. Clips, each anchored on approved stills. For chains, anchor each clip's start on the **exact extracted last frame** of the previous clip, not on the still, so colour drift does not accumulate as a jump.+3. Check every clip: `loop_check.py` for loops, `scroll-film/scripts/prep.py seams` for chains, the whole clip by eye for detail drift.++Clip prompts that behave:++- Name the camera: "locked-off camera" or the exact move ("slow push in, no rotation").+- Name what must not move: "the body, background and lighting stay perfectly still".+- For loops: "constant, even motion; no slowing down at the end". Models ease to a stop by default, which hitches every loop. `loop_check.py` reports it.+- Repeat the plate colour for anything that will be keyed.++## Fixing instead of regenerating++| Problem | Fix |+| --- | --- |+| Loop jumps slightly | `loop_check.py clip.mp4 --fix loop.mp4` cuts at the best loop point; add `--blend 6` to cross-fade small drift |+| Loop jumps a lot (over ~8) | Regenerate with start = end frame and the constant-motion wording |+| Outpaint softened the subject | `paste_back.py original.png extended.png out.png` |+| Seam between chained clips | Regenerate the later clip from the extracted last frame of the earlier one |+| One detail changes colour mid-clip | Recolour that hue in post if it is isolated; otherwise regenerate |++## Log everything++Every generation goes in `prompts/asset-prompts.md` (and machine-readable in a JSONL log): the asset name, model, exact prompt, input images, settings, job id, cost, and which output was kept. It is the only way to regenerate one asset months later in the same style, and the honest record of what was AI-generated.diff --git a/skills/motion-assets/agents/openai.yaml b/skills/motion-assets/agents/openai.yamlnew file mode 100644index 0000000..b670d7a--- /dev/null+++ b/skills/motion-assets/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Motion Assets"+ short_description: "Plan, generate and fix AI images and clips for animated sites"diff --git a/skills/motion-assets/scripts/loop_check.py b/skills/motion-assets/scripts/loop_check.pynew file mode 100644index 0000000..e892be6--- /dev/null+++ b/skills/motion-assets/scripts/loop_check.py@@ -0,0 +1,99 @@+#!/usr/bin/env python3+"""Check and fix a generated clip that should loop seamlessly.++ python3 loop_check.py clip.mp4 # score the loop, find the best cut+ python3 loop_check.py clip.mp4 --fix loop.mp4 # trim to the best loop point+ python3 loop_check.py clip.mp4 --fix loop.mp4 --blend 8 # and cross-fade the last 8 frames into the first++Video models given the same start and end frame rarely land exactly on it: the last frame is+close, but colour or position has drifted, and the motion often eases to a stop. Played as a+loop, that shows as a jump or a hitch once per cycle.++The score is the mean absolute difference (0..255) between the frame that would play last+and the first frame. Under ~3 is invisible, 3..8 is visible on flat backgrounds, over 8 jumps.+The script also searches the last --search seconds for the frame most like the first one+(the best loop point) and reports it. --fix cuts there; --blend N additionally cross-fades+the final N frames into the opening N and starts the loop after them, which hides small drift.++Needs: pip install numpy opencv-python-headless; ffmpeg on PATH for --fix.+"""+import argparse+import subprocess++import cv2+import numpy as np+++def read(path, width=320):+ cap = cv2.VideoCapture(path)+ fps = cap.get(cv2.CAP_PROP_FPS) or 24+ small, full = [], []+ while True:+ ok, f = cap.read()+ if not ok:+ break+ full.append(f)+ h = round(f.shape[0] * width / f.shape[1])+ small.append(cv2.resize(f, (width, h), interpolation=cv2.INTER_AREA).astype(np.float32))+ cap.release()+ return fps, small, full+++def diff(a, b):+ return float(np.abs(a - b).mean())+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("clip")+ ap.add_argument("--fix", help="write a trimmed (and optionally blended) loop here")+ ap.add_argument("--blend", type=int, default=0, help="cross-fade this many final frames into the opening")+ ap.add_argument("--search", type=float, default=1.0, help="seconds at the end to search for the loop point")+ ap.add_argument("--crf", type=int, default=18)+ a = ap.parse_args()++ fps, small, full = read(a.clip)+ n = len(small)+ if n < 4:+ raise SystemExit("clip too short")+ as_is = diff(small[-1], small[0])+ # the frame that should play last is the one just before a frame matching frame 0+ lo = max(1, n - 1 - round(a.search * fps))+ scores = [(diff(small[i], small[0]), i) for i in range(lo, n)]+ best_d, best_i = min(scores)+ last = best_i - 1 # frame best_i duplicates frame 0, so stop before it+ step = np.mean([diff(small[i], small[i + 1]) for i in range(min(n - 1, 12))])+ print(f"{n} frames at {fps:g} fps")+ print(f"as is: last -> first {as_is:5.2f} (typical frame-to-frame change {step:.2f})")+ print(f"best cut: frame {best_i} matches frame 0 at {best_d:5.2f}; loop = frames 0..{last} ({(last + 1) / fps:.2f}s)")+ verdict = "seamless" if best_d < 3 else "visible on flat areas" if best_d < 8 else "jumps: regenerate, or --blend"+ print(f"verdict: {verdict}")+ # a hitch: motion slowing to a stop before the loop point+ tail = np.mean([diff(small[i], small[i + 1]) for i in range(max(0, last - 6), last)]) if last > 6 else step+ if step > 0.5 and tail < step * 0.35:+ print(f"note: motion slows to {tail:.2f} at the end (from {step:.2f}); the loop will hitch. Ask for constant motion.")++ if a.fix:+ frames = full[: last + 1]+ k = min(a.blend, len(frames) // 3)+ if k:+ # classic cross-fade loop: the tail fades into the opening frames 0..k-1, and the+ # loop restarts at frame k, the frame that follows them. The clip gets k frames shorter.+ body = frames[k:len(frames) - k]+ tail = frames[len(frames) - k:]+ mixed = [np.clip(tail[j].astype(np.float32) * (1 - (j + 1) / (k + 1)) + full[j].astype(np.float32) * ((j + 1) / (k + 1)),+ 0, 255).astype(np.uint8) for j in range(k)]+ frames = body + mixed+ h, w = frames[0].shape[:2]+ proc = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}",+ "-r", str(fps), "-i", "-", "-c:v", "libx264", "-preset", "slow", "-crf", str(a.crf),+ "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-an", a.fix], stdin=subprocess.PIPE)+ for f in frames:+ proc.stdin.write(f.tobytes())+ proc.stdin.close()+ proc.wait()+ print(f"wrote {a.fix}: {len(frames)} frames" + (f", last {k} blended" if k else ""))+++if __name__ == "__main__":+ main()diff --git a/skills/motion-assets/scripts/paste_back.py b/skills/motion-assets/scripts/paste_back.pynew file mode 100644index 0000000..27e3e5d--- /dev/null+++ b/skills/motion-assets/scripts/paste_back.py@@ -0,0 +1,92 @@+#!/usr/bin/env python3+"""Put the original pixels back into an outpainted or AI-extended image.++ python3 paste_back.py original.png extended.png out.png [--feather 24] [--no-match]++Outpainting models re-render the whole image, not only the new margins: the original area+comes back softer, shifted by a few pixels, sometimes recoloured. This finds where the+original sits in the extended image (scale and position, by multi-scale template matching),+colour-matches the original to its surroundings, and pastes it back with a feathered edge,+so the middle is the untouched original and only the new margins are generated.++Prints the placement and a match score; under 0.9 means the model moved or changed the+subject too much to paste back cleanly.++Needs: pip install numpy opencv-python-headless.+"""+import argparse++import cv2+import numpy as np+++def locate(orig, ext):+ """Best (scale, x, y, score) placing orig inside ext."""+ small = 640 / max(ext.shape[:2])+ e = cv2.cvtColor(cv2.resize(ext, None, fx=small, fy=small, interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2GRAY)+ best = (0, 1.0, 0, 0)+ base = min(ext.shape[0] / orig.shape[0], ext.shape[1] / orig.shape[1])+ for s in np.linspace(base * 0.5, base * 1.0, 26):+ w, h = round(orig.shape[1] * s * small), round(orig.shape[0] * s * small)+ if w < 16 or h < 16 or w > e.shape[1] or h > e.shape[0]:+ continue+ t = cv2.cvtColor(cv2.resize(orig, (w, h), interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2GRAY)+ r = cv2.matchTemplate(e, t, cv2.TM_CCOEFF_NORMED)+ _, score, _, loc = cv2.minMaxLoc(r)+ if score > best[0]:+ best = (score, s, loc[0] / small, loc[1] / small)+ score, s, x, y = best+ # refine at full resolution in a small window+ w, h = round(orig.shape[1] * s), round(orig.shape[0] * s)+ t = cv2.resize(orig, (w, h), interpolation=cv2.INTER_AREA)+ pad = 12+ x0, y0 = max(0, int(x) - pad), max(0, int(y) - pad)+ win = ext[y0:y0 + h + 2 * pad, x0:x0 + w + 2 * pad]+ if win.shape[0] >= h and win.shape[1] >= w:+ r = cv2.matchTemplate(cv2.cvtColor(win, cv2.COLOR_BGR2GRAY), cv2.cvtColor(t, cv2.COLOR_BGR2GRAY), cv2.TM_CCOEFF_NORMED)+ _, score, _, loc = cv2.minMaxLoc(r)+ x, y = x0 + loc[0], y0 + loc[1]+ return s, int(x), int(y), float(score), t+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("original")+ ap.add_argument("extended")+ ap.add_argument("out")+ ap.add_argument("--feather", type=int, default=24, help="px of soft edge inside the original's border")+ ap.add_argument("--no-match", action="store_true", help="skip colour matching")+ a = ap.parse_args()++ orig, ext = cv2.imread(a.original), cv2.imread(a.extended)+ if orig is None or ext is None:+ raise SystemExit("could not read the images")+ s, x, y, score, t = locate(orig, ext)+ h, w = t.shape[:2]+ print(f"original found at ({x},{y}), {w}x{h} (scale {s:.3f}), match {score:.3f}")+ if score < 0.9:+ print("warning: weak match; the model changed the original area a lot. Check the result closely.")+ region = ext[y:y + h, x:x + w].astype(np.float32)+ src = t.astype(np.float32)+ if not a.no_match:+ # per-channel gain and offset fitted on the border band, so the seam disappears+ band = np.zeros((h, w), bool)+ b = max(4, a.feather)+ band[:b], band[-b:], band[:, :b], band[:, -b:] = True, True, True, True+ for c in range(3):+ sv, rv = src[..., c][band], region[..., c][band]+ gain = rv.std() / max(sv.std(), 1e-3)+ gain = float(np.clip(gain, 0.9, 1.1))+ src[..., c] = (src[..., c] - sv.mean()) * gain + rv.mean()+ m = np.zeros((h, w), np.float32)+ f = a.feather+ m[f:h - f, f:w - f] = 1+ m = cv2.GaussianBlur(m, (0, 0), max(1, f / 2.5))[..., None]+ out = ext.astype(np.float32)+ out[y:y + h, x:x + w] = src * m + region * (1 - m)+ cv2.imwrite(a.out, np.clip(out, 0, 255).astype(np.uint8))+ print(f"wrote {a.out}")+++if __name__ == "__main__":+ main()diff --git a/skills/scroll-film/SKILL.md b/skills/scroll-film/SKILL.mdnew file mode 100644index 0000000..3ba0ae8--- /dev/null+++ b/skills/scroll-film/SKILL.md@@ -0,0 +1,107 @@+---+name: scroll-film+description: Builds scroll-scrubbed film sections, where scrolling plays a pre-rendered camera move, a product turning, a liquid pour or a fly-through one exact frame at a time, from AI-generated or rendered clips. Covers chaining clips into one seamless film with start and end frames, frame sequences versus scrub-ready video, pinned sections with holds for text, phone versions, loading budgets and reduced motion. Use for "scroll-driven animation", "Apple-style scroll video", "fly through the world as you scroll", scroll cinematics, or when a scrubbed video on a page stutters, jumps at a seam or loads too slowly.+---++# Scroll film++A scroll film pins a canvas while the visitor scrolls through a tall section, and the scroll position picks the frame. The visitor drives the camera, which is why it feels three-dimensional even when every frame was rendered in advance. It is the right tool when the motion is too rich for real-time 3D (generated worlds, liquids, people) and the path is fixed.++## Tools++| File | What it does |+| --- | --- |+| `assets/scroll-film.js` | The engine: pinned canvas, progress-to-frame keys with holds, frame sequences or video, smoothing, reduced motion |+| `scripts/prep.py frames` | Joins clips into one numbered WebP sequence and a manifest |+| `scripts/prep.py video` | Joins clips into one MP4 encoded for instant seeking |+| `scripts/prep.py seams` | Scores every join between clips and fails on a visible jump |++Needs ffmpeg and ffprobe, Python 3.9+ and `pip install pillow numpy`. Making the clips is `motion-assets`; transparent subjects are `alpha-cutout`; checking the result is `site-check` and `frame-capture`.++## Plan before generating anything++1. **Write the story as beats.** One beat per scene: what the camera sees at the start, where it goes, what the visitor reads there. Four to seven beats fill a landing page. A beat is one generated clip (a "leg").+2. **Make the keyframes first, all of them, in one style.** A leg is generated between a start frame and an end frame, and the end frame of one leg is the start frame of the next. Generate every keyframe still with the same model and the same style reference before any video, and lay them out side by side. A style that drifts between stills drifts across the whole film.+3. **Budget it out loud.** Cost is roughly stills plus legs times the price of one clip. A phone version in portrait doubles the video cost (see Phones). Calibrate with one still and one clip before committing (`motion-assets` covers model choice, pricing and rate limits).++## Build++1. **Generate the legs** with start and end frames from step 2. Check every join:++ ```bash+ python3 scripts/prep.py seams legs/01.mp4 legs/02.mp4 legs/03.mp4+ ```++ Under 4 is invisible; over 10 is a jump. Fix a bad seam by regenerating that leg anchored on the exact last frame of the previous one (extract it with ffmpeg rather than reusing the still: models shift colour and framing slightly).++2. **Choose frames or video.**++ | | Frame sequence (default) | Scrub video |+ | --- | --- | --- |+ | Accuracy | Exact frame for every scroll position | Seeks land a little late, worst on Safari and low-end phones |+ | Size | 20 to 60 kB a frame at 1280 to 1600 px | About a third of that |+ | Good for | Up to roughly 300 frames | Long films where size matters more than precision |++ ```bash+ python3 scripts/prep.py frames legs/*.mp4 site/film/lg --width 1600 --fps 24+ python3 scripts/prep.py frames legs/*.mp4 site/film/sm --width 900 --fps 24 --quality 72+ python3 scripts/prep.py video legs/*.mp4 site/film.mp4 --width 1920 --gop 4+ ```++ `frames` drops each later leg's first frame, which duplicates the previous leg's last. `video` uses a 4-frame GOP and no B-frames: a normal export with a 250-frame GOP makes every seek decode hundreds of frames, and scrubbing stutters.++3. **Mark up the section.** Height sets how much scrolling the film takes. Roughly one viewport of scroll per second of film feels deliberate; less feels rushed.++ ```html+ <section id="film" style="height: 600vh">+ <div class="pin" style="position: sticky; top: 0; height: 100vh">+ <canvas style="width: 100%; height: 100%; display: block"></canvas>+ <div class="captions">...</div>+ </div>+ </section>+ ```++4. **Wire the engine.**++ ```js+ import { ScrollFilm } from "./scroll-film.js";+ const small = matchMedia("(max-width: 760px)").matches;+ const film = new ScrollFilm({+ section: document.querySelector("#film"),+ canvas: document.querySelector("#film canvas"),+ frames: { count: 247, src: (i) => `film/${small ? "sm" : "lg"}/${String(i).padStart(3, "0")}.webp` },+ keys: [[0, 0], [0.18, 60], [0.3, 60], [0.62, 160], [0.72, 160], [1, 246]],+ onUpdate: ({ progress }) => captions(progress),+ onReady: () => document.body.classList.add("film-ready"),+ });+ ```++ `keys` are `[progress, frame]` pairs. Two keys with the same frame make a hold: the film waits at a beat while its caption scrolls in and out. Put a hold at every beat that carries words. Without holds, text slides over a moving picture and nobody reads it.++ `smooth` (default 0.18) eases the film toward the scroll position, frame-rate independently, so mouse-wheel steps become motion instead of jumps. If the page already smooths scrolling (Lenis), set `smooth: 1`.++ Captions and layers read `progress` in `onUpdate`. Fade a caption in over a short range at the start of its hold and out at the end; keep it off the busiest part of the frame, with a soft scrim behind if needed.++## Phones++A 16:9 film centre-cropped to a portrait phone usually loses the subject. Check the crop on every beat. If it fails, generate portrait (9:16) legs from portrait keyframes and ship them as a separate set, switched by a media query, and say up front that this doubles the video budget. A centre crop is acceptable only when every beat keeps its subject in the middle third.++Phones also get the small frame set and should stay under about 8 MB for the whole film.++## Loading++- Put frame 0 in the HTML as an `<img>` (or as the canvas background) so the first paint is the film, not a blank box.+- The engine loads frame 0, then the last frame, then a coarse-to-fine spread (every 64th, every 32nd, and so on), six at a time. A visitor who scrolls fast always lands near a decoded frame and sees it sharpen.+- Video mode fetches the whole file into a blob before playing, so seeks never wait on the network.+- Serve from a host that answers Range requests. `python3 -m http.server` does not, and videos it serves cannot seek; locally, use the `frame-capture` skill's serve.py.++## Reduced motion++With `prefers-reduced-motion: reduce`, the engine steps between the key frames (`reducedMotion: "steps"`, the default) instead of playing, so every beat still shows its picture. `"still"` shows only the last key frame.++## Check++- Record a scroll-through at low frame rate to judge pacing in seconds, with the `frame-capture` skill: `record.py URL check.mp4 --fps 8 --seconds 20 --scroll "0:0 18:100%"`.+- Scrub fast up and down: nothing blank, no flash at a seam, the pin releases cleanly at the end.+- Load on a throttled connection: first paint shows frame 0.+- Check a phone viewport and a short laptop viewport (1280x720): captions must not cover the subject.diff --git a/skills/scroll-film/agents/openai.yaml b/skills/scroll-film/agents/openai.yamlnew file mode 100644index 0000000..690c734--- /dev/null+++ b/skills/scroll-film/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Scroll Film"+ short_description: "Scroll-scrubbed films from generated clips, seamless and fast to load"diff --git a/skills/scroll-film/assets/scroll-film.js b/skills/scroll-film/assets/scroll-film.jsnew file mode 100644index 0000000..fc8567a--- /dev/null+++ b/skills/scroll-film/assets/scroll-film.js@@ -0,0 +1,179 @@+// Scroll-scrubbed film: a tall section pins a canvas while the visitor scrolls, and scroll+// position picks the frame. Plays an image sequence (exact, recommended) or a video.+//+// <section id="film" style="height: 500vh">+// <div style="position: sticky; top: 0; height: 100vh"><canvas></canvas></div>+// </section>+//+// import { ScrollFilm } from "./scroll-film.js";+// const film = new ScrollFilm({+// section: document.querySelector("#film"),+// canvas: document.querySelector("#film canvas"),+// frames: { count: 120, src: (i) => `film/${innerWidth < 760 ? "sm" : "lg"}/${String(i).padStart(3, "0")}.webp` },+// keys: [[0, 0], [0.25, 40], [0.4, 40], [1, 119]], // optional: [progress, frame] with holds+// onUpdate: ({ progress, frame, index }) => {}, // captions, counters, layer parallax+// onReady: () => document.body.classList.add("film-ready"), // first frame decoded+// });+//+// Video instead of frames: video: { src: "film.mp4" }. The file is fetched whole into a blob,+// so seeks never wait on the network; encode it with prep.py --video (short GOP) or seeks lag.+//+// keys map scroll progress (0..1 through the pinned stretch) to frame numbers, piecewise+// linear. Two keys with the same frame make a hold: the film waits while text scrolls past.+// Without keys, progress maps straight onto the whole film.+//+// Reduced motion: with prefers-reduced-motion, the film steps between key frames instead of+// playing continuously (reducedMotion: "steps"), or shows one still (reducedMotion: "still").++const clamp = (v, a, b) => Math.min(b, Math.max(a, v));++export class ScrollFilm {+ constructor({ section, canvas, frames = null, video = null, keys = null, fit = "cover", focus = [0.5, 0.5],+ smooth = 0.18, reducedMotion = "steps", maxDpr = 2, onUpdate = null, onReady = null }) {+ if (!frames === !video) throw new Error("ScrollFilm needs frames or video");+ Object.assign(this, { section, canvas, keys, fit, focus, smooth, maxDpr, onUpdate, onReady });+ this.ctx = canvas.getContext("2d");+ this.reduced = matchMedia("(prefers-reduced-motion: reduce)").matches ? reducedMotion : null;+ this.progress = 0;+ this.frame = 0;+ this.shown = -1;+ this.live = true;+ this.last = 0;++ if (frames) {+ this.count = frames.count;+ this.images = new Array(this.count);+ this.srcOf = frames.src;+ this.loadFrames();+ } else {+ this.count = 0;+ this.loadVideo(video);+ }++ this.resize();+ new ResizeObserver(() => this.resize()).observe(canvas);+ new IntersectionObserver(([e]) => { this.live = e.isIntersecting; }, { rootMargin: "50% 0px" }).observe(section);+ this.tick = this.tick.bind(this);+ requestAnimationFrame(this.tick);+ }++ // frame 0 first (it is the poster), then a coarse-to-fine spread so a fast scroller always+ // finds a near frame, then the rest+ loadFrames() {+ const order = [0];+ for (let stride = 64; stride >= 1; stride >>= 1)+ for (let i = 0; i < this.count; i += stride) if (!order.includes(i)) order.push(i);+ if (!order.includes(this.count - 1)) order.splice(1, 0, this.count - 1);+ let next = 0;+ const worker = async () => {+ while (next < order.length) {+ const i = order[next++];+ const img = new Image();+ img.decoding = "async";+ img.src = this.srcOf(i);+ try { await img.decode(); this.images[i] = img; if (i === this.target()) this.shown = -1; } catch { /* skip */ }+ if (i === 0) this.onReady?.(this);+ }+ };+ for (let k = 0; k < 6; k++) worker(); // six in flight+ }++ async loadVideo({ src, fps = 24 }) {+ const v = document.createElement("video");+ Object.assign(v, { muted: true, playsInline: true, preload: "auto" });+ v.setAttribute("muted", "");+ v.setAttribute("playsinline", "");+ try {+ const blob = await (await fetch(src)).blob();+ v.src = URL.createObjectURL(blob);+ } catch {+ v.src = src;+ }+ await new Promise((r) => v.addEventListener("loadeddata", r, { once: true }));+ this.video = v;+ this.fps = fps;+ this.count = Math.max(1, Math.round(v.duration * fps));+ v.addEventListener("seeked", () => { this.shown = -1; });+ this.shown = -1;+ this.onReady?.(this);+ }++ resize() {+ const dpr = Math.min(window.devicePixelRatio || 1, this.maxDpr);+ const w = Math.round(this.canvas.clientWidth * dpr), h = Math.round(this.canvas.clientHeight * dpr);+ if (w && h && (this.canvas.width !== w || this.canvas.height !== h)) {+ this.canvas.width = w;+ this.canvas.height = h;+ this.shown = -1;+ }+ }++ scrollProgress() {+ const r = this.section.getBoundingClientRect();+ const run = r.height - innerHeight;+ return run > 0 ? clamp(-r.top / run, 0, 1) : 0;+ }++ frameAt(p) {+ const last = this.count - 1;+ if (!this.keys) return p * last;+ const k = this.keys;+ if (p <= k[0][0]) return k[0][1];+ for (let i = 1; i < k.length; i++) {+ if (p <= k[i][0]) {+ const [p0, f0] = k[i - 1], [p1, f1] = k[i];+ return f0 + (f1 - f0) * (p1 > p0 ? (p - p0) / (p1 - p0) : 1);+ }+ }+ return k[k.length - 1][1];+ }++ target() { return clamp(Math.round(this.frame), 0, Math.max(0, this.count - 1)); }++ tick(now) {+ requestAnimationFrame(this.tick);+ const dt = this.last ? Math.min(0.1, (now - this.last) / 1000) : 1 / 60;+ this.last = now;+ if (!this.live || !this.count) return;+ this.progress = this.scrollProgress();+ let want = this.frameAt(this.progress);+ if (this.reduced === "still") want = this.keys ? this.keys[this.keys.length - 1][1] : 0;+ else if (this.reduced === "steps" && this.keys) {+ want = this.keys.reduce((best, [, f]) => (Math.abs(f - want) < Math.abs(best - want) ? f : best), this.keys[0][1]);+ }+ // ease toward the scroll target, frame-rate independent: wheel steps become motion, not jumps+ const s = this.reduced ? 1 : this.smooth;+ this.frame += (want - this.frame) * (s >= 1 ? 1 : 1 - Math.pow(1 - s, dt * 60));+ if (Math.abs(want - this.frame) < 0.02) this.frame = want;+ const i = this.target();+ if (this.video) this.seekVideo(i);+ if (i !== this.shown) this.draw(i);+ this.onUpdate?.({ progress: this.progress, frame: this.frame, index: i });+ }++ seekVideo(i) {+ const v = this.video, t = Math.min(i / this.fps, v.duration - 0.001);+ if (!v.seeking && Math.abs(v.currentTime - t) > 0.5 / this.fps) v.currentTime = t;+ }++ nearest(i) {+ for (let d = 0; d < this.count; d++) {+ if (this.images[i - d]) return this.images[i - d];+ if (this.images[i + d]) return this.images[i + d];+ }+ return null;+ }++ draw(i) {+ const src = this.video || this.nearest(i);+ if (!src) return;+ const sw = src.videoWidth || src.naturalWidth, sh = src.videoHeight || src.naturalHeight;+ const { width: cw, height: ch } = this.canvas;+ const scale = this.fit === "cover" ? Math.max(cw / sw, ch / sh) : Math.min(cw / sw, ch / sh);+ const dw = sw * scale, dh = sh * scale;+ const dx = (cw - dw) * this.focus[0], dy = (ch - dh) * this.focus[1];+ this.ctx.clearRect(0, 0, cw, ch);+ this.ctx.drawImage(src, dx, dy, dw, dh);+ if (this.video ? !this.video.seeking : this.images[i]) this.shown = i;+ }+}diff --git a/skills/scroll-film/scripts/prep.py b/skills/scroll-film/scripts/prep.pynew file mode 100644index 0000000..eca1ed6--- /dev/null+++ b/skills/scroll-film/scripts/prep.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3+"""Turn rendered clips into scroll-film assets: WebP frame sequences and scrub-ready MP4.++ python3 prep.py frames leg1.mp4 [leg2.mp4 ...] OUT_DIR [--width 1600] [--fps 24] [--quality 78]+ python3 prep.py video leg1.mp4 [leg2.mp4 ...] OUT.mp4 [--width 1920] [--gop 4]+ python3 prep.py seams leg1.mp4 leg2.mp4 [...]++frames: extracts every leg in order into one numbered sequence (000.webp ...) plus+manifest.json, dropping each later leg's first frame, which repeats the previous leg's last+frame when the legs were chained with start/end frames. Make two sets, lg and sm.+video: joins the legs into one MP4 with a short GOP and no B-frames, so setting currentTime+lands fast in every browser. A normal export (GOP 250) makes scrubbing stutter.+seams: measures how well each leg's last frame matches the next leg's first frame (mean+absolute difference, 0..255). Under ~4 is invisible, over ~10 shows as a jump; regenerate+the leg or re-anchor it on the exact previous frame.++Needs: ffmpeg + ffprobe on PATH; pillow for seams (pip install pillow numpy).+"""+import argparse+import json+import subprocess+import tempfile+from pathlib import Path+++def run(cmd):+ subprocess.run(cmd, check=True)+++def last_frame(path, out):+ run(["ffmpeg", "-v", "error", "-y", "-sseof", "-0.25", "-i", str(path), "-update", "1", "-q:v", "1", str(out)])+++def first_frame(path, out):+ run(["ffmpeg", "-v", "error", "-y", "-i", str(path), "-frames:v", "1", "-q:v", "1", str(out)])+++def cmd_frames(a):+ # ffmpeg writes PNGs and Pillow encodes the WebP: many ffmpeg builds ship without libwebp+ from PIL import Image+ out = Path(a.out)+ out.mkdir(parents=True, exist_ok=True)+ n = 0+ with tempfile.TemporaryDirectory() as tmp:+ for li, leg in enumerate(a.legs):+ d = Path(tmp) / f"leg{li}"+ d.mkdir()+ vf = f"fps={a.fps},scale={a.width}:-2:flags=lanczos"+ run(["ffmpeg", "-v", "error", "-y", "-i", leg, "-vf", vf, "-start_number", "0", str(d / "%05d.png")])+ files = sorted(d.glob("*.png"))+ if li > 0 and not a.keep_joins:+ files = files[1:]+ for f in files:+ Image.open(f).save(out / f"{n:03d}.webp", "WEBP", quality=a.quality, method=6)+ n += 1+ w, h = Image.open(out / "000.webp").size+ size = sum(f.stat().st_size for f in out.glob("*.webp"))+ (out / "manifest.json").write_text(json.dumps({"count": n, "width": w, "height": h, "fps": a.fps,+ "pattern": "{i:03d}.webp", "bytes": size}))+ print(f"{out}: {n} frames {w}x{h}, {size / 1e6:.1f} MB ({size / n / 1e3:.0f} kB a frame)")+++def cmd_video(a):+ with tempfile.TemporaryDirectory() as tmp:+ lst = Path(tmp) / "list.txt"+ lst.write_text("".join(f"file '{Path(p).resolve()}'\n" for p in a.legs))+ run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(lst),+ "-vf", f"scale={a.width}:-2:flags=lanczos,fps={a.fps}", "-c:v", "libx264", "-preset", "slow",+ "-crf", str(a.crf), "-g", str(a.gop), "-keyint_min", str(a.gop), "-bf", "0", "-sc_threshold", "0",+ "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-an", a.out])+ print(f"wrote {a.out} (GOP {a.gop}, no B-frames, {Path(a.out).stat().st_size / 1e6:.1f} MB)")+++def cmd_seams(a):+ import numpy as np+ from PIL import Image+ worst = 0+ with tempfile.TemporaryDirectory() as tmp:+ for i in range(len(a.legs) - 1):+ l, f = Path(tmp) / "l.png", Path(tmp) / "f.png"+ last_frame(a.legs[i], l)+ first_frame(a.legs[i + 1], f)+ A = np.asarray(Image.open(l).convert("RGB"), np.float32)+ B = Image.open(f).convert("RGB")+ if B.size != (A.shape[1], A.shape[0]):+ B = B.resize((A.shape[1], A.shape[0]), Image.LANCZOS)+ d = float(np.abs(A - np.asarray(B, np.float32)).mean())+ worst = max(worst, d)+ verdict = "clean" if d < 4 else "visible" if d > 10 else "check by eye"+ print(f"{Path(a.legs[i]).name} -> {Path(a.legs[i + 1]).name}: {d:.2f} {verdict}")+ raise SystemExit(1 if worst > 10 else 0)+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ sub = ap.add_subparsers(dest="cmd", required=True)+ f = sub.add_parser("frames")+ f.add_argument("legs", nargs="+")+ f.add_argument("out")+ f.add_argument("--width", type=int, default=1600)+ f.add_argument("--fps", type=float, default=24)+ f.add_argument("--quality", type=int, default=78)+ f.add_argument("--keep-joins", action="store_true", help="keep each leg's first frame")+ v = sub.add_parser("video")+ v.add_argument("legs", nargs="+")+ v.add_argument("out")+ v.add_argument("--width", type=int, default=1920)+ v.add_argument("--fps", type=float, default=24)+ v.add_argument("--gop", type=int, default=4)+ v.add_argument("--crf", type=int, default=20)+ s = sub.add_parser("seams")+ s.add_argument("legs", nargs="+")+ a = ap.parse_args()+ if a.cmd in ("frames", "video") and len(a.legs) < 1:+ ap.error("give at least one clip")+ {"frames": cmd_frames, "video": cmd_video, "seams": cmd_seams}[a.cmd](a)+++if __name__ == "__main__":+ main()diff --git a/skills/site-check/SKILL.md b/skills/site-check/SKILL.mdnew file mode 100644index 0000000..690c349--- /dev/null+++ b/skills/site-check/SKILL.md@@ -0,0 +1,69 @@+---+name: site-check+description: Verifies a 3D or animated web page in real headless browsers before anyone else sees it. Shoots every view, light state and scroll position at desktop, tablet and phone widths in Chromium and WebKit (Safari), measures frame time, draw calls and triangles, catches page errors, failed requests, blank WebGL canvases, horizontal overflow and reduced-motion behaviour, and builds one contact sheet. Use after building or changing any three.js, WebGL, canvas, scroll-driven or animated page, before publishing or recording it, or when someone asks "does it work", "check it on mobile", "why is it slow" or "test it in Safari".+---++# Site check++An animated page can look perfect in the one browser tab it was built in and fail everywhere else: a blank canvas in Safari, a crop on phones, a seam in a scroll film, a 40 ms frame on a laptop. This skill looks at the page the way visitors will, in several real browsers at several sizes, and reports what broke with pictures.++## Tool++`scripts/check.py` drives headless Chromium (on the real GPU) and WebKit through Playwright.++```bash+python3 scripts/check.py http://127.0.0.1:8000/ --out shots \+ --widths 1440,768,390 --browser both \+ --query "view=front" "view=aerial&light=night" \+ --scroll-steps 6 --ready "window.__ready === true"+```++| Option | Meaning |+| --- | --- |+| `--query` | Query strings appended to the URL, each shot at every width. Give pages deep links (`?view=`, `?light=`, `?step=`) so every state is reachable |+| `--widths` | 1440 (laptop), 768 (tablet), 390 (phone, emulated with touch and DPR 2) |+| `--browser` | `chromium`, `webkit` (Safari's engine) or `both` |+| `--scroll-steps N` | Also shoots N evenly spaced scroll positions, for scroll-driven pages |+| `--ready` | JS expression that is true once the page has rendered for real |+| `--wait` | Seconds to let things settle before measuring |++Output: one PNG per shot, `report.json`, and `sheet.jpg` with every shot labelled; problem shots are labelled in red. The script exits 1 if any shot had a page error, a failed or 4xx/5xx request, a blank canvas or horizontal overflow. Each shot also gets a reduced-motion pass at the widest width.++Needs Python 3.9+, `pip install playwright pillow`, and `python3 -m playwright install chromium webkit`. Serve the page over HTTP (ES modules and video seeking need it) with `scripts/serve.py DIR --port 8000`; it answers Range requests, which `python3 -m http.server` does not.++## Reading the report++- **ms per frame** is measured over 60 real frames. Under 16.7 is 60 fps; headless on a laptop GPU should sit near 16.7 (vsync), so a higher number means real cost. Compare runs with each other. If the report says the renderer is SwiftShader or llvmpipe, the GPU was not used and frame times mean nothing.+- **calls / triangles** come from `window.__app.renderer` (three.js), counted for a whole frame including every post-processing pass. Expose the renderer there so the check can see it.+- **ready_s** is how long the page took to set its ready flag. Over 3 s on a fast machine means the loader is visible for too long on a phone.+- **blank canvas** means a visible canvas was one flat colour: a WebGL context that failed, a shader that did not compile in that browser, or a frame drawn before assets loaded.++## Then look++The numbers catch breakage; your eyes catch ugliness. Open `sheet.jpg` and check each shot for:++- The subject cropped or tiny on the phone shot. 3D scenes should widen their vertical field of view on portrait screens; layouts should restack.+- Text over busy imagery without contrast.+- UI covering the subject, or sitting under the phone's home indicator.+- Lighting states that crush to black or clip to white.+- WebKit shots that differ from Chromium: colour (Safari ignores some colour-space hints), missing transparency (VP9 alpha video does not play in Safari), fonts.++## Checks the script cannot do alone++Run these by hand or with `frame-capture` at a low frame rate (`--fps 8`), which is fast and exact:++- **Seams and loops.** Scrub every scroll film up and down fast; watch each join and the wrap of every loop. `scroll-film/scripts/prep.py seams` scores joins numerically.+- **Pins release.** At the end of every pinned section the page must scroll on without a jump.+- **Long sessions.** Leave the page running for a minute, switch light presets back and forth, resize the window a few times; frame time should not creep up (leaked geometries and textures show in `report.json` as rising counts).+- **Throttled first load.** With network throttling, the first paint should be the hero's poster or first frame, not a blank page.+- **Interaction.** Orbit, zoom, hover states, keyboard focus on every control, and touch on a phone.++## Environment traps++- An embedded browser preview that is hidden, or a background tab, throttles or freezes `requestAnimationFrame`. A page that "does not animate" there may be fine. Headless browsers do not have this problem.+- `python3 -m http.server` ignores Range requests, so videos cannot seek and scroll-scrubbed video freezes. Use a server that answers them.+- A missing Playwright browser build after an upgrade: the script falls back to any Chromium in the Playwright cache; `CHROME_PATH` overrides it.++## Report back++Lead with what is broken, ranked by how many visitors it hits: errors and blank canvases first, then phone layout, then Safari differences, then performance, then polish. Attach the contact sheet. Say what was not checked (no real phone, no Windows GPU, no slow network) rather than implying it was.diff --git a/skills/site-check/agents/openai.yaml b/skills/site-check/agents/openai.yamlnew file mode 100644index 0000000..c064d7e--- /dev/null+++ b/skills/site-check/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Site Check"+ short_description: "Shoot, measure and stress a 3D or animated page in real browsers"diff --git a/skills/site-check/scripts/check.py b/skills/site-check/scripts/check.pynew file mode 100644index 0000000..5025d94--- /dev/null+++ b/skills/site-check/scripts/check.py@@ -0,0 +1,205 @@+#!/usr/bin/env python3+"""Check a 3D or animated page in real browsers: stills, frame time, errors, blank canvases,+overflow, reduced motion, phone layout and scroll states, plus a contact sheet.++ python3 check.py URL [--out shots] [--widths 1440,768,390] [--browser chromium|webkit|both]+ [--query "view=front" "view=aerial&light=night"] [--scroll-steps 6]+ [--ready "window.__ready === true"] [--wait 1.5]++Each query string is appended to URL and shot at every width. --scroll-steps N also shoots+the page at N evenly spaced scroll positions (for scroll-driven pages). Every shot records:+milliseconds per frame over 60 real frames, page errors and console errors, whether a+<canvas> came out blank (one flat colour), horizontal overflow, and WebGL renderer info+(draw calls and triangles when the page exposes window.__app.renderer). A reduced-motion+pass shoots the first query at the widest width with prefers-reduced-motion: reduce.++Writes OUT/report.json and OUT/sheet.jpg; exits 1 when any shot has errors, a blank canvas+or overflow. Frame times from headless runs are indicative: compare runs with each other,+not with a phone.++Needs: pip install playwright pillow; python3 -m playwright install chromium webkit.+"""+import argparse+import glob+import json+import os+import re+import sys+import time+from pathlib import Path++from PIL import Image, ImageDraw, ImageStat+from playwright.sync_api import sync_playwright++FRAME_TIME = """() => new Promise(r => { let n = 0; const t0 = performance.now();+ const f = () => { if (++n < 60) requestAnimationFrame(f); else r((performance.now() - t0) / 60); };+ requestAnimationFrame(f); })"""++PROBE = """async () => {+ const out = { overflow: document.documentElement.scrollWidth > innerWidth + 1, canvases: [] };+ for (const c of document.querySelectorAll('canvas')) {+ const r = c.getBoundingClientRect();+ if (r.width < 40 || r.height < 40 || r.bottom < 0 || r.top > innerHeight) continue;+ out.canvases.push({ x: r.left, y: r.top, w: r.width, h: r.height });+ }+ const gl = (() => { const c = document.querySelector('canvas'); if (!c) return null;+ const g = c.getContext('webgl2') || c.getContext('webgl'); if (!g) return null;+ const ext = g.getExtension('WEBGL_debug_renderer_info');+ return { lost: g.isContextLost(), renderer: ext ? g.getParameter(ext.UNMASKED_RENDERER_WEBGL) : g.getParameter(g.RENDERER) }; })();+ out.gl = gl;+ const app = window.__app;+ if (app && app.renderer && app.renderer.info) {+ // a composer renders many passes per frame; count the whole frame, not the last pass+ const i = app.renderer.info;+ i.autoReset = false; i.reset();+ await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));+ out.three = { calls: i.render.calls, triangles: i.render.triangles, geometries: i.memory.geometries, textures: i.memory.textures, programs: (i.programs || []).length };+ i.autoReset = true;+ }+ if (performance.memory) out.heapMB = Math.round(performance.memory.usedJSHeapSize / 1e6);+ return out;+}"""+++def cached_chromium():+ roots = [os.environ.get("PLAYWRIGHT_BROWSERS_PATH", ""), "~/Library/Caches/ms-playwright", "~/.cache/ms-playwright",+ os.path.join(os.environ.get("LOCALAPPDATA", ""), "ms-playwright")]+ pats = ["chromium_headless_shell-*/chrome-headless-shell-*/chrome-headless-shell*",+ "chromium-*/chrome-*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",+ "chromium-*/chrome-*/chrome", "chromium-*/chrome-*/chrome.exe"]+ found = [f for r in filter(None, roots) for pat in pats for f in glob.glob(os.path.join(os.path.expanduser(r), pat))]+ found = [f for f in found if os.path.isfile(f) and os.access(f, os.X_OK)]+ return sorted(found, key=lambda f: int(re.search(r"-(\d+)/", f).group(1)))[-1] if found else None+++def launch(p, name):+ if name == "webkit":+ return p.webkit.launch()+ args = ["--enable-gpu", "--ignore-gpu-blocklist"] + (["--use-angle=metal"] if sys.platform == "darwin" else [])+ exe = os.environ.get("CHROME_PATH")+ try:+ return p.chromium.launch(args=args, executable_path=exe) if exe else p.chromium.launch(args=args)+ except Exception as e:+ exe = cached_chromium()+ if "Executable doesn't exist" not in str(e) or not exe:+ raise+ return p.chromium.launch(args=args, executable_path=exe)+++def blank(img, box):+ x, y, w, h = (int(v) for v in (box["x"], box["y"], box["w"], box["h"]))+ crop = img.crop((max(x, 0), max(y, 0), min(x + w, img.width), min(y + h, img.height))).convert("L")+ return max(ImageStat.Stat(crop).stddev) < 1.5+++def shoot(browser, bname, url, width, out, args, reduced=False, scroll=None):+ mobile = width < 600+ height = {1440: 900, 768: 1024, 390: 844}.get(width, round(width * 0.62))+ ctx = browser.new_context(viewport={"width": width, "height": height}, device_scale_factor=2 if mobile else 1,+ is_mobile=mobile and bname == "chromium", has_touch=mobile,+ reduced_motion="reduce" if reduced else "no-preference")+ page = ctx.new_page()+ errors = []+ page.on("pageerror", lambda e: errors.append(f"pageerror: {e}"))+ page.on("console", lambda m: m.type == "error" and not m.text.startswith("Failed to load resource")+ and errors.append(f"console: {m.text}"))+ page.on("requestfailed", lambda r: "favicon" not in r.url and errors.append(f"failed: {r.url} {r.failure}"))+ page.on("response", lambda r: r.status >= 400 and "favicon" not in r.url and errors.append(f"HTTP {r.status}: {r.url}"))+ t0 = time.monotonic()+ page.goto(url, wait_until="load", timeout=90000)+ try:+ page.wait_for_function(args.ready, timeout=60000, polling=100)+ except Exception:+ errors.append(f"never ready: {args.ready}")+ ready_s = time.monotonic() - t0+ page.evaluate("document.fonts.ready")+ if scroll is not None:+ page.evaluate(f"window.scrollTo(0, (document.documentElement.scrollHeight - innerHeight) * {scroll})")+ time.sleep(args.wait)+ ms = page.evaluate(FRAME_TIME)+ probe = page.evaluate(PROBE)+ tag = f"{bname}-{width}" + ("-reduced" if reduced else "") + (f"-scroll{round(scroll * 100):03d}" if scroll is not None else "")+ q = url.split("?", 1)[1] if "?" in url else "default"+ name = re.sub(r"[^a-z0-9]+", "-", f"{q}-{tag}".lower()).strip("-")+ path = out / f"{name}.png"+ page.screenshot(path=str(path))+ img = Image.open(path)+ scale = img.width / width+ blanks = [c for c in probe["canvases"] if blank(img, {k: v * scale for k, v in c.items()})]+ ctx.close()+ return {"name": name, "url": url, "browser": bname, "width": width, "reduced": reduced, "scroll": scroll,+ "ready_s": round(ready_s, 2), "ms_per_frame": round(ms, 1), "fps": round(1000 / ms, 1) if ms else None,+ "errors": sorted(set(e for e in errors if "favicon" not in e)), "blank_canvases": len(blanks),+ "overflow": probe["overflow"], "gl": probe.get("gl"), "three": probe.get("three"),+ "heapMB": probe.get("heapMB"), "file": str(path)}+++def sheet(results, out):+ thumbs = []+ for r in results:+ im = Image.open(r["file"]).convert("RGB")+ im.thumbnail((480, 360))+ card = Image.new("RGB", (480, 400), "#111")+ card.paste(im, ((480 - im.width) // 2, 0))+ d = ImageDraw.Draw(card)+ bad = r["errors"] or r["blank_canvases"] or r["overflow"]+ d.text((8, 366), f"{r['name'][:58]}", fill="#ff7a6b" if bad else "#ddd")+ d.text((8, 382), f"{r['ms_per_frame']} ms/frame" + (f" {r['three']['calls']} calls" if r.get("three") else ""), fill="#aaa")+ thumbs.append(card)+ cols = min(4, len(thumbs))+ rows = (len(thumbs) + cols - 1) // cols+ s = Image.new("RGB", (cols * 480, rows * 400), "#000")+ for i, t in enumerate(thumbs):+ s.paste(t, ((i % cols) * 480, (i // cols) * 400))+ s.save(out / "sheet.jpg", quality=86)+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("url")+ ap.add_argument("--out", default="shots")+ ap.add_argument("--widths", default="1440,768,390")+ ap.add_argument("--browser", choices=["chromium", "webkit", "both"], default="chromium")+ ap.add_argument("--query", nargs="*", default=[""])+ ap.add_argument("--scroll-steps", type=int, default=0)+ ap.add_argument("--ready", default="document.readyState === 'complete'")+ ap.add_argument("--wait", type=float, default=1.5, help="seconds after ready before measuring")+ args = ap.parse_args()++ out = Path(args.out)+ out.mkdir(parents=True, exist_ok=True)+ widths = [int(w) for w in args.widths.split(",")]+ browsers = ["chromium", "webkit"] if args.browser == "both" else [args.browser]+ join = lambda q: args.url if not q else args.url + ("&" if "?" in args.url else "?") + q+ results = []+ with sync_playwright() as p:+ for bname in browsers:+ b = launch(p, bname)+ for q in args.query:+ for w in widths:+ results.append(shoot(b, bname, join(q), w, out, args))+ r = results[-1]+ flag = (" ERR" if r["errors"] else "") + (" BLANK" if r["blank_canvases"] else "") + (" OVERFLOW" if r["overflow"] else "")+ print(f"{r['name']:60s} {r['ms_per_frame']:6.1f} ms/frame ready {r['ready_s']:4.1f}s{flag}", flush=True)+ for i in range(args.scroll_steps):+ s = i / max(1, args.scroll_steps - 1)+ results.append(shoot(b, bname, join(args.query[0]), widths[0], out, args, scroll=s))+ print(f"{results[-1]['name']:60s} {results[-1]['ms_per_frame']:6.1f} ms/frame", flush=True)+ results.append(shoot(b, bname, join(args.query[0]), widths[0], out, args, reduced=True))+ print(f"{results[-1]['name']:60s} reduced motion", flush=True)+ b.close()+ (out / "report.json").write_text(json.dumps(results, indent=2))+ sheet(results, out)+ bad = [r for r in results if r["errors"] or r["blank_canvases"] or r["overflow"]]+ for r in bad:+ print(f"\nPROBLEM {r['name']}:" + "".join(f"\n {e}" for e in r["errors"])+ + ("\n blank canvas" if r["blank_canvases"] else "") + ("\n horizontal overflow" if r["overflow"] else ""))+ gl = next((r["gl"] for r in results if r.get("gl")), None)+ if gl:+ print(f"\nWebGL renderer: {gl['renderer']}" + (" (software: frame times are not representative)" if re.search("swiftshader|llvmpipe|software", gl["renderer"] or "", re.I) else ""))+ print(f"{len(results)} shots, {len(bad)} with problems -> {out / 'sheet.jpg'}")+ sys.exit(1 if bad else 0)+++if __name__ == "__main__":+ main()diff --git a/skills/site-check/scripts/serve.py b/skills/site-check/scripts/serve.pynew file mode 100644index 0000000..9108bb1--- /dev/null+++ b/skills/site-check/scripts/serve.py@@ -0,0 +1,90 @@+#!/usr/bin/env python3+"""Static file server with HTTP Range support, for previewing and recording pages.++ python3 serve.py [DIR] [--port 8000]++`python3 -m http.server` ignores Range headers. Browsers then cannot seek a <video> it+serves (video.seekable is empty), so scroll-scrubbed video freezes and recorded videos hold+their first frame. This server answers byte ranges, never caches (edits show on reload) and+sends the right type for .mjs, .wasm, .glb, .webp, .avif and .webm.+"""+import argparse+import http.server+import os+import re+from functools import partial++EXTRA_TYPES = {".mjs": "text/javascript", ".js": "text/javascript", ".wasm": "application/wasm",+ ".glb": "model/gltf-binary", ".gltf": "model/gltf+json", ".webp": "image/webp",+ ".avif": "image/avif", ".webm": "video/webm", ".mp4": "video/mp4", ".json": "application/json"}+++class Handler(http.server.SimpleHTTPRequestHandler):+ extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map, **EXTRA_TYPES}++ def end_headers(self):+ self.send_header("Cache-Control", "no-store")+ self.send_header("Accept-Ranges", "bytes")+ super().end_headers()++ def send_head(self):+ rng = self.headers.get("Range")+ path = self.translate_path(self.path)+ if not rng or os.path.isdir(path) or not os.path.isfile(path):+ return super().send_head()+ m = re.fullmatch(r"bytes=(\d*)-(\d*)", rng.strip())+ size = os.path.getsize(path)+ if not m or (not m[1] and not m[2]):+ return super().send_head()+ if m[1]:+ start, end = int(m[1]), int(m[2]) if m[2] else size - 1+ else:+ start, end = max(0, size - int(m[2])), size - 1+ if start >= size:+ self.send_response(416)+ self.send_header("Content-Range", f"bytes */{size}")+ self.end_headers()+ return None+ end = min(end, size - 1)+ f = open(path, "rb")+ f.seek(start)+ self.send_response(206)+ self.send_header("Content-Type", self.guess_type(path))+ self.send_header("Content-Range", f"bytes {start}-{end}/{size}")+ self.send_header("Content-Length", str(end - start + 1))+ self.end_headers()+ self._remaining = end - start + 1+ return f++ def copyfile(self, source, outputfile):+ left = getattr(self, "_remaining", None)+ if left is None:+ return super().copyfile(source, outputfile)+ while left > 0:+ chunk = source.read(min(65536, left))+ if not chunk:+ break+ outputfile.write(chunk)+ left -= len(chunk)+ self._remaining = None++ def log_message(self, fmt, *args):+ pass+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("dir", nargs="?", default=".")+ ap.add_argument("--port", type=int, default=8000)+ ap.add_argument("--host", default="127.0.0.1")+ args = ap.parse_args()+ httpd = http.server.ThreadingHTTPServer((args.host, args.port), partial(Handler, directory=args.dir))+ print(f"serving {os.path.abspath(args.dir)} at http://{args.host}:{args.port}/", flush=True)+ try:+ httpd.serve_forever()+ except KeyboardInterrupt:+ pass+++if __name__ == "__main__":+ main()diff --git a/skills/threejs-scene/SKILL.md b/skills/threejs-scene/SKILL.mdnew file mode 100644index 0000000..2eb7d2d--- /dev/null+++ b/skills/threejs-scene/SKILL.md@@ -0,0 +1,104 @@+---+name: threejs-scene+description: Builds real-time 3D websites in three.js from code alone, with no model files. Covers buildings and landmarks, vehicles, machines, landscapes and product studies made of procedural geometry (profile sweeps, lathes, instancing), canvas textures, shader patches, a physically based sky and sun, soft shadows, ambient occlusion and bloom, light presets, camera vantages and flights, quality tiers, and a starter that runs at 60 fps. Use when someone asks for a 3D website, a three.js scene, a WebGL hero, an interactive 3D model of a real place or object, a "3D version" of something, or when an existing three.js page looks flat, plasticky, aliased, washed out or slow.+---++# three.js scene++A convincing 3D page is mostly light and proportion, not polygon count. The White House reads as the White House because its storeys, column spacing and cornice depth are right, and because a low sun throws long shadows across it, not because every window has a frame. This skill builds scenes the way an architect's model is made: from real dimensions, in code, with lighting done properly.++## Start from the starter++`assets/starter/` is a complete, working scene (a round pavilion on a lawn) with everything below already wired. Copy it, keep `env.js`, `kit.js` and `main.js`, and replace `scene.js` with your subject.++```bash+cp -r assets/starter my-scene && cd my-scene+python3 -m http.server 8000 # any static server; ES modules need http://, not file://+```++| File | Holds |+| --- | --- |+| `index.html` | Import map pinned to three r169 (`[email protected]`), canvas, title, light buttons, loader |+| `main.js` | Renderer, camera, post stack, quality tiers, vantages and flights, recording hooks, frame loop |+| `env.js` | Sky, sun, image-based light, fog, clouds, night sky; three presets that blend; shadow fitting |+| `kit.js` | Seeded RNG, canvas textures, instancing kit, lathe, arc, profile sweep with mitred corners |+| `scene.js` | The example subject and every pattern worth copying |++URL parameters work out of the box: `?view=front|corner|low|aerial`, `?light=morning|golden|night`, `?quality=high|balanced|fast`, and `?record=1` for a frame-exact recording with `frame-capture`.++## Workflow++1. **Collect references and dimensions before writing geometry.** Plans, elevations, a photo from each side, the real measurements (storey heights, bay spacing, column diameter, wheelbase). Write them as constants at the top of the scene file in metres. A building built from guessed proportions looks like a toy however detailed it is.+2. **Block it out in boxes** at the right size and check from the vantages a visitor will see. Fix proportions now; detail hides nothing.+3. **Detail by kind, not by instance.** Write one column, one window, one baluster as a function, then place hundreds through the `Kit` (one draw call per part). Mouldings, kerbs, steps and rails are profiles swept along paths (`sweep`); round things are lathes.+4. **Light it** with a preset from `env.js`, then tune exposure, sun elevation and fog for the mood. Most of the realism arrives in this step.+5. **Add life:** wind in trees, water, flags, people or traffic as instanced sprites, lamps that come on at night. Drive all of it from the shared uniforms (`U.uTime`, `U.uWind`, `U.uNight`) so recording and light changes stay in sync.+6. **Measure and check** with `site-check`: frame time, draw calls, every vantage at every light, a phone. Then record with `frame-capture`.++## Rendering setup that matters++These are set in `main.js`; keep them unless you know why not.++- **Tone mapping** `ACESFilmicToneMapping` with exposure per preset (0.6 to 1.0). Without tone mapping, bright skies clip and everything looks like a game from 2009.+- **Antialiasing in the composer, not the canvas:** `antialias: false` on the renderer, and a `HalfFloatType` render target with `samples: 4` for the effect composer. Canvas MSAA does nothing once post-processing is on.+- **Post stack:** `RenderPass` → `GTAOPass` (ambient occlusion: contact shadows under cornices, between columns, where walls meet ground) → `UnrealBloomPass` (strength about 0.12 by day, 0.5 at night) → `OutputPass` (tone mapping and sRGB last). The GTAO pass is subclassed to hide anything with `userData.noAO` (sky layers, particles, glass) because AO darkens whatever it sees.+- **Image-based light from the sky itself:** `env.js` renders a private copy of the sky into a PMREM environment map, so reflections and ambient light match the sky's colour at every preset. Regenerate it while presets blend (every sixth frame is enough: PMREM is expensive).+- **One shadow-casting sun** with a 4096 map, its frustum sized to the view and centred on the camera target, snapped to whole texels so shadows do not shimmer as the camera moves. `normalBias` scaled to the scene removes acne without peter-panning.+- **Long lens:** field of view 38. On tall screens the starter widens the vertical FOV so the horizontal view matches a 16:9 screen; a phone sees the whole subject instead of a crop.+- **Pixel ratio capped at 2.** A 3x phone renders 2.25 times the pixels of 2x for no visible gain.++## Light++Each preset in `env.js` moves the sky, sun, hemisphere light, fog, exposure and clouds together. Read `references/lighting.md` before tuning. The short version:++- Low sun (5 to 10 degrees) is where scenes look expensive: long shadows, warm faces, a gradient sky. Set the light a few degrees above the painted sun so faces still read.+- Night is mostly the absence of light. Keep sun intensity near 0.15, let windows and lamps carry the scene with emissive materials plus bloom, and add very few real lights. Point and spot lights use physical units (candela) with `decay: 2`. With decay 1.4 and a guessed intensity, a single fountain light blew out half a scene.+- Every dark light still costs a shadow pass. Hide lights (`visible = false`) when their intensity is zero.++## Geometry patterns++See `references/geometry.md` for details and code. The ones used most:++- `sweep(profile, path, { closed, y })`: a 2D profile of `[outward offset, height]` pairs swept along a path in the XZ plane with mitred corners. Cornices, entablatures, kerbs, road edges, steps, skirting, picture rails. Closed paths detect their winding, so "outward" is always outward.+- `lathe([[r, y], ...])`: columns with entasis, balusters, urns, domes, lamp posts, wheels, bottles.+- `Kit`: define a part once, `add` matrices, `build` one `InstancedMesh` per part. Per-instance colour gives variety (leaf greens, brick tones) at no cost.+- `canvasTex(w, h, draw)`: textures drawn in code with a seeded RNG. Stone speckle, grass, gravel, signage, window grids. No downloads, no licensing, identical on every load.+- Merge static geometry that shares a material (`BufferGeometryUtils.mergeGeometries`) when it is not repeated enough to instance.++## Shader patches++Extend built-in materials with `onBeforeCompile` instead of writing shaders from scratch; you keep lighting, shadows and fog for free. `references/shaders.md` has tested patches for: wind sway, snow on upward faces, seasonal foliage tint, windows that light up at night, water ripple.++The rule that is easy to miss: **a patch that moves vertices must also patch the shadow pass.** Give the mesh a `customDepthMaterial` (a `MeshDepthMaterial` with `RGBADepthPacking`) carrying the same `onBeforeCompile`, as `scene.js` does for the trees. Otherwise leaves sway while their shadows stand still.++## Performance++Budget for a laptop GPU at 1440x900: under 10 ms a frame, under 300 draw calls, under 2 million triangles. `references/performance.md` covers measuring and fixing. In order of payoff:++1. Instance repeated parts (the `Kit`). Draw calls, not triangles, are usually the limit.+2. Quality tiers: `high` (DPR up to 2, GTAO, 4096 shadows), `balanced` (DPR 1.5), `fast` (DPR 1, no GTAO, 2048 shadows). The starter drops a tier by itself after three seconds of slow frames, and never while recording.+3. Do not render what is not moving: if nothing animates and the camera is still, skip `composer.render()`.+4. Keep `castShadow` off for small, distant and flat things.++## Camera++- Define named **vantages** (position plus look-at target) for every view worth seeing. Buttons, deep links, stills and recordings all use them.+- **Flights** between vantages rise over the midpoint and ease in and out (`flyTo` in `main.js`). A straight lerp clips through buildings and feels robotic.+- Limit `OrbitControls`: `maxPolarAngle` just under horizontal, sensible min and max distance, damping on.+- With `prefers-reduced-motion`, flights jump instead of fly, and nothing moves by itself.++## Recording++`?record=1` hides the UI and runs a scripted tour from `window.__recordFrame(t)`, timed on the page clock. Anything delayed must use `later(secs, fn)` from `main.js`, not `setTimeout`. Record with the `frame-capture` skill (`<frame-capture>` is where that skill is installed):++```bash+python3 <frame-capture>/scripts/record.py "http://127.0.0.1:8000/?record=1" tour.mp4 --seconds 20 --ready "window.__ready === true"+```++## Before calling it done++- Every vantage at every light preset, on a laptop size and a phone (`site-check`).+- No shadow acne, no shimmering shadow edges while orbiting, no z-fighting where surfaces meet (offset coplanar decals by 1 to 2 cm).+- Nothing floats or sinks: check where every object meets the ground from a low vantage.+- Frame time and draw calls inside budget.+- If the subject is a real place, object or brand, label the page as an unofficial study and do not use logos.diff --git a/skills/threejs-scene/agents/openai.yaml b/skills/threejs-scene/agents/openai.yamlnew file mode 100644index 0000000..0c00c6c--- /dev/null+++ b/skills/threejs-scene/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "three.js Scene"+ short_description: "Code-built 3D worlds with real light, shadows and 60 fps"diff --git a/skills/threejs-scene/assets/starter/env.js b/skills/threejs-scene/assets/starter/env.jsnew file mode 100644index 0000000..291bb31--- /dev/null+++ b/skills/threejs-scene/assets/starter/env.js@@ -0,0 +1,169 @@+// Sky, sun, image-based light, fog, clouds and night. Presets blend smoothly; the shadow+// camera follows what the viewer looks at and snaps to its texel grid so shadows never swim.+import * as THREE from 'three';+import { Sky } from 'three/addons/objects/Sky.js';++// shared uniforms: every custom shader reads time, wind and night from here+export const U = {+ uTime: { value: 0 },+ uWind: { value: 0.5 },+ uNight: { value: 0 },+ uSunDir: { value: new THREE.Vector3(0.5, 0.6, 0.5) },+};++// skyEl drives the sky gradient, el the light: at golden hour the light sits a little above+// the painted sun so faces still read. sunI/hemiI/envI are tuned together with exposure (exp).+export const PRESETS = {+ morning: { skyEl: 30, el: 32, az: 130, sunI: 3.0, sunC: '#fff1dc', hemiS: '#cfe0ff', hemiG: '#5a6a4a', hemiI: 0.5, envI: 0.75,+ turb: 2.6, ray: 1.1, mie: 0.0035, mieG: 0.8, fogC: '#bccde2', fogD: 0.0035, exp: 0.62, night: 0, cloudLit: '#ffffff', cloudShade: '#b9c3d1', cloudA: 0.7 },+ golden: { skyEl: 5, el: 9, az: 250, sunI: 3.4, sunC: '#ffb066', hemiS: '#f2c9a3', hemiG: '#4a3c2e', hemiI: 0.42, envI: 0.62,+ turb: 5.0, ray: 2.4, mie: 0.007, mieG: 0.86, fogC: '#dcae88', fogD: 0.0042, exp: 0.72, night: 0, cloudLit: '#ffd2a6', cloudShade: '#9a8a8c', cloudA: 0.68 },+ night: { skyEl: -14, el: 42, az: 205, sunI: 0.14, sunC: '#a8bcff', hemiS: '#22324f', hemiG: '#07090d', hemiI: 0.28, envI: 0.16,+ turb: 2.0, ray: 0.6, mie: 0.002, mieG: 0.8, fogC: '#0b1322', fogD: 0.005, exp: 1.0, night: 1, cloudLit: '#3a4660', cloudShade: '#141b29', cloudA: 0.42 },+};+const NUM = ['skyEl', 'el', 'az', 'sunI', 'hemiI', 'envI', 'turb', 'ray', 'mie', 'mieG', 'fogD', 'exp', 'night', 'cloudA'];+const COL = ['sunC', 'hemiS', 'hemiG', 'fogC', 'cloudLit', 'cloudShade'];++export function dirFrom(el, az) {+ const e = THREE.MathUtils.degToRad(el), a = THREE.MathUtils.degToRad(az);+ return new THREE.Vector3(Math.sin(a) * Math.cos(e), Math.sin(e), -Math.cos(a) * Math.cos(e));+}++function cloudLayer(height, size) {+ const g = new THREE.PlaneGeometry(size, size);+ g.rotateX(Math.PI / 2);+ const m = new THREE.ShaderMaterial({+ transparent: true, depthWrite: false, side: THREE.DoubleSide, fog: false,+ uniforms: { uTime: U.uTime, uWind: U.uWind, uLit: { value: new THREE.Color() }, uShade: { value: new THREE.Color() }, uA: { value: 0.7 }, uScale: { value: 9 / size } },+ vertexShader: `varying vec3 vW; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`,+ fragmentShader: `+ uniform float uTime, uWind, uA, uScale; uniform vec3 uLit, uShade; varying vec3 vW;+ float h(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }+ float n(vec2 p){ vec2 i = floor(p), f = fract(p); vec2 u = f*f*(3.0-2.0*f);+ return mix(mix(h(i), h(i+vec2(1,0)), u.x), mix(h(i+vec2(0,1)), h(i+vec2(1,1)), u.x), u.y); }+ float fbm(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 6; i++){ s += a * n(p); p = p * 2.07 + 13.1; a *= 0.5; } return s; }+ void main(){+ vec2 p = vW.xz * uScale + vec2(uTime * (0.004 + uWind * 0.012), uTime * 0.002);+ vec2 q = vec2(fbm(p), fbm(p + 5.2));+ float d = fbm(p + q * 1.3);+ float c = smoothstep(0.44, 0.72, d);+ float edge = smoothstep(0.44, 0.56, d) - smoothstep(0.56, 0.86, d);+ float fade = 1.0 - smoothstep(0.15, 0.48, length(vW.xz - cameraPosition.xz) * uScale / 9.0);+ vec3 col = mix(uShade, uLit, clamp(0.35 + edge * 0.9 + (1.0 - c) * 0.4, 0.0, 1.0));+ gl_FragColor = vec4(col, c * fade * uA);+ }`,+ });+ const mesh = new THREE.Mesh(g, m);+ mesh.position.y = height; mesh.renderOrder = -1; mesh.frustumCulled = false;+ return mesh;+}++function nightDome(radius) {+ const m = new THREE.ShaderMaterial({+ side: THREE.BackSide, depthWrite: false, transparent: true, fog: false, uniforms: { uNight: U.uNight },+ vertexShader: `varying vec3 vD; void main(){ vD = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,+ fragmentShader: `+ uniform float uNight; varying vec3 vD;+ float h(vec3 p){ return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); }+ void main(){+ float y = max(vD.y, 0.0);+ vec3 col = mix(vec3(0.075, 0.11, 0.2), vec3(0.008, 0.016, 0.045), pow(y, 0.5));+ col += vec3(0.16, 0.12, 0.08) * pow(1.0 - y, 8.0); // glow on the horizon+ vec3 c = floor(vD * 700.0);+ col += vec3(0.8, 0.85, 1.0) * step(0.9975, h(c)) * smoothstep(0.05, 0.3, y) * (0.4 + 0.6 * h(c + 1.0));+ gl_FragColor = vec4(col, uNight);+ }`,+ });+ const mesh = new THREE.Mesh(new THREE.SphereGeometry(radius, 32, 16), m);+ mesh.renderOrder = -2; mesh.frustumCulled = false;+ return mesh;+}++/**+ * createEnvironment(renderer, scene, { preset, scale })+ * scale: rough size of the scene in metres (sets sky, cloud and shadow distances).+ */+export function createEnvironment(renderer, scene, { preset = 'morning', scale = 120 } = {}) {+ const far = scale * 40;+ const sky = new Sky(); sky.scale.setScalar(far * 0.95); sky.renderOrder = -3; sky.frustumCulled = false; scene.add(sky);+ const dome = nightDome(far * 0.9); scene.add(dome);+ const clouds = cloudLayer(scale * 6, far * 2.4); scene.add(clouds);++ const sun = new THREE.DirectionalLight(0xffffff, 3);+ sun.castShadow = true;+ sun.shadow.mapSize.set(4096, 4096);+ sun.shadow.bias = -0.0002;+ sun.shadow.normalBias = scale * 0.0006;+ sun.shadow.camera.near = 1; sun.shadow.camera.far = scale * 12;+ scene.add(sun, sun.target);+ const hemi = new THREE.HemisphereLight(0xffffff, 0x444444, 0.5); scene.add(hemi);+ scene.fog = new THREE.FogExp2(0xbccde2, 0.003);++ // image-based light rendered from a private copy of the sky, so reflections match the sky+ const envScene = new THREE.Scene();+ const envSky = new Sky(); envSky.scale.setScalar(far * 0.5); envScene.add(envSky);+ const envGround = new THREE.Mesh(new THREE.CircleGeometry(far * 0.4, 32), new THREE.MeshBasicMaterial({ color: 0x4d5a45 }));+ envGround.rotation.x = -Math.PI / 2; envGround.position.y = -2; envScene.add(envGround);+ const pmrem = new THREE.PMREMGenerator(renderer);+ let envRT = null;++ const cur = structuredClone(PRESETS[preset]);+ for (const k of COL) cur[k] = new THREE.Color(PRESETS[preset][k]);+ let from = null, to = null, t0 = 0, dur = 1, envDirty = true, ticks = 0;++ function apply() {+ const sd = dirFrom(cur.skyEl, cur.az);+ for (const s of [sky, envSky]) {+ const u = s.material.uniforms;+ u.turbidity.value = cur.turb; u.rayleigh.value = cur.ray; u.mieCoefficient.value = cur.mie; u.mieDirectionalG.value = cur.mieG;+ u.sunPosition.value.copy(sd);+ }+ U.uSunDir.value.copy(dirFrom(cur.el, cur.az));+ sun.color.copy(cur.sunC); sun.intensity = cur.sunI;+ hemi.color.copy(cur.hemiS); hemi.groundColor.copy(cur.hemiG); hemi.intensity = cur.hemiI;+ scene.fog.color.copy(cur.fogC); scene.fog.density = cur.fogD * (120 / scale);+ renderer.toneMappingExposure = cur.exp;+ U.uNight.value = cur.night;+ scene.environmentIntensity = cur.envI;+ const cu = clouds.material.uniforms;+ cu.uLit.value.copy(cur.cloudLit); cu.uShade.value.copy(cur.cloudShade); cu.uA.value = cur.cloudA;+ envGround.material.color.setRGB(0.3, 0.36, 0.27).multiplyScalar(1 - cur.night * 0.9);+ sky.visible = cur.night < 0.995;+ }+ function regenEnv() {+ envRT?.dispose();+ envRT = pmrem.fromScene(envScene, 0, 1, far);+ scene.environment = envRT.texture;+ }+ apply(); regenEnv();++ return {+ sun, hemi, current: preset,+ set(name, seconds = 2.5) {+ this.current = name;+ from = { ...cur }; for (const k of COL) from[k] = cur[k].clone();+ to = PRESETS[name]; t0 = performance.now() / 1000; dur = Math.max(seconds, 0.001);+ if (Math.abs(to.az - from.az) > 180) from.az += to.az > from.az ? 360 : -360; // short way round+ },+ update(camera, target) {+ if (to) {+ const k = Math.min((performance.now() / 1000 - t0) / dur, 1), e = k * k * (3 - 2 * k);+ for (const n of NUM) cur[n] = THREE.MathUtils.lerp(from[n], to[n], e);+ for (const c of COL) cur[c].copy(from[c]).lerp(new THREE.Color(to[c]), e);+ apply();+ if (++ticks % 6 === 0 || k >= 1) envDirty = true; // PMREM is costly: refresh every 6th frame+ if (k >= 1) to = null;+ }+ if (envDirty) { regenEnv(); envDirty = false; }+ // shadow frustum sized to the view, centred on the target, snapped to whole texels+ const half = THREE.MathUtils.clamp(camera.position.distanceTo(target) * 0.85, scale * 0.25, scale * 4);+ const sc = sun.shadow.camera;+ if (sc.right !== half) { sc.left = -half; sc.right = half; sc.top = half; sc.bottom = -half; sc.updateProjectionMatrix(); }+ const texel = (2 * half) / sun.shadow.mapSize.x;+ sun.target.position.set(Math.round(target.x / texel) * texel, 0, Math.round(target.z / texel) * texel);+ sun.position.copy(sun.target.position).addScaledVector(U.uSunDir.value, scale * 6);+ sun.target.updateMatrixWorld();+ dome.position.copy(camera.position);+ },+ };+}diff --git a/skills/threejs-scene/assets/starter/index.html b/skills/threejs-scene/assets/starter/index.htmlnew file mode 100644index 0000000..0506223--- /dev/null+++ b/skills/threejs-scene/assets/starter/index.html@@ -0,0 +1,49 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <link rel="icon" href="data:,">+ <title>Pavilion · three.js starter</title>+ <meta name="description" content="A procedural three.js scene: sky, sun, soft shadows, ambient occlusion and bloom, built from code.">+ <!-- Pin the version. For production, vendor these files next to the page (see SKILL.md). -->+ <script type="importmap">+ { "imports": {+ "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",+ "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"+ } }+ </script>+ <style>+ :root { color-scheme: dark; --ink: #f4efe6; --muted: rgba(244, 239, 230, .62); }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; background: #0d0f12; overflow: hidden; }+ canvas#gl { position: fixed; inset: 0; width: 100%; height: 100%; display: block; outline: none; touch-action: none; }+ .title { position: fixed; left: clamp(16px, 4vw, 48px); top: clamp(16px, 4vw, 44px); color: var(--ink);+ font: 600 clamp(20px, 2.4vw, 30px)/1.1 ui-sans-serif, system-ui, sans-serif; letter-spacing: .02em;+ text-shadow: 0 1px 12px rgba(0, 0, 0, .35); pointer-events: none; }+ .title small { display: block; margin-top: 8px; font-weight: 400; font-size: 14px; color: var(--muted); letter-spacing: .04em; }+ .bar { position: fixed; left: 50%; bottom: max(16px, env(safe-area-inset-bottom)); transform: translateX(-50%);+ display: flex; gap: 6px; padding: 6px; border-radius: 999px; background: rgba(16, 18, 22, .55);+ backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); box-shadow: 0 0 0 1px rgba(255, 255, 255, .08); }+ .bar button { appearance: none; border: 0; border-radius: 999px; padding: 9px 14px; min-height: 40px;+ font: 500 13px/1 ui-sans-serif, system-ui, sans-serif; color: var(--ink); background: transparent; cursor: pointer; }+ .bar button[aria-pressed="true"] { background: rgba(255, 255, 255, .16); }+ .bar button:focus-visible { outline: 2px solid #ffd28a; outline-offset: 2px; }+ #loader { position: fixed; inset: 0; display: grid; place-items: center; background: #0d0f12; color: var(--muted);+ font: 14px ui-sans-serif, system-ui, sans-serif; transition: opacity .8s ease; }+ #loader.done { opacity: 0; pointer-events: none; }+ @media (max-width: 560px) { .bar { width: calc(100% - 24px); justify-content: center; flex-wrap: wrap; } }+ </style>+</head>+<body>+ <canvas id="gl" tabindex="0" aria-label="A 3D pavilion on a lawn. Drag to orbit, scroll or pinch to zoom."></canvas>+ <div class="title">Pavilion<small>procedural three.js starter</small></div>+ <nav class="bar" aria-label="Light">+ <button data-light="morning">Morning</button>+ <button data-light="golden">Golden hour</button>+ <button data-light="night">Night</button>+ </nav>+ <div id="loader">Building the scene</div>+ <script type="module" src="./main.js"></script>+</body>+</html>diff --git a/skills/threejs-scene/assets/starter/kit.js b/skills/threejs-scene/assets/starter/kit.jsnew file mode 100644index 0000000..2a8178d--- /dev/null+++ b/skills/threejs-scene/assets/starter/kit.js@@ -0,0 +1,130 @@+// Building blocks for procedural scenes: seeded randomness, canvas textures, an instancing+// kit, profile sweeps and lathes. Units are metres; +Y up.+import * as THREE from 'three';++/** Seeded random numbers in [0, 1). The same seed draws the same scene on every load. */+export function rng(seed = 1) {+ let s = (seed >>> 0) || 1;+ return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296);+}++/** A texture drawn with the 2D canvas API. No image files, nothing to download. */+export function canvasTex(w, h, draw, { srgb = true, repeat = null, aniso = 8 } = {}) {+ const c = document.createElement('canvas');+ c.width = w; c.height = h;+ draw(c.getContext('2d'), w, h);+ const t = new THREE.CanvasTexture(c);+ if (srgb) t.colorSpace = THREE.SRGBColorSpace;+ if (repeat) { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(repeat[0], repeat[1]); }+ t.anisotropy = aniso;+ return t;+}++const _q = new THREE.Quaternion(), _s = new THREE.Vector3(), _p = new THREE.Vector3(), UP = new THREE.Vector3(0, 1, 0);++/** Matrix for a part at (x, y, z), turned `angle` radians about +Y, scaled (sx, sy, sz). */+export function place(x, y, z, angle = 0, sx = 1, sy = 1, sz = 1) {+ _q.setFromAxisAngle(UP, angle);+ return new THREE.Matrix4().compose(_p.set(x, y, z), _q, _s.set(sx, sy, sz));+}++/**+ * Collects instance matrices per named part, then builds one InstancedMesh per part.+ * Ten thousand balusters become one draw call.+ * const kit = new Kit().def('column', columnGeo, stone);+ * kit.add('column', place(x, 0, z));+ * kit.build(group);+ */+export class Kit {+ constructor() { this.parts = new Map(); }+ def(name, geometry, material, opts = {}) {+ if (!this.parts.has(name)) this.parts.set(name, { geometry, material, mats: [], colors: [], opts });+ return this;+ }+ add(name, matrix, color) {+ const p = this.parts.get(name);+ if (!p) throw new Error('undefined part ' + name);+ p.mats.push(matrix);+ if (color) p.colors.push(color);+ }+ build(group) {+ const meshes = {};+ for (const [name, p] of this.parts) {+ if (!p.mats.length) continue;+ const m = new THREE.InstancedMesh(p.geometry, p.material, p.mats.length);+ p.mats.forEach((mm, i) => m.setMatrixAt(i, mm));+ if (p.colors.length === p.mats.length) p.colors.forEach((c, i) => m.setColorAt(i, c));+ m.castShadow = p.opts.cast !== false;+ m.receiveShadow = p.opts.receive !== false;+ if (p.opts.depth) m.customDepthMaterial = p.opts.depth;+ m.name = name;+ m.computeBoundingSphere();+ group.add(m);+ meshes[name] = m;+ }+ return meshes;+ }+}++/** Lathe from [radius, height] pairs: columns, balusters, urns, domes, lamp posts. */+export function lathe(points, segs = 24) {+ return new THREE.LatheGeometry(points.map(([r, y]) => new THREE.Vector2(r, y)), segs);+}++/** Points along a circle in the XZ plane; angle 0 is +Z, turning toward +X. */+export function arc(cx, cz, r, a0, a1, n) {+ const pts = [];+ for (let i = 0; i <= n; i++) { const a = a0 + (a1 - a0) * i / n; pts.push([cx + Math.sin(a) * r, cz + Math.cos(a) * r]); }+ return pts;+}++const norm2 = (x, z) => { const l = Math.hypot(x, z) || 1; return [x / l, z / l]; };++/**+ * Sweep a 2D profile along a path in the XZ plane, with mitred corners: cornices, kerbs,+ * steps, rails, mouldings. profile: [[offset, height], ...], offset measured outward from the+ * path. For a closed path "outward" is away from the enclosed area; for an open one it is the+ * right-hand side of travel (side = -1 flips it). UVs are planar at 1 unit per `uvScale` m.+ */+export function sweep(profile, path, { closed = false, y = 0, side = 1, uvScale = 4 } = {}) {+ const n = path.length;+ let s = side;+ if (closed) {+ let a = 0;+ for (let i = 0; i < n; i++) { const [x0, z0] = path[i], [x1, z1] = path[(i + 1) % n]; a += x0 * z1 - x1 * z0; }+ s = a > 0 ? -1 : 1;+ }+ const dirs = [];+ for (let i = 0; i < n; i++) {+ const prev = closed ? path[(i - 1 + n) % n] : path[Math.max(i - 1, 0)];+ const next = closed ? path[(i + 1) % n] : path[Math.min(i + 1, n - 1)];+ const cur = path[i];+ const d0 = norm2(cur[0] - prev[0], cur[1] - prev[1]), d1 = norm2(next[0] - cur[0], next[1] - cur[1]);+ const a = (i === 0 && !closed) ? d1 : d0, b = (i === n - 1 && !closed) ? d0 : d1;+ const n0 = [-a[1] * s, a[0] * s], n1 = [-b[1] * s, b[0] * s];+ const m = norm2(n0[0] + n1[0], n0[1] + n1[1]);+ const k = 1 / Math.max(m[0] * n1[0] + m[1] * n1[1], 0.3); // mitre length, capped at sharp corners+ dirs.push([m[0] * k, m[1] * k]);+ }+ const pos = [], idx = [];+ const rings = closed ? n + 1 : n;+ for (let k = 0; k < profile.length - 1; k++) {+ const base = pos.length / 3;+ for (let r = 0; r < rings; r++) {+ const i = r % n, [px, pz] = path[i], [dx, dz] = dirs[i];+ for (const [o, h] of [profile[k], profile[k + 1]]) pos.push(px + dx * o, y + h, pz + dz * o);+ }+ for (let r = 0; r < rings - 1; r++) {+ const a = base + r * 2, b = a + 1, c = a + 2, d = a + 3;+ if (s > 0) idx.push(a, c, b, b, c, d); else idx.push(a, b, c, b, d, c);+ }+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));+ g.setIndex(idx);+ g.computeVertexNormals();+ const uv = [];+ for (let i = 0; i < pos.length; i += 3) uv.push((pos[i] + pos[i + 2]) / uvScale, pos[i + 1] / uvScale);+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));+ return g;+}diff --git a/skills/threejs-scene/assets/starter/main.js b/skills/threejs-scene/assets/starter/main.jsnew file mode 100644index 0000000..c42550b--- /dev/null+++ b/skills/threejs-scene/assets/starter/main.js@@ -0,0 +1,176 @@+// Renderer, camera, post-processing, quality tiers, camera flights and the frame loop.+// ?light=morning|golden|night ?view=front|corner|aerial ?quality=high|balanced|fast+// ?record=1 hides the UI and plays a scripted tour on the page clock (see frame-capture)+import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';+import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';+import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';+import { createEnvironment, U } from './env.js';+import { buildScene } from './scene.js';++const params = new URLSearchParams(location.search);+const RECORD = params.has('record');+const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;++// named vantages: camera position + look-at target. Every still and every flight uses these.+export const VANTAGE = {+ front: { pos: [0, 3.4, 26], tgt: [0, 3.6, 0] },+ corner: { pos: [15, 6.5, 15], tgt: [0, 3.2, 0] },+ low: { pos: [-7.5, 1.4, 9], tgt: [0, 5.2, 0] },+ aerial: { pos: [26, 30, 34], tgt: [0, 2, 0] },+};++const canvas = document.getElementById('gl');+const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: RECORD, stencil: false });+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.shadowMap.enabled = true;+renderer.shadowMap.type = THREE.PCFSoftShadowMap;+let pixelRatio = Math.min(devicePixelRatio, 2);+renderer.setPixelRatio(pixelRatio);+renderer.setSize(innerWidth, innerHeight, false);++const scene = new THREE.Scene();+// a longer lens (fov 38) keeps verticals calm; wide angles make architecture look like a toy+const camera = new THREE.PerspectiveCamera(38, innerWidth / innerHeight, 0.3, 6000);+const controls = new OrbitControls(camera, canvas);+controls.enableDamping = true; controls.dampingFactor = 0.07;+controls.maxPolarAngle = 1.52; controls.minDistance = 3; controls.maxDistance = 140;+camera.fov = fitFov(camera.aspect); camera.updateProjectionMatrix();+const startView = VANTAGE[params.get('view')] || VANTAGE.corner;+camera.position.set(...startView.pos); controls.target.set(...startView.tgt); controls.update();++const env = createEnvironment(renderer, scene, { preset: params.get('light') || 'golden', scale: 120 });+const world = buildScene();+scene.add(world.group);+scene.traverse((o) => { if (o.isPoints || o.renderOrder < 0) o.userData.noAO = true; });++// ---- post: MSAA half-float target -> ambient occlusion -> bloom -> tone map + sRGB+// GTAO darkens everything it sees; sky layers and particles must not get contact shadows+class SelectiveGTAO extends GTAOPass {+ overrideVisibility() {+ super.overrideVisibility();+ this.scene.traverse((o) => { if (o.userData.noAO) o.visible = false; });+ }+}+const size = renderer.getDrawingBufferSize(new THREE.Vector2());+const target = new THREE.WebGLRenderTarget(size.x, size.y, { type: THREE.HalfFloatType, samples: 4 });+const composer = new EffectComposer(renderer, target);+composer.addPass(new RenderPass(scene, camera));+const gtao = new SelectiveGTAO(scene, camera, size.x, size.y);+gtao.updateGtaoMaterial({ radius: 0.9, distanceExponent: 1.5, thickness: 1.2, scale: 1.0, samples: 16 });+gtao.updatePdMaterial({ radius: 6, rings: 2, samples: 16 });+gtao.blendIntensity = 0.8;+composer.addPass(gtao);+const bloom = new UnrealBloomPass(new THREE.Vector2(size.x, size.y), 0.15, 0.5, 0.9);+composer.addPass(bloom);+composer.addPass(new OutputPass());++// keep the horizontal field of view on tall screens, so a phone sees the same width of the+// scene as a laptop instead of a crop of its middle+function fitFov(aspect, base = 38, baseAspect = 16 / 9) {+ if (aspect >= baseAspect) return base;+ const h = Math.tan(THREE.MathUtils.degToRad(base) / 2) * baseAspect;+ return Math.min(THREE.MathUtils.radToDeg(2 * Math.atan(h / aspect)), 75);+}+function resize() {+ camera.aspect = innerWidth / innerHeight; camera.fov = fitFov(camera.aspect); camera.updateProjectionMatrix();+ renderer.setPixelRatio(pixelRatio); renderer.setSize(innerWidth, innerHeight, false);+ composer.setPixelRatio(pixelRatio); composer.setSize(innerWidth, innerHeight);+}+addEventListener('resize', resize);++// ---- quality tiers; drops one tier by itself if frames run long (never during a recording)+const TIERS = ['high', 'balanced', 'fast'];+let quality = TIERS.includes(params.get('quality')) ? params.get('quality') : 'high';+function setQuality(q) {+ quality = q;+ pixelRatio = q === 'high' ? Math.min(devicePixelRatio, 2) : q === 'balanced' ? Math.min(devicePixelRatio, 1.5) : 1;+ gtao.enabled = q === 'high';+ const ms = q === 'fast' ? 2048 : 4096;+ if (env.sun.shadow.mapSize.x !== ms) { env.sun.shadow.mapSize.set(ms, ms); env.sun.shadow.map?.dispose(); env.sun.shadow.map = null; }+ resize();+}+setQuality(quality);+const perf = { sum: 0, n: 0, since: 0 };+function watchFrameTime(dt, now) {+ if (RECORD || params.has('quality') || dt > 0.25) return; // ignore tab switches+ perf.sum += dt; perf.n++;+ if (now - perf.since > 3 && perf.n > 60) {+ if (perf.sum / perf.n > 1 / 40 && quality !== 'fast') setQuality(TIERS[TIERS.indexOf(quality) + 1]);+ perf.sum = 0; perf.n = 0; perf.since = now;+ }+}++// ---- time on the page clock (setTimeout keeps real time and breaks frame-exact recording)+const pending = [];+const later = (secs, fn) => pending.push({ at: performance.now() / 1000 + secs, fn });+function runPending(now) { for (let i = pending.length - 1; i >= 0; i--) if (now >= pending[i].at) pending.splice(i, 1)[0].fn(); }++// ---- camera flights: rise over the midpoint, ease in and out, look at a moving target+let flight = null;+function flyTo(name, secs = 2.8) {+ const v = VANTAGE[name];+ const p0 = camera.position.clone(), t0 = controls.target.clone();+ const p1 = new THREE.Vector3(...v.pos), t1 = new THREE.Vector3(...v.tgt);+ const mid = p0.clone().lerp(p1, 0.5);+ mid.y = Math.max(mid.y, Math.max(p0.y, p1.y) + Math.min(p0.distanceTo(p1) * 0.22, 40) * 0.6);+ flight = { p0, t0, p1, t1, mid, start: performance.now() / 1000, secs: REDUCED ? 0.001 : secs };+ controls.enabled = false;+}+function stepFlight(now) {+ if (!flight) return;+ const k = Math.min((now - flight.start) / flight.secs, 1), e = k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;+ const a = flight.p0.clone().lerp(flight.mid, e), b = flight.mid.clone().lerp(flight.p1, e);+ camera.position.copy(a.lerp(b, e));+ controls.target.copy(flight.t0).lerp(flight.t1, e);+ camera.lookAt(controls.target);+ if (k >= 1) { flight = null; controls.enabled = !RECORD; controls.update(); }+}++// ---- UI+const buttons = [...document.querySelectorAll('[data-light]')];+const pressLight = (name) => buttons.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.light === name)));+buttons.forEach((b) => b.addEventListener('click', () => { env.set(b.dataset.light); pressLight(b.dataset.light); }));+pressLight(env.current);+addEventListener('keydown', (e) => {+ const i = ['1', '2', '3', '4'].indexOf(e.key);+ if (i >= 0) flyTo(Object.keys(VANTAGE)[i]);+});++// ---- recording: a scripted tour driven by the page clock+if (RECORD) {+ controls.enabled = false;+ for (const el of document.querySelectorAll('.bar, .title')) el.style.display = 'none';+ const TOUR = [[0.5, 'front'], [5, 'low'], [10, 'aerial'], [15, () => env.set('night', 3)], [16, 'corner']];+ let next = 0;+ window.__recordFrame = (t) => {+ while (next < TOUR.length && t >= TOUR[next][0]) {+ const step = TOUR[next++][1];+ typeof step === 'function' ? step() : flyTo(step, 3.6);+ }+ };+}+window.__app = { scene, camera, controls, renderer, env, flyTo, later, setQuality, VANTAGE, U };++let frames = 0, last = performance.now() / 1000;+function frame() {+ const now = performance.now() / 1000;+ const dt = now - last; last = now;+ U.uTime.value = now;+ runPending(now);+ stepFlight(now);+ if (!flight && controls.enabled) controls.update();+ env.update(camera, controls.target);+ world.update(now);+ const night = U.uNight.value;+ bloom.strength = 0.12 + 0.5 * night;+ bloom.threshold = 0.9 - 0.15 * night;+ composer.render();+ watchFrameTime(dt, now);+ if (++frames === 3) { document.getElementById('loader').classList.add('done'); window.__ready = true; }+ requestAnimationFrame(frame);+}+requestAnimationFrame(frame);diff --git a/skills/threejs-scene/assets/starter/scene.js b/skills/threejs-scene/assets/starter/scene.jsnew file mode 100644index 0000000..91d947a--- /dev/null+++ b/skills/threejs-scene/assets/starter/scene.js@@ -0,0 +1,181 @@+// The example scene: a round pavilion (tholos) on a lawn. Replace it with your subject; keep+// the patterns: real dimensions, one instanced kit, sweeps and lathes, canvas textures,+// shader patches that read the shared uniforms, and an update(now) for anything alive.+import * as THREE from 'three';+import { Kit, place, lathe, arc, sweep, canvasTex, rng } from './kit.js';+import { U } from './env.js';++const R = 4.2; // column ring radius, m+const COL_H = 5.0; // column height including base and capital+const PODIUM = 0.75; // three steps of 0.25 m++// ---------------------------------------------------------------- materials+function speckle(g, w, h, n, r0, r1, colors, rand) {+ for (let i = 0; i < n; i++) {+ g.fillStyle = colors[(rand() * colors.length) | 0];+ g.globalAlpha = 0.04 + rand() * 0.08;+ g.beginPath(); g.arc(rand() * w, rand() * h, r0 + rand() * (r1 - r0), 0, Math.PI * 2); g.fill();+ }+ g.globalAlpha = 1;+}+const stoneMap = canvasTex(512, 512, (g, w, h) => {+ g.fillStyle = '#efe9dc'; g.fillRect(0, 0, w, h);+ speckle(g, w, h, 1400, 3, 34, ['#e2dbcc', '#f8f5ee', '#e8e1d3', '#d6cfbf'], rng(7));+}, { repeat: [1, 1] });+const grassMap = canvasTex(512, 512, (g, w, h) => {+ const r = rng(11);+ g.fillStyle = '#5f7a3a'; g.fillRect(0, 0, w, h);+ speckle(g, w, h, 5000, 1, 7, ['#6f8a44', '#526b31', '#7b9650', '#4a6129'], r);+ for (let i = 0; i < 9000; i++) { // blades+ g.strokeStyle = r() > 0.5 ? 'rgba(130,160,80,.25)' : 'rgba(40,60,25,.25)';+ const x = r() * w, y = r() * h;+ g.beginPath(); g.moveTo(x, y); g.lineTo(x + (r() - 0.5) * 3, y - 4 - r() * 6); g.stroke();+ }+}, { repeat: [60, 60] });+const gravelMap = canvasTex(256, 256, (g, w, h) => {+ g.fillStyle = '#cbbfa8'; g.fillRect(0, 0, w, h);+ speckle(g, w, h, 4000, 0.6, 2.6, ['#b5a68d', '#ddd3c0', '#a89980', '#efe7d6'], rng(3));+}, { repeat: [1, 1] });++const stone = new THREE.MeshStandardMaterial({ map: stoneMap, color: '#ffffff', roughness: 0.82 });+const grass = new THREE.MeshStandardMaterial({ map: grassMap, roughness: 0.95 });+const gravel = new THREE.MeshStandardMaterial({ map: gravelMap, roughness: 1 });+const bronze = new THREE.MeshStandardMaterial({ color: '#3b3128', metalness: 0.7, roughness: 0.45 });+const glow = new THREE.MeshStandardMaterial({ color: '#fff3dc', emissive: '#ffcf8a', emissiveIntensity: 0 });++// ---------------------------------------------------------------- geometry+// column: Attic base, shaft with entasis (it swells slightly a third of the way up), capital+function columnGeometry(H, D) {+ const r = D / 2, base = 0.5 * D, cap = 0.55 * D, shaft = H - base - cap;+ const p = [[0.001, 0], [r * 1.42, 0], [r * 1.42, 0.12 * D], [r * 1.25, 0.16 * D], [r * 1.3, 0.24 * D],+ [r * 1.12, 0.34 * D], [r * 1.18, 0.42 * D], [r * 1.02, base]];+ for (let i = 0; i <= 12; i++) {+ const t = i / 12, ent = 1 + 0.035 * Math.sin(Math.PI * Math.min(t * 1.5, 1)) - 0.16 * t;+ p.push([r * ent, base + shaft * t]);+ }+ const top = base + shaft, rt = r * 0.84;+ p.push([rt * 1.12, top + 0.04 * D], [rt * 1.0, top + 0.1 * D], [rt * 1.38, top + 0.28 * D], [r * 1.5, top + 0.4 * D],+ [r * 1.5, H], [0.001, H]);+ return lathe(p, 28);+}++// classical entablature: architrave, frieze, cornice; [outward offset, height] in metres+const ENTABLATURE = [[-0.32, 0], [0.32, 0], [0.32, 0.18], [0.36, 0.2], [0.36, 0.3], [0.3, 0.32], [0.3, 0.7],+ [0.38, 0.72], [0.44, 0.8], [0.66, 0.84], [0.7, 0.9], [0.76, 0.92], [0.78, 1.0], [0.82, 1.06], [0.78, 1.12], [-0.32, 1.12], [-0.32, 0]];++const CLEAR = [[15, 15], [0, 26], [-7.5, 9], [26, 34]]; // vantage positions in main.js++function trees(group, rand) {+ // instanced trees: a trunk and a clump of foliage balls each, swaying in the wind+ const trunkGeo = lathe([[0.001, 0], [0.22, 0], [0.16, 1.2], [0.12, 2.6], [0.001, 2.8]], 8);+ const leafGeo = new THREE.IcosahedronGeometry(1, 2);+ const leafMat = new THREE.MeshStandardMaterial({ color: '#4f6e2c', roughness: 0.9, flatShading: true });+ const sway = `+ vec4 wp = modelMatrix * instanceMatrix * vec4(position, 1.0);+ float ph = dot(wp.xz, vec2(0.13, 0.17));+ transformed.x += sin(uTime * 1.7 + ph) * 0.06 * uWind * (position.y + 1.0);+ transformed.z += cos(uTime * 1.3 + ph * 1.3) * 0.05 * uWind * (position.y + 1.0);`;+ const patch = (sh) => {+ Object.assign(sh.uniforms, { uTime: U.uTime, uWind: U.uWind });+ sh.vertexShader = 'uniform float uTime, uWind;\n' + sh.vertexShader.replace('#include <begin_vertex>', '#include <begin_vertex>' + sway);+ };+ leafMat.onBeforeCompile = patch;+ // the shadow pass draws with a depth material: patch it the same way or shadows stay still+ const leafDepth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking });+ leafDepth.onBeforeCompile = patch;++ const kit = new Kit()+ .def('trunk', trunkGeo, new THREE.MeshStandardMaterial({ color: '#4a3a2c', roughness: 0.95 }))+ .def('leaves', leafGeo, leafMat, { depth: leafDepth });+ const greens = ['#4f6e2c', '#5d7a33', '#46632a', '#6a8540'].map((c) => new THREE.Color(c));+ for (let i = 0; i < 46; i++) {+ const a = rand() * Math.PI * 2, d = 17 + rand() * 30;+ const x = Math.sin(a) * d, z = Math.cos(a) * d;+ if (Math.abs(x) < 4 && z > 0) continue; // keep the approach clear+ if (CLEAR.some(([cx, cz]) => Math.hypot(x - cx, z - cz) < 7)) continue; // and the camera spots+ const s = 0.8 + rand() * 0.6, rot = rand() * 6.28;+ kit.add('trunk', place(x, 0, z, rot, s, s, s));+ for (let k = 0; k < 5; k++) {+ const ox = (rand() - 0.5) * 2.2 * s, oz = (rand() - 0.5) * 2.2 * s, oy = (2.6 + rand() * 1.8) * s, ls = (1.1 + rand() * 0.9) * s;+ kit.add('leaves', place(x + ox, oy, z + oz, rand() * 6.28, ls, ls * 0.85, ls), greens[(rand() * 4) | 0]);+ }+ }+ kit.build(group);+}++export function buildScene() {+ const group = new THREE.Group();+ const rand = rng(2024);++ const ground = new THREE.Mesh(new THREE.CircleGeometry(400, 64), grass);+ ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true;+ group.add(ground);++ // gravel path: a ring around the podium and a straight approach, swept as thin flat bands+ const ring = sweep([[-1.4, 0.01], [1.4, 0.01]], arc(0, 0, R + 4.2, 0, Math.PI * 2, 96), { closed: true });+ const lane = sweep([[-1.2, 0.012], [1.2, 0.012]], [[0, R + 5], [0, 60]], { uvScale: 2 });+ for (const g of [ring, lane]) { const m = new THREE.Mesh(g, gravel); m.receiveShadow = true; group.add(m); }++ // podium: three round steps in one lathe+ const steps = lathe([[0.001, 0], [R + 1.6, 0], [R + 1.6, 0.25], [R + 1.25, 0.25], [R + 1.25, 0.5], [R + 0.9, 0.5],+ [R + 0.9, PODIUM], [0.001, PODIUM]], 96);+ const podium = new THREE.Mesh(steps, stone); podium.castShadow = podium.receiveShadow = true; group.add(podium);++ // twelve columns, one draw call+ const kit = new Kit().def('column', columnGeometry(COL_H, 0.56), stone);+ for (let i = 0; i < 12; i++) {+ const a = (i / 12) * Math.PI * 2 + Math.PI / 12;+ kit.add('column', place(Math.sin(a) * R, PODIUM, Math.cos(a) * R));+ }+ kit.build(group);++ // entablature swept round the ring, then a drum and a shallow dome+ const top = PODIUM + COL_H;+ const ent = new THREE.Mesh(sweep(ENTABLATURE, arc(0, 0, R, 0, Math.PI * 2, 96), { closed: true, y: top }), stone);+ ent.castShadow = ent.receiveShadow = true; group.add(ent);+ const domeP = [[0.001, 0], [R + 0.3, 0], [R + 0.3, 0.55], [R + 0.05, 0.62]];+ for (let i = 0; i <= 16; i++) { const t = (i / 16) * Math.PI / 2; domeP.push([(R + 0.05) * Math.cos(t), 0.62 + R * 0.62 * Math.sin(t)]); }+ domeP.push([0.35, 0.62 + R * 0.62 + 0.05], [0.35, 0.62 + R * 0.62 + 0.45], [0.001, 0.62 + R * 0.62 + 0.5]);+ const dome = new THREE.Mesh(lathe(domeP, 96), stone);+ dome.position.y = top + 1.12; dome.castShadow = dome.receiveShadow = true; group.add(dome);++ // an urn at the centre+ const urn = new THREE.Mesh(lathe([[0.001, 0], [0.42, 0], [0.42, 0.12], [0.2, 0.2], [0.18, 0.4], [0.5, 0.8], [0.62, 1.15],+ [0.5, 1.45], [0.3, 1.55], [0.34, 1.62], [0.001, 1.62]], 40), bronze);+ urn.position.y = PODIUM; urn.castShadow = true; group.add(urn);++ // lamp posts on the approach; at night their globes glow and two real lights spill on the path+ const postGeo = lathe([[0.001, 0], [0.16, 0], [0.16, 0.1], [0.07, 0.25], [0.05, 2.9], [0.09, 3.0], [0.001, 3.0]], 12);+ const lamps = new Kit().def('post', postGeo, bronze).def('globe', new THREE.SphereGeometry(0.2, 20, 12), glow, { cast: false });+ const lights = [];+ for (const z of [12, 22, 32, 42]) for (const x of [-2.2, 2.2]) {+ lamps.add('post', place(x, 0, z));+ lamps.add('globe', place(x, 3.18, z));+ if (z === 12) {+ const l = new THREE.PointLight('#ffc98a', 0, 18, 2); // decay 2: physically based falloff+ l.position.set(x, 3.1, z); l.userData.candela = 40; group.add(l); lights.push(l);+ }+ }+ lamps.build(group);++ // a lantern hung under the dome: at night the columns read against their own warm light+ // (no shadow: a point-light shadow renders the scene six more times, for little gain here)+ const lantern = new THREE.PointLight('#ffc27a', 0, 16, 2);+ lantern.position.set(0, PODIUM + COL_H - 0.6, 0); lantern.userData.candela = 70;+ group.add(lantern); lights.push(lantern);+ const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.16, 16, 10), glow);+ bulb.position.copy(lantern.position).add(new THREE.Vector3(0, 0.3, 0)); group.add(bulb);++ trees(group, rand);++ return {+ group,+ center: new THREE.Vector3(0, 3.2, 0),+ update(now) {+ const night = U.uNight.value;+ glow.emissiveIntensity = night * 3.5; // bloom picks the globes up at night+ for (const l of lights) l.intensity = night * l.userData.candela;+ lights.forEach((l) => { l.visible = night > 0.01; }); // a dark light still costs a shadow pass+ },+ };+}diff --git a/skills/threejs-scene/references/geometry.md b/skills/threejs-scene/references/geometry.mdnew file mode 100644index 0000000..1371d5d--- /dev/null+++ b/skills/threejs-scene/references/geometry.md@@ -0,0 +1,68 @@+# Geometry++## Work from real dimensions++Put the measurements at the top of the scene file, in metres, with where they came from:++```js+const R = 4.2; // column ring radius+const COL_H = 5.0; // column height including base and capital (about 9 lower diameters)+const STOREY = [0, 4.6, 10.2, 15.0]; // floor levels from the elevation drawing+```++Derive everything else from these. When something looks wrong, it is almost always a proportion, and a named constant is easy to fix.++## Profiles and sweeps++A profile is a list of `[outward offset, height]` points drawn as if you cut through the moulding. `sweep(profile, path, { closed, y })` extrudes it along a polyline in the XZ plane:++- Corners are mitred: each vertex offsets along the bisector, lengthened by `1 / cos` of the half-angle (capped so a sharp corner does not spike).+- For a closed path the winding is detected, so positive offsets always point away from the enclosed area.+- UVs are planar at world scale, so a stone texture tiles at the same size on every moulding.++Use it for cornices and entablatures, string courses, plinths, kerbs and road edges, steps (a stair-step profile), parapets, window surrounds (a closed rectangle), picture rails, car body creases.++Round plans use `arc(cx, cz, r, a0, a1, n)` as the path. 96 segments is smooth for a 4 m radius at normal viewing distance.++## Lathes++`lathe([[r, y], ...], segments)` turns a profile around the Y axis. Columns get entasis (a slight swelling about a third of the way up, then taper to about 0.84 of the base radius at the top); without it, columns look like pipes. Balusters, urns, domes, finials, lamp posts, bollards, wheels, tyres, bottles and glasses are all lathes.++## Instancing++The `Kit` collects matrices per named part and builds one `InstancedMesh` per part:++```js+const kit = new Kit()+ .def('window', windowGeo, glassFrameMat)+ .def('baluster', balusterGeo, stone, { cast: false });+for (const bay of bays) kit.add('window', place(bay.x, LEVEL.state + 1.2, FACE_Z, 0));+kit.build(group);+```++- `place(x, y, z, angle, sx, sy, sz)` makes the matrix; angle turns about +Y with 0 facing +Z.+- Pass a `THREE.Color` as the third argument to `add` for per-instance colour.+- Pass `{ depth: material }` to give the instanced mesh a `customDepthMaterial` (needed when a shader patch moves vertices).+- 10,000 instances of a 2,000-triangle part is cheap; 10,000 separate meshes is not.++## Canvas textures++`canvasTex(w, h, draw, { repeat })` draws with the 2D canvas API and returns a texture. Seed every random choice (`rng(seed)`) so the scene is identical on every load, which also keeps recordings repeatable.++Patterns that work:++- **Stone and render:** a base colour plus a few thousand low-alpha speckles of nearby tones at varied radii.+- **Grass:** speckles plus thousands of short random strokes for blades; repeat 40 to 80 times over a large ground.+- **Brick and ashlar:** draw courses with slight per-block tone variation, then mortar lines; use the same canvas, white on black, as a bump map.+- **Window glass:** a vertical gradient from sky colour to darker, with a faint reflection band.+- **Signs and text:** draw with a web font after `document.fonts.ready`, or the first frame draws the fallback font.++Set `colorSpace = SRGBColorSpace` on colour textures and leave data textures (bump, roughness) linear.++## Detail where the eye goes++Spend triangles on what the camera dwells on: the entrance, the silhouette against the sky, anything within ten metres of a vantage. Far facades can be flat boxes with a window-grid texture. Check from every vantage before adding detail anywhere else.++## Ground contact++Objects that do not meet the ground properly give a scene away. Sink posts and trees a few centimetres into the ground, give buildings a plinth, and rely on GTAO for the contact darkening. Check from a low vantage.diff --git a/skills/threejs-scene/references/lighting.md b/skills/threejs-scene/references/lighting.mdnew file mode 100644index 0000000..c614dcc--- /dev/null+++ b/skills/threejs-scene/references/lighting.md@@ -0,0 +1,41 @@+# Lighting++Light carries most of the realism in a code-built scene. Geometry tells the viewer what a thing is; light tells them it is real.++## The preset model++`env.js` describes a time of day as one flat object and blends between objects. Keeping every light-related value in one place is what lets "golden hour" stay coherent: the sky gradient, the sun, the ambient bounce, the fog and the exposure all move together.++| Key | Meaning | Typical day / golden / night |+| --- | --- | --- |+| `skyEl`, `az` | Sun position used to paint the sky (degrees) | 30 / 5 / -14 |+| `el` | Sun position used to light the scene | 32 / 9 / 42 (moon) |+| `sunI`, `sunC` | Directional light intensity and colour | 3.0 white-warm / 3.4 orange / 0.14 blue |+| `hemiS`, `hemiG`, `hemiI` | Sky and ground bounce colours, intensity | cool blue over green / peach over brown / navy over black |+| `envI` | `scene.environmentIntensity`, the image-based light | 0.75 / 0.62 / 0.16 |+| `turb`, `ray`, `mie`, `mieG` | Sky shader scattering | haze rises at golden hour |+| `fogC`, `fogD` | Exponential fog colour and density | fog takes the sky's horizon colour |+| `exp` | `toneMappingExposure` | 0.62 / 0.72 / 1.0 |+| `night` | 0 to 1, drives emissives, bloom, stars, lamps | 0 / 0 / 1 |++Separating `skyEl` from `el` is deliberate. A sun painted at 5 degrees looks right in the sky, but light from 5 degrees grazes every vertical face into darkness; lifting the light to 9 degrees keeps facades readable while the sky still says "sunset".++## Rules that held up++- **Fog colour equals the horizon colour.** Distant objects should dissolve into the sky, not into grey. Exponential fog (`FogExp2`) reads more naturally than linear.+- **Exposure is per preset.** Night needs more exposure, not brighter lights. Raising light intensities at night lifts the whole scene to a grey day.+- **The ambient term has a colour.** A hemisphere light with a cool sky and a warm or green ground gives faces in shadow the colour they have outdoors. A plain white ambient light flattens everything.+- **Regenerate the environment map when the sky changes,** or reflections show noon on a night scene. PMREM generation costs a few milliseconds; during a blend, refresh it every sixth frame.+- **Shadows**: one directional sun with a 4096 map, frustum fitted to what the camera looks at (about 0.85 times the camera distance as half-width, clamped), centred on the camera target and snapped to whole shadow texels. Without snapping, shadow edges crawl as the camera moves. `bias` of about -0.0002 and a `normalBias` proportional to scene scale remove acne.++## Night++- Sun intensity near 0.15 with a blue tint, standing in for moonlight.+- Windows, lamps and signs carry the scene: emissive materials (or a shader patch that lights windows by `uNight`) plus bloom. Bloom threshold drops and strength rises with night (0.9 to 0.75 threshold, 0.12 to 0.6 strength).+- Real lights are few, physically based (`decay: 2`, intensity in candela) and placed where light would really come from: floodlights on poles aimed at a facade, a lantern under a dome, lamps along a path. A light at ground level aimed up a wall lights the wall's base and nothing else.+- Hide lights whose intensity is zero. Three.js still renders their shadow maps.+- Floodlit pale surfaces with snow on them blow out quickly; scale flood intensity down when the scene is snowy.++## Checking light++Shoot every vantage at every preset in one contact sheet (`site-check`). Look for: crushed blacks in shadow at golden hour (raise `hemiI`), white facades clipping at noon (lower `sunI` or exposure), fog that hides the subject from the far vantage (lower `fogD`), and banding in the sky (the half-float composer target avoids it; an 8-bit target does not).diff --git a/skills/threejs-scene/references/performance.md b/skills/threejs-scene/references/performance.mdnew file mode 100644index 0000000..039b70c--- /dev/null+++ b/skills/threejs-scene/references/performance.md@@ -0,0 +1,38 @@+# Performance++## Measure first++`site-check` reports milliseconds per frame over 60 real frames and, when the page exposes `window.__app.renderer`, draw calls and triangles for a whole frame (all passes). Headless Chromium on a real GPU (Metal on macOS) gives repeatable numbers; compare runs against each other, not against a phone. If the reported renderer is SwiftShader or llvmpipe, the numbers are software rendering and meaningless.++In the browser, `renderer.info` after one frame with `info.autoReset = false` gives the same counts.++## Budget (laptop GPU, 1440x900, high tier)++| | Target |+| --- | --- |+| Frame time | under 10 ms (leaves headroom for 60 fps on weaker machines) |+| Draw calls | under 300 |+| Triangles | under 2 million |+| Shader programs | under 40 (each new material variant compiles one, and compiling stalls) |+| Textures | under 100 MB of GPU memory |++## Fixes, biggest first++1. **Instance repeated parts.** One `InstancedMesh` per part type. This is usually a 10x win on architecture, forests, crowds, traffic.+2. **Merge static meshes** that share a material and never move (`mergeGeometries`).+3. **Quality tiers.** Device pixel ratio is the largest single cost: `high` caps it at 2, `balanced` at 1.5, `fast` at 1. GTAO costs about as much as the rest of the frame; drop it in `balanced` or `fast` if needed. Shadow maps go from 4096 to 2048 in `fast`.+4. **Shadows.** Only things that cast visible shadows get `castShadow`: not small props, not distant buildings, not flat ground decals. Point-light shadows render six times (a cube); give at most one or two lights shadows.+5. **Hide dark lights.** A light at intensity 0 still renders its shadow map.+6. **Do not render idle frames.** When nothing animates and the camera is still, skip `composer.render()`. On a laptop this is the difference between a fan and silence.+7. **Pre-compile** with `renderer.compile(scene, camera)` behind the loader, so the first orbit does not stutter while shaders compile.+8. **Textures**: power-of-two canvas textures with mipmaps; 512 or 1024 is enough for tiling materials. Use KTX2 for large photographic textures if you have any.++## Auto tiering++The starter averages frame time over three-second windows and drops one tier when the average exceeds 25 ms. It never raises the tier again in a session (oscillating quality is worse than slightly low quality), never acts during a recording, and ignores frames longer than 250 ms (tab switches).++## Phones++- Expect a third of laptop throughput. Start phones on `balanced`.+- Touch: `OrbitControls` handles one-finger orbit and pinch; set `touch-action: none` on the canvas so the page does not scroll instead.+- Safe areas: keep UI above `env(safe-area-inset-bottom)`.diff --git a/skills/threejs-scene/references/shaders.md b/skills/threejs-scene/references/shaders.mdnew file mode 100644index 0000000..adfc674--- /dev/null+++ b/skills/threejs-scene/references/shaders.md@@ -0,0 +1,68 @@+# Shader patches++Patch built-in materials with `onBeforeCompile` instead of writing `ShaderMaterial`s: the patched material keeps physically based lighting, shadows, fog, tone mapping and instancing. Every patch reads the shared uniforms in `env.js` (`U.uTime`, `U.uWind`, `U.uNight`, `U.uSunDir`), so a light-preset blend or a recording drives all of them at once.++Two rules:++1. **Vertex patches need a matching depth material** for shadows: `mesh.customDepthMaterial = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking })` with the same `onBeforeCompile`. Otherwise the shadow is drawn from the unmoved geometry.+2. **Patches with different code need different cache keys.** Three.js reuses compiled programs by material type; if two materials of the same type get different patches, set `material.customProgramCacheKey = () => 'leaves-evergreen'`.++## Wind sway (instanced foliage)++```js+const sway = `+ vec4 wp = modelMatrix * instanceMatrix * vec4(position, 1.0);+ float ph = dot(wp.xz, vec2(0.13, 0.17)); // phase varies across the scene+ transformed.x += sin(uTime * 1.7 + ph) * 0.06 * uWind * (position.y + 1.0);+ transformed.z += cos(uTime * 1.3 + ph * 1.3) * 0.05 * uWind * (position.y + 1.0);`;+const patch = (sh) => {+ Object.assign(sh.uniforms, { uTime: U.uTime, uWind: U.uWind });+ sh.vertexShader = 'uniform float uTime, uWind;\n' ++ sh.vertexShader.replace('#include <begin_vertex>', '#include <begin_vertex>' + sway);+};+leafMaterial.onBeforeCompile = patch;+leafDepth.onBeforeCompile = patch; // same patch on the depth material+```++Scale the motion with height (`position.y`) so trunks stay planted and crowns move.++## Snow on upward faces++```js+mat.onBeforeCompile = (sh) => {+ sh.uniforms.uSnow = U.uSnow;+ sh.fragmentShader = sh.fragmentShader+ .replace('#include <common>', '#include <common>\nuniform float uSnow;')+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>+ { vec3 wn = inverseTransformDirection(normal, viewMatrix);+ float s = smoothstep(0.55, 0.85, wn.y) * uSnow;+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.93, 0.95, 0.98), s);+ roughnessFactor = mix(roughnessFactor, 0.7, s); }`);+};+```++Snow collects where the world-space normal points up. Add noise to the threshold for patchy cover; fade `uSnow` in over a few seconds.++## Season tint (foliage)++Blend four tints with a `vec4 uSeason` holding spring, summer, autumn and winter weights; tween the vector to change season. Multiply by a per-instance random (`vRand`, from `instanceMatrix` or an instanced attribute) so neighbouring trees differ. For winter, also shrink foliage (`uLeaf` from 1 to 0) in the vertex shader rather than recolouring it brown.++## Windows that light at night++```js+mat.onBeforeCompile = (sh) => {+ sh.uniforms.uNight = U.uNight;+ sh.fragmentShader = sh.fragmentShader+ .replace('#include <common>', '#include <common>\nuniform float uNight;')+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>+ { float h = fract(sin(dot(floor(vMapUv * vec2(24.0, 6.0)), vec2(12.9898, 78.233))) * 43758.5453);+ float lit = step(0.35, h) * uNight; // about two thirds of rooms lit+ totalEmissiveRadiance += vec3(1.0, 0.78, 0.5) * lit * (0.6 + 0.6 * h); }`);+};+```++The hash picks a stable random set of lit windows per window cell. Warm, uneven light reads as rooms; uniform light reads as a texture.++## Water++A plane with a normal map scrolled in two directions at different speeds, `roughness` around 0.08, `metalness` 0, and the environment map doing the reflection. A fountain is particles (`Points` with a small shader for falling droplets) plus a ripple patch on the basin; mark the particles `userData.noAO`.diff --git a/tests/check.mjs b/tests/check.mjsnew file mode 100644index 0000000..26de6ee--- /dev/null+++ b/tests/check.mjs@@ -0,0 +1,106 @@+#!/usr/bin/env node+// Every skill must load in every agent, and every script must at least parse.+//+// Claude Code, Codex, Cursor and Gemini CLI read SKILL.md frontmatter with strict YAML parsers+// and silently skip a skill whose frontmatter fails (an unquoted "word: word" in a description+// is enough), so this parses each one the same way and fails loudly. It also checks the plugin+// manifests point at real skills, every JavaScript file passes `node --check`, and every Python+// script compiles.+//+// npm install --no-save --no-package-lock [email protected] (once; CI does this)+// node tests/check.mjs+import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';+import { join, dirname, relative } from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';++let YAML;+try { YAML = await import('yaml'); } catch {+ console.error('needs the "yaml" package: npm install --no-save --no-package-lock [email protected]');+ process.exit(2);+}++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const SKILLS = join(ROOT, 'skills');+const errors = [];+const fail = (where, msg) => errors.push(`${where}: ${msg}`);+const parse = (text, where) => {+ const doc = YAML.parseDocument(text, { strict: true, uniqueKeys: true, prettyErrors: true });+ for (const e of [...doc.errors, ...doc.warnings]) fail(where, `YAML ${e.name}: ${e.message.split('\n')[0]}`);+ return doc.errors.length ? null : doc.toJS();+};+const walk = (dir) => readdirSync(dir).flatMap((f) => {+ const p = join(dir, f);+ return statSync(p).isDirectory() ? (f === 'node_modules' ? [] : walk(p)) : [p];+});++// skills: frontmatter, names, descriptions, Codex metadata+const names = new Map();+for (const dir of readdirSync(SKILLS)) {+ const file = join(SKILLS, dir, 'SKILL.md');+ if (!statSync(join(SKILLS, dir)).isDirectory()) continue;+ const where = `skills/${dir}/SKILL.md`;+ if (!existsSync(file)) { fail(`skills/${dir}`, 'no SKILL.md'); continue; }+ const src = readFileSync(file, 'utf8');+ const m = src.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);+ if (!m) { fail(where, 'no frontmatter block at the top'); continue; }+ const fm = parse(m[1], where);+ if (!fm) continue;+ if (typeof fm.name !== 'string' || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(fm.name) || fm.name.length > 64) fail(where, `name must be kebab-case, 64 characters at most (got ${JSON.stringify(fm.name)})`);+ if (fm.name !== dir) fail(where, `name "${fm.name}" should match its folder "${dir}" (Gemini CLI and Cursor key skills by folder)`);+ if (typeof fm.description !== 'string' || !fm.description.trim()) fail(where, 'description must be a non-empty string');+ else if (fm.description.length > 1024) fail(where, `description is ${fm.description.length} characters; agents allow 1024 at most`);+ if (names.has(fm.name)) fail(where, `name "${fm.name}" is also used by ${names.get(fm.name)}`); else names.set(fm.name, where);+ if (/—/.test(src)) fail(where, 'contains an em dash');+ // every file the skill mentions under scripts/, assets/ or references/ must exist+ for (const [, ref] of src.matchAll(/`((?:scripts|assets|references)\/[^`\s]+?)`/g)) {+ if (!existsSync(join(SKILLS, dir, ref))) fail(where, `mentions ${ref}, which does not exist`);+ }+ const openai = join(SKILLS, dir, 'agents', 'openai.yaml');+ if (existsSync(openai)) {+ const o = parse(readFileSync(openai, 'utf8'), `skills/${dir}/agents/openai.yaml`);+ if (o && !o.interface?.display_name) fail(`skills/${dir}/agents/openai.yaml`, 'interface.display_name missing');+ }+}++// plugin manifests: valid JSON, names agree, and every skill path they list exists+const manifests = ['.claude-plugin/marketplace.json', '.codex-plugin/plugin.json', '.agents/plugins/marketplace.json', '.cursor-plugin/plugin.json', 'gemini-extension.json'];+const versions = new Set();+for (const rel of manifests) {+ const p = join(ROOT, rel);+ if (!existsSync(p)) { fail(rel, 'missing'); continue; }+ let j; try { j = JSON.parse(readFileSync(p, 'utf8')); } catch (e) { fail(rel, 'invalid JSON: ' + e.message); continue; }+ if (j.name !== 'open-3d-skills') fail(rel, `name is ${JSON.stringify(j.name)}, expected "open-3d-skills"`);+ for (const plugin of j.plugins || []) {+ if (plugin.version) versions.add(plugin.version);+ for (const s of [].concat(plugin.skills || [])) if (!existsSync(join(ROOT, s, 'SKILL.md'))) fail(rel, `lists ${s}, which has no SKILL.md`);+ }+ if (j.version) versions.add(j.version);+ if (typeof j.skills === 'string' && !existsSync(join(ROOT, j.skills))) fail(rel, `skills path ${j.skills} does not exist`);+ if (j.logo && !existsSync(join(ROOT, j.logo))) fail(rel, `logo ${j.logo} does not exist`);+}+if (versions.size > 1) fail('manifests', `versions disagree: ${[...versions].join(', ')}`);+const claudeSkills = JSON.parse(readFileSync(join(ROOT, '.claude-plugin/marketplace.json'), 'utf8')).plugins[0].skills.length;+if (claudeSkills !== names.size) fail('.claude-plugin/marketplace.json', `lists ${claudeSkills} skills, the repo has ${names.size}`);++// scripts parse+const files = walk(SKILLS);+for (const f of files.filter((f) => f.endsWith('.js') || f.endsWith('.mjs'))) {+ try { execFileSync(process.execPath, ['--check', f], { stdio: 'pipe' }); } catch (e) { fail(relative(ROOT, f), String(e.stderr || e).split('\n').slice(0, 3).join(' ')); }+}+const py = files.filter((f) => f.endsWith('.py'));+if (py.length) {+ const python = ['python3', 'python'].find((p) => { try { execFileSync(p, ['--version'], { stdio: 'pipe' }); return true; } catch { return false; } });+ if (!python) fail('python', 'python3 not found; cannot check scripts');+ else for (const f of py) {+ try { execFileSync(python, ['-c', 'import ast,sys; ast.parse(open(sys.argv[1]).read())', f], { stdio: 'pipe' }); }+ catch (e) { fail(relative(ROOT, f), String(e.stderr || e).split('\n').slice(-3).join(' ')); }+ }+}++if (errors.length) {+ console.error(`not ok - ${errors.length} problem(s):`);+ for (const e of errors) console.error(' ' + e);+ process.exit(1);+}+console.log(`ok - ${names.size} skills load, ${manifests.length} manifests agree, ${files.filter((f) => /\.(m?js|py)$/.test(f)).length} scripts parse`);