Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Blockout to film: the builder, the composer's Blockout panel and Use as blockout in the 3D scene

Claude0807f932b5e2
diff --git a/src/components/cinema/blockout-builder.tsx b/src/components/cinema/blockout-builder.tsx
new file mode 100644
index 00000000..32b2b2a1
--- /dev/null
+++ b/src/components/cinema/blockout-builder.tsx
@@ -0,0 +1,566 @@
+"use client";
+
+import { Box, Camera, Clapperboard, DoorOpen, Eye, Flag, Footprints, Loader2, Move3d, Pause, Play, Plus, RotateCw, Shapes, SquareDashed, Trash2, Video, X } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Slider } from "@/components/ui/slider";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { uploadFile, useAssets } from "@/lib/api";
+import {
+ BLOCKOUT,
+ EXAMPLE_SCENE,
+ OPEN_FPS,
+ PRIMS,
+ blockoutSize,
+ cameraAt,
+ emptyScene,
+ newId,
+ newPrim,
+ type BlockoutCameraKey,
+ type BlockoutPrim,
+ type BlockoutScene,
+ type PrimKind,
+ type Vec3,
+} from "@/lib/blockout";
+import { cn } from "@/lib/utils";
+import { toastError } from "@/lib/refusals";
+import type { BlockoutEngine, ViewMode } from "./blockout-engine";
+
+/**
+ * Blockout to film, the builder (package blockout-film): place grey boxes, walls, a doorway, stairs, a door, a mannequin
+ * and meshes from your 3D models; key where they move, where the camera is (lens and handheld shake) and where the beats
+ * start; then "Use this blockout" renders the grey box (24 fps, MP4 where the browser can: the cloud's reference clip)
+ * and its depth (16 fps: the open engine's guide) in the browser and hands them to the composer.
+ */
+
+export interface BuiltBlockout {
+ video: string;
+ depth: string;
+ firstFrame: string;
+ seconds: number;
+ aspect: string;
+ /** The render's own type ("video/mp4" or "video/webm"). */
+ type: string;
+}
+
+export interface BlockoutBuilderProps {
+ initial: BlockoutScene;
+ onClose: (scene: BlockoutScene) => void;
+ onDone: (built: BuiltBlockout, scene: BlockoutScene) => void;
+}
+
+const ADD: { kind: PrimKind; icon: typeof Box }[] = [
+ { kind: "box", icon: Box },
+ { kind: "wall", icon: SquareDashed },
+ { kind: "floor", icon: Shapes },
+ { kind: "doorway", icon: DoorOpen },
+ { kind: "door", icon: DoorOpen },
+ { kind: "stairs", icon: Shapes },
+ { kind: "mannequin", icon: Footprints },
+];
+const ASPECTS = ["16:9", "21:9", "4:3", "1:1", "9:16"];
+const fmt = (t: number) => `${t.toFixed(1)} s`;
+const near = (a: number, b: number) => Math.abs(a - b) < 0.05;
+const r2 = (n: number) => Math.round(n * 100) / 100;
+
+/** A gizmo move: a primitive that moves over time gets a key at the playhead, one that stays is simply moved. */
+function movePrim(s: BlockoutScene, id: string, position: Vec3, rotation: number, at: number): BlockoutScene {
+ return {
+ ...s,
+ prims: s.prims.map((p) => {
+ if (p.id !== id) return p;
+ if (!p.keys?.length) return { ...p, position, rotation };
+ const keys = p.keys.filter((k) => !near(k.t, at));
+ return { ...p, keys: [...keys, { t: r2(at), position, rotation }].sort((a, b) => a.t - b.t) };
+ }),
+ };
+}
+
+function Field({ label, value, onChange, step = 0.1, min, max }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number; max?: number }) {
+ return (
+ <label className="grid gap-1 text-[11.5px] text-muted-foreground">
+ {label}
+ <Input
+ type="number"
+ inputMode="decimal"
+ step={step}
+ min={min}
+ max={max}
+ value={Number.isFinite(value) ? r2(value) : 0}
+ onChange={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n)) onChange(min !== undefined || max !== undefined ? Math.max(min ?? -Infinity, Math.min(max ?? Infinity, n)) : n);
+ }}
+ className="h-8 px-2 text-[13px] tabular-nums"
+ />
+ </label>
+ );
+}
+
+function Vec({ label, value, onChange, min }: { label: string; value: Vec3; onChange: (v: Vec3) => void; min?: number }) {
+ return (
+ <fieldset className="grid gap-1">
+ <legend className="mb-1 text-[12px] font-medium">{label}</legend>
+ <div className="grid grid-cols-3 gap-1.5">
+ {(["x", "y", "z"] as const).map((k, i) => (
+ <Field key={k} label={k} value={value[i]} min={min} onChange={(n) => onChange(value.map((x, j) => (j === i ? n : x)) as Vec3)} />
+ ))}
+ </div>
+ </fieldset>
+ );
+}
+
+export default function BlockoutBuilder({ initial, onClose, onDone }: BlockoutBuilderProps) {
+ const [scene, setScene] = useState<BlockoutScene>(initial);
+ const [t, setT] = useState(0);
+ const [playing, setPlaying] = useState(false);
+ const [mode, setMode] = useState<ViewMode>("edit");
+ const [selected, setSelected] = useState<string | null>(null);
+ const [gizmo, setGizmo] = useState<"translate" | "rotate">("translate");
+ const [lens, setLens] = useState<number>(BLOCKOUT.lens.default);
+ const [shake, setShake] = useState(0.3);
+ const [busy, setBusy] = useState<{ label: string; p: number } | null>(null);
+ const [error, setError] = useState("");
+ const [canvasEl, setCanvasEl] = useState<HTMLCanvasElement | null>(null);
+ const [stageEl, setStageEl] = useState<HTMLDivElement | null>(null);
+ const engineRef = useRef<BlockoutEngine | null>(null);
+ const sceneRef = useRef(scene);
+ const tRef = useRef(t);
+ const abort = useRef<AbortController | null>(null);
+ const meshes = useAssets(undefined, "model3d");
+ useEffect(() => {
+ sceneRef.current = scene;
+ tRef.current = t;
+ }, [scene, t]);
+
+ // The engine (three.js) loads with the builder.
+ useEffect(() => {
+ if (!canvasEl) return;
+ let eng: BlockoutEngine | null = null;
+ let gone = false;
+ void import("./blockout-engine")
+ .then(({ BlockoutEngine }) => {
+ if (gone) return;
+ eng = new BlockoutEngine(canvasEl, {
+ onSelect: setSelected,
+ onMove: (id, position, rotation) => setScene((s) => movePrim(s, id, position, rotation, tRef.current)),
+ });
+ engineRef.current = eng;
+ eng.setScene(sceneRef.current);
+ eng.setTime(tRef.current);
+ const r = canvasEl.getBoundingClientRect();
+ eng.resize(r.width, r.height);
+ })
+ .catch((e) => setError(/webgl|context/i.test(String((e as Error)?.message)) ? "This browser can't show 3D here (WebGL is off). Try another browser, or upload a render from your 3D app." : String((e as Error)?.message ?? e)));
+ return () => {
+ gone = true;
+ abort.current?.abort();
+ eng?.dispose();
+ engineRef.current = null;
+ };
+ }, [canvasEl]);
+
+ useEffect(() => {
+ if (!stageEl) return;
+ const ro = new ResizeObserver(([e]) => engineRef.current?.resize(e.contentRect.width, e.contentRect.height));
+ ro.observe(stageEl);
+ return () => ro.disconnect();
+ }, [stageEl]);
+
+ useEffect(() => engineRef.current?.setScene(scene), [scene]);
+ useEffect(() => engineRef.current?.setTime(t), [t]);
+ useEffect(() => engineRef.current?.setMode(mode), [mode]);
+ useEffect(() => engineRef.current?.setGizmo(gizmo), [gizmo]);
+ useEffect(() => engineRef.current?.select(selected), [selected]);
+
+ // Play: the playhead runs in real time, then stops at the end.
+ useEffect(() => {
+ if (!playing) return;
+ let raf = 0;
+ let last = performance.now();
+ const tick = (now: number) => {
+ const next = tRef.current + (now - last) / 1000;
+ last = now;
+ if (next >= sceneRef.current.duration) {
+ setT(sceneRef.current.duration);
+ setPlaying(false);
+ return;
+ }
+ setT(next);
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [playing]);
+
+ const patch = (fn: (s: BlockoutScene) => BlockoutScene) => setScene((s) => fn(s));
+ const prim = scene.prims.find((p) => p.id === selected) ?? null;
+ const updatePrim = (id: string, fn: (p: BlockoutPrim) => BlockoutPrim) => patch((s) => ({ ...s, prims: s.prims.map((p) => (p.id === id ? fn(p) : p)) }));
+
+ const add = (kind: PrimKind, extra: Partial<BlockoutPrim> = {}) => {
+ if (scene.prims.length >= BLOCKOUT.maxPrims) {
+ toast.error(`A blockout holds up to ${BLOCKOUT.maxPrims} pieces`);
+ return;
+ }
+ const view = engineRef.current?.viewPose();
+ const at: Vec3 = view ? [r2(view.target[0]), 0, r2(view.target[2])] : [0, 0, 0];
+ const p = { ...newPrim(kind, at), ...extra };
+ patch((s) => ({ ...s, prims: [...s.prims, p] }));
+ setSelected(p.id);
+ setMode("edit");
+ };
+
+ const keyHere = (p: BlockoutPrim) => {
+ const at = r2(t);
+ const cur = { position: p.position, rotation: p.rotation };
+ const base = p.keys?.length ? p.keys : at > 0 ? [{ t: 0, ...cur }] : [];
+ const keys = [...base.filter((k) => !near(k.t, at)), { t: at, ...cur }].sort((a, b) => a.t - b.t);
+ updatePrim(p.id, (x) => ({ ...x, keys }));
+ toast(`${p.name} keyed at ${fmt(at)}: move the playhead, then move it to make it walk or swing there`);
+ };
+
+ const setCameraKey = () => {
+ const view = engineRef.current?.viewPose();
+ if (!view) return;
+ const at = r2(t);
+ const key: BlockoutCameraKey = { t: at, position: view.position, target: view.target, lens, shake };
+ patch((s) => {
+ if (s.camera.length >= BLOCKOUT.maxCameraKeys && !s.camera.some((k) => near(k.t, at))) {
+ toast.error(`Up to ${BLOCKOUT.maxCameraKeys} camera keys`);
+ return s;
+ }
+ return { ...s, camera: [...s.camera.filter((k) => !near(k.t, at)), key].sort((a, b) => a.t - b.t) };
+ });
+ toast(`Camera keyed at ${fmt(at)} · ${Math.round(lens)} mm${shake ? ` · shake ${Math.round(shake * 100)}%` : ""}`);
+ };
+
+ const addMarker = () => {
+ const at = r2(t);
+ if (scene.markers.length >= BLOCKOUT.maxMarkers) return toast.error(`Up to ${BLOCKOUT.maxMarkers} markers`);
+ patch((s) => ({ ...s, markers: [...s.markers.filter((m) => !near(m.t, at)), { id: newId("m"), t: at, label: `Beat ${s.markers.length + 1}` }].sort((a, b) => a.t - b.t) }));
+ };
+
+ const shotNow = useMemo(() => cameraAt(scene.camera, t), [scene.camera, t]);
+
+ const render = async () => {
+ const eng = engineRef.current;
+ if (!eng || busy) return;
+ setPlaying(false);
+ setMode("shot");
+ const ctl = new AbortController();
+ abort.current = ctl;
+ try {
+ const grey = blockoutSize(scene.aspect, 1280);
+ const small = blockoutSize(scene.aspect, 832);
+ setBusy({ label: "Rendering the grey box", p: 0 });
+ const g = await eng.render({ kind: "grey", fps: BLOCKOUT.fps, ...grey, preferMp4: true, signal: ctl.signal, onProgress: (p) => setBusy({ label: "Rendering the grey box", p }) });
+ setBusy({ label: "Rendering its depth", p: 0 });
+ const d = await eng.render({ kind: "depth", fps: OPEN_FPS, ...small, signal: ctl.signal, onProgress: (p) => setBusy({ label: "Rendering its depth", p }) });
+ setBusy({ label: "Saving", p: 1 });
+ const ext = (type: string) => (type.includes("mp4") ? "mp4" : "webm");
+ const [video, depth, first] = await Promise.all([
+ uploadFile(new File([g.video], `blockout.${ext(g.type)}`, { type: g.type })),
+ uploadFile(new File([d.video], `blockout-depth.${ext(d.type)}`, { type: d.type })),
+ uploadFile(new File([g.first!], "blockout-first-frame.png", { type: "image/png" })),
+ ]);
+ onDone({ video: video.url, depth: depth.url, firstFrame: first.url, seconds: scene.duration, aspect: scene.aspect, type: g.type }, scene);
+ } catch (e) {
+ if ((e as Error).name !== "AbortError") toastError(e, "Couldn't render the blockout");
+ } finally {
+ setBusy(null);
+ abort.current = null;
+ }
+ };
+
+ const keyTicks = (list: { t: number }[], cls: string) =>
+ list.map((k, i) => <span key={i} aria-hidden className={cn("pointer-events-none absolute top-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full", cls)} style={{ left: `${(k.t / scene.duration) * 100}%` }} />);
+
+ return (
+ <Dialog open onOpenChange={(v) => !v && !busy && onClose(scene)}>
+ <DialogContent showCloseButton={false} className="flex h-[100svh] w-screen max-w-none flex-col gap-0 overflow-hidden rounded-none p-0 sm:max-w-none md:flex-row" onOpenAutoFocus={(e) => e.preventDefault()}>
+ <DialogTitle className="sr-only">Blockout builder</DialogTitle>
+ <DialogDescription className="sr-only">Place grey boxes, a mannequin and the camera, key their moves and the beats, then render the blockout.</DialogDescription>
+ <div className="relative flex min-h-0 min-w-0 flex-1 flex-col bg-[#161617]">
+ <div className="flex items-center gap-2 px-3 py-2 text-white">
+ <Clapperboard className="size-4 shrink-0" aria-hidden />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[14px] font-medium">Blockout builder</p>
+ <p className="truncate text-[11.5px] text-white/65">{mode === "edit" ? "Drag to orbit · click a piece to move it" : "Through the shot camera"}</p>
+ </div>
+ <div className="inline-flex h-8 shrink-0 rounded-full bg-white/10 p-0.5" role="radiogroup" aria-label="View">
+ {(
+ [
+ ["edit", "Build", Move3d],
+ ["shot", "Shot", Video],
+ ] as const
+ ).map(([id, label, Icon]) => (
+ <button
+ key={id}
+ type="button"
+ role="radio"
+ aria-checked={mode === id}
+ onClick={() => setMode(id)}
+ className={cn("inline-flex items-center gap-1 rounded-full px-2.5 text-[12.5px] font-medium", mode === id ? "bg-white text-black" : "text-white/80 hover:text-white")}
+ >
+ <Icon className="size-3.5" /> {label}
+ </button>
+ ))}
+ </div>
+ <button type="button" onClick={() => !busy && onClose(scene)} className="grid size-9 shrink-0 place-items-center rounded-full hover:bg-white/15" aria-label="Close the builder">
+ <X className="size-[18px]" />
+ </button>
+ </div>
+ <div ref={setStageEl} className="relative min-h-[38svh] flex-1 overflow-hidden">
+ <canvas ref={setCanvasEl} tabIndex={0} aria-label="Blockout 3D view: drag to orbit, scroll to zoom, click a piece to select it" className="absolute inset-0 size-full touch-none outline-none" />
+ {mode === "shot" && (
+ <span className="pointer-events-none absolute top-2 left-2 rounded bg-black/55 px-1.5 py-0.5 font-mono text-[11px] text-white/90">
+ {scene.aspect} · {Math.round(shotNow.lens)} mm · {fmt(t)}
+ </span>
+ )}
+ {error && <p className="absolute inset-x-4 top-4 rounded-lg bg-black/70 p-3 text-[13px] text-white">{error}</p>}
+ {busy && (
+ <div className="absolute inset-0 grid place-items-center bg-black/55 text-white" role="status">
+ <div className="w-64 max-w-[80%] space-y-2 text-center">
+ <Loader2 className="mx-auto size-5 animate-spin" />
+ <p className="text-[13px]">{busy.label}… {Math.round(busy.p * 100)}%</p>
+ <div className="h-1.5 overflow-hidden rounded-full bg-white/20">
+ <div className="h-full bg-white" style={{ width: `${busy.p * 100}%` }} />
+ </div>
+ <Button size="sm" variant="secondary" onClick={() => abort.current?.abort()}>
+ Stop
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ {/* The timeline: play, scrub, the camera keys (amber) and the beat markers (blue). */}
+ <div className="space-y-1.5 border-t border-white/10 px-3 py-2 text-white">
+ <div className="flex items-center gap-2">
+ <button type="button" onClick={() => (t >= scene.duration ? (setT(0), setPlaying(true)) : setPlaying((p) => !p))} className="grid size-8 shrink-0 place-items-center rounded-full bg-white/12 hover:bg-white/20" aria-label={playing ? "Pause" : "Play"}>
+ {playing ? <Pause className="size-4" /> : <Play className="size-4" />}
+ </button>
+ <div className="relative min-w-0 flex-1">
+ <Slider value={[t]} min={0} max={scene.duration} step={1 / BLOCKOUT.fps} onValueChange={([v]) => (setPlaying(false), setT(v))} aria-label="Playhead" />
+ {keyTicks(scene.camera, "bg-amber-400")}
+ {keyTicks(scene.markers, "bg-sky-400 ring-2 ring-[#161617]")}
+ </div>
+ <span className="w-14 shrink-0 text-right font-mono text-[12px] tabular-nums">{fmt(t)}</span>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {scene.markers.map((m) => (
+ <button key={m.id} type="button" onClick={() => setT(m.t)} className="h-7 rounded-full bg-sky-500/20 px-2.5 text-[12px] text-sky-100 hover:bg-sky-500/30">
+ <Flag className="mr-1 inline size-3" />
+ {fmt(m.t)} · {m.label}
+ </button>
+ ))}
+ <button type="button" onClick={addMarker} className="inline-flex h-7 items-center gap-1 rounded-full border border-dashed border-white/30 px-2.5 text-[12px] hover:bg-white/10">
+ <Plus className="size-3" /> Marker at {fmt(t)}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <aside className="flex max-h-[46svh] min-h-0 w-full shrink-0 flex-col border-t bg-background md:max-h-none md:w-[340px] md:border-t-0 md:border-l">
+ <Tabs defaultValue="build" className="flex min-h-0 flex-1 flex-col gap-0">
+ <TabsList className="mx-3 mt-3 grid grid-cols-4">
+ <TabsTrigger value="build">Build</TabsTrigger>
+ <TabsTrigger value="piece">Piece</TabsTrigger>
+ <TabsTrigger value="camera">Camera</TabsTrigger>
+ <TabsTrigger value="beats">Beats</TabsTrigger>
+ </TabsList>
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 py-3">
+ <TabsContent value="build" className="mt-0 space-y-3">
+ <p className="text-[12.5px] text-muted-foreground">Grey boxes stand in for the set; the mannequin for a person. Keep it simple: the references say what everything looks like.</p>
+ <div className="grid grid-cols-2 gap-1.5">
+ {ADD.map(({ kind, icon: Icon }) => (
+ <button key={kind} type="button" onClick={() => add(kind)} title={PRIMS[kind].hint} className="flex items-center gap-2 rounded-lg border px-2.5 py-2 text-left text-[13px] hover:bg-accent">
+ <Icon className="size-4 shrink-0 text-muted-foreground" />
+ {PRIMS[kind].name}
+ </button>
+ ))}
+ <Popover>
+ <PopoverTrigger asChild>
+ <button type="button" className="flex items-center gap-2 rounded-lg border px-2.5 py-2 text-left text-[13px] hover:bg-accent">
+ <Box className="size-4 shrink-0 text-muted-foreground" /> Your 3D model
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[min(92vw,300px)] p-2" align="start">
+ <p className="px-1 pb-1.5 text-[12px] text-muted-foreground">From Image to 3D and your Library: it stands in grey, scaled to 1 m (resize it under Piece).</p>
+ <div className="max-h-56 space-y-0.5 overflow-y-auto">
+ {(meshes.data ?? []).slice(0, 30).map((a) => (
+ <button key={a.id} type="button" onClick={() => add("mesh", { url: a.url, name: (a.name ?? "Model").replace(/\.glb$/i, "").slice(0, 40) })} className="block w-full truncate rounded-md px-2 py-1.5 text-left text-[13px] hover:bg-accent">
+ {a.name ?? "3D model"}
+ </button>
+ ))}
+ {!meshes.isLoading && !meshes.data?.length && <p className="px-2 py-2 text-[12.5px] text-muted-foreground">No 3D models yet: make one in Image to 3D.</p>}
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ <label className="grid gap-1 text-[12px] font-medium">
+ Length (s)
+ <Input
+ type="number"
+ min={BLOCKOUT.minSeconds}
+ max={BLOCKOUT.maxSeconds}
+ step={0.5}
+ value={scene.duration}
+ onChange={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n)) patch((s) => ({ ...s, duration: Math.max(BLOCKOUT.minSeconds, Math.min(BLOCKOUT.maxSeconds, n)) }));
+ }}
+ className="h-8 text-[13px]"
+ />
+ </label>
+ <label className="grid gap-1 text-[12px] font-medium">
+ Frame
+ <select value={scene.aspect} onChange={(e) => patch((s) => ({ ...s, aspect: e.target.value }))} className="h-8 rounded-md border bg-background px-2 text-[13px]">
+ {ASPECTS.map((a) => (
+ <option key={a}>{a}</option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ <Button size="sm" variant="secondary" onClick={() => (setScene(structuredClone(EXAMPLE_SCENE)), setT(0), setSelected(null))}>
+ Corridor example
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => (setScene(emptyScene()), setT(0), setSelected(null))}>
+ Start empty
+ </Button>
+ </div>
+ <ul className="space-y-0.5" aria-label="Pieces">
+ {scene.prims.map((p) => (
+ <li key={p.id}>
+ <button type="button" onClick={() => setSelected(p.id)} className={cn("flex w-full items-center justify-between rounded-md px-2 py-1 text-left text-[13px] hover:bg-accent", selected === p.id && "bg-brand-faint text-brand-text")}>
+ <span className="truncate">{p.name}</span>
+ <span className="text-[11.5px] text-muted-foreground">{p.keys?.length ? `${p.keys.length} keys` : PRIMS[p.kind].name}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </TabsContent>
+
+ <TabsContent value="piece" className="mt-0 space-y-3">
+ {!prim ? (
+ <p className="text-[13px] text-muted-foreground">Click a piece in the view, or in the list under Build.</p>
+ ) : (
+ <>
+ <Input value={prim.name} onChange={(e) => updatePrim(prim.id, (p) => ({ ...p, name: e.target.value.slice(0, 60) }))} aria-label="Name" className="h-8 text-[13px]" />
+ <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="radiogroup" aria-label="Gizmo">
+ {(
+ [
+ ["translate", "Move", Move3d],
+ ["rotate", "Turn", RotateCw],
+ ] as const
+ ).map(([id, label, Icon]) => (
+ <button key={id} type="button" role="radio" aria-checked={gizmo === id} onClick={() => setGizmo(id)} className={cn("inline-flex items-center gap-1 rounded-full px-2.5 text-[12.5px] font-medium", gizmo === id ? "bg-background shadow-soft" : "text-muted-foreground")}>
+ <Icon className="size-3.5" /> {label}
+ </button>
+ ))}
+ </div>
+ {!prim.keys?.length && (
+ <>
+ <Vec label="Position (m)" value={prim.position} onChange={(position) => updatePrim(prim.id, (p) => ({ ...p, position }))} />
+ <Field label="Turn (°)" value={prim.rotation} step={5} onChange={(rotation) => updatePrim(prim.id, (p) => ({ ...p, rotation }))} />
+ </>
+ )}
+ <Vec label="Size (m)" value={prim.size} min={0.01} onChange={(size) => updatePrim(prim.id, (p) => ({ ...p, size }))} />
+ <div className="space-y-1.5 rounded-lg bg-muted/60 p-2.5">
+ <p className="text-[12.5px] font-medium">Moves</p>
+ <p className="text-[12px] text-muted-foreground">
+ {prim.keys?.length
+ ? `${prim.keys.length} keys: ${prim.keys.map((k) => fmt(k.t)).join(", ")}. Drag it with the gizmo at another time to add one.`
+ : prim.kind === "door"
+ ? "Key it shut, move the playhead, then turn it open."
+ : "Key it here, move the playhead, then move it: it walks or slides between keys."}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ <Button size="sm" variant="secondary" onClick={() => keyHere(prim)}>
+ Key at {fmt(t)}
+ </Button>
+ {!!prim.keys?.length && (
+ <Button size="sm" variant="ghost" onClick={() => updatePrim(prim.id, (p) => ({ ...p, keys: undefined, position: p.keys![0].position, rotation: p.keys![0].rotation }))}>
+ Clear moves
+ </Button>
+ )}
+ </div>
+ </div>
+ <Button size="sm" variant="ghost" className="text-destructive" onClick={() => (patch((s) => ({ ...s, prims: s.prims.filter((p) => p.id !== prim.id) })), setSelected(null))}>
+ <Trash2 className="size-3.5" /> Remove
+ </Button>
+ </>
+ )}
+ </TabsContent>
+
+ <TabsContent value="camera" className="mt-0 space-y-3">
+ <p className="text-[12.5px] text-muted-foreground">Frame the shot in the Build view, then key the camera at the playhead. Shot shows what the camera films.</p>
+ <div className="space-y-1.5">
+ <div className="flex justify-between text-[12.5px] font-medium">
+ <span>Lens</span>
+ <span className="font-mono">{Math.round(lens)} mm</span>
+ </div>
+ <Slider value={[lens]} min={BLOCKOUT.lens.min} max={BLOCKOUT.lens.max} step={1} onValueChange={([v]) => setLens(v)} aria-label="Lens" />
+ </div>
+ <div className="space-y-1.5">
+ <div className="flex justify-between text-[12.5px] font-medium">
+ <span>Handheld shake</span>
+ <span className="font-mono">{Math.round(shake * 100)}%</span>
+ </div>
+ <Slider value={[shake]} min={0} max={1} step={0.05} onValueChange={([v]) => setShake(v)} aria-label="Handheld shake" />
+ </div>
+ <Button size="sm" onClick={setCameraKey} className="w-full">
+ <Camera className="size-3.5" /> Key the camera at {fmt(t)}
+ </Button>
+ <ul className="space-y-1" aria-label="Camera keys">
+ {scene.camera.map((k, i) => (
+ <li key={i} className="flex items-center gap-1.5 rounded-md bg-muted/60 px-2 py-1 text-[12.5px]">
+ <span className="flex-1 tabular-nums">
+ {fmt(k.t)} · {Math.round(k.lens)} mm{k.shake ? ` · shake ${Math.round(k.shake * 100)}%` : ""}
+ </span>
+ <button type="button" onClick={() => (setT(k.t), setLens(k.lens), setShake(k.shake), setMode("edit"), engineRef.current?.viewFromShot(k.t))} className="grid size-7 place-items-center rounded-md hover:bg-accent" aria-label={`Look from the key at ${fmt(k.t)}`}>
+ <Eye className="size-3.5" />
+ </button>
+ <button type="button" disabled={scene.camera.length < 2} onClick={() => patch((s) => ({ ...s, camera: s.camera.filter((_, j) => j !== i) }))} className="grid size-7 place-items-center rounded-md hover:bg-accent disabled:opacity-40" aria-label={`Remove the key at ${fmt(k.t)}`}>
+ <Trash2 className="size-3.5" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </TabsContent>
+
+ <TabsContent value="beats" className="mt-0 space-y-2">
+ <p className="text-[12.5px] text-muted-foreground">Each marker starts a beat (“Lights out”, “Door kicked”); you write what happens in each next to the composer.</p>
+ {scene.markers.map((m) => (
+ <div key={m.id} className="flex items-end gap-1.5">
+ <div className="w-20 shrink-0">
+ <Field label="At (s)" value={m.t} min={0} max={scene.duration} onChange={(n) => patch((s) => ({ ...s, markers: s.markers.map((x) => (x.id === m.id ? { ...x, t: n } : x)).sort((a, b) => a.t - b.t) }))} />
+ </div>
+ <Input value={m.label} onChange={(e) => patch((s) => ({ ...s, markers: s.markers.map((x) => (x.id === m.id ? { ...x, label: e.target.value.slice(0, 80) } : x)) }))} aria-label={`Marker at ${fmt(m.t)}`} className="h-8 flex-1 text-[13px]" />
+ <button type="button" onClick={() => patch((s) => ({ ...s, markers: s.markers.filter((x) => x.id !== m.id) }))} className="grid size-8 place-items-center rounded-md hover:bg-accent" aria-label={`Remove the marker ${m.label}`}>
+ <Trash2 className="size-3.5" />
+ </button>
+ </div>
+ ))}
+ <Button size="sm" variant="secondary" onClick={addMarker}>
+ <Plus className="size-3.5" /> Marker at {fmt(t)}
+ </Button>
+ </TabsContent>
+ </div>
+ </Tabs>
+ <div className="border-t p-3">
+ <Button className="w-full" disabled={!!busy || !!error} onClick={render}>
+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Clapperboard className="size-4" />} Use this blockout
+ </Button>
+ <p className="mt-1.5 text-center text-[11.5px] text-muted-foreground">Renders in your browser: the grey box and its depth, {fmt(scene.duration)}</p>
+ </div>
+ </aside>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/cinema/blockout-engine.ts b/src/components/cinema/blockout-engine.ts
new file mode 100644
index 00000000..35df2994
--- /dev/null
+++ b/src/components/cinema/blockout-engine.ts
@@ -0,0 +1,582 @@
+"use client";
+
+import * as THREE from "three";
+import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
+import { TransformControls } from "three/examples/jsm/controls/TransformControls.js";
+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
+import { DOOR_GAP, STAIR_STEPS, aspectOf, cameraAt, lensVFov, primAt, primSpeed, type BlockoutPrim, type BlockoutScene, type Vec3 } from "@/lib/blockout";
+import { encodeFrames } from "./video-encode";
+
+/**
+ * The blockout builder's renderer (three.js, loaded only when the builder opens): grey boxes, planes, a doorway, stairs,
+ * a door on its hinge, a mannequin that walks between its keys and GLB meshes; an orbit view to build in with a move /
+ * turn gizmo, the shot camera along its keys (eased, with handheld shake), and the render of the grey box and its depth
+ * (near = bright, as Depth Anything draws it) frame by frame into video.
+ */
+
+const GREY = 0xb4b4b4;
+const FIGURE = 0x8e8e8e;
+const BACKGROUND = 0x404040;
+const DEG = Math.PI / 180;
+
+export type ViewMode = "edit" | "shot";
+
+export interface EngineEvents {
+ onSelect?: (id: string | null) => void;
+ /** A primitive moved or turned with the gizmo (at the playhead: the builder decides whether that is a key). */
+ onMove?: (id: string, position: Vec3, rotation: number) => void;
+}
+
+const depthVertex = /* glsl */ `
+varying float vDepth;
+void main() {
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
+ vDepth = -mv.z;
+ gl_Position = projectionMatrix * mv;
+}`;
+const depthFragment = /* glsl */ `
+uniform float uNear;
+uniform float uFar;
+varying float vDepth;
+void main() {
+ // Inverse depth between near and far: near = white, far = black (Depth Anything's convention, which VACE was trained on).
+ float d = max(vDepth, uNear);
+ float v = (1.0 / d - 1.0 / uFar) / (1.0 / uNear - 1.0 / uFar);
+ gl_FragColor = vec4(vec3(clamp(v, 0.0, 1.0)), 1.0);
+}`;
+
+/** A box `size` standing on y = 0 (its bottom centre at the origin). */
+function standing(w: number, h: number, d: number): THREE.BufferGeometry {
+ return new THREE.BoxGeometry(Math.max(0.01, w), Math.max(0.01, h), Math.max(0.01, d)).translate(0, h / 2, 0);
+}
+
+function meshOf(geo: THREE.BufferGeometry, mat: THREE.Material): THREE.Mesh {
+ const m = new THREE.Mesh(geo, mat);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ return m;
+}
+
+interface Figure {
+ root: THREE.Group;
+ arms: [THREE.Object3D, THREE.Object3D];
+ legs: [THREE.Object3D, THREE.Object3D];
+}
+
+/** A plain mannequin 1.75 m tall facing −Z (towards the default camera when turned 180°): torso, head, arms and legs on pivots. */
+function mannequin(mat: THREE.Material): Figure {
+ const root = new THREE.Group();
+ const capsule = (r: number, len: number) => new THREE.CapsuleGeometry(r, len, 4, 10);
+ const torso = meshOf(capsule(0.17, 0.42), mat);
+ torso.position.y = 1.18;
+ const head = meshOf(new THREE.SphereGeometry(0.12, 16, 12), mat);
+ head.position.y = 1.62;
+ root.add(torso, head);
+ const limb = (x: number, y: number, r: number, len: number): THREE.Object3D => {
+ const pivot = new THREE.Group();
+ pivot.position.set(x, y, 0);
+ const m = meshOf(capsule(r, len), mat);
+ m.position.y = -(len / 2 + r);
+ pivot.add(m);
+ root.add(pivot);
+ return pivot;
+ };
+ const arms: [THREE.Object3D, THREE.Object3D] = [limb(-0.24, 1.42, 0.055, 0.52), limb(0.24, 1.42, 0.055, 0.52)];
+ const legs: [THREE.Object3D, THREE.Object3D] = [limb(-0.1, 0.86, 0.075, 0.68), limb(0.1, 0.86, 0.075, 0.68)];
+ return { root, arms, legs };
+}
+
+/** The object a primitive draws as (its pose is set per frame). */
+function build(p: BlockoutPrim, mat: THREE.Material, figureMat: THREE.Material, loader: GLTFLoader, dirty: () => void): { obj: THREE.Object3D; figure?: Figure } {
+ const [w, h, d] = p.size;
+ const group = new THREE.Group();
+ switch (p.kind) {
+ case "doorway": {
+ const gw = Math.min(DOOR_GAP.width, w - 0.1);
+ const gh = Math.min(DOOR_GAP.height, h - 0.1);
+ const side = (w - gw) / 2;
+ const left = meshOf(standing(side, h, d), mat);
+ left.position.x = -(gw / 2 + side / 2);
+ const right = meshOf(standing(side, h, d), mat);
+ right.position.x = gw / 2 + side / 2;
+ const top = meshOf(standing(gw, h - gh, d), mat);
+ top.position.y = gh;
+ group.add(left, right, top);
+ break;
+ }
+ case "stairs": {
+ for (let i = 0; i < STAIR_STEPS; i++) {
+ const step = meshOf(standing(w, (h * (i + 1)) / STAIR_STEPS, d / STAIR_STEPS), mat);
+ step.position.z = d / 2 - ((i + 0.5) * d) / STAIR_STEPS;
+ group.add(step);
+ }
+ break;
+ }
+ case "door": {
+ // Hinged on its left edge: the group's origin is the hinge.
+ const door = meshOf(standing(w, h, d).translate(w / 2, 0, 0), mat);
+ group.add(door);
+ break;
+ }
+ case "mannequin": {
+ const f = mannequin(figureMat);
+ f.root.scale.setScalar(h / 1.75);
+ group.add(f.root);
+ return { obj: group, figure: f };
+ }
+ case "mesh": {
+ const holder = meshOf(standing(w, h, d), new THREE.MeshBasicMaterial({ color: GREY, wireframe: true }));
+ group.add(holder);
+ if (p.url) {
+ loader.load(
+ p.url,
+ (gltf) => {
+ const model = gltf.scene;
+ model.traverse((o) => {
+ const m = o as THREE.Mesh;
+ if (m.isMesh) {
+ m.material = mat;
+ m.castShadow = true;
+ m.receiveShadow = true;
+ }
+ });
+ // Fit the model in the primitive's box, standing on its floor.
+ const box = new THREE.Box3().setFromObject(model);
+ const size = box.getSize(new THREE.Vector3());
+ const k = Math.min(w / (size.x || 1), h / (size.y || 1), d / (size.z || 1));
+ model.scale.setScalar(k);
+ const fit = new THREE.Box3().setFromObject(model);
+ const c = fit.getCenter(new THREE.Vector3());
+ model.position.set(-c.x, -fit.min.y, -c.z);
+ group.remove(holder);
+ holder.geometry.dispose();
+ group.add(model);
+ dirty();
+ },
+ undefined,
+ () => {},
+ );
+ }
+ break;
+ }
+ default:
+ group.add(meshOf(standing(w, h, d), mat));
+ }
+ return { obj: group };
+}
+
+export class BlockoutEngine {
+ readonly renderer: THREE.WebGLRenderer;
+ private readonly scene3 = new THREE.Scene();
+ private readonly props = new THREE.Group();
+ private readonly helpers = new THREE.Group();
+ private readonly view: THREE.PerspectiveCamera;
+ private readonly shot: THREE.PerspectiveCamera;
+ private readonly orbit: OrbitControls;
+ private readonly gizmo: TransformControls;
+ private readonly mat = new THREE.MeshStandardMaterial({ color: GREY, roughness: 0.95, metalness: 0 });
+ private readonly figureMat = new THREE.MeshStandardMaterial({ color: FIGURE, roughness: 0.9, metalness: 0 });
+ private readonly depthMat = new THREE.ShaderMaterial({ vertexShader: depthVertex, fragmentShader: depthFragment, uniforms: { uNear: { value: 0.3 }, uFar: { value: 40 } } });
+ private readonly loader = new GLTFLoader();
+ private readonly objects = new Map<string, { obj: THREE.Object3D; figure?: Figure; prim: BlockoutPrim }>();
+ private readonly path: THREE.Line;
+ private readonly frustum = new THREE.Group();
+ private outline: THREE.BoxHelper | null = null;
+ private data: BlockoutScene | null = null;
+ private time = 0;
+ private mode: ViewMode = "edit";
+ private selected: string | null = null;
+ private raf = 0;
+ private dirty = true;
+ private disposed = false;
+ private rendering = false;
+ private size = { w: 1, h: 1 };
+ private down: { x: number; y: number } | null = null;
+
+ constructor(
+ private readonly canvas: HTMLCanvasElement,
+ private readonly events: EngineEvents = {},
+ ) {
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: false });
+ this.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
+ this.renderer.shadowMap.enabled = true;
+ this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ this.scene3.background = new THREE.Color(BACKGROUND);
+ const hemi = new THREE.HemisphereLight(0xffffff, 0x555555, 1.6);
+ const sun = new THREE.DirectionalLight(0xffffff, 1.8);
+ sun.position.set(4, 9, 6);
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(1024, 1024);
+ Object.assign(sun.shadow.camera, { left: -15, right: 15, top: 15, bottom: -15, near: 0.5, far: 40 });
+ this.scene3.add(hemi, sun, this.props, this.helpers);
+ const grid = new THREE.GridHelper(40, 40, 0x6b6b6b, 0x535353);
+ grid.position.y = 0.001;
+ this.helpers.add(grid);
+ this.path = new THREE.Line(new THREE.BufferGeometry(), new THREE.LineBasicMaterial({ color: 0xffc04d }));
+ this.helpers.add(this.path, this.frustum);
+ this.view = new THREE.PerspectiveCamera(50, 1, 0.05, 400);
+ this.view.position.set(6, 5, 8);
+ this.shot = new THREE.PerspectiveCamera(40, 16 / 9, 0.05, 400);
+ this.orbit = new OrbitControls(this.view, canvas);
+ this.orbit.target.set(0, 1, -4);
+ this.orbit.enableDamping = false;
+ this.orbit.addEventListener("change", () => (this.dirty = true));
+ this.gizmo = new TransformControls(this.view, canvas);
+ this.gizmo.setSize(0.8);
+ this.gizmo.addEventListener("dragging-changed", (e) => {
+ this.orbit.enabled = !(e as unknown as { value: boolean }).value;
+ if (!(e as unknown as { value: boolean }).value) this.reportMove();
+ });
+ this.gizmo.addEventListener("change", () => {
+ this.outline?.update();
+ this.dirty = true;
+ });
+ this.helpers.add(this.gizmo.getHelper());
+ canvas.addEventListener("pointerdown", this.onDown);
+ canvas.addEventListener("pointerup", this.onUp);
+ this.loop();
+ }
+
+ private readonly onDown = (e: PointerEvent) => {
+ this.down = { x: e.clientX, y: e.clientY };
+ };
+
+ /** A click (not a drag) picks the primitive under it in the edit view, or clears the pick. */
+ private readonly onUp = (e: PointerEvent) => {
+ const d = this.down;
+ this.down = null;
+ if (!d || this.mode !== "edit" || this.gizmo.dragging || Math.hypot(e.clientX - d.x, e.clientY - d.y) > 5) return;
+ const r = this.canvas.getBoundingClientRect();
+ const ray = new THREE.Raycaster();
+ ray.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), this.view);
+ const hit = ray.intersectObjects(this.props.children, true)[0];
+ let o: THREE.Object3D | null = hit?.object ?? null;
+ while (o && !o.userData.primId) o = o.parent;
+ const id = (o?.userData.primId as string | undefined) ?? null;
+ this.select(id);
+ this.events.onSelect?.(id);
+ };
+
+ private reportMove() {
+ const id = this.selected;
+ const entry = id ? this.objects.get(id) : undefined;
+ if (!id || !entry) return;
+ const p = entry.obj.position;
+ this.events.onMove?.(id, [round(p.x), round(p.y), round(p.z)], round(entry.obj.rotation.y / DEG));
+ }
+
+ private loop = () => {
+ if (this.disposed) return;
+ this.raf = requestAnimationFrame(this.loop);
+ if (!this.dirty || this.rendering) return;
+ this.dirty = false;
+ this.draw();
+ };
+
+ /** The whole scene, rebuilt where a primitive changed (same id and same shape: only its pose moves). */
+ setScene(s: BlockoutScene) {
+ const prev = this.data;
+ this.data = s;
+ const keep = new Set(s.prims.map((p) => p.id));
+ for (const [id, e] of this.objects) {
+ if (!keep.has(id)) {
+ this.props.remove(e.obj);
+ dispose(e.obj, [this.mat, this.figureMat]);
+ this.objects.delete(id);
+ }
+ }
+ for (const p of s.prims) {
+ const had = this.objects.get(p.id);
+ if (had && sameShape(had.prim, p)) {
+ had.prim = p;
+ continue;
+ }
+ if (had) {
+ this.props.remove(had.obj);
+ dispose(had.obj, [this.mat, this.figureMat]);
+ }
+ const made = build(p, this.mat, this.figureMat, this.loader, () => (this.dirty = true));
+ made.obj.userData.primId = p.id;
+ this.props.add(made.obj);
+ this.objects.set(p.id, { ...made, prim: p });
+ }
+ if (this.selected && !keep.has(this.selected)) this.select(null);
+ if (!prev || prev.camera !== s.camera || prev.duration !== s.duration) this.drawPath();
+ this.pose(this.time);
+ if (this.selected) this.attach(this.selected);
+ this.dirty = true;
+ }
+
+ /** The camera's path over the length (a line), and a small frustum where the shot camera is now. */
+ private drawPath() {
+ const s = this.data;
+ if (!s) return;
+ const pts: THREE.Vector3[] = [];
+ for (let i = 0; i <= 60; i++) {
+ const c = cameraAt(s.camera, (i / 60) * s.duration);
+ pts.push(new THREE.Vector3(...c.position));
+ }
+ this.path.geometry.dispose();
+ this.path.geometry = new THREE.BufferGeometry().setFromPoints(pts);
+ }
+
+ private placeFrustum(position: Vec3, target: Vec3) {
+ this.frustum.clear();
+ const cone = new THREE.Mesh(new THREE.ConeGeometry(0.18, 0.3, 4, 1, true), new THREE.MeshBasicMaterial({ color: 0xffc04d, wireframe: true }));
+ cone.rotation.x = -Math.PI / 2;
+ cone.rotation.y = Math.PI / 4;
+ const g = new THREE.Group();
+ g.add(cone);
+ g.position.set(...position);
+ g.lookAt(new THREE.Vector3(...target));
+ this.frustum.add(g);
+ }
+
+ /** Every primitive and the shot camera at time t. */
+ private pose(t: number) {
+ const s = this.data;
+ if (!s) return;
+ for (const { obj, figure, prim } of this.objects.values()) {
+ // The picked primitive stays where the gizmo holds it while it is dragged.
+ if (this.gizmo.dragging && prim.id === this.selected) continue;
+ const at = primAt(prim, t);
+ obj.position.set(...at.position);
+ obj.rotation.set(0, at.rotation * DEG, 0);
+ if (figure) {
+ const speed = primSpeed(prim, t);
+ const k = Math.min(1, speed / 1.4) * 0.55;
+ const swing = Math.sin(2 * Math.PI * 1.7 * t) * k;
+ figure.legs[0].rotation.x = swing;
+ figure.legs[1].rotation.x = -swing;
+ figure.arms[0].rotation.x = -swing * 0.8;
+ figure.arms[1].rotation.x = swing * 0.8;
+ }
+ }
+ const c = cameraAt(s.camera, t);
+ this.shot.position.set(...c.position);
+ this.shot.fov = lensVFov(c.lens, aspectOf(s.aspect));
+ this.shot.lookAt(new THREE.Vector3(...c.target));
+ this.shot.updateProjectionMatrix();
+ this.placeFrustum(c.position, c.target);
+ this.outline?.update();
+ }
+
+ setTime(t: number) {
+ this.time = t;
+ this.pose(t);
+ this.dirty = true;
+ }
+
+ setMode(m: ViewMode) {
+ this.mode = m;
+ this.gizmo.enabled = m === "edit";
+ this.gizmo.getHelper().visible = m === "edit" && !!this.selected;
+ this.dirty = true;
+ }
+
+ /** "move" or "rotate" (about the vertical only). */
+ setGizmo(kind: "translate" | "rotate") {
+ this.gizmo.setMode(kind);
+ this.gizmo.showX = kind === "translate";
+ this.gizmo.showZ = kind === "translate";
+ this.gizmo.showY = true;
+ this.dirty = true;
+ }
+
+ select(id: string | null) {
+ this.selected = id;
+ if (this.outline) {
+ this.helpers.remove(this.outline);
+ this.outline.dispose();
+ this.outline = null;
+ }
+ this.gizmo.detach();
+ if (id) this.attach(id);
+ this.dirty = true;
+ }
+
+ private attach(id: string) {
+ const e = this.objects.get(id);
+ if (!e) return;
+ this.gizmo.attach(e.obj);
+ this.gizmo.getHelper().visible = this.mode === "edit";
+ if (!this.outline) {
+ this.outline = new THREE.BoxHelper(e.obj, 0x6aa8ff);
+ this.helpers.add(this.outline);
+ } else this.outline.setFromObject(e.obj);
+ }
+
+ /** Where the edit view is now, as a camera key (what "Set camera here" keeps). */
+ viewPose(): { position: Vec3; target: Vec3 } {
+ const p = this.view.position;
+ const t = this.orbit.target;
+ return { position: [round(p.x), round(p.y), round(p.z)], target: [round(t.x), round(t.y), round(t.z)] };
+ }
+
+ /** Put the edit view where the shot camera is at time t (to adjust a key from there). */
+ viewFromShot(t: number) {
+ if (!this.data) return;
+ const c = cameraAt(this.data.camera.map((k) => ({ ...k, shake: 0 })), t);
+ this.view.position.set(...c.position);
+ this.orbit.target.set(...c.target);
+ this.orbit.update();
+ this.dirty = true;
+ }
+
+ resize(w: number, h: number) {
+ this.size = { w: Math.max(1, w), h: Math.max(1, h) };
+ this.renderer.setSize(this.size.w, this.size.h, false);
+ this.view.aspect = this.size.w / this.size.h;
+ this.view.updateProjectionMatrix();
+ this.dirty = true;
+ }
+
+ /** The frame the shot camera sees, inside the canvas (letterboxed to the blockout's shape). */
+ frameRect(): { x: number; y: number; w: number; h: number } {
+ const a = aspectOf(this.data?.aspect ?? "16:9");
+ const { w, h } = this.size;
+ const fw = Math.min(w, h * a);
+ const fh = fw / a;
+ return { x: (w - fw) / 2, y: (h - fh) / 2, w: fw, h: fh };
+ }
+
+ private draw() {
+ const r = this.renderer;
+ r.setScissorTest(false);
+ r.setViewport(0, 0, this.size.w, this.size.h);
+ if (this.mode === "edit") {
+ this.helpers.visible = true;
+ r.render(this.scene3, this.view);
+ return;
+ }
+ // The shot camera, letterboxed.
+ this.helpers.visible = false;
+ r.setClearColor(0x000000, 1);
+ r.clear();
+ const f = this.frameRect();
+ r.setScissorTest(true);
+ r.setScissor(f.x, f.y, f.w, f.h);
+ r.setViewport(f.x, f.y, f.w, f.h);
+ this.shot.aspect = f.w / f.h;
+ this.shot.updateProjectionMatrix();
+ r.render(this.scene3, this.shot);
+ r.setScissorTest(false);
+ }
+
+ /** The nearest and furthest the shot camera sees anything over the whole blockout (the depth video's fixed range). */
+ private depthRange(): { near: number; far: number } {
+ const s = this.data!;
+ const box = new THREE.Box3().setFromObject(this.props);
+ const corners: THREE.Vector3[] = [];
+ for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) corners.push(new THREE.Vector3(x, y, z));
+ let far = 1;
+ for (let i = 0; i <= 24; i++) {
+ const c = new THREE.Vector3(...cameraAt(s.camera, (i / 24) * s.duration).position);
+ for (const k of corners) far = Math.max(far, c.distanceTo(k));
+ }
+ return { near: 0.3, far: Math.min(200, far) };
+ }
+
+ /**
+ * Render the blockout through the shot camera at `fps`, `width` × `height`: the grey box ("grey") or its depth ("depth",
+ * near = bright), every frame, into a video (MP4 where the browser can, for the cloud; WebM otherwise). Also returns
+ * frame 0 as a PNG for the grey box (the open engine's first frame is drawn from it).
+ */
+ async render(o: { kind: "grey" | "depth"; fps: number; width: number; height: number; preferMp4?: boolean; onProgress?: (p: number) => void; signal?: AbortSignal }): Promise<{ video: Blob; type: string; first?: Blob; frames: number }> {
+ const s = this.data;
+ if (!s) throw new Error("Nothing to render yet");
+ const { width, height, fps } = o;
+ const frames = Math.max(1, Math.floor(s.duration * fps + 1e-6));
+ const target = new THREE.WebGLRenderTarget(width, height, { samples: 4 });
+ const buf = new Uint8Array(width * height * 4);
+ const img = new ImageData(width, height);
+ const cam = new THREE.PerspectiveCamera(40, width / height, 0.05, 400);
+ const depth = o.kind === "depth";
+ const range = depth ? this.depthRange() : null;
+ if (range) {
+ this.depthMat.uniforms.uNear.value = range.near;
+ this.depthMat.uniforms.uFar.value = range.far;
+ }
+ let first: Blob | undefined;
+ const r = this.renderer;
+ this.rendering = true;
+ this.helpers.visible = false;
+ const bg = this.scene3.background;
+ if (depth) {
+ this.scene3.overrideMaterial = this.depthMat;
+ this.scene3.background = new THREE.Color(0x000000);
+ }
+ const draw = (i: number) => {
+ if (o.signal?.aborted || this.disposed) throw new DOMException("Stopped", "AbortError");
+ const t = i / fps;
+ this.pose(t);
+ const c = cameraAt(s.camera, t);
+ cam.position.set(...c.position);
+ cam.fov = lensVFov(c.lens, width / height);
+ cam.lookAt(new THREE.Vector3(...c.target));
+ cam.updateProjectionMatrix();
+ r.setRenderTarget(target);
+ r.setScissorTest(false);
+ r.setViewport(0, 0, width, height);
+ r.render(this.scene3, cam);
+ r.readRenderTargetPixels(target, 0, 0, width, height, buf);
+ for (let y = 0; y < height; y++) img.data.set(buf.subarray((height - 1 - y) * width * 4, (height - y) * width * 4), y * width * 4);
+ o.onProgress?.((i + 1) / frames);
+ return img;
+ };
+ try {
+ if (!depth) first = await pngOf(draw(0));
+ const out = await encodeFrames(frames, width, height, fps, draw, !!o.preferMp4);
+ return { video: out.blob, type: out.type, first, frames };
+ } finally {
+ this.scene3.overrideMaterial = null;
+ this.scene3.background = bg;
+ r.setRenderTarget(null);
+ target.dispose();
+ this.rendering = false;
+ this.helpers.visible = true;
+ this.pose(this.time);
+ this.dirty = true;
+ }
+ }
+
+ dispose() {
+ this.disposed = true;
+ cancelAnimationFrame(this.raf);
+ this.canvas.removeEventListener("pointerdown", this.onDown);
+ this.canvas.removeEventListener("pointerup", this.onUp);
+ this.gizmo.detach();
+ this.gizmo.dispose();
+ this.orbit.dispose();
+ for (const e of this.objects.values()) dispose(e.obj, []);
+ this.mat.dispose();
+ this.figureMat.dispose();
+ this.depthMat.dispose();
+ this.path.geometry.dispose();
+ this.renderer.dispose();
+ this.renderer.forceContextLoss();
+ }
+}
+
+const round = (n: number) => Math.round(n * 1000) / 1000 + 0;
+
+function sameShape(a: BlockoutPrim, b: BlockoutPrim): boolean {
+ return a.kind === b.kind && a.url === b.url && a.size.every((n, i) => n === b.size[i]);
+}
+
+/** Free an object's geometry (and materials other than the shared ones). */
+function dispose(o: THREE.Object3D, shared: THREE.Material[]) {
+ o.traverse((x) => {
+ const m = x as THREE.Mesh;
+ m.geometry?.dispose();
+ for (const mat of (Array.isArray(m.material) ? m.material : m.material ? [m.material] : []) as THREE.Material[]) if (!shared.includes(mat)) mat.dispose();
+ });
+}
+
+async function pngOf(img: ImageData): Promise<Blob> {
+ const c = document.createElement("canvas");
+ c.width = img.width;
+ c.height = img.height;
+ c.getContext("2d")!.putImageData(img, 0, 0);
+ return new Promise((resolve, reject) => c.toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't save the first frame"))), "image/png"));
+}
diff --git a/src/components/cinema/blockout-panel.tsx b/src/components/cinema/blockout-panel.tsx
new file mode 100644
index 00000000..354123d1
--- /dev/null
+++ b/src/components/cinema/blockout-panel.tsx
@@ -0,0 +1,552 @@
+"use client";
+
+import { Box, Clapperboard, Layers, Loader2, Plus, RotateCcw, Trash2, Upload, Volume2, VolumeX } from "lucide-react";
+import { nanoid } from "nanoid";
+import Link from "next/link";
+import { useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Textarea } from "@/components/ui/textarea";
+import { uploadFile, useAssets, useElements, useStatus } from "@/lib/api";
+import { BLOCKOUT, EXAMPLE_SCENE, EXAMPLE_WORDS, REF_ROLES, beatsFrom, roleFor, type BlockoutRef, type BlockoutScene, type RefRole } from "@/lib/blockout";
+import { BLOCKOUT_MODELS, BLOCKOUT_SHOTS, blockoutPrompt, planCinema, type CinemaGenerateInput, type DirectorSettings } from "@/lib/catalog/cinema";
+import { getModel } from "@/lib/catalog";
+import type { Engine } from "@/lib/catalog/types";
+import { placeholdersOn } from "@/lib/demo-mode";
+import { formatCost } from "@/lib/format";
+import { toastError } from "@/lib/refusals";
+import { cn } from "@/lib/utils";
+import type { BuiltBlockout } from "./blockout-builder";
+import { useCinemaGenerate } from "./hooks";
+import { mediaDuration } from "./media";
+
+/**
+ * Blockout to film in Cinema's take composer (package blockout-film): the blockout (an uploaded grey-box render from any
+ * 3D app, the builder's render, or the 3D scene's fly path), its beats with words, the reference stills with a role each,
+ * the style, sounds and "No" list, the prompt compiled from them (editable), what each engine does, the price, Render.
+ */
+
+export interface BlockoutSource {
+ video: string;
+ depth?: string;
+ firstFrame?: string;
+ seconds: number;
+ aspect?: string;
+ from: "upload" | "build" | "scene";
+ name?: string;
+}
+
+export interface BlockoutBeat {
+ id: string;
+ start: number;
+ label: string;
+ words: string;
+}
+
+export interface BlockoutRefItem extends BlockoutRef {
+ id: string;
+ uploading?: boolean;
+}
+
+export interface BlockoutDraft {
+ source: BlockoutSource | null;
+ /** The builder's scene (to open it again where it was left). */
+ scene: BlockoutScene | null;
+ beats: BlockoutBeat[];
+ refs: BlockoutRefItem[];
+ style: string;
+ sounds: string;
+ avoid: string;
+ constraints: string;
+ modelId: string;
+ resolution?: string;
+ audio: boolean;
+ /** The prompt as the user edited it (null: compiled). */
+ prompt: string | null;
+}
+
+export const initialBlockout = (): BlockoutDraft => ({
+ source: null,
+ scene: null,
+ beats: [],
+ refs: [],
+ style: "",
+ sounds: "",
+ avoid: "",
+ constraints: "",
+ modelId: BLOCKOUT_MODELS.cloud[0],
+ audio: true,
+ prompt: null,
+});
+
+/** The draft's beats after a build: one per marker, keeping the words already written for a marker that stayed. */
+export function beatsForScene(scene: BlockoutScene, old: BlockoutBeat[]): BlockoutBeat[] {
+ const words = Object.fromEntries(old.map((b) => [b.id, b.words]));
+ const example = scene.markers.every((m) => EXAMPLE_SCENE.markers.some((x) => x.id === m.id));
+ return beatsFrom(scene.markers, scene.duration, { ...(example ? EXAMPLE_WORDS : {}), ...Object.fromEntries(Object.entries(words).filter(([, w]) => w)) }).map((b) => ({ id: b.id, start: b.start, label: b.label, words: b.words }));
+}
+
+const list = (s: string) =>
+ s
+ .split(/[,;\n]/)
+ .map((x) => x.trim())
+ .filter(Boolean);
+
+/** The request body the composer sends (and planCinema prices live). */
+export function blockoutInput(d: BlockoutDraft, engine: Engine, settings: DirectorSettings): Omit<CinemaGenerateInput, "brief"> {
+ const s = d.source;
+ return {
+ engine,
+ mode: "video",
+ action: "blockout",
+ modelId: engine === "cloud" ? d.modelId : undefined,
+ prompt: engine === "cloud" && d.prompt !== null ? d.prompt : "",
+ settings,
+ resolution: d.resolution,
+ aspectRatio: s?.aspect,
+ audio: d.audio,
+ blockout: {
+ video: s?.video ?? "",
+ ...(s?.depth ? { depth: s.depth } : {}),
+ ...(s?.firstFrame ? { firstFrame: s.firstFrame } : {}),
+ seconds: s?.seconds ?? 0,
+ beats: d.beats.map((b) => ({ id: b.id, start: b.start, label: b.label.trim() || "Beat", words: b.words })),
+ refs: d.refs.filter((r) => r.url && !r.uploading).map((r) => ({ url: r.url, role: r.role, ...(r.name?.trim() ? { name: r.name.trim() } : {}) })),
+ ...(d.style.trim() ? { style: d.style.trim() } : {}),
+ ...(d.constraints.trim() ? { constraints: d.constraints.trim() } : {}),
+ ...(list(d.sounds).length ? { sounds: list(d.sounds) } : {}),
+ ...(list(d.avoid).length ? { avoid: list(d.avoid) } : {}),
+ },
+ };
+}
+
+const MODEL_LINES: Record<string, string> = {
+ "seedance-2-5": "Follows the blockout as its reference video, with sound · up to 30 s a shot",
+ "minimax-h3-max-3d": "MiniMax's own blockout model: up to 8 stills, no sound · up to 15 s a shot",
+};
+
+const fmt = (n: number) => `${Math.round(n * 10) / 10} s`;
+const section = "space-y-2.5 border-t pt-4 first:border-t-0 first:pt-0";
+const h3 = "text-[12px] font-medium tracking-wide text-muted-foreground uppercase";
+
+export interface BlockoutPanelProps {
+ open: boolean;
+ onOpenChange: (o: boolean) => void;
+ projectId: string;
+ folderId: string | null;
+ engine: Engine;
+ settings: DirectorSettings;
+ brief: string;
+ context: { cloudAllowed: boolean; civitai?: boolean };
+ draft: BlockoutDraft;
+ setDraft: (fn: (d: BlockoutDraft) => BlockoutDraft) => void;
+ /** Open the builder (with the draft's scene, or the example). */
+ onBuild: (scene: BlockoutScene) => void;
+}
+
+export function BlockoutPanel(props: BlockoutPanelProps) {
+ const { open, onOpenChange, projectId, folderId, engine, settings, brief, context, draft, setDraft, onBuild } = props;
+ const generate = useCinemaGenerate(projectId);
+ const status = useStatus().data;
+ const demo = placeholdersOn(status?.demoMode);
+ const [uploading, setUploading] = useState<"video" | "depth" | null>(null);
+ const videoInput = useRef<HTMLInputElement>(null);
+ const depthInput = useRef<HTMLInputElement>(null);
+ const refInput = useRef<HTMLInputElement>(null);
+ const [refsOpen, setRefsOpen] = useState(false);
+ const elements = useElements();
+ const images = useAssets(undefined, "image");
+
+ const input = useMemo(() => blockoutInput(draft, engine, settings), [draft, engine, settings]);
+ const plan = useMemo(() => planCinema({ ...input, brief }, context), [input, brief, context]);
+ const compiled = useMemo(() => blockoutPrompt(input), [input]);
+ const s = draft.source;
+ const built = s?.from === "build";
+ const seconds = s?.seconds ?? 0;
+ const set = (patch: Partial<BlockoutDraft>) => setDraft((d) => ({ ...d, ...patch }));
+ const cost = plan.costUsd;
+ const price = demo ? "Placeholder · free" : cost === 0 ? "Free" : cost != null ? `≈ ${formatCost(cost)}` : "Price unknown";
+ const model = getModel(engine === "cloud" ? draft.modelId : BLOCKOUT_MODELS.open);
+ const resolutions = engine === "cloud" ? (getModel(draft.modelId)?.options.resolutions ?? []) : ["480p", "720p"];
+ const resolution = draft.resolution && resolutions.some((r) => r.toLowerCase() === draft.resolution!.toLowerCase()) ? draft.resolution : (engine === "cloud" ? getModel(draft.modelId)?.defaults?.resolution : "480p");
+ const seedance = engine === "cloud" && BLOCKOUT_SHOTS[draft.modelId]?.tag === "seedance";
+
+ const uploadVideo = async (f: File, kind: "video" | "depth") => {
+ if (f.size > 200 * 1024 * 1024) return toast.error("That file's over 200 MB. Try a smaller one.");
+ setUploading(kind);
+ try {
+ const preview = URL.createObjectURL(f);
+ const [asset, length] = await Promise.all([uploadFile(f), mediaDuration(preview, "video").catch(() => NaN)]);
+ URL.revokeObjectURL(preview);
+ if (kind === "depth") return set({ source: draft.source ? { ...draft.source, depth: asset.url } : null });
+ const secs = Number.isFinite(length) && length > 0 ? Math.round(length * 100) / 100 : 8;
+ if (secs > BLOCKOUT.maxSeconds) toast(`Blockouts run up to ${BLOCKOUT.maxSeconds} s: this one is ${fmt(secs)}, so its first ${BLOCKOUT.maxSeconds} s are used`);
+ setDraft((d) => ({
+ ...d,
+ source: { video: asset.url, seconds: Math.min(BLOCKOUT.maxSeconds, secs), from: "upload", name: f.name },
+ beats: d.beats.length ? d.beats.filter((b) => b.start < secs) : [{ id: nanoid(6), start: 0, label: "Opening", words: "" }],
+ prompt: null,
+ }));
+ } catch (e) {
+ toastError(e, "Upload failed. Please try again.");
+ } finally {
+ setUploading(null);
+ }
+ };
+
+ const addRef = (r: Omit<BlockoutRefItem, "id">) => {
+ if (draft.refs.length >= BLOCKOUT.maxRefs) return toast.error(`Up to ${BLOCKOUT.maxRefs} references`);
+ setDraft((d) => ({ ...d, refs: [...d.refs, { ...r, id: nanoid(6) }], prompt: null }));
+ setRefsOpen(false);
+ };
+ const uploadRef = (f: File) => {
+ const id = nanoid(6);
+ setDraft((d) => ({ ...d, refs: [...d.refs, { id, url: "", role: d.refs.some((r) => r.role === "character") ? "location" : "character", uploading: true }] }));
+ setRefsOpen(false);
+ uploadFile(f)
+ .then((a) => setDraft((d) => ({ ...d, refs: d.refs.map((r) => (r.id === id ? { ...r, url: a.url, uploading: false } : r)) })))
+ .catch((e) => {
+ setDraft((d) => ({ ...d, refs: d.refs.filter((r) => r.id !== id) }));
+ toastError(e, "Upload failed. Please try again.");
+ });
+ };
+
+ const run = async () => {
+ if (plan.blocker) return toast.error(plan.blocker);
+ try {
+ await generate.mutateAsync({ input: input as CinemaGenerateInput, folderId });
+ onOpenChange(false);
+ const silent = engine === "open" || !seedance || !draft.audio;
+ toast.success(engine === "open" ? "Filming the blockout on your GPU — it lands in this scene as a new take" : "Filming the blockout — it lands in this scene as a new take", {
+ duration: 8000,
+ ...(silent ? { description: "It comes without sound: add it afterwards with Sound for video.", action: { label: "Sound for video", onClick: () => window.open("/audio/video", "_self") } } : {}),
+ });
+ } catch (e) {
+ toastError(e, "Couldn't film the blockout");
+ }
+ };
+
+ const span = (i: number) => {
+ const end = i + 1 < draft.beats.length ? draft.beats[i + 1].start : seconds;
+ return `${fmt(draft.beats[i].start)}–${fmt(Math.max(draft.beats[i].start, end))}`;
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex max-h-[100svh] w-full max-w-[calc(100%-1rem)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[92svh] sm:max-w-2xl">
+ <DialogHeader className="border-b px-4 pt-4 pb-3 text-left sm:px-5">
+ <DialogTitle className="flex items-center gap-2 text-[16px]">
+ <Box className="size-4" /> Blockout to film
+ </DialogTitle>
+ <DialogDescription className="text-[12.5px]">A grey-box blockout sets the camera, blocking and timing. Your stills and beats say what it becomes.</DialogDescription>
+ </DialogHeader>
+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 py-4 sm:px-5">
+ <section className={section} aria-label="Blockout">
+ <h3 className={h3}>Blockout</h3>
+ {!s ? (
+ <div className="grid gap-2 sm:grid-cols-2">
+ <button type="button" onClick={() => onBuild(draft.scene ?? structuredClone(EXAMPLE_SCENE))} className="flex items-start gap-3 rounded-xl border p-3 text-left hover:border-primary hover:bg-brand-faint">
+ <Layers className="mt-0.5 size-5 shrink-0 text-brand-text" />
+ <span>
+ <span className="block text-[14px] font-medium">Build it here</span>
+ <span className="block text-[12.5px] text-muted-foreground">Boxes, a mannequin and a camera in your browser. Starts from a corridor-and-door example.</span>
+ </span>
+ </button>
+ <button type="button" onClick={() => videoInput.current?.click()} disabled={!!uploading} className="flex items-start gap-3 rounded-xl border p-3 text-left hover:border-primary hover:bg-brand-faint">
+ {uploading === "video" ? <Loader2 className="mt-0.5 size-5 shrink-0 animate-spin" /> : <Upload className="mt-0.5 size-5 shrink-0 text-brand-text" />}
+ <span>
+ <span className="block text-[14px] font-medium">Upload a render</span>
+ <span className="block text-[12.5px] text-muted-foreground">A grey-box video from Blender, Unreal, Cinema 4D… MP4 or MOV, up to {BLOCKOUT.maxSeconds} s.</span>
+ </span>
+ </button>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3 sm:flex-row">
+ <video src={s.video} controls muted playsInline className="aspect-video w-full rounded-lg bg-black sm:w-56" aria-label="The blockout" />
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <p className="text-[14px] font-medium">
+ {built ? "Built in your browser" : s.from === "scene" ? "From the 3D scene's fly path" : (s.name ?? "Uploaded render")}
+ </p>
+ <p className="text-[12.5px] text-muted-foreground">
+ {fmt(seconds)}
+ {s.aspect ? ` · ${s.aspect}` : ""}
+ {s.depth ? " · with its depth" : engine === "open" ? " · no depth pass: Depth Anything 3 reads it on your GPU" : ""}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ {built && (
+ <Button size="sm" variant="secondary" onClick={() => onBuild(draft.scene ?? structuredClone(EXAMPLE_SCENE))}>
+ <Layers className="size-3.5" /> Edit the blockout
+ </Button>
+ )}
+ {!built && (
+ <Button size="sm" variant="secondary" onClick={() => depthInput.current?.click()} disabled={!!uploading}>
+ {uploading === "depth" ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />} {s.depth ? "Replace depth pass" : "Add a depth pass"}
+ </Button>
+ )}
+ <Button size="sm" variant="ghost" onClick={() => set({ source: null, prompt: null })}>
+ <RotateCcw className="size-3.5" /> Start over
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ <input ref={videoInput} type="file" accept="video/mp4,video/quicktime,video/webm" hidden onChange={(e) => (e.target.files?.[0] && void uploadVideo(e.target.files[0], "video"), (e.target.value = ""))} />
+ <input ref={depthInput} type="file" accept="video/mp4,video/quicktime,video/webm" hidden onChange={(e) => (e.target.files?.[0] && void uploadVideo(e.target.files[0], "depth"), (e.target.value = ""))} />
+ </section>
+
+ <section className={section} aria-label="Beats">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className={h3}>Beats</h3>
+ {!built && s && (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={draft.beats.length >= BLOCKOUT.maxMarkers}
+ onClick={() => setDraft((d) => ({ ...d, beats: [...d.beats, { id: nanoid(6), start: Math.min(seconds - 0.5, (d.beats.at(-1)?.start ?? 0) + 2), label: `Beat ${d.beats.length + 1}`, words: "" }], prompt: null }))}
+ >
+ <Plus className="size-3.5" /> Beat
+ </Button>
+ )}
+ </div>
+ {seconds > 0 && draft.beats.length > 0 && (
+ <div className="flex h-2 overflow-hidden rounded-full bg-muted" aria-hidden>
+ {draft.beats.map((b, i) => {
+ const end = i + 1 < draft.beats.length ? draft.beats[i + 1].start : seconds;
+ return <span key={b.id} className={cn("h-full border-r-2 border-background", i % 2 ? "bg-primary/45" : "bg-primary/75")} style={{ width: `${(Math.max(0, end - b.start) / seconds) * 100}%` }} />;
+ })}
+ </div>
+ )}
+ {!draft.beats.length && <p className="text-[12.5px] text-muted-foreground">{s ? "Add a beat for each thing that happens." : "Markers in the builder become beats; for an upload you add them here."}</p>}
+ <ol className="space-y-2">
+ {draft.beats.map((b, i) => (
+ <li key={b.id} className="grid gap-1.5 rounded-lg border p-2.5">
+ <div className="flex flex-wrap items-center gap-1.5">
+ {built ? (
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">{span(i)}</span>
+ ) : (
+ <label className="flex items-center gap-1 text-[12px] text-muted-foreground">
+ from
+ <Input
+ type="number"
+ step={0.1}
+ min={0}
+ max={seconds}
+ value={b.start}
+ disabled={i === 0}
+ onChange={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n)) setDraft((d) => ({ ...d, beats: d.beats.map((x) => (x.id === b.id ? { ...x, start: Math.max(0, Math.min(seconds, n)) } : x)).sort((a, c) => a.start - c.start), prompt: null }));
+ }}
+ className="h-7 w-16 px-1.5 text-[12.5px] tabular-nums"
+ aria-label={`Beat ${i + 1} starts at (s)`}
+ />
+ s
+ </label>
+ )}
+ <Input value={b.label} onChange={(e) => setDraft((d) => ({ ...d, beats: d.beats.map((x) => (x.id === b.id ? { ...x, label: e.target.value.slice(0, 80) } : x)), prompt: null }))} className="h-7 min-w-0 flex-1 text-[13px] font-medium" aria-label={`Beat ${i + 1} name`} />
+ {!built && i > 0 && (
+ <button type="button" onClick={() => setDraft((d) => ({ ...d, beats: d.beats.filter((x) => x.id !== b.id), prompt: null }))} className="grid size-7 place-items-center rounded-md hover:bg-accent" aria-label={`Remove beat ${i + 1}`}>
+ <Trash2 className="size-3.5" />
+ </button>
+ )}
+ </div>
+ <Textarea
+ value={b.words}
+ onChange={(e) => setDraft((d) => ({ ...d, beats: d.beats.map((x) => (x.id === b.id ? { ...x, words: e.target.value.slice(0, BLOCKOUT.maxBeatWords) } : x)), prompt: null }))}
+ placeholder="What happens: who does what, what we hear"
+ rows={2}
+ className="min-h-0 resize-none text-[13px]"
+ aria-label={`What happens in beat ${i + 1}`}
+ />
+ </li>
+ ))}
+ </ol>
+ </section>
+
+ <section className={section} aria-label="References">
+ <h3 className={h3}>References</h3>
+ <div className="flex flex-wrap gap-2">
+ {draft.refs.map((r, i) => (
+ <div key={r.id} className="w-[132px] space-y-1">
+ <div className="relative aspect-[4/3] overflow-hidden rounded-lg bg-muted">
+ {r.url ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={r.url} alt="" className="size-full object-cover" />
+ ) : (
+ <Loader2 className="absolute inset-0 m-auto size-4 animate-spin text-muted-foreground" />
+ )}
+ <span className="absolute top-1 left-1 rounded bg-black/60 px-1 font-mono text-[10.5px] text-white">{engine === "cloud" && seedance ? `@Image${i + 1}` : `#${i + 1}`}</span>
+ <button type="button" onClick={() => setDraft((d) => ({ ...d, refs: d.refs.filter((x) => x.id !== r.id), prompt: null }))} className="absolute top-1 right-1 grid size-6 place-items-center rounded-full bg-black/60 text-white" aria-label={`Remove reference ${i + 1}`}>
+ <Trash2 className="size-3" />
+ </button>
+ </div>
+ <select
+ value={r.role}
+ onChange={(e) => setDraft((d) => ({ ...d, refs: d.refs.map((x) => (x.id === r.id ? { ...x, role: e.target.value as RefRole } : x)), prompt: null }))}
+ className="h-7 w-full rounded-md border bg-background px-1.5 text-[12.5px]"
+ aria-label={`Reference ${i + 1} is the`}
+ title={REF_ROLES.find((x) => x.id === r.role)?.hint}
+ >
+ {REF_ROLES.map((x) => (
+ <option key={x.id} value={x.id}>
+ {x.name}
+ </option>
+ ))}
+ </select>
+ <Input value={r.name ?? ""} placeholder="Name (optional)" onChange={(e) => setDraft((d) => ({ ...d, refs: d.refs.map((x) => (x.id === r.id ? { ...x, name: e.target.value.slice(0, 60) } : x)), prompt: null }))} className="h-7 px-1.5 text-[12.5px]" aria-label={`Reference ${i + 1} name`} />
+ </div>
+ ))}
+ <Popover open={refsOpen} onOpenChange={setRefsOpen}>
+ <PopoverTrigger asChild>
+ <button type="button" disabled={draft.refs.length >= BLOCKOUT.maxRefs} className="flex aspect-[4/3] w-[132px] flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-border-strong text-[12px] text-muted-foreground hover:border-primary hover:bg-brand-faint hover:text-brand-text disabled:opacity-50">
+ <Plus className="size-4" /> Add a still
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[min(92vw,360px)] p-2" align="start" collisionPadding={12}>
+ <button type="button" onClick={() => refInput.current?.click()} className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] font-medium hover:bg-accent">
+ <Upload className="size-4" /> Upload a picture
+ </button>
+ {!!elements.data?.some((e) => e.references.length && e.kind !== "voice") && <p className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Elements · Soul Cast · Soul Location</p>}
+ <div className="max-h-40 space-y-0.5 overflow-y-auto">
+ {(elements.data ?? [])
+ .filter((e) => e.references.length && e.kind !== "voice")
+ .slice(0, 30)
+ .map((e) => (
+ <button key={e.id} type="button" onClick={() => addRef({ url: e.references[0], role: roleFor({ category: e.kind }), name: e.name })} className="flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-[13px] hover:bg-accent">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={e.references[0]} alt="" className="size-7 rounded object-cover" />
+ <span className="min-w-0 flex-1 truncate">{e.name}</span>
+ <span className="text-[11.5px] text-muted-foreground capitalize">{e.kind}</span>
+ </button>
+ ))}
+ </div>
+ <p className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">From your library</p>
+ <div className="grid max-h-44 grid-cols-4 gap-1 overflow-y-auto">
+ {(images.data ?? []).slice(0, 40).map((a) => (
+ <button key={a.id} type="button" onClick={() => addRef({ url: a.url, role: "location", name: undefined })} className="aspect-square overflow-hidden rounded-md bg-muted" aria-label={`Use ${a.name ?? "this picture"}`}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={a.url} alt="" loading="lazy" className="size-full object-cover" />
+ </button>
+ ))}
+ {!images.isLoading && !images.data?.length && <p className="col-span-4 px-2 py-2 text-[12px] text-muted-foreground">Nothing in your library yet.</p>}
+ </div>
+ </PopoverContent>
+ </Popover>
+ <input ref={refInput} type="file" accept="image/png,image/jpeg,image/webp" hidden onChange={(e) => (e.target.files?.[0] && uploadRef(e.target.files[0]), (e.target.value = ""))} />
+ </div>
+ <p className="text-[12px] text-muted-foreground">Each still’s role is written into the prompt for you: the interior, who the mannequin becomes, the exterior, a prop.</p>
+ </section>
+
+ <section className={section} aria-label="Look and sound">
+ <h3 className={h3}>Look and sound</h3>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <label className="grid gap-1 text-[12.5px] font-medium">
+ Style
+ <Input value={draft.style} onChange={(e) => set({ style: e.target.value.slice(0, BLOCKOUT.maxBeatWords), prompt: null })} placeholder="Low-key horror, cold torchlight, 35 mm grain" className="h-8 text-[13px]" />
+ </label>
+ <label className="grid gap-1 text-[12.5px] font-medium">
+ Sounds
+ <Input value={draft.sounds} onChange={(e) => set({ sounds: e.target.value.slice(0, 600), prompt: null })} placeholder="Footsteps on concrete, a long door creak" className="h-8 text-[13px]" />
+ </label>
+ <label className="grid gap-1 text-[12.5px] font-medium">
+ No…
+ <Input value={draft.avoid} onChange={(e) => set({ avoid: e.target.value.slice(0, 600), prompt: null })} placeholder="jump cuts, text on screen, extra people" className="h-8 text-[13px]" />
+ </label>
+ <label className="grid gap-1 text-[12.5px] font-medium">
+ Rules
+ <Input value={draft.constraints} onChange={(e) => set({ constraints: e.target.value.slice(0, BLOCKOUT.maxBeatWords), prompt: null })} placeholder="She never looks at the camera" className="h-8 text-[13px]" />
+ </label>
+ </div>
+ </section>
+
+ <section className={section} aria-label="Render">
+ <h3 className={h3}>Render</h3>
+ {engine === "cloud" ? (
+ <div className="grid gap-2 sm:grid-cols-2" role="radiogroup" aria-label="Cloud model">
+ {BLOCKOUT_MODELS.cloud.map((id) => (
+ <button key={id} type="button" role="radio" aria-checked={draft.modelId === id} onClick={() => set({ modelId: id, resolution: undefined, prompt: null })} className={cn("rounded-xl border p-3 text-left", draft.modelId === id ? "border-primary bg-brand-faint" : "hover:bg-accent")}>
+ <span className="block text-[13.5px] font-medium">{getModel(id)?.name ?? id}</span>
+ <span className="block text-[12px] text-muted-foreground">{MODEL_LINES[id]}</span>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="rounded-xl bg-muted/60 p-3 text-[12.5px]">
+ <span className="font-medium">Your GPU (open source) · Free.</span> The blockout’s depth drives Wan 2.2 Fun VACE from a first frame drawn from your stills. It follows the depth and timing, not the dialogue or sound: add sound afterwards with{" "}
+ <Link href="/audio/video" className="underline underline-offset-2">
+ Sound for video
+ </Link>
+ .
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="flex items-center gap-1.5 text-[12.5px]">
+ Quality
+ <select value={resolution ?? ""} onChange={(e) => set({ resolution: e.target.value })} className="h-8 rounded-md border bg-background px-2 text-[13px]">
+ {resolutions.map((r) => (
+ <option key={r}>{r}</option>
+ ))}
+ </select>
+ </label>
+ {seedance && (
+ <button type="button" onClick={() => set({ audio: !draft.audio, prompt: null })} aria-pressed={draft.audio} className={cn("inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium", draft.audio ? "bg-brand-faint text-brand-text" : "bg-secondary")}>
+ {draft.audio ? <Volume2 className="size-3.5" /> : <VolumeX className="size-3.5" />} Sound {draft.audio ? "on" : "off"}
+ </button>
+ )}
+ </div>
+ </section>
+
+ <section className={section} aria-label="Prompt">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className={h3}>{engine === "cloud" ? "Prompt" : "Prompt (first window)"}</h3>
+ {draft.prompt !== null && engine === "cloud" && (
+ <Button size="sm" variant="ghost" onClick={() => set({ prompt: null })}>
+ <RotateCcw className="size-3.5" /> Back to compiled
+ </Button>
+ )}
+ </div>
+ <Textarea
+ value={engine === "cloud" ? (draft.prompt ?? compiled) : compiled}
+ readOnly={engine !== "cloud"}
+ onChange={(e) => set({ prompt: e.target.value.slice(0, 60_000) })}
+ rows={9}
+ className="font-mono text-[12px] leading-relaxed"
+ aria-label="Compiled prompt"
+ />
+ <p className="text-[12px] text-muted-foreground">
+ {engine === "cloud" ? "Compiled from the beats, references and words above. Edit it freely: a film longer than one shot gets each shot's own beats instead." : "Each window gets the beats inside it, briefly: Wan follows the depth for everything else."}
+ </p>
+ </section>
+ </div>
+ <div className="border-t px-4 py-3 sm:px-5">
+ {!!plan.notes.length && (
+ <ul className="mb-2 space-y-0.5 text-[12px] text-muted-foreground">
+ {plan.notes.map((n) => (
+ <li key={n}>· {n}</li>
+ ))}
+ </ul>
+ )}
+ <div className="flex items-center gap-2">
+ <p className="min-w-0 flex-1 text-[12.5px]">
+ <span className="font-medium">{price}</span>
+ <span className="text-muted-foreground"> · {model?.name ?? (engine === "cloud" ? "Cloud" : "Your GPU")}</span>
+ {plan.blocker && <span className="block truncate text-[12px] text-muted-foreground">{plan.blocker}</span>}
+ </p>
+ <Button onClick={run} disabled={!!plan.blocker || generate.isPending || draft.refs.some((r) => r.uploading)}>
+ {generate.isPending ? <Loader2 className="size-4 animate-spin" /> : <Clapperboard className="size-4" />} Film it
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** The draft after the builder hands back a render: the source, the scene, its beats (words kept). */
+export function withBuilt(d: BlockoutDraft, b: BuiltBlockout, scene: BlockoutScene): BlockoutDraft {
+ return { ...d, source: { video: b.video, depth: b.depth, firstFrame: b.firstFrame, seconds: b.seconds, aspect: b.aspect, from: "build" }, scene, beats: beatsForScene(scene, d.beats), prompt: null };
+}
+
diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsx
index fb8ad5ce..98ffbc45 100644
--- a/src/components/cinema/cinema-feed.tsx
+++ b/src/components/cinema/cinema-feed.tsx
@@ -158,10 +158,10 @@ function dayLabel(ts: number): string {
return d.toLocaleDateString(undefined, { weekday: diff < 7 ? "long" : undefined, month: "short", day: "numeric", year: d.getFullYear() === today.getFullYear() ? undefined : "numeric" });
}
-const FEATURE_TITLES: Record<string, string> = { "cinema-scene": "3D scene", "cinema-recompose": "Recomposed view", "cinema-path": "Fly path", "cinema-turnaround": "Turnaround" };
+const FEATURE_TITLES: Record<string, string> = { "cinema-scene": "3D scene", "cinema-recompose": "Recomposed view", "cinema-path": "Fly path", "cinema-turnaround": "Turnaround", "cinema-blockout": "Blockout film" };
const promptOf = (g: CinemaGeneration) => g.take?.prompt?.trim() || FEATURE_TITLES[g.feature] || g.request.prompt?.trim() || g.prompt || "Untitled";
-const STEP_HINT: Record<string, string> = { "cinema-cast": "Cast", "cinema-location": "Location", "cinema-grid": "Grid", "cinema-scene": "3D scene", "cinema-recompose": "Recomposed", "cinema-path": "Fly path", "cinema-turnaround": "Turnaround" };
+const STEP_HINT: Record<string, string> = { "cinema-cast": "Cast", "cinema-location": "Location", "cinema-grid": "Grid", "cinema-scene": "3D scene", "cinema-recompose": "Recomposed", "cinema-path": "Fly path", "cinema-turnaround": "Turnaround", "cinema-blockout": "Blockout film" };
function Badge({ children, className }: { children: React.ReactNode; className?: string }) {
return <span className={cn("inline-flex h-5 items-center rounded-full bg-black/50 px-1.5 text-[10.5px] font-medium text-white backdrop-blur", className)}>{children}</span>;
diff --git a/src/components/cinema/prompt-bar.tsx b/src/components/cinema/prompt-bar.tsx
index 920bd685..91f8c155 100644
--- a/src/components/cinema/prompt-bar.tsx
+++ b/src/components/cinema/prompt-bar.tsx
@@ -6,6 +6,7 @@ import {
ArrowUp,
AtSign,
AudioLines,
+ Box,
Check,
ChevronDown,
Clapperboard,
@@ -337,6 +338,8 @@ export interface PromptBarProps {
promptRef: React.RefObject<PromptInputHandle | null>;
onCast: () => void;
onLocation: () => void;
+ /** Blockout to film: a grey-box blockout (uploaded or built) as the take's camera, blocking and timing. */
+ onBlockout?: () => void;
}
const ACTIONS: { id: BarAction; label: string; icon: typeof Video; hint: string }[] = [
@@ -586,6 +589,19 @@ export function PromptBar(props: PromptBarProps) {
</TooltipTrigger>
<TooltipContent>Soul Location: keep every scene in the same world</TooltipContent>
</Tooltip>
+ {draft.mode === "video" && props.onBlockout && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button type="button" onClick={() => {
+ setDirectorOpen(false);
+ props.onBlockout!();
+ }} className={cn(chip, chipIdle)} aria-label="Blockout: film a grey-box blockout">
+ <Box className="size-3.5" /> Blockout
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Blockout to film: a grey box from Blender or built here sets the camera and timing</TooltipContent>
+ </Tooltip>
+ )}
</>
);
const picks = directorPicks(settings, draft.mode);
diff --git a/src/components/cinema/scene-engine.ts b/src/components/cinema/scene-engine.ts
index bb2b6f1f..92b57919 100644
--- a/src/components/cinema/scene-engine.ts
+++ b/src/components/cinema/scene-engine.ts
@@ -26,7 +26,7 @@ import {
type Rect,
} from "@/lib/scene3d";
import type { SceneSource } from "./scene-actions";
-import { encodeVp8, pathVideoType, recordWithMediaRecorder, vp8Supported } from "./video-encode";
+import { encodeFrames, encodeVp8, pathVideoType, recordWithMediaRecorder, vp8Supported } from "./video-encode";
/**
* The 3D scene viewer's renderer (three.js, loaded only when a scene opens): a MoGe mesh (GLB) or a point cloud
@@ -571,7 +571,7 @@ export class SceneEngine {
*/
async recordPath(
path: FramePoses,
- o: { fps: number; mask?: boolean; onProgress?: (p: number) => void; signal?: AbortSignal },
+ o: { fps: number; mask?: boolean; mp4?: boolean; onProgress?: (p: number) => void; signal?: AbortSignal },
): Promise<{ render: Blob; mask?: Blob; type: string; frames: number }> {
if (!this.view || !this.info) throw new Error("The scene isn't ready yet");
const { width, height, poses, intrinsic } = path;
@@ -612,6 +612,11 @@ export class SceneEngine {
};
this.playing = true;
try {
+ // Blockout to film: the render as the cloud models read it (MP4 where the browser encodes H.264).
+ if (o.mp4 && !mask) {
+ const out = await encodeFrames(poses.length, width, height, o.fps, (i) => (stop(), frame(i), o.onProgress?.((i + 1) / poses.length), render), true);
+ return { render: out.blob, type: out.type, frames: poses.length };
+ }
if (exact) {
const [a, b] = await encodeVp8(poses.length, width, height, o.fps, images.length, (i) => {
stop();
diff --git a/src/components/cinema/scene-viewer.tsx b/src/components/cinema/scene-viewer.tsx
index a53288ee..40525b31 100644
--- a/src/components/cinema/scene-viewer.tsx
+++ b/src/components/cinema/scene-viewer.tsx
@@ -46,6 +46,8 @@ export interface SceneViewerProps {
context: { cloudAllowed: boolean; civitai?: boolean };
brief: string;
onClose: () => void;
+ /** Blockout to film: the path rendered through the scene (24 fps) handed to the composer as a blockout. */
+ onUseAsBlockout?: (b: { video: string; seconds: number; aspect: string; still: string }) => void;
}
const SPEEDS = [
@@ -86,7 +88,7 @@ function Section({ title, value, children }: { title: string; value?: React.Reac
);
}
-export default function SceneViewer({ take, projectId, engine, onEngine, settings, context, brief, onClose }: SceneViewerProps) {
+export default function SceneViewer({ take, projectId, engine, onEngine, settings, context, brief, onClose, onUseAsBlockout }: SceneViewerProps) {
// Elements in state, not refs: the dialog's portal mounts its content a render after this component.
const [stageEl, setStageEl] = useState<HTMLDivElement | null>(null);
const [canvasEl, setCanvasEl] = useState<HTMLCanvasElement | null>(null);
@@ -363,6 +365,39 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
}
};
+ /** The path rendered through the scene at 24 fps for its length, then handed to the Blockout composer with the still. */
+ const takeAsBlockout = async () => {
+ const eng = engineRef.current;
+ if (!eng || !info || filming || previewing || !onUseAsBlockout) return;
+ if (keys.length < 2) {
+ toast.error("Add a keyframe or pick a move first");
+ return;
+ }
+ setPathOpen(false);
+ try {
+ setFilming("render");
+ setProgress(0);
+ const fps = 24;
+ const frames = Math.max(2, Math.round(pathSeconds * fps));
+ const poses = framePoses(keys, frames, info.pivotDepth, info.photoFov.h, renderSize(info.photoAspect, 1280));
+ const rec = await eng.recordPath(poses, { fps, mp4: true, onProgress: setProgress });
+ setFilming("send");
+ const asset = await uploadFile(new File([rec.render], `blockout-path.${rec.type.includes("mp4") ? "mp4" : "webm"}`, { type: rec.type }));
+ onUseAsBlockout({ video: asset.url, seconds: Math.round((frames / fps) * 100) / 100, aspect, still: take.still });
+ } catch (e) {
+ if ((e as Error).name !== "AbortError") toastError(e, "Couldn't render the path as a blockout");
+ } finally {
+ setFilming(null);
+ }
+ };
+
+ const blockoutButton = (className?: string) =>
+ onUseAsBlockout ? (
+ <Button variant="secondary" onClick={() => void takeAsBlockout()} disabled={status !== "ready" || previewing || !!filming || keys.length < 2} className={cn("rounded-full", className)}>
+ <Box /> Use as blockout
+ </Button>
+ ) : null;
+
const resetView = () => {
engineRef.current?.reset();
if (info) setLens(clampLens(info.photoLens));
@@ -747,6 +782,7 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
{pathOptions}
<EngineSwitch value={engine} onChange={onEngine} size="sm" />
{filmButton("w-full")}
+ {blockoutButton("w-full")}
</div>
</SheetContent>
</Sheet>
@@ -760,6 +796,7 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
<div className="space-y-1.5 border-t p-4">
{captureButton("w-full")}
{filmButton("w-full")}
+ {blockoutButton("w-full")}
<p className="text-center text-[11.5px] text-muted-foreground">Capture re-renders the frame; Film follows the path. Both land next to the scene</p>
</div>
</aside>
diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsx
index 1e76ba18..716960d8 100644
--- a/src/components/cinema/workspace.tsx
+++ b/src/components/cinema/workspace.tsx
@@ -4,7 +4,7 @@ import { Bot, ChevronLeft, Clapperboard, Copy, FileText, Folder, FolderOpen, Fol
import { nanoid } from "nanoid";
import dynamic from "next/dynamic";
import Link from "next/link";
-import { useRouter } from "next/navigation";
+import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
import { ErrorState, NotFoundState } from "@/components/empty-state";
@@ -37,6 +37,18 @@ import { PromptBar, useAddRefs } from "./prompt-bar";
import { SceneCreateDialog, askSceneConfirmAgain, sceneTake, skipSceneConfirm, usePlanPrice, useScenePlan, type SceneTake } from "./scene-actions";
import { SidePanel } from "./side-panel";
import { SoulCastDialog, SoulLocationDialog } from "./soul-builders";
+import { BlockoutPanel, initialBlockout, withBuilt, type BlockoutDraft } from "./blockout-panel";
+import type { BlockoutScene } from "@/lib/blockout";
+
+/** The blockout builder (three.js) loads when it opens. */
+const BlockoutBuilder = dynamic(() => import("./blockout-builder"), {
+ ssr: false,
+ loading: () => (
+ <div className="fixed inset-0 z-50 grid place-items-center bg-[#161617] text-[14px] text-white" role="status">
+ Opening the blockout builder…
+ </div>
+ ),
+});
/** The 3D viewer (and three.js inside it) loads when a scene is opened. */
const SceneViewer = dynamic(() => import("./scene-viewer"), {
@@ -203,6 +215,12 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
const [castOpen, setCastOpen] = useState(false);
const [locationOpen, setLocationOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
+ // Blockout to film: the composer's panel (its draft kept while the project is open) and the builder.
+ // /cinema/<id>?blockout=1 (a link to Blockout to film) opens it.
+ const search = useSearchParams();
+ const [blockoutOpen, setBlockoutOpen] = useState(() => search.get("blockout") === "1");
+ const [blockout, setBlockout] = useState<BlockoutDraft>(initialBlockout);
+ const [builder, setBuilder] = useState<BlockoutScene | null>(null);
const [dropping, setDropping] = useState(false);
const promptRef = useRef<PromptInputHandle>(null);
const studio = useStudioGenerations(id, view.kind === "studio");
@@ -572,6 +590,7 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
promptRef={promptRef}
onCast={() => setCastOpen(true)}
onLocation={() => setLocationOpen(true)}
+ onBlockout={() => setBlockoutOpen(true)}
/>
</div>
</div>
@@ -620,6 +639,46 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
context={context}
brief={project.brief.body}
onClose={() => setOpenScene(null)}
+ onUseAsBlockout={(b) => {
+ setBlockout((d) => ({
+ ...d,
+ source: { video: b.video, seconds: b.seconds, aspect: b.aspect, from: "scene" },
+ scene: null,
+ beats: d.source?.from === "scene" && d.beats.length ? d.beats.filter((x) => x.start < b.seconds) : [{ id: "start", start: 0, label: "Opening", words: "" }],
+ refs: d.refs.some((r) => r.url === b.still) ? d.refs : [{ id: "scene-still", url: b.still, role: "location" as const }, ...d.refs].slice(0, 8),
+ prompt: null,
+ }));
+ setOpenScene(null);
+ setBlockoutOpen(true);
+ }}
+ />
+ )}
+ <BlockoutPanel
+ open={blockoutOpen && !builder}
+ onOpenChange={setBlockoutOpen}
+ projectId={id}
+ folderId={folderId}
+ engine={engine}
+ settings={settings}
+ brief={project.brief.body}
+ context={context}
+ draft={blockout}
+ setDraft={setBlockout}
+ onBuild={(scene) => setBuilder(scene)}
+ />
+ {builder && (
+ <BlockoutBuilder
+ initial={builder}
+ onClose={(scene) => {
+ setBlockout((d) => ({ ...d, scene }));
+ setBuilder(null);
+ }}
+ onDone={(built, scene) => {
+ setBlockout((d) => withBuilt(d, built, scene));
+ setBuilder(null);
+ setBlockoutOpen(true);
+ if (!built.type.includes("mp4") && engine === "cloud") toast("This browser saved the grey box as WebM. If the cloud model refuses it, render it in Chrome or Edge, or upload an MP4 from your 3D app.");
+ }}
/>
)}
<SoulCastDialog open={castOpen} onOpenChange={setCastOpen} {...builderProps} />