The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Blockout: a score file for the timeline, and the staging view's maths
Adarshed3405650aa6
diff --git a/src/lib/blockout-score.ts b/src/lib/blockout-score.tsnew file mode 100644index 00000000..c28b3275--- /dev/null+++ b/src/lib/blockout-score.ts@@ -0,0 +1,343 @@+/**+ * A Blockout score: the timeline of a blockout as a plain text file (JSON), so camera moves and actor paths can be+ * written by hand or by another tool, played against a reference clip, and brought back as an ordinary blockout.+ *+ * Format, version 1. Times are seconds from the start. Positions are metres [x, y, z], y up, the floor at y = 0.+ * The lens is the focal length in mm on a full-frame body.+ *+ * {+ * "score": 1, optional; a higher number is refused+ * "name": "Corridor and door", optional+ * "duration": 8, optional; default: the last key's time (2 to 60 s)+ * "aspect": "16:9", optional; width:height+ * "camera": [ up to 32 keys+ * { "t": 0, "position": [0.35, 1.55, 1.8], "target": [0, 1.3, -6], "lens": 28, "shake": 0.45 }+ * ], lens optional (default: the key before, else 28); shake optional, 0 to 1+ * "actors": [ up to 24 actors, each with 1 to 32 keys+ * { "name": "Woman", "kind": "mannequin", "keys": [{ "t": 0, "position": [0, 0, -1], "turn": 180 }] }+ * ], id, kind and turn (degrees about the vertical) optional+ * "markers": [{ "t": 4.5, "label": "The door opens" }]+ * }+ *+ * At least one camera key or one actor. Numbers out of range are brought into range; the file size and the key counts+ * are capped. Importing: the camera keys, markers, length, shape and name replace the scene's when the score has them;+ * an actor whose id (or else name) matches a piece moves that piece; any other actor is added as a new piece.+ */++import { BLOCKOUT, PRIMS, newId, newPrim, normalizeScene, type BlockoutPrim, type BlockoutScene, type PrimKind, type Vec3 } from "./blockout";++export const SCORE = {+ version: 1,+ /** The largest score file (characters). */+ maxChars: 256 * 1024,+ maxCameraKeys: BLOCKOUT.maxCameraKeys,+ maxActors: 24,+ maxActorKeys: BLOCKOUT.maxCameraKeys,+ maxMarkers: BLOCKOUT.maxMarkers,+ /** Positions stay within this many metres of the origin. */+ reach: 500,+} as const;++export interface ScoreCameraKey {+ t: number;+ position: Vec3;+ target: Vec3;+ lens: number;+ shake?: number;+}++export interface ScoreActorKey {+ t: number;+ position: Vec3;+ turn?: number;+}++export interface ScoreActor {+ id?: string;+ name: string;+ kind?: PrimKind;+ keys: ScoreActorKey[];+}++export interface ScoreMarker {+ t: number;+ label: string;+}++export interface BlockoutScore {+ score: 1;+ name?: string;+ duration: number;+ aspect?: string;+ /** Absent: the scene keeps its own. */+ camera?: ScoreCameraKey[];+ actors?: ScoreActor[];+ markers?: ScoreMarker[];+}++export type ScoreResult = { ok: true; score: BlockoutScore; notes: string[] } | { ok: false; error: string };++const r3 = (n: number) => Math.round(n * 1000) / 1000 + 0;+const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;+const ASPECT = /^\d+(\.\d+)?:\d+(\.\d+)?$/;++class ScoreError extends Error {}++/** Read a score file's text: the score, or a message that says in plain words what to fix. */+export function parseScore(text: string): ScoreResult {+ if (typeof text !== "string") return { ok: false, error: "This file couldn't be read as text." };+ if (text.length > SCORE.maxChars) return { ok: false, error: `This score is too big: a score file holds up to ${SCORE.maxChars / 1024} KB.` };+ const body = text.replace(/^/, "").trim();+ if (!body) return { ok: false, error: "This file is empty." };+ let raw: unknown;+ try {+ raw = JSON.parse(body);+ } catch (e) {+ const line = lineOf(body, String((e as Error)?.message ?? ""));+ return { ok: false, error: `This isn't a score Blockout can read${line ? `: check near line ${line} for a missing comma, quote or bracket` : ""}.` };+ }+ return validateScore(raw);+}++/** The line a JSON.parse message points at ("line 3 column 5" or "position 45"). */+function lineOf(text: string, message: string): number | null {+ const line = /line (\d+)/i.exec(message);+ if (line) return Number(line[1]);+ const pos = /position (\d+)/i.exec(message);+ if (!pos) return null;+ return text.slice(0, Number(pos[1])).split("\n").length;+}++/** A score as read from a file, checked and brought into range. */+export function validateScore(raw: unknown): ScoreResult {+ try {+ return read(raw);+ } catch (e) {+ if (e instanceof ScoreError) return { ok: false, error: e.message };+ throw e;+ }+}++function read(raw: unknown): ScoreResult {+ if (!isObject(raw)) throw new ScoreError("A score starts with { and lists the camera keys and actors inside it.");+ if (raw.score !== undefined) {+ if (typeof raw.score === "number" && raw.score > SCORE.version) throw new ScoreError("This score was written for a newer version of Blockout.");+ if (raw.score !== SCORE.version) throw new ScoreError(`"score" should be ${SCORE.version}.`);+ }+ let moved = 0;+ const num = (v: unknown, where: string, what: string, lo: number, hi: number): number => {+ if (typeof v !== "number" || !Number.isFinite(v)) throw new ScoreError(`${where} needs ${what} as a number.`);+ const n = Math.max(lo, Math.min(hi, v));+ if (n !== v) moved++;+ return r3(n);+ };+ const vec = (v: unknown, where: string, field: string, example: string): Vec3 => {+ if (!Array.isArray(v) || v.length !== 3 || v.some((n) => typeof n !== "number" || !Number.isFinite(n))) throw new ScoreError(`${where}: "${field}" needs three numbers, like ${example}.`);+ return v.map((n) => num(n, where, field, -SCORE.reach, SCORE.reach)) as Vec3;+ };+ const list = (v: unknown, field: string, max: number, what: string): unknown[] | undefined => {+ if (v === undefined) return undefined;+ if (!Array.isArray(v)) throw new ScoreError(`"${field}" should be a list in [ ].`);+ if (v.length > max) throw new ScoreError(`A score holds up to ${plural(max, what)}; this one has ${v.length}.`);+ return v;+ };+ const time = (k: Record<string, unknown>, where: string) => {+ if (typeof k.t !== "number" || !Number.isFinite(k.t)) throw new ScoreError(`${where} needs a time "t" in seconds.`);+ return num(k.t, where, "its time", 0, BLOCKOUT.maxSeconds);+ };+ const entry = (v: unknown, where: string): Record<string, unknown> => {+ if (!isObject(v)) throw new ScoreError(`${where} should be written inside { }.`);+ return v;+ };++ let lastLens: number = BLOCKOUT.lens.default;+ const camera = list(raw.camera, "camera", SCORE.maxCameraKeys, "camera key")+ ?.map((v, i) => {+ const where = `Camera key ${i + 1}`;+ const k = entry(v, where);+ const t = time(k, where);+ const lens = k.lens === undefined ? lastLens : num(k.lens, where, "the lens in mm", BLOCKOUT.lens.min, BLOCKOUT.lens.max);+ lastLens = lens;+ const shake = k.shake === undefined ? undefined : num(k.shake, where, "shake (0 to 1)", 0, 1);+ return { t, position: vec(k.position, where, "position", "[0, 1.6, 4]"), target: vec(k.target, where, "target", "[0, 1.2, 0]"), lens, ...(shake ? { shake } : {}) };+ })+ .sort((a, b) => a.t - b.t);++ const kinds = Object.keys(PRIMS) as PrimKind[];+ const actors = list(raw.actors, "actors", SCORE.maxActors, "actor")?.map((v, i) => {+ const where = `Actor ${i + 1}`;+ const a = entry(v, where);+ if (a.name !== undefined && typeof a.name !== "string") throw new ScoreError(`${where}: "name" should be words in quotes.`);+ if (a.id !== undefined && typeof a.id !== "string") throw new ScoreError(`${where}: "id" should be words in quotes.`);+ if (a.kind !== undefined && !kinds.includes(a.kind as PrimKind)) throw new ScoreError(`${where}: "kind" can be ${kinds.join(", ")}.`);+ const name = (typeof a.name === "string" ? a.name.trim().slice(0, 60) : "") || `Actor ${i + 1}`;+ const keysRaw = list(a.keys, `${where}'s keys`, SCORE.maxActorKeys, "keys per actor");+ if (!keysRaw?.length) throw new ScoreError(`${where} (${name}) needs at least one key in "keys".`);+ const keys = keysRaw+ .map((kv, j) => {+ const kw = `${where} (${name}), key ${j + 1}`;+ const k = entry(kv, kw);+ const turn = k.turn === undefined ? undefined : num(k.turn, kw, "a turn in degrees", -3600, 3600);+ return { t: time(k, kw), position: vec(k.position, kw, "position", "[0, 0, -1]"), ...(turn !== undefined ? { turn } : {}) };+ })+ .sort((x, y) => x.t - y.t);+ return {+ ...(typeof a.id === "string" && a.id.trim() ? { id: a.id.trim().slice(0, 40) } : {}),+ name,+ ...(a.kind !== undefined ? { kind: a.kind as PrimKind } : {}),+ keys,+ };+ });++ const markers = list(raw.markers, "markers", SCORE.maxMarkers, "marker")+ ?.map((v, i) => {+ const where = `Marker ${i + 1}`;+ const m = entry(v, where);+ if (m.label !== undefined && typeof m.label !== "string") throw new ScoreError(`${where}: "label" should be words in quotes.`);+ return { t: time(m, where), label: (typeof m.label === "string" ? m.label.trim().slice(0, 80) : "") || `Beat ${i + 1}` };+ })+ .sort((a, b) => a.t - b.t);++ if (!camera?.length && !actors?.length) throw new ScoreError("This score has no camera keys and no actors: add a \"camera\" or an \"actors\" list.");+ if (raw.name !== undefined && typeof raw.name !== "string") throw new ScoreError('"name" should be words in quotes.');+ if (raw.aspect !== undefined && (typeof raw.aspect !== "string" || !ASPECT.test(raw.aspect.trim()))) throw new ScoreError('"aspect" should look like "16:9".');++ const times = [...(camera ?? []).map((k) => k.t), ...(actors ?? []).flatMap((a) => a.keys.map((k) => k.t)), ...(markers ?? []).map((m) => m.t)];+ const latest = Math.max(0, ...times);+ const duration = raw.duration === undefined ? r3(Math.max(BLOCKOUT.minSeconds, Math.min(BLOCKOUT.maxSeconds, latest))) : num(raw.duration, "The score", '"duration" in seconds', BLOCKOUT.minSeconds, BLOCKOUT.maxSeconds);+ const late = times.filter((t) => t > duration + 1e-6).length;++ const notes: string[] = [];+ if (moved) notes.push(`${plural(moved, "number")} ${moved === 1 ? "was" : "were"} outside what Blockout allows and ${moved === 1 ? "was" : "were"} brought into range.`);+ if (late) notes.push(`${plural(late, "key")} after the end (${duration} s) ${late === 1 ? "lands" : "land"} on the last frame.`);+ const name = typeof raw.name === "string" ? raw.name.trim().slice(0, 80) : "";+ return {+ ok: true,+ notes,+ score: {+ score: 1,+ ...(name ? { name } : {}),+ duration,+ ...(typeof raw.aspect === "string" ? { aspect: raw.aspect.trim() } : {}),+ ...(camera ? { camera } : {}),+ ...(actors ? { actors } : {}),+ ...(markers ? { markers } : {}),+ },+ };+}++/** A scene's timeline as a score: its camera keys, every piece that moves, and its markers. */+export function scoreFromScene(s: BlockoutScene): BlockoutScore {+ return {+ score: 1,+ name: s.name,+ duration: s.duration,+ aspect: s.aspect,+ camera: s.camera.map((k) => ({ t: r3(k.t), position: k.position.map(r3) as Vec3, target: k.target.map(r3) as Vec3, lens: r3(k.lens), ...(k.shake ? { shake: r3(k.shake) } : {}) })),+ actors: s.prims+ .filter((p) => p.keys?.length)+ .map((p) => ({ id: p.id, name: p.name, kind: p.kind, keys: p.keys!.map((k) => ({ t: r3(k.t), position: k.position.map(r3) as Vec3, turn: r3(k.rotation) })) })),+ markers: s.markers.map((m) => ({ t: r3(m.t), label: m.label })),+ };+}++/** One value on one line: `{ "t": 0, "position": [0, 1.6, 4] }`. */+function inline(v: unknown): string {+ if (Array.isArray(v)) return `[${v.map(inline).join(", ")}]`;+ if (isObject(v)) {+ const parts = Object.entries(v)+ .filter(([, x]) => x !== undefined)+ .map(([k, x]) => `${JSON.stringify(k)}: ${inline(x)}`);+ return parts.length ? `{ ${parts.join(", ")} }` : "{}";+ }+ return JSON.stringify(v);+}++/** A score as the text of a file: one key per line, easy to read and edit by hand. */+export function scoreText(score: BlockoutScore): string {+ const block = (items: string[], pad: string) => (items.length ? `[\n${items.map((x) => `${pad} ${x}`).join(",\n")}\n${pad}]` : "[]");+ const actor = (a: ScoreActor) => {+ const head = inline({ id: a.id, name: a.name, kind: a.kind }).slice(2, -2);+ return `{ ${head}, "keys": ${block(a.keys.map(inline), " ")} }`;+ };+ const lines: string[] = [`"score": ${score.score}`];+ if (score.name !== undefined) lines.push(`"name": ${JSON.stringify(score.name)}`);+ lines.push(`"duration": ${score.duration}`);+ if (score.aspect !== undefined) lines.push(`"aspect": ${JSON.stringify(score.aspect)}`);+ if (score.camera) lines.push(`"camera": ${block(score.camera.map(inline), " ")}`);+ if (score.actors) lines.push(`"actors": ${block(score.actors.map(actor), " ")}`);+ if (score.markers) lines.push(`"markers": ${block(score.markers.map(inline), " ")}`);+ return `{\n${lines.map((l) => ` ${l}`).join(",\n")}\n}\n`;+}++export interface ScoreApplied {+ scene: BlockoutScene;+ /** Pieces already in the scene that now follow the score. */+ moved: number;+ added: number;+ /** Actors left out: the scene was full. */+ dropped: number;+}++/** The scene with a score's timeline in it: still an ordinary blockout (normalized), so everything after it works as before. */+export function applyScore(scene: BlockoutScene, score: BlockoutScore): ScoreApplied {+ const prims: BlockoutPrim[] = scene.prims.map((p) => ({ ...p }));+ const taken = new Set<string>();+ const ids = new Set(prims.map((p) => p.id));+ let moved = 0;+ let added = 0;+ let dropped = 0;+ for (const a of score.actors ?? []) {+ const wanted = a.name.trim().toLowerCase();+ const match = (a.id ? prims.find((p) => p.id === a.id && !taken.has(p.id)) : undefined) ?? prims.find((p) => !taken.has(p.id) && p.name.trim().toLowerCase() === wanted);+ const keysFrom = (startTurn: number) => {+ let turn = startTurn;+ return a.keys.map((k) => {+ turn = k.turn ?? turn;+ return { t: k.t, position: [...k.position] as Vec3, rotation: turn };+ });+ };+ if (match) {+ const keys = keysFrom(match.keys?.[0]?.rotation ?? match.rotation);+ Object.assign(match, { keys, position: keys[0].position, rotation: keys[0].rotation });+ taken.add(match.id);+ moved++;+ continue;+ }+ if (prims.length >= BLOCKOUT.maxPrims) {+ dropped++;+ continue;+ }+ const kind: PrimKind = a.kind === "mesh" ? "box" : (a.kind ?? "mannequin");+ const keys = keysFrom(0);+ const id = a.id && !ids.has(a.id) ? a.id : newId(kind[0]);+ ids.add(id);+ taken.add(id);+ prims.push({ ...newPrim(kind, keys[0].position, a.name), id, rotation: keys[0].rotation, keys });+ added++;+ }+ const next = normalizeScene({+ ...scene,+ name: score.name ?? scene.name,+ duration: score.duration,+ aspect: score.aspect ?? scene.aspect,+ prims,+ camera: score.camera?.length ? score.camera.map((k) => ({ t: k.t, position: k.position, target: k.target, lens: k.lens, shake: k.shake ?? 0 })) : scene.camera,+ // A marker keeps its id (and so the words written for its beat) when the scene has one of the same name.+ markers: score.markers+ ? score.markers.map((m) => ({ id: scene.markers.find((x) => x.label.trim().toLowerCase() === m.label.toLowerCase())?.id ?? newId("m"), t: m.t, label: m.label }))+ : scene.markers,+ });+ return { scene: next, moved, added, dropped };+}++/** "corridor-and-door.score.json": a file name for a scene's score. */+export function scoreFileName(name: string): string {+ const slug = name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 48);+ return `${slug || "blockout"}.score.json`;+}diff --git a/src/lib/blockout-staging.ts b/src/lib/blockout-staging.tsnew file mode 100644index 00000000..bc607d9e--- /dev/null+++ b/src/lib/blockout-staging.ts@@ -0,0 +1,104 @@+/**+ * The Blockout staging view's maths: the camera's trail and each moving piece's path over the blockout, the frustum of+ * the shot camera, a reference clip's time against the playhead, and the timeline's keys. No DOM, no three.js.+ */++import { BLOCKOUT, cameraAt, lensVFov, primAt, type BlockoutCameraKey, type BlockoutPrim, type BlockoutScene, type Vec3 } from "./blockout";++const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));+const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+const scale = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k];+const cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const len = (a: Vec3) => Math.hypot(a[0], a[1], a[2]);+const unit = (a: Vec3, fallback: Vec3): Vec3 => {+ const l = len(a);+ return l > 1e-9 ? scale(a, 1 / l) : fallback;+};++/** The camera's path over `duration` (no handheld shake: the line the move follows), `samples` + 1 points. */+export function cameraTrail(keys: readonly BlockoutCameraKey[], duration: number, samples = 96): Vec3[] {+ const still = keys.map((k) => ({ ...k, shake: 0 }));+ const n = Math.max(1, Math.round(samples));+ return Array.from({ length: n + 1 }, (_, i) => cameraAt(still, (i / n) * Math.max(0, duration)).position);+}++export interface PiecePath {+ id: string;+ name: string;+ /** Where it is over the blockout, on the floor of its own position. */+ points: Vec3[];+ /** Where its keys are. */+ keys: Vec3[];+}++/** The path of each piece that travels (keys more than 5 cm apart): a door that only swings has none. */+export function piecePaths(s: Pick<BlockoutScene, "prims" | "duration">, samples = 96): PiecePath[] {+ const n = Math.max(1, Math.round(samples));+ return s.prims+ .filter((p): p is BlockoutPrim & { keys: NonNullable<BlockoutPrim["keys"]> } => (p.keys?.length ?? 0) > 1)+ .map((p) => ({ id: p.id, name: p.name, points: Array.from({ length: n + 1 }, (_, i) => primAt(p, (i / n) * Math.max(0, s.duration)).position), keys: p.keys.map((k) => [...k.position] as Vec3) }))+ .filter((p) => p.keys.some((k) => len(sub(k, p.keys[0])) > 0.05));+}++/**+ * The four far corners of the shot camera's frustum at `depth` metres along its view (top left, top right, bottom+ * right, bottom left), for a lens on a frame of `aspect` (width ÷ height). Up is +y, as the shot camera's.+ */+export function frustumCorners(position: Vec3, target: Vec3, lens: number, aspect: number, depth: number): [Vec3, Vec3, Vec3, Vec3] {+ const forward = unit(sub(target, position), [0, 0, -1]);+ // Looking straight up or down: the frame's right is +x.+ const right = unit(cross(forward, [0, 1, 0]), [1, 0, 0]);+ const up = cross(right, forward);+ const halfH = Math.tan((lensVFov(lens, aspect) * Math.PI) / 360) * depth;+ const halfW = halfH * aspect;+ const centre = add(position, scale(forward, depth));+ const at = (x: number, y: number) => add(add(centre, scale(right, x * halfW)), scale(up, y * halfH));+ return [at(-1, 1), at(1, 1), at(1, -1), at(-1, -1)];+}++/** How deep the staging view draws the frustum: out to what the camera looks at, within 1.5–8 m. */+export const frustumDepth = (position: Vec3, target: Vec3) => clamp(len(sub(target, position)), 1.5, 8);++/**+ * A reference clip's time at playhead `t` when it starts at `start` seconds of the blockout (earlier than 0: it starts+ * before the blockout). Outside the clip it holds its first or last frame, and `inside` is false.+ */+export function clipTimeAt(t: number, start: number, clipSeconds: number): { time: number; inside: boolean } {+ const at = t - start;+ const length = Number.isFinite(clipSeconds) && clipSeconds > 0 ? clipSeconds : Infinity;+ return { time: clamp(at, 0, Math.max(0, length - 0.001)), inside: at >= 0 && at <= length };+}++/** The furthest a reference clip may be moved against the blockout (seconds, either way). */+export const CLIP_SHIFT = BLOCKOUT.maxSeconds;++/**+ * The staging view's keyboard: the new playhead for a key, "toggle" for play and pause, or null when the key isn't+ * the timeline's. Space or K play and pause; comma and full stop step one frame; J and L one second; Home and End.+ */+export function timelineKey(key: string, t: number, duration: number, fps: number = BLOCKOUT.fps): number | "toggle" | null {+ const at = (n: number) => clamp(Math.round(n * fps) / fps, 0, duration);+ switch (key) {+ case " ":+ case "k":+ case "K":+ return "toggle";+ case ",":+ return at(t - 1 / fps);+ case ".":+ return at(t + 1 / fps);+ case "j":+ case "J":+ return at(t - 1);+ case "l":+ case "L":+ return at(t + 1);+ case "Home":+ return 0;+ case "End":+ return duration;+ default:+ return null;+ }+}diff --git a/tests/blockout-score.test.ts b/tests/blockout-score.test.tsnew file mode 100644index 00000000..16be0c95--- /dev/null+++ b/tests/blockout-score.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it } from "vitest";+import { BLOCKOUT, EXAMPLE_SCENE, emptyScene, normalizeScene } from "@/lib/blockout";+import { SCORE, applyScore, parseScore, scoreFileName, scoreFromScene, scoreText, validateScore } from "@/lib/blockout-score";++/** The Blockout score: a scene's timeline as a text file, read back with plain messages, and brought in as a scene. */++const ok = (text: string) => {+ const r = parseScore(text);+ if (!r.ok) throw new Error(r.error);+ return r;+};+const fails = (raw: unknown) => {+ const r = typeof raw === "string" ? parseScore(raw) : validateScore(raw);+ if (r.ok) throw new Error("expected a refusal");+ return r.error;+};++const SMALL = {+ score: 1,+ name: "Walk and turn",+ aspect: "2.39:1",+ camera: [+ { t: 0, position: [0, 1.6, 4], target: [0, 1.2, 0], lens: 35 },+ { t: 5, position: [2, 1.6, 2], target: [0, 1.2, -2], lens: 50, shake: 0.3 },+ ],+ actors: [{ name: "Hero", keys: [{ t: 0, position: [0, 0, 0], turn: 180 }, { t: 5, position: [0, 0, -4] }] }],+ markers: [{ t: 0, label: "Start" }, { t: 3, label: "Turn" }],+};++describe("parseScore", () => {+ it("reads a score, sorts keys and takes the length from the last key", () => {+ const { score, notes } = ok(JSON.stringify({ ...SMALL, camera: [...SMALL.camera].reverse() }));+ expect(notes).toEqual([]);+ expect(score.duration).toBe(5);+ expect(score.aspect).toBe("2.39:1");+ expect(score.camera!.map((k) => k.t)).toEqual([0, 5]);+ expect(score.camera![1].shake).toBe(0.3);+ expect(score.actors![0]).toMatchObject({ name: "Hero", keys: [{ t: 0, turn: 180 }, { t: 5 }] });+ expect(score.markers!.map((m) => m.label)).toEqual(["Start", "Turn"]);+ });++ it("round-trips the example scene through its own text", () => {+ const text = scoreText(scoreFromScene(EXAMPLE_SCENE));+ expect(text).toContain('{ "t": 0, "position": [0.35, 1.55, 1.8], "target": [0, 1.3, -6], "lens": 28, "shake": 0.45 }');+ const { score } = ok(text);+ expect(score).toEqual(scoreFromScene(EXAMPLE_SCENE));+ expect(applyScore(EXAMPLE_SCENE, score).scene).toEqual(normalizeScene(EXAMPLE_SCENE));+ });++ it("keeps the shortest blockout and the default lens", () => {+ const { score } = ok(JSON.stringify({ camera: [{ t: 0, position: [0, 1, 3], target: [0, 1, 0] }, { t: 1, position: [0, 1, 2], target: [0, 1, 0], lens: 85 }, { t: 1.5, position: [0, 1, 1], target: [0, 1, 0] }] }));+ expect(score.duration).toBe(BLOCKOUT.minSeconds);+ expect(score.camera!.map((k) => k.lens)).toEqual([BLOCKOUT.lens.default, 85, 85]);+ });++ it("brings numbers into range and says so", () => {+ const { score, notes } = ok(JSON.stringify({ duration: 400, camera: [{ t: -2, position: [9999, 1, 0], target: [0, 0, 0], lens: 5, shake: 3 }] }));+ expect(score.duration).toBe(BLOCKOUT.maxSeconds);+ expect(score.camera![0]).toEqual({ t: 0, position: [SCORE.reach, 1, 0], target: [0, 0, 0], lens: BLOCKOUT.lens.min, shake: 1 });+ expect(notes[0]).toMatch(/^5 numbers were outside what Blockout allows/);+ });++ it("says when keys fall after the given length", () => {+ const { score, notes } = ok(JSON.stringify({ duration: 4, actors: [{ name: "A", keys: [{ t: 0, position: [0, 0, 0] }, { t: 9, position: [1, 0, 0] }] }] }));+ expect(score.duration).toBe(4);+ expect(notes).toEqual(["1 key after the end (4 s) lands on the last frame."]);+ });++ it("strips a byte-order mark and blank space", () => {+ expect(ok(` ${JSON.stringify(SMALL)}\n`).score.name).toBe("Walk and turn");+ });++ it("refuses bad files in plain words", () => {+ expect(fails("")).toBe("This file is empty.");+ expect(fails("x".repeat(SCORE.maxChars + 1))).toMatch(/too big/);+ expect(fails('{\n "camera": [\n { "t": 0 }\n { "t": 1 }\n ]\n}')).toMatch(/^This isn't a score Blockout can read: check near line 4/);+ expect(fails([])).toMatch(/starts with \{/);+ expect(fails({ score: 2, camera: [] })).toBe("This score was written for a newer version of Blockout.");+ expect(fails({ score: "one" })).toBe('"score" should be 1.');+ expect(fails({ camera: [] })).toMatch(/no camera keys and no actors/);+ expect(fails({ camera: {} })).toBe('"camera" should be a list in [ ].');+ expect(fails({ camera: [{ position: [0, 0, 0], target: [0, 0, 1] }] })).toBe('Camera key 1 needs a time "t" in seconds.');+ expect(fails({ camera: [{ t: 0, position: [0, 0], target: [0, 0, 1] }] })).toBe('Camera key 1: "position" needs three numbers, like [0, 1.6, 4].');+ expect(fails({ camera: [{ t: 0, position: [0, 0, 0], target: [0, "a", 1] }] })).toMatch(/^Camera key 1: "target" needs three numbers/);+ expect(fails({ camera: [{ t: 0, position: [0, 0, 0], target: [0, 0, 1], lens: "wide" }] })).toBe("Camera key 1 needs the lens in mm as a number.");+ expect(fails({ camera: ["key"] })).toBe("Camera key 1 should be written inside { }.");+ expect(fails({ actors: [{ name: "Ann", keys: [] }] })).toBe('Actor 1 (Ann) needs at least one key in "keys".');+ expect(fails({ actors: [{ name: "Ann", kind: "dragon", keys: [{ t: 0, position: [0, 0, 0] }] }] })).toMatch(/^Actor 1: "kind" can be box, wall/);+ expect(fails({ actors: [{ name: 3, keys: [{ t: 0, position: [0, 0, 0] }] }] })).toBe('Actor 1: "name" should be words in quotes.');+ expect(fails({ actors: [{ name: "Ann", keys: [{ t: 1, position: [0, 0, 0], turn: "left" }] }] })).toBe("Actor 1 (Ann), key 1 needs a turn in degrees as a number.");+ expect(fails({ ...SMALL, aspect: "wide" })).toBe('"aspect" should look like "16:9".');+ expect(fails({ ...SMALL, duration: "long" })).toBe('The score needs "duration" in seconds as a number.');+ expect(fails({ ...SMALL, markers: [{ t: 1, label: 7 }] })).toBe('Marker 1: "label" should be words in quotes.');+ });++ it("caps the key and actor counts", () => {+ const key = (t: number) => ({ t, position: [0, 1, 2], target: [0, 1, 0] });+ expect(fails({ camera: Array.from({ length: SCORE.maxCameraKeys + 1 }, (_, i) => key(i / 10)) })).toBe(`A score holds up to ${SCORE.maxCameraKeys} camera keys; this one has ${SCORE.maxCameraKeys + 1}.`);+ const actor = { name: "A", keys: [{ t: 0, position: [0, 0, 0] }] };+ expect(fails({ actors: Array.from({ length: SCORE.maxActors + 1 }, () => actor) })).toMatch(/^A score holds up to 24 actors/);+ expect(fails({ actors: [{ name: "A", keys: Array.from({ length: SCORE.maxActorKeys + 1 }, (_, i) => ({ t: i / 10, position: [0, 0, 0] })) }] })).toMatch(/keys per actor/);+ expect(ok(JSON.stringify({ camera: Array.from({ length: SCORE.maxCameraKeys }, (_, i) => key(i / 10)) })).score.camera).toHaveLength(SCORE.maxCameraKeys);+ });+});++describe("applyScore", () => {+ it("moves a piece of the same name, adds the rest, and keeps the set", () => {+ const base = emptyScene();+ const { score } = ok(JSON.stringify(SMALL));+ const first = applyScore(base, score);+ expect(first).toMatchObject({ moved: 0, added: 1, dropped: 0 });+ const s = first.scene;+ expect(s.name).toBe("Walk and turn");+ expect(s.aspect).toBe("2.39:1");+ expect(s.duration).toBe(5);+ expect(s.prims[0].kind).toBe("floor");+ const hero = s.prims[1];+ expect(hero).toMatchObject({ kind: "mannequin", name: "Hero", position: [0, 0, 0], rotation: 180 });+ // A key with no turn keeps the one before.+ expect(hero.keys).toEqual([+ { t: 0, position: [0, 0, 0], rotation: 180 },+ { t: 5, position: [0, 0, -4], rotation: 180 },+ ]);+ expect(s.camera).toHaveLength(2);+ expect(s.camera[0].shake).toBe(0);++ // The same score again moves the hero instead of adding a second one, and the markers keep their ids.+ const again = applyScore(s, score);+ expect(again).toMatchObject({ moved: 1, added: 0 });+ expect(again.scene.prims).toHaveLength(2);+ expect(again.scene.markers.map((m) => m.id)).toEqual(s.markers.map((m) => m.id));+ });++ it("matches by id before name, and keeps the scene's camera and markers when the score has none", () => {+ const { score } = ok(JSON.stringify({ duration: 8, actors: [{ id: "door", name: "Anything", keys: [{ t: 1, position: [-0.5, 0, -12], turn: 0 }, { t: 2, position: [-0.5, 0, -12], turn: 90 }] }] }));+ const { scene, moved } = applyScore(EXAMPLE_SCENE, score);+ expect(moved).toBe(1);+ const door = scene.prims.find((p) => p.id === "door")!;+ expect(door.kind).toBe("door");+ expect(door.keys!.map((k) => k.rotation)).toEqual([0, 90]);+ expect(scene.camera).toEqual(normalizeScene(EXAMPLE_SCENE).camera);+ expect(scene.markers).toEqual(normalizeScene(EXAMPLE_SCENE).markers);+ });++ it("drops actors past the most pieces a blockout holds", () => {+ const full = { ...emptyScene(), prims: Array.from({ length: BLOCKOUT.maxPrims }, (_, i) => ({ ...emptyScene().prims[0], id: `f${i}`, name: `Floor ${i}` })) };+ const { score } = ok(JSON.stringify({ actors: [{ name: "Late", keys: [{ t: 0, position: [0, 0, 0] }] }] }));+ expect(applyScore(full, score)).toMatchObject({ added: 0, dropped: 1 });+ });++ it("adds a mesh actor as a box (it has no model of its own)", () => {+ const { score } = ok(JSON.stringify({ actors: [{ name: "Car", kind: "mesh", keys: [{ t: 0, position: [1, 0, 0] }, { t: 2, position: [5, 0, 0] }] }] }));+ expect(applyScore(emptyScene(), score).scene.prims[1]).toMatchObject({ kind: "box", name: "Car" });+ });+});++describe("scoreFileName", () => {+ it("makes a plain file name", () => {+ expect(scoreFileName("Corridor and door")).toBe("corridor-and-door.score.json");+ expect(scoreFileName(" ")).toBe("blockout.score.json");+ });+});diff --git a/tests/blockout-staging.test.ts b/tests/blockout-staging.test.tsnew file mode 100644index 00000000..412da25a--- /dev/null+++ b/tests/blockout-staging.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "vitest";+import { EXAMPLE_SCENE, aspectOf, cameraAt, lensVFov, type Vec3 } from "@/lib/blockout";+import { cameraTrail, clipTimeAt, frustumCorners, frustumDepth, piecePaths, timelineKey } from "@/lib/blockout-staging";++/** The Blockout staging view's maths: trails, paths, the frustum, a reference clip's time and the timeline keys. */++const close = (a: Vec3, b: Vec3, digits = 6) => a.forEach((n, i) => expect(n).toBeCloseTo(b[i], digits));++describe("cameraTrail", () => {+ it("runs from the first key to the last, with no shake", () => {+ const pts = cameraTrail(EXAMPLE_SCENE.camera, EXAMPLE_SCENE.duration, 10);+ expect(pts).toHaveLength(11);+ close(pts[0], EXAMPLE_SCENE.camera[0].position);+ close(pts[10], EXAMPLE_SCENE.camera[2].position);+ });+});++describe("piecePaths", () => {+ it("draws a path for a piece that travels, not for a door that only swings", () => {+ const paths = piecePaths(EXAMPLE_SCENE, 8);+ expect(paths.map((p) => p.id)).toEqual(["walker"]);+ expect(paths[0].points).toHaveLength(9);+ expect(paths[0].keys).toHaveLength(4);+ close(paths[0].points[8], [0, 0, -13.2]);+ });+});++describe("frustumCorners", () => {+ it("frames the lens's field of view around the line of sight", () => {+ const aspect = aspectOf("16:9");+ const [tl, tr, br, bl] = frustumCorners([0, 1, 0], [0, 1, -10], 28, aspect, 2);+ const half = Math.tan((lensVFov(28, aspect) * Math.PI) / 360) * 2;+ close(tl, [-half * aspect, 1 + half, -2]);+ close(tr, [half * aspect, 1 + half, -2]);+ close(br, [half * aspect, 1 - half, -2]);+ close(bl, [-half * aspect, 1 - half, -2]);+ });++ it("keeps a frame when the camera looks straight down", () => {+ const c = frustumCorners([0, 5, 0], [0, 0, 0], 50, 1, 1);+ for (const p of c) expect(p.every(Number.isFinite)).toBe(true);+ close(c[0].map((n, i) => (n + c[2][i]) / 2) as Vec3, [0, 4, 0]);+ });++ it("reaches out to what the camera looks at, within limits", () => {+ expect(frustumDepth([0, 0, 0], [0, 0, -4])).toBe(4);+ expect(frustumDepth([0, 0, 0], [0, 0, -0.2])).toBe(1.5);+ expect(frustumDepth([0, 0, 0], [0, 0, -50])).toBe(8);+ const c = cameraAt(EXAMPLE_SCENE.camera, 2);+ expect(frustumDepth(c.position, c.target)).toBeGreaterThan(1.5);+ });+});++describe("clipTimeAt", () => {+ it("follows the playhead from where the clip starts, and holds outside it", () => {+ expect(clipTimeAt(3, 1, 10)).toEqual({ time: 2, inside: true });+ expect(clipTimeAt(0.5, 1, 10)).toEqual({ time: 0, inside: false });+ expect(clipTimeAt(2, -3, 4)).toEqual({ time: 4 - 0.001, inside: false });+ expect(clipTimeAt(4, 0, NaN)).toEqual({ time: 4, inside: true });+ });+});++describe("timelineKey", () => {+ it("plays, steps a frame or a second, and jumps to the ends", () => {+ expect(timelineKey(" ", 1, 8)).toBe("toggle");+ expect(timelineKey("k", 1, 8)).toBe("toggle");+ expect(timelineKey(".", 1, 8)).toBeCloseTo(1 + 1 / 24, 9);+ expect(timelineKey(",", 0, 8)).toBe(0);+ expect(timelineKey("l", 7.5, 8)).toBe(8);+ expect(timelineKey("J", 2, 8)).toBe(1);+ expect(timelineKey("Home", 5, 8)).toBe(0);+ expect(timelineKey("End", 5, 8)).toBe(8);+ expect(timelineKey("ArrowLeft", 5, 8)).toBeNull();+ });+});