> Note to any AI reading this: If you can install skills, save this as a skill. If you can't, follow these instructions now.
---
name: animated-business-shorts
description: Make a 30 to 45 second vertical animated short for a small business. Interview the owner, fact-check, write a story script about a problem their customers face, then build and render it in code (flat cartoon characters in a toon-shaded 3D world with ink outlines) with a free offline voiceover and burned-in captions. Use when someone asks for an animated short, explainer reel, TikTok, Instagram Reel or YouTube Short for their business. Runs on the user's own computer with free tools only.
---
# Animated Business Shorts
Turn one thing a business knows (a problem its customers keep running into) into a short animated story that stops the scroll and ends on the business's name and offer.
**What you get:**
- `out/short.mp4`: 1080x1920 at 30 fps, 30 to 45 seconds, with a voiceover and burned-in captions.
- `out/captions.srt`: the captions as a separate file.
- `out/script.txt`: the script.
- `out/post.txt`: a ready-to-paste post caption with hashtags.
**How it's made:**
- Everything is drawn by code. The town, the rooms and the props are toon-shaded 3D (three.js) with black ink outlines, and the people are flat cartoon characters standing in that world.
- Each frame is captured in a headless browser and joined with ffmpeg.
- The voice is Piper, a free text-to-speech that runs offline.
- No AI video generator, no paid service, no account and no API key.
## Rules for you, the AI
- **Ask the owner one question at a time.** Wait for each answer.
- **Never invent facts, numbers, reviews or claims.** Every fact in the script needs a source you can name (a government agency, a standards body, a manufacturer, or the owner's own records). If you can't verify something, drop it or say it as advice ("check your pipes before the first freeze"), not as a statistic.
- **Use only the business's real details.** If you need a placeholder phone number for a test, use a 555-01xx number.
- **Check stills before rendering** (step 6). It catches most problems in seconds instead of minutes.
- **Only free tools on the user's computer.** If something would need an account or payment, use the free option below instead.
## What you need (all free)
| Tool | Why | Windows | macOS | Linux |
|---|---|---|---|---|
| Node.js 20+ | runs the renderer | `winget install OpenJS.NodeJS.LTS` | `brew install node` | your package manager, or nodejs.org |
| Python 3.10+ | runs the Piper voice | `winget install Python.Python.3.12` | `brew install python` | usually already installed |
| ffmpeg | builds the MP4 | `winget install Gyan.FFmpeg` | `brew install ffmpeg` | `sudo apt install ffmpeg` |
After installing, open a new terminal so the commands are found. Check with `node -v`, `python --version` (or `python3`) and `ffmpeg -version`.
## Step 1: Interview the owner (one question at a time)
1. What's the business called, and what do you do?
2. Which town or area do you serve?
3. What's one problem your customers run into that surprises them, or a mistake people make before they call you?
4. What should viewers do at the end? (For example "Book a winter pipe check", "Order before Friday", "Call for a free quote".) Add a phone number or web address to show.
5. Your brand colours? (Main and accent, as hex codes or colour names. If they don't know, take them from their logo, or suggest a strong blue and a warm yellow.)
6. Anything we must not say? (Legal limits, prices, promises.)
## Step 2: Find the story and check the facts
- Pick **one** surprising, true fact about the customer problem from step 1. Good stories have a cause people don't expect. For example, a burst pipe is caused by ice growing, not by old pipes.
- Verify each fact from a reliable source and write it down with the source in `story.json` under `"facts"`. Prefer government, university or industry sources. Use round, safe numbers ("about 9%", "up to 250 gallons a day").
- No fear-mongering and no guarantees. The business is the helpful expert at the end, not the hero of a disaster.
## Step 3: Write the script
About **80 to 100 words**, which is 30 to 40 seconds at the default voice speed. One sentence per line, short words, said out loud before you keep them.
1. **The hook (first line):** a statement that sounds impossible but is true. No intro, no "Hi, we're...". Example: "The water in your pipes can split them wide open without moving an inch."
2. **The setup (1 to 2 lines):** when and where it happens, so viewers picture it.
3. **The turn:** a short pivot line into the reason, like "Here's the catch." or "Here's what's really going on."
4. **The payoff (1 to 2 lines):** the real cause, with the verified fact.
5. **The twist (1 line):** flip the meaning in a few words. Example: "So your pipe didn't fail. The weather won."
6. **The call to action (1 to 2 lines):** the business name, the town, what to do and the contact.
Read it at the speed of the voice. If any line is longer than about 22 words, split it.
## Step 4: Turn the script into shots (`story.json`)
Use 5 to 7 shots, each carrying 1 or 2 lines. Plan the light like a story: **warm day** for the setup, **dusk** as it builds, **night** for the explanation, and **day** again for the business and the ending.
```json
{
"business": { "name": "...", "town": "...", "color": "#1565c0", "accent": "#ffca28", "cta": "Book a winter pipe check", "contact": "Call (303) 555-0142" },
"voice": { "model": "voices/en_US-joe-medium.onnx", "speed": 0.9 },
"say": [["(303) 555-0142", "three oh three, five five five, oh one four two"]],
"facts": ["fact (source)", "fact (source)"],
"post": "the social caption with 4 or 5 hashtags",
"shots": [
{ "set": "house", "mood": "day", "camera": "push", "characters": [{ "role": "customer", "face": "smile" }], "lines": ["..."] },
{ "set": "room", "mood": "night", "camera": "close", "label": "+9%", "props": { "pipe": { "ice": true } }, "characters": [{ "role": "customer", "face": "talk", "x": -0.6 }], "lines": ["..."] },
{ "set": "street", "mood": "day", "camera": "wide", "card": true, "hold": 1.6, "characters": [{ "role": "owner", "face": "smile", "action": "wave" }], "lines": ["..."] }
]
}
```
**Building blocks:**
- **set:** `street` (a row of shops, with the business in the middle under its own sign and awning in brand colours), `house` (a family home and yard) or `room` (a kitchen corner with a sink).
- **mood:** `day`, `dusk` or `night`. The light, the sky, the window glow and the people's shading all follow it.
- **camera:** `push` (slow move in), `pan` (slide sideways), `rise` (crane up), `orbit` (gentle arc), `wide` (establishing shot) or `close`. Every shot moves slowly and eases in and out. The camera never snaps.
- **characters** (up to 3 per shot):
- `role`: `owner` (wears the brand colours and cap), `customer`, `kid` or `neighbor`
- `face`: `smile`, `talk`, `worried` or `shock`
- `action`: `idle`, `walk` (moves by `dx`), `wave` or `point`
- `x` and `z` place them (units are about half a metre; 0 is the centre of the set)
- **props:** `pipe` (`{ "ice": true, "burst": true, "burstAt": 0.6 }`), `snow` and `clock`. Add your own in `PROPS` inside `scene.js` (see "Adding your own sets and props").
- **label:** big text at the top for a key number, like `"+9%"`. Use one or two per video at most.
- **card: true** shows the end card with the business name, call to action and contact. Use it only on the last shot, and give that shot `"hold": 1.6` so the card stays up.
- **say:** how to pronounce things the voice would misread (phone numbers, brand names, abbreviations). The captions still show the written form.
- **The voice:** `en_US-joe-medium` (male) and `en_US-kristin-medium` (female) are free for commercial use (CC0 and public domain). Avoid voices whose model card says "NC" (non-commercial) for business videos. `speed` below 1 is faster; 0.9 suits these shorts.
## Step 5: Set up the project
Make a new folder (for example `story-short`), save the four files from **The files** at the end of this skill into it exactly as written, add your `story.json`, then run:
```
npm install
npx playwright install chromium
python -m venv .venv
```
- **Windows:** `.venv\Scripts\python -m pip install piper-tts`
- **macOS / Linux:** `.venv/bin/python -m pip install piper-tts`
Then download the voices (same `.venv` python):
```
python -m piper.download_voices --download-dir voices en_US-joe-medium en_US-kristin-medium
```
These are one-off downloads: about 90 MB of browser and about 60 MB per voice. No sign-in.
## Step 6: Check stills first
```
node render.mjs story.json --stills
```
This writes one frame per shot to `out/stills/`. **Look at every one** and check:
- Nobody's face or body is hidden behind a fence, tree or wall, and nobody is cut off at the edge. If they are, move them (`x`, `z`) or pick another camera.
- The captions (lower middle) sit over the scene and don't cover a face.
- The business sign is readable in the shop shots.
- The mood is right for the moment in the story.
- People don't float, and their shadows sit under their feet.
Fix `story.json` (or `scene.js`) and run `--stills` again until every frame is clean. The voice is cached, so this takes seconds.
## Step 7: Render and verify
```
node render.mjs story.json
```
A 30-second short takes about 4 minutes on a normal laptop (the 3D is drawn in software for identical results every time). Then check:
- `ffprobe out/short.mp4` shows 1080x1920, 30 fps, an AAC audio stream, and the length you expected.
- Watch it once with sound: the captions should match the voice, and the end card should stay up for at least a second.
- Pull a few frames if you can't watch it: `ffmpeg -i out/short.mp4 -vf "fps=1/3,scale=270:480,tile=5x2" -frames:v 1 out/contact.jpg`
## Step 8: Hand it over
Tell the owner where the files are, read them the script, and give them `out/post.txt`. Suggest posting at the times their customers scroll, and pinning a comment with the call to action.
## Adding your own sets and props
- **A new prop:** add a function to `PROPS` in `scene.js`. It gets `(group, options)`, builds meshes with the `add()` helper (which adds the ink outline), and returns `update(t)`. `update(t)` must depend **only** on `t`, the seconds since the shot started: no timers and no `Math.random()`. Use `rand(seed)` for repeatable randomness.
- **A new set:** build a `THREE.Group` in `buildSets()` from boxes, cylinders and cones with `toon(colour)` materials, and register it as `SETS.name = { group, anchor }`. The anchor is where people stand.
- **Industry ideas:**
- a bakery: an oven, a counter and loaves (stretched spheres)
- a dentist: a chair, a lamp and a giant tooth prop
- a garage: a car built from boxes, wheels from cylinders
- a garden service: hedges (icosahedrons) and a mower
## Troubleshooting
| Problem | Fix |
|---|---|
| `python` not found | Use `python3`, or the full path `.venv/Scripts/python` (Windows) or `.venv/bin/python`. |
| Piper error about the model | Check the `.onnx` and `.onnx.json` files are both in `voices/` and that `story.json` points at the `.onnx`. |
| Stills are black or the scene never loads | Run `npx playwright install chromium` again, and check the terminal for `[scene error]` lines. |
| Text looks plain | The captions use Arial Black. On Linux, install it (`sudo apt install ttf-mscorefonts-installer`) or change the font in `scene.html`. |
| Voice says a number or name wrong | Add a pair to `"say"`, like `["HVAC", "H V A C"]`. |
| Video is too long | Cut words, not shots. Each line costs about 1 second per 2.8 words. |
| Rendering is slow | It's normal. Use `--stills` while you edit and render the full video once at the end. |
## The files
### package.json
```json
{ "name": "story-short", "private": true, "type": "module", "dependencies": { "three": "0.181.0", "playwright": "1.56.1" } }
```
### scene.html
```html
```
### scene.js
```js
// Story-short scene: a toon-shaded 3D town with black ink outlines and flat drawn characters.
// Every frame is a pure function of time: window.renderFrame(n) always draws the same picture for the same n.
import * as THREE from 'three';
import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
const W = 1080, H = 1920, FPS = 30;
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(50, W / H, 0.1, 500);
// ---------- helpers ----------
const rand = (seed) => { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); };
const ease = (p) => 0.5 - 0.5 * Math.cos(Math.PI * Math.min(1, Math.max(0, p)));
const grad = new THREE.DataTexture(new Uint8Array([110, 110, 110, 255, 190, 190, 190, 255, 255, 255, 255, 255]), 3, 1);
grad.minFilter = grad.magFilter = THREE.NearestFilter; grad.needsUpdate = true;
const toon = (color, extra = {}) => new THREE.MeshToonMaterial({ color, gradientMap: grad, ...extra });
const INK = new LineMaterial({ color: 0x1b1512, linewidth: 3.4, resolution: new THREE.Vector2(W, H) });
function ink(mesh) { // black comic outline on the mesh's hard edges
const g = new LineSegmentsGeometry().fromEdgesGeometry(new THREE.EdgesGeometry(mesh.geometry, 28));
const l = new LineSegments2(g, INK);
mesh.add(l);
return mesh;
}
function add(group, geo, mat, x, y, z, opts = {}) {
const m = new THREE.Mesh(geo, mat);
m.position.set(x, y, z);
if (opts.ry) m.rotation.y = opts.ry;
if (opts.rx) m.rotation.x = opts.rx;
if (opts.rz) m.rotation.z = opts.rz;
m.castShadow = opts.cast !== false; m.receiveShadow = true;
if (opts.ink !== false) ink(m);
group.add(m);
return m;
}
function canvasTex(w, h, draw, repeat = 1) {
const c = document.createElement('canvas'); c.width = w; c.height = h;
draw(c.getContext('2d'), w, h);
const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace;
t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(repeat, repeat); t.anisotropy = 8;
return t;
}
// Textures painted in code: grass strokes, cobbles, painted wood.
const grassTex = canvasTex(512, 512, (g, w, h) => {
g.fillStyle = '#5fae3c'; g.fillRect(0, 0, w, h); const r = rand(7);
for (let i = 0; i < 2600; i++) { g.strokeStyle = ['#4f9a31', '#73c24a', '#3f8a2a', '#86cf5a'][i % 4]; g.lineWidth = 2; const x = r() * w, y = r() * h; g.beginPath(); g.moveTo(x, y); g.lineTo(x + (r() - 0.5) * 6, y - 6 - r() * 8); g.stroke(); }
}, 14);
const stoneTex = canvasTex(512, 512, (g, w, h) => {
g.fillStyle = '#7b6f86'; g.fillRect(0, 0, w, h); const r = rand(11);
for (let y = 0; y < h; y += 32) for (let x = (y / 32) % 2 ? 0 : 24; x < w; x += 48) {
g.fillStyle = ['#9a8fa6', '#8c8199', '#a89bb3'][Math.floor(r() * 3)]; g.beginPath(); g.roundRect(x + 3, y + 3, 42, 26, 9); g.fill();
g.strokeStyle = '#3c3346'; g.lineWidth = 3; g.stroke();
}
}, 6);
const woodTex = canvasTex(256, 256, (g, w, h) => {
g.fillStyle = '#c98a4b'; g.fillRect(0, 0, w, h); const r = rand(3);
for (let y = 0; y < h; y += 32) { g.fillStyle = '#5a3417'; g.fillRect(0, y, w, 3); for (let k = 0; k < 6; k++) { g.strokeStyle = 'rgba(90,52,23,.35)'; g.beginPath(); g.moveTo(0, y + 8 + r() * 20); g.bezierCurveTo(w * 0.3, y + r() * 30, w * 0.6, y + r() * 30, w, y + 8 + r() * 20); g.stroke(); } }
}, 2);
// ---------- moods: the light follows the story (warm set-up, cool explanation, warm ending) ----------
const MOODS = {
day: { top: '#3f9cf0', bottom: '#c9ecff', sun: 0xfff0d2, sunI: 2.6, sunPos: [10, 16, 8], sky: 0xcfe8ff, ground: 0x7a5fc8, hemiI: 1.1, fog: 0xbfe2ff, win: 0x2e4a66, winI: 0, people: 1.0 },
dusk: { top: '#40287a', bottom: '#ff9a55', sun: 0xffa45c, sunI: 2.4, sunPos: [-14, 6, 6], sky: 0xffc590, ground: 0x5b3c99, hemiI: 1.0, fog: 0xe8a07a, win: 0xffc35a, winI: 0.6, people: 0.95 },
night: { top: '#071338', bottom: '#2a4f9c', sun: 0x9cc0ff, sunI: 1.3, sunPos: [-6, 14, 10], sky: 0x4466bb, ground: 0x1a1d4d, hemiI: 0.75, fog: 0x1d3263, win: 0xffd166, winI: 1.4, people: 0.72 },
};
const hemi = new THREE.HemisphereLight(0xffffff, 0x444444, 1); scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffffff, 2); sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048); Object.assign(sun.shadow.camera, { left: -30, right: 30, top: 30, bottom: -30, near: 1, far: 90 }); sun.shadow.bias = -0.0006;
scene.add(sun, sun.target);
const skyTex = {};
for (const [k, m] of Object.entries(MOODS)) skyTex[k] = canvasTex(4, 512, (g, w, h) => { const gr = g.createLinearGradient(0, 0, 0, h); gr.addColorStop(0, m.top); gr.addColorStop(1, m.bottom); g.fillStyle = gr; g.fillRect(0, 0, w, h); });
const windowMats = [];
let skyWindow = null;
function setMood(name) {
const m = MOODS[name] || MOODS.day;
scene.background = skyTex[name] || skyTex.day;
scene.fog = new THREE.Fog(m.fog, 28, 95);
hemi.color.set(m.sky); hemi.groundColor.set(m.ground); hemi.intensity = m.hemiI;
sun.color.set(m.sun); sun.intensity = m.sunI; sun.position.set(...m.sunPos);
for (const w of windowMats) { w.emissive.set(m.win); w.emissiveIntensity = m.winI; }
if (skyWindow) skyWindow.color.set({ day: 0x9fd4ff, dusk: 0xffb27a, night: 0x1d2f6b }[name] || 0x9fd4ff);
return m;
}
// ---------- sets ----------
const brand = { color: '#1e88e5', accent: '#ffc107' };
function building(g, x, z, w, h, d, wall, roof, opts = {}) {
add(g, new THREE.BoxGeometry(w, h, d), opts.wood ? toon(0xffffff, { map: woodTex }) : toon(wall), x, h / 2, z);
const roofGeo = new THREE.ConeGeometry(Math.max(w, d) * 0.78, h * 0.45, 4);
add(g, roofGeo, toon(roof), x, h + h * 0.225, z, { ry: Math.PI / 4 });
const winMat = toon(0x2e4a66, { emissive: 0x000000 }); windowMats.push(winMat);
for (let row = 0; row < Math.floor(h / 2.4); row++) for (let col = -1; col <= 1; col += 2) {
add(g, new THREE.BoxGeometry(0.9, 1.1, 0.12), winMat, x + col * w * 0.25, 1.8 + row * 2.3, z + d / 2 + 0.05, { cast: false });
}
}
function tree(g, x, z, s = 1) {
add(g, new THREE.CylinderGeometry(0.18 * s, 0.25 * s, 1.6 * s, 6), toon(0x7a4a26), x, 0.8 * s, z);
add(g, new THREE.IcosahedronGeometry(1.25 * s, 0), toon(0x3f9b3a), x, 2.3 * s, z);
}
function signTexture(text, bg, fg) {
return canvasTex(1024, 256, (g, w, h) => {
g.fillStyle = bg; g.fillRect(0, 0, w, h); g.strokeStyle = '#1b1512'; g.lineWidth = 16; g.strokeRect(8, 8, w - 16, h - 16);
g.fillStyle = fg; g.font = 'bold 110px "Arial Black", Arial, sans-serif'; g.textAlign = 'center'; g.textBaseline = 'middle';
let size = 110; while (g.measureText(text).width > w - 80 && size > 40) { size -= 6; g.font = `bold ${size}px "Arial Black", Arial, sans-serif`; }
g.fillText(text, w / 2, h / 2 + 6);
});
}
const SETS = {};
function buildSets(biz) {
// street: a row of shops; the business is the one in the middle with its sign and awning
const street = new THREE.Group();
add(street, new THREE.PlaneGeometry(220, 220), toon(0xffffff, { map: grassTex }), 0, 0, 0, { rx: -Math.PI / 2, ink: false, cast: false });
const road = stoneTex.clone(); road.repeat.set(60, 2); road.needsUpdate = true;
add(street, new THREE.PlaneGeometry(220, 7), toon(0xffffff, { map: road }), 0, 0.02, 4, { rx: -Math.PI / 2, ink: false, cast: false });
const walls = [0xf2a65a, 0x7fc8a9, 0xf6d55c, 0xe76f51, 0x9b8bd6];
[-15, -7.5, 7.5, 15].forEach((x, i) => building(street, x, -3, 6.2, 5 + (i % 2) * 2.2, 5, walls[i], [0x8e3b46, 0x335c81, 0x6d4c41, 0x2a7f62][i]));
building(street, 0, -3, 7.4, 6, 5.4, 0xffffff, 0x3b2f2f, { wood: true });
add(street, new THREE.BoxGeometry(7.8, 0.25, 2.2), toon(new THREE.Color(biz.color)), 0, 3.4, 0.7, { rx: 0.35 });
const sign = new THREE.Mesh(new THREE.PlaneGeometry(6.4, 1.6), new THREE.MeshBasicMaterial({ map: signTexture(biz.name, biz.color, '#ffffff') }));
sign.position.set(0, 4.75, -0.28); street.add(sign);
add(street, new THREE.BoxGeometry(1.6, 2.6, 0.15), toon(0x5a3417), 0, 1.3, -0.28);
[-21, -11, 11, 21, -26, 26].forEach((x, i) => tree(street, x, 1 - (i % 3), 1 + (i % 2) * 0.3));
for (let i = 0; i < 18; i++) tree(street, -60 + i * 7, -14 - (i % 3) * 3, 1.3);
SETS.street = { group: street, anchor: new THREE.Vector3(0, 0, 3) };
// house: a family home with a yard, fence and an outside wall pipe
const house = new THREE.Group();
add(house, new THREE.PlaneGeometry(220, 220), toon(0xffffff, { map: grassTex }), 0, 0, 0, { rx: -Math.PI / 2, ink: false, cast: false });
building(house, 0, -2, 8, 4.6, 6, 0xf4e1c1, 0xb5523b);
add(house, new THREE.BoxGeometry(1.4, 2.4, 0.15), toon(new THREE.Color(biz.color)), -1.8, 1.2, 1.05);
for (const side of [-1, 1]) { for (let x = 5; x <= 11; x += 1.5) add(house, new THREE.BoxGeometry(0.22, 1.2, 0.12), toon(0xffffff), side * x, 0.6, 2.2, { cast: true }); add(house, new THREE.BoxGeometry(6.4, 0.18, 0.1), toon(0xffffff), side * 8, 1.0, 2.2); }
[-12, 12, -16, 16].forEach((x, i) => tree(house, x, -3 + (i % 2) * 2, 1.2 + (i % 2) * 0.3));
for (let i = 0; i < 14; i++) tree(house, -45 + i * 7, -15 - (i % 2) * 4, 1.4);
SETS.house = { group: house, anchor: new THREE.Vector3(0.6, 0, 3.4) };
// room: a kitchen corner with a sink and the pipe under it
const room = new THREE.Group();
add(room, new THREE.PlaneGeometry(14, 14), toon(0xffffff, { map: woodTex }), 0, 0, 0, { rx: -Math.PI / 2, ink: false, cast: false });
add(room, new THREE.BoxGeometry(14, 7, 0.3), toon(0xf7d6a5), 0, 3.5, -4);
add(room, new THREE.BoxGeometry(0.3, 7, 14), toon(0xa5d8c9), -7, 3.5, 3);
add(room, new THREE.BoxGeometry(5, 0.3, 1.8), toon(0xeeeeee), 1.5, 2.1, -2.9);
add(room, new THREE.BoxGeometry(5, 1.95, 1.6), toon(0x4d7ea8), 1.5, 0.98, -3.0);
add(room, new THREE.BoxGeometry(1.6, 0.45, 1.0), toon(0xb8c4cc), 1.5, 2.0, -2.8);
add(room, new THREE.CylinderGeometry(0.06, 0.06, 1.0, 8), toon(0xb8c4cc), 1.5, 2.7, -3.35);
skyWindow = toon(0x9fd4ff);
add(room, new THREE.BoxGeometry(3, 2.2, 0.12), skyWindow, 1.5, 4.4, -3.82, { cast: false });
add(room, new THREE.BoxGeometry(3.3, 0.18, 0.2), toon(0xffffff), 1.5, 3.25, -3.75);
SETS.room = { group: room, anchor: new THREE.Vector3(0.9, 0, 0.6) };
for (const s of Object.values(SETS)) { s.group.visible = false; scene.add(s.group); }
}
// ---------- props (add new ones here: each gets (group, options) and returns an update(t) function) ----------
const PROPS = {
pipe(g, o) { // a pipe along a wall; o.ice adds frost, o.burst sprays water from o.burstAt seconds
const p = new THREE.Group(); g.add(p);
const pos = o.at || [1.6, 0.95, -1.95];
const pipe = add(p, new THREE.CylinderGeometry(0.16, 0.16, 3.2, 12), toon(0xc0712f), pos[0], pos[1], pos[2], { rz: Math.PI / 2 });
const ice = o.ice ? add(p, new THREE.CylinderGeometry(0.26, 0.26, 2.2, 12), new THREE.MeshToonMaterial({ color: 0xdff4ff, gradientMap: grad, transparent: true, opacity: 0.85 }), pos[0], pos[1], pos[2], { rz: Math.PI / 2, cast: false }) : null;
const drops = [];
if (o.burst) for (let i = 0; i < 70; i++) { const d = new THREE.Mesh(new THREE.SphereGeometry(0.07, 6, 6), toon(0x5ec8ff)); d.visible = false; p.add(d); drops.push(d); }
const r = rand(5);
const seeds = drops.map(() => [r(), r(), r()]);
return (t) => {
if (ice) ice.scale.y = 0.6 + 0.4 * Math.min(1, t / 2);
if (!o.burst) return;
const on = t >= (o.burstAt || 0);
drops.forEach((d, i) => {
d.visible = on;
if (!on) return;
const [a, b, c] = seeds[i]; const life = (t * 1.6 + a) % 1;
d.position.set(pos[0] + (b - 0.5) * 0.3 + life * (1.5 + c), pos[1] + 0.1 + life * 2.2 - life * life * 3.4, pos[2] + 0.2 + (c - 0.5) * 0.6);
});
};
},
snow(g, o) { // falling snow, deterministic
const n = o.count || 900, r = rand(9);
const geo = new THREE.SphereGeometry(0.05, 5, 5), mat = new THREE.MeshBasicMaterial({ color: 0xffffff });
const m = new THREE.InstancedMesh(geo, mat, n); g.add(m);
const s = Array.from({ length: n }, () => [r() * 24 - 12, r() * 14, r() * 16 - 4, 0.6 + r() * 0.8]);
const M = new THREE.Matrix4();
return (t) => s.forEach(([x, y, z, v], i) => { M.makeTranslation(x + Math.sin(t + i) * 0.3, 14 - ((14 - y + t * v) % 14), z); m.setMatrixAt(i, M); m.instanceMatrix.needsUpdate = true; });
},
clock(g, o) { // a big wall clock whose hand spins (time passing)
const at = o.at || [-3, 4.6, -3.8];
add(g, new THREE.CylinderGeometry(0.8, 0.8, 0.12, 24), toon(0xffffff), at[0], at[1], at[2], { rx: Math.PI / 2 });
const hand = add(g, new THREE.BoxGeometry(0.07, 0.65, 0.05), toon(0x1b1512), at[0], at[1], at[2] + 0.1, { ink: false });
return (t) => { hand.rotation.z = -t * 2.2; hand.position.set(at[0] + Math.sin(t * 2.2) * 0.3, at[1] + Math.cos(t * 2.2) * 0.3, at[2] + 0.1); };
},
};
// ---------- flat characters: drawn in 2D on a canvas each frame, standing in the 3D world ----------
const SKIN = ['#f1c27d', '#c68642', '#8d5524', '#ffdbac', '#e0ac69'];
function drawPerson(g, spec, t, mood) {
const w = 256, h = 512; g.clearRect(0, 0, w, h);
const bob = Math.sin(t * 5) * 2, walk = spec.action === 'walk' ? Math.sin(t * 9) : 0;
const cx = w / 2, headY = 104 + bob, headR = 50;
g.lineCap = 'round'; g.lineJoin = 'round';
const line = (x1, y1, x2, y2, col, lw) => { g.strokeStyle = '#1b1512'; g.lineWidth = lw + 9; g.beginPath(); g.moveTo(x1, y1); g.lineTo(x2, y2); g.stroke(); g.strokeStyle = col; g.lineWidth = lw; g.stroke(); };
// legs
line(cx - 16, 330, cx - 22 - walk * 26, 470, spec.pants || '#34495e', 16);
line(cx + 16, 330, cx + 22 + walk * 26, 470, spec.pants || '#34495e', 16);
// arms (wave and point lift the right arm)
const wave = spec.action === 'wave' ? Math.sin(t * 10) * 0.5 : 0;
const rx = spec.action === 'point' ? cx + 112 : spec.action === 'wave' ? cx + 70 + wave * 30 : cx + 50 - walk * 16;
const ry = spec.action === 'point' ? 205 : spec.action === 'wave' ? 120 : 300;
line(cx - 40, 200, cx - 52 + walk * 16, 300, spec.shirt, 14);
line(cx + 40, 200, rx, ry, spec.shirt, 14);
// body
g.fillStyle = spec.shirt; g.strokeStyle = '#1b1512'; g.lineWidth = 9;
g.beginPath(); g.roundRect(cx - 50, 164 + bob, 100, 180, 34); g.fill(); g.stroke();
// head
g.fillStyle = spec.skin; g.beginPath(); g.arc(cx, headY, headR, 0, Math.PI * 2); g.fill(); g.stroke();
if (spec.cap) { g.fillStyle = spec.cap; g.beginPath(); g.arc(cx, headY - 18, headR + 2, Math.PI, 0); g.fill(); g.stroke(); g.fillRect(cx, headY - 30, 66, 13); g.strokeRect(cx, headY - 30, 66, 13); }
else { g.fillStyle = spec.hair || '#3b2a1e'; g.beginPath(); g.arc(cx, headY - 10, headR, Math.PI * 1.05, Math.PI * 1.95); g.fill(); }
// face
const f = spec.face || 'smile', blink = (Math.floor(t * 3 + spec.seed) % 11 === 0);
g.fillStyle = '#1b1512';
const eyeR = f === 'shock' ? 9 : 6;
[-17, 17].forEach((dx) => { if (blink) g.fillRect(cx + dx - 7, headY - 6, 14, 4); else { g.beginPath(); g.arc(cx + dx, headY - 6, eyeR, 0, Math.PI * 2); g.fill(); } });
g.lineWidth = 6; g.beginPath();
if (f === 'shock') { g.ellipse(cx, headY + 24, 10, 14, 0, 0, Math.PI * 2); g.fill(); }
else if (f === 'worried') { g.arc(cx, headY + 34, 14, Math.PI * 1.15, Math.PI * 1.85); g.stroke(); }
else if (f === 'talk') { const o = 4 + Math.abs(Math.sin(t * 14)) * 9; g.ellipse(cx, headY + 22, 12, o, 0, 0, Math.PI * 2); g.fill(); }
else { g.arc(cx, headY + 12, 18, Math.PI * 0.15, Math.PI * 0.85); g.stroke(); }
// mood tint: people pick up the scene's light so they don't look pasted on
if (mood.people < 1) { g.globalCompositeOperation = 'source-atop'; g.fillStyle = `rgba(20,30,90,${(1 - mood.people) * 1.3})`; g.fillRect(0, 0, w, h); g.globalCompositeOperation = 'source-over'; }
}
function makePerson(spec, i) {
const c = document.createElement('canvas'); c.width = 256; c.height = 512;
const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace;
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1.15, 2.3), new THREE.MeshBasicMaterial({ map: tex, transparent: true, alphaTest: 0.5, side: THREE.DoubleSide }));
mesh.castShadow = true;
mesh.customDepthMaterial = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: tex, alphaTest: 0.5 });
const shadow = new THREE.Mesh(new THREE.CircleGeometry(0.42, 24), new THREE.MeshBasicMaterial({ color: 0x1b1030, transparent: true, opacity: 0.35 }));
shadow.rotation.x = -Math.PI / 2; shadow.scale.y = 0.45;
const roleLook = { owner: { shirt: brand.color, cap: brand.accent, pants: '#2c3e50' }, customer: { shirt: '#e76f51', pants: '#3d405b' }, kid: { shirt: '#f4d35e', pants: '#457b9d' }, neighbor: { shirt: '#8ecae6', pants: '#6d597a' } };
const s = { skin: SKIN[i % SKIN.length], seed: i * 3, ...(roleLook[spec.role] || roleLook.customer), ...spec };
if (spec.role === 'kid') mesh.scale.setScalar(0.72);
return { mesh, shadow, tex, ctx: c.getContext('2d'), spec: s };
}
// ---------- the timeline ----------
let story, shots = [], total = 0;
window.setup = (s) => {
story = s; total = s.total;
Object.assign(brand, { color: s.business.color || brand.color, accent: s.business.accent || brand.accent });
document.documentElement.style.setProperty('--brand', brand.color);
document.documentElement.style.setProperty('--accent', brand.accent);
buildSets(s.business);
shots = s.shots.map((shot, si) => {
const set = SETS[shot.set] || SETS.street;
const group = new THREE.Group(); group.visible = false; scene.add(group);
const people = (shot.characters || []).map((c, i) => { const p = makePerson(c, si * 10 + i); group.add(p.mesh, p.shadow); return p; });
const updates = Object.entries(shot.props || {}).map(([k, o]) => (PROPS[k] ? PROPS[k](group, o === true ? {} : o) : null)).filter(Boolean);
return { ...shot, setObj: set, group, people, updates };
});
document.getElementById('card-name').textContent = s.business.name;
document.getElementById('card-cta').textContent = s.business.cta;
document.getElementById('card-contact').textContent = s.business.contact || '';
return { frames: Math.ceil(total * FPS) };
};
const CAMS = { // camera moves around the focus point P, from start (p=0) to end (p=1)
push: (P, p) => [P.x, P.y + 2.1 - p * 0.3, P.z + 8.6 - p * 2.2],
pan: (P, p) => [P.x - 3.5 + p * 7, P.y + 2.2, P.z + 9],
rise: (P, p) => [P.x, P.y + 1.3 + p * 4.5, P.z + 7 + p * 4],
orbit: (P, p) => [P.x + Math.sin(-0.4 + p * 0.8) * 11, P.y + 2.6, P.z + Math.cos(-0.4 + p * 0.8) * 11],
wide: (P, p) => [P.x, P.y + 7 - p * 1.5, P.z + 22 - p * 4],
close: (P, p) => [P.x + 0.1, P.y + 1.8, P.z + 6.6 - p * 0.9],
};
function captionAt(t) {
for (const shot of story.shots) for (const line of shot.lines) {
if (t < line.start || t > line.end + 0.15) continue;
const words = line.words; let k = words.findIndex((w) => t < w.t + w.dur); if (k < 0) k = words.length - 1;
const chunks = []; let cur = [];
for (const w of words) { cur.push(w); if (cur.length === 3 || cur.map((x) => x.w).join(' ').length > 16 || /[.,!?]$/.test(w.w)) { chunks.push(cur); cur = []; } }
if (cur.length) chunks.push(cur);
let idx = 0; for (const c of chunks) { if (c.includes(words[k])) break; idx += c.length; }
const chunk = chunks.find((c) => c.includes(words[k]));
return chunk.map((w) => `${w.w.replace(/[<>&]/g, '')}`).join(' ');
}
return '';
}
window.renderFrame = (n) => {
const t = n / FPS;
let si = shots.findIndex((s) => t >= s.start && t < s.end); if (si < 0) si = shots.length - 1;
const shot = shots[si], lt = t - shot.start, p = ease(lt / (shot.end - shot.start));
for (const s of Object.values(SETS)) s.group.visible = s === shot.setObj;
shots.forEach((s) => (s.group.visible = s === shot));
const mood = setMood(shot.mood || 'day');
// people
const P = shot.setObj.anchor.clone();
shot.people.forEach((pp, i) => {
const c = pp.spec; const x0 = (c.x ?? (i - (shot.people.length - 1) / 2) * 1.6), z0 = c.z ?? 0;
const x = c.action === 'walk' ? x0 + (c.dx ?? 2.5) * p : x0;
pp.mesh.position.set(P.x + x, (pp.mesh.scale.y * 2.3) / 2, P.z + z0);
pp.shadow.position.set(P.x + x, 0.03, P.z + z0 + 0.05);
drawPerson(pp.ctx, c, t, mood); pp.tex.needsUpdate = true;
pp.mesh.rotation.y = Math.atan2(camera.position.x - pp.mesh.position.x, camera.position.z - pp.mesh.position.z);
});
shot.updates.forEach((u) => u(lt));
// camera
const focus = shot.focus != null && shot.people[shot.focus] ? shot.people[shot.focus].mesh.position.clone().setY(0) : P;
const cam = (CAMS[shot.camera] || CAMS.push)(focus, p);
camera.position.set(...cam);
camera.lookAt(focus.x, focus.y + (shot.camera === 'wide' ? 2.5 : 1.35), focus.z);
sun.target.position.copy(focus); sun.position.add(focus);
// overlays: captions, a big label, fades between shots, the end card
document.getElementById('cap').innerHTML = captionAt(t);
const label = document.getElementById('label');
label.textContent = shot.label || ''; label.style.opacity = shot.label ? Math.min(1, lt * 4) : 0;
const edge = Math.min(lt, shot.end - lt);
document.getElementById('fade').style.opacity = si > 0 && lt < 0.2 ? 1 - lt / 0.2 : 0;
const card = document.getElementById('card'); const isCard = !!shot.card;
card.style.opacity = isCard ? Math.min(1, lt * 2.5) : 0;
card.style.transform = `translateY(${isCard ? (1 - Math.min(1, lt * 2.5)) * 40 : 40}px)`;
renderer.render(scene, camera);
return { t, shot: si, edge };
};
window.ready = true;
```
### render.mjs
```js
// Story-short renderer: voice (Piper, offline) -> timeline -> frames (headless Chromium) -> MP4 (ffmpeg).
// node render.mjs story.json full video -> out/short.mp4, out/captions.srt, out/script.txt
// node render.mjs story.json --stills one frame from the middle of each shot -> out/stills/ (check these first)
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const args = process.argv.slice(2);
const storyFile = path.resolve(args.find((a) => !a.startsWith('--')) || 'story.json');
const STILLS = args.includes('--stills');
const FPS = 30, LEAD = 0.35, GAP = 0.16, TAIL = 0.3;
const story = JSON.parse(fs.readFileSync(storyFile, 'utf8'));
const OUT = path.join(HERE, 'out');
fs.mkdirSync(path.join(OUT, 'voice'), { recursive: true });
const log = (...a) => console.log('[short]', ...a);
// Empty a folder by deleting its files (not the folder itself, which Windows may have open).
function freshDir(name) { const d = path.join(OUT, name); fs.mkdirSync(d, { recursive: true }); for (const f of fs.readdirSync(d)) fs.rmSync(path.join(d, f), { force: true }); return d; }
// ---------- 1. voice every line with Piper (cached: only changed lines are re-voiced) ----------
const PY = story.voice?.python || path.join(HERE, '.venv', process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python');
const MODEL = path.resolve(HERE, story.voice?.model || 'voices/en_US-joe-medium.onnx');
const SPEED = story.voice?.speed ?? 0.92; // below 1 = faster
function readWav(file) { // 16-bit PCM mono -> { rate, samples }
const b = fs.readFileSync(file); let off = 12, rate = 22050, data = null;
while (off < b.length) { const id = b.toString('ascii', off, off + 4), size = b.readUInt32LE(off + 4); if (id === 'fmt ') rate = b.readUInt32LE(off + 12); if (id === 'data') { data = b.subarray(off + 8, off + 8 + size); break; } off += 8 + size; }
return { rate, samples: new Int16Array(data.buffer.slice(data.byteOffset, data.byteOffset + data.length)) };
}
function trim({ rate, samples }) { // cut leading/trailing silence so pauses are ours
const th = 500; let a = 0, b = samples.length - 1;
while (a < b && Math.abs(samples[a]) < th) a++; while (b > a && Math.abs(samples[b]) < th) b--;
return { rate, samples: samples.subarray(Math.max(0, a - rate * 0.02), Math.min(samples.length, b + rate * 0.05)) };
}
const spoken = (s) => (story.say || []).reduce((txt, [from, to]) => txt.split(from).join(to), s);
let rate = 22050;
for (const shot of story.shots) for (let i = 0; i < shot.lines.length; i++) {
if (typeof shot.lines[i] === 'string') shot.lines[i] = { text: shot.lines[i] };
const line = shot.lines[i];
const key = crypto.createHash('sha1').update(`${MODEL}|${SPEED}|${spoken(line.text)}`).digest('hex').slice(0, 14);
line.wav = path.join(OUT, 'voice', `${key}.wav`);
if (!fs.existsSync(line.wav)) {
const r = spawnSync(PY, ['-m', 'piper', '-m', MODEL, '-f', line.wav, '--length-scale', String(SPEED), '--', spoken(line.text)], { encoding: 'utf8' });
if (r.status !== 0 || !fs.existsSync(line.wav)) throw new Error(`Piper failed on "${line.text}": ${r.stderr || r.error}`);
}
line.audio = trim(readWav(line.wav)); rate = line.audio.rate;
line.dur = line.audio.samples.length / rate;
}
// ---------- 2. timeline: shots last as long as their lines; words timed by their length ----------
let t = LEAD;
for (const shot of story.shots) {
shot.start = t === LEAD ? 0 : t;
for (const line of shot.lines) {
line.start = t; line.end = t + line.dur;
const words = line.text.split(/\s+/).filter(Boolean), weight = (w) => w.replace(/[^\p{L}\p{N}]/gu, '').length + 2.2;
const total = words.reduce((n, w) => n + weight(w), 0); let wt = t;
line.words = words.map((w) => { const d = (line.dur * weight(w)) / total; const o = { w, t: wt, dur: d }; wt += d; return o; });
t = line.end + GAP;
}
t += shot.hold ?? 0.25; shot.end = t;
}
story.shots[story.shots.length - 1].end += TAIL; story.total = t + TAIL;
log(`${story.shots.length} shots, ${story.total.toFixed(1)} s`);
// mix the voice track (and an optional music file, quiet, under it)
const mix = new Int16Array(Math.ceil(story.total * rate));
for (const shot of story.shots) for (const line of shot.lines) mix.set(line.audio.samples.subarray(0, Math.min(line.audio.samples.length, mix.length - Math.floor(line.start * rate))), Math.floor(line.start * rate));
const header = Buffer.alloc(44); header.write('RIFF', 0); header.writeUInt32LE(36 + mix.length * 2, 4); header.write('WAVEfmt ', 8); header.writeUInt32LE(16, 16);
header.writeUInt16LE(1, 20); header.writeUInt16LE(1, 22); header.writeUInt32LE(rate, 24); header.writeUInt32LE(rate * 2, 28); header.writeUInt16LE(2, 32); header.writeUInt16LE(16, 34); header.write('data', 36); header.writeUInt32LE(mix.length * 2, 40);
fs.writeFileSync(path.join(OUT, 'voice.wav'), Buffer.concat([header, Buffer.from(mix.buffer)]));
// captions file + script, for uploads
const ts = (s) => { const ms = Math.round(s * 1000); return `${String(Math.floor(ms / 3600000)).padStart(2, '0')}:${String(Math.floor(ms / 60000) % 60).padStart(2, '0')}:${String(Math.floor(ms / 1000) % 60).padStart(2, '0')},${String(ms % 1000).padStart(3, '0')}`; };
const allLines = story.shots.flatMap((s) => s.lines);
fs.writeFileSync(path.join(OUT, 'captions.srt'), allLines.map((l, i) => `${i + 1}\n${ts(l.start)} --> ${ts(l.end)}\n${l.text}\n`).join('\n'));
fs.writeFileSync(path.join(OUT, 'script.txt'), allLines.map((l) => l.text).join('\n') + '\n');
if (story.post) fs.writeFileSync(path.join(OUT, 'post.txt'), story.post.trim() + '\n');
// ---------- 3. frames: serve this folder, drive the scene in headless Chromium ----------
const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' };
const server = http.createServer((req, res) => {
const f = path.join(HERE, decodeURIComponent(req.url.split('?')[0]));
if (!f.startsWith(HERE) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { res.writeHead(404); return res.end(); }
res.writeHead(200, { 'Content-Type': MIME[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(res);
}).listen(0);
const port = server.address().port;
const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
const page = await browser.newPage({ viewport: { width: 1080, height: 1920 } });
page.on('pageerror', (e) => console.error('[scene error]', e.message));
page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') console.error('[scene ' + m.type() + ']', m.text()); });
page.on('requestfailed', (r) => console.error('[scene request failed]', r.url()));
await page.goto(`http://localhost:${port}/scene.html`);
await page.waitForFunction(() => window.ready === true, null, { timeout: 20000 });
const plain = JSON.parse(JSON.stringify(story, (k, v) => (k === 'audio' || k === 'wav' ? undefined : v)));
const { frames } = await page.evaluate((s) => window.setup(s), plain);
await page.evaluate(() => document.fonts.ready);
if (STILLS) {
const dir = freshDir('stills');
for (const [i, s] of story.shots.entries()) {
const n = Math.floor(((s.start + s.end) / 2) * FPS);
await page.evaluate((n) => window.renderFrame(n), n);
await page.screenshot({ path: path.join(dir, `shot-${String(i + 1).padStart(2, '0')}.jpg`), type: 'jpeg', quality: 90 });
}
log(`stills -> ${dir}`);
} else {
const dir = freshDir('frames');
const t0 = Date.now();
for (let n = 0; n < frames; n++) {
await page.evaluate((n) => window.renderFrame(n), n);
await page.screenshot({ path: path.join(dir, `${String(n).padStart(5, '0')}.jpg`), type: 'jpeg', quality: 92 });
if (n % 150 === 0) log(`frame ${n}/${frames} (${((Date.now() - t0) / 1000).toFixed(0)} s)`);
}
const r = spawnSync('ffmpeg', ['-y', '-v', 'error', '-framerate', String(FPS), '-i', path.join(dir, '%05d.jpg'), '-i', path.join(OUT, 'voice.wav'),
'-c:v', 'libx264', '-preset', 'medium', '-crf', '19', '-pix_fmt', 'yuv420p', '-af', 'loudnorm=I=-16:TP=-1.5:LRA=11', '-ar', '48000', '-c:a', 'aac', '-b:a', '160k', '-shortest', '-movflags', '+faststart', path.join(OUT, 'short.mp4')], { encoding: 'utf8' });
if (r.status !== 0) throw new Error(`ffmpeg: ${r.stderr}`);
log(`video -> ${path.join(OUT, 'short.mp4')} (${frames} frames, ${((Date.now() - t0) / 1000).toFixed(0)} s)`);
}
await browser.close(); server.close();
```