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.

Cinema Studio: Create 3D scene, the fly-through viewer and Capture to re-render

Claudee69c2b86dda3
diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsx
index 67d7fea7..edd7eecd 100644
--- a/src/components/cinema/cinema-feed.tsx
+++ b/src/components/cinema/cinema-feed.tsx
@@ -1,6 +1,7 @@
"use client";
import {
+ Box,
CalendarDays,
Clapperboard,
ExternalLink,
@@ -107,13 +108,14 @@ function usePrefs(): [Prefs, (p: Partial<Prefs>) => void] {
return [prefs, set];
}
-/** One tile: a pending/failed take, one output of a take, or a tile cut from a grid sheet. */
+/** One tile: a pending/failed take, one output of a take, a tile cut from a grid sheet, or a 3D scene (shown by its still). */
interface Unit {
key: string;
g: CinemaGeneration;
output?: OutputFile;
index: number;
tile?: { row: number; col: number };
+ scene?: boolean;
}
const active = (g: Generation) => g.status === "queued" || g.status === "running";
@@ -125,6 +127,12 @@ function units(items: CinemaGeneration[]): Unit[] {
out.push({ key: g.id, g, index: 0 });
continue;
}
+ // A 3D scene is one tile showing its still; it opens in the 3D viewer.
+ if (g.feature === "cinema-scene") {
+ const still = g.request.inputs?.images?.[0];
+ out.push({ key: g.id, g, output: still ? { url: still, kind: "image" } : g.outputs[0], index: 0, scene: true });
+ continue;
+ }
// Open-source grids return the sheet first, then its tiles.
const sheetTiles = g.feature === "cinema-grid" && g.outputs.length > 1;
const outputs = sheetTiles ? g.outputs.slice(0, 1) : g.outputs;
@@ -145,9 +153,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 promptOf = (g: CinemaGeneration) => g.take?.prompt?.trim() || g.request.prompt?.trim() || g.prompt || "Untitled";
+const FEATURE_TITLES: Record<string, string> = { "cinema-scene": "3D scene", "cinema-recompose": "Recomposed view" };
+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" };
+const STEP_HINT: Record<string, string> = { "cinema-cast": "Cast", "cinema-location": "Location", "cinema-grid": "Grid", "cinema-scene": "3D scene", "cinema-recompose": "Recomposed" };
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>;
@@ -159,6 +168,11 @@ export interface FeedHandlers {
onAnimate: (url: string) => void;
onReference: (url: string, kind: OutputFile["kind"]) => void;
onSaveElement: (g: CinemaGeneration, url: string, kind: "character" | "location") => void;
+ /** "Create 3D scene" from a still (asks first, with the price). */
+ onCreateScene: (g: CinemaGeneration, url: string) => void;
+ onOpenScene: (g: CinemaGeneration) => void;
+ /** What building a scene costs on the current engine ("Free", "≈ $0.03"). */
+ scenePrice: string;
}
/** A grid contact sheet and its tiles are one take: deleting any of them deletes the lot. */
@@ -184,11 +198,19 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56" onClick={(e) => e.stopPropagation()}>
+ {u.scene && (
+ <DropdownMenuItem onClick={() => handlers.onOpenScene(u.g)}>
+ <Box /> Open 3D scene
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={() => handlers.onLoad(u.g)}>
<RotateCcw /> Load into prompt bar
</DropdownMenuItem>
- {o?.kind === "image" && (
+ {o?.kind === "image" && !u.scene && (
<>
+ <DropdownMenuItem onClick={() => handlers.onCreateScene(u.g, o.url)}>
+ <Box /> Create 3D scene <span className="ml-auto text-[11.5px] text-muted-foreground">{handlers.scenePrice}</span>
+ </DropdownMenuItem>
<DropdownMenuItem onClick={() => handlers.onAnimate(o.url)}>
<Clapperboard /> Animate (start frame)
</DropdownMenuItem>
@@ -213,13 +235,21 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold
</DropdownMenuItem>
</>
)}
- {o && (
- <DropdownMenuItem asChild>
- <a href={`${o.url}?download=${encodeURIComponent(downloadName(u.g, o, u.index))}`}>
- <Download /> Download
- </a>
- </DropdownMenuItem>
- )}
+ {u.scene
+ ? u.g.outputs.slice(0, 1).map((f) => (
+ <DropdownMenuItem key={f.url} asChild>
+ <a href={`${f.url}?download=${encodeURIComponent(downloadName(u.g, f, 0))}`}>
+ <Download /> {f.kind === "model3d" ? "Download the 3D mesh (.glb)" : "Download the depth map"}
+ </a>
+ </DropdownMenuItem>
+ ))
+ : o && (
+ <DropdownMenuItem asChild>
+ <a href={`${o.url}?download=${encodeURIComponent(downloadName(u.g, o, u.index))}`}>
+ <Download /> Download
+ </a>
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={() => void actions.favorite([u.g.id], !u.g.favorite).catch((e) => toast.error((e as Error).message))}>
<Heart /> {u.g.favorite ? "Unlike" : "Like"}
</DropdownMenuItem>
@@ -366,7 +396,7 @@ function TileView({
const overlay = (clickable || selecting) && (
<button
type="button"
- aria-label={selecting ? `${selected ? "Unselect" : "Select"}: ${promptOf(g)}` : `Open ${step ? `${step}: ` : ""}${promptOf(g)}`}
+ aria-label={selecting ? `${selected ? "Unselect" : "Select"}: ${promptOf(g)}` : u.scene ? "Open 3D scene" : `Open ${step ? `${step}: ` : ""}${promptOf(g)}`}
aria-pressed={selecting ? selected : undefined}
onClick={(e) => {
if (selecting || e.metaKey || e.ctrlKey || e.shiftKey) onToggle(e.shiftKey);
@@ -397,6 +427,11 @@ function TileView({
{checkbox}
<div className="pointer-events-none absolute top-2 right-2 flex items-center gap-1">
{g.favorite && <Heart className="size-4 fill-highlight text-highlight drop-shadow" />}
+ {u.scene && (
+ <span className="inline-flex h-6 items-center gap-1 rounded-full bg-black/55 px-2 text-[11.5px] font-medium text-white backdrop-blur" aria-hidden>
+ <Box className="size-3.5" /> 3D
+ </span>
+ )}
</div>
{g.status === "succeeded" && (
<div className="pointer-events-none absolute inset-x-0 bottom-0 flex items-end justify-between gap-1 bg-gradient-to-t from-black/65 to-transparent p-2 pt-8 opacity-100 transition-opacity sm:opacity-0 sm:group-focus-within/tile:opacity-100 sm:group-hover/tile:opacity-100">
@@ -415,15 +450,36 @@ function TileView({
<TooltipContent>Extend · Prequel · Edit</TooltipContent>
</Tooltip>
)}
- {u.output?.kind === "image" && (
+ {u.scene ? (
<Tooltip>
<TooltipTrigger asChild>
- <button type="button" onClick={() => handlers.onAnimate(u.output!.url)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label="Animate">
- <Clapperboard className="size-4" />
+ <button type="button" onClick={() => handlers.onOpenScene(g)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label="Open 3D scene">
+ <Box className="size-4" />
</button>
</TooltipTrigger>
- <TooltipContent>Animate: use as the start frame</TooltipContent>
+ <TooltipContent>Open the 3D scene: fly, frame, capture</TooltipContent>
</Tooltip>
+ ) : (
+ u.output?.kind === "image" && (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button type="button" onClick={() => handlers.onAnimate(u.output!.url)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label="Animate">
+ <Clapperboard className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Animate: use as the start frame</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button type="button" onClick={() => handlers.onCreateScene(g, u.output!.url)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label="Create 3D scene">
+ <Box className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Create 3D scene · {handlers.scenePrice}</TooltipContent>
+ </Tooltip>
+ </>
+ )
)}
<TileMenu u={u} folders={folders} projectId={projectId} handlers={handlers} onDelete={onDelete} />
</div>
@@ -520,7 +576,7 @@ export function CinemaFeed({
});
}, [items, prefs, now]);
const all = useMemo(() => units(filtered), [filtered]);
- const viewable = all.filter((u) => u.g.status === "succeeded");
+ const viewable = all.filter((u) => u.g.status === "succeeded" && !u.scene);
const pos = open ? viewable.findIndex((u) => u.key === open) : -1;
const ids = useMemo(() => [...new Set(all.map((u) => u.g.id))], [all]);
const live = [...selected].filter((id) => ids.includes(id));
@@ -722,7 +778,7 @@ export function CinemaFeed({
selected={selected.has(u.g.id)}
selecting={selecting}
onToggle={(shift) => toggle(u.g.id, shift)}
- onOpen={() => setOpen(u.key)}
+ onOpen={() => (u.scene ? handlers.onOpenScene(u.g) : setOpen(u.key))}
projectId={projectId}
folders={folders}
handlers={handlers}
diff --git a/src/components/cinema/scene-actions.tsx b/src/components/cinema/scene-actions.tsx
new file mode 100644
index 00000000..7b88e442
--- /dev/null
+++ b/src/components/cinema/scene-actions.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+import { Box } from "lucide-react";
+import { useId, useMemo, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { useStatus } from "@/lib/api";
+import { IMAGE_ASPECTS, planCinema, type CinemaPlan, type DirectorSettings } from "@/lib/catalog/cinema";
+import type { Engine } from "@/lib/catalog/types";
+import { formatCost } from "@/lib/format";
+import type { CinemaGeneration } from "./hooks";
+
+/**
+ * Cinema Studio's 3D scene, the light half (the viewer and three.js load only when a scene opens): which takes
+ * are scenes, what a step costs, and the "Create 3D scene" confirmation (Higgsfield asks the same, with
+ * "Don't show this again").
+ */
+
+export type SceneSource = { kind: "mesh"; url: string } | { kind: "points"; photo: string; depth: string };
+
+export interface SceneTake {
+ generation: CinemaGeneration;
+ /** The still the scene was built from: image 2 of every recomposition. */
+ still: string;
+ source: SceneSource;
+ /** The frame starts on the still's ratio when it is one of the project's, else 16:9. */
+ aspect: string;
+}
+
+/** A finished "Create 3D scene" take, ready for the viewer: MoGe's mesh (open) or the still + depth map (cloud). */
+export function sceneTake(g: CinemaGeneration): SceneTake | null {
+ if (g.feature !== "cinema-scene" || g.status !== "succeeded") return null;
+ const still = g.request.inputs?.images?.[0];
+ if (!still) return null;
+ const mesh = g.outputs.find((o) => o.kind === "model3d");
+ const depth = g.outputs.find((o) => o.kind === "image");
+ const source: SceneSource | null = mesh ? { kind: "mesh", url: mesh.url } : depth ? { kind: "points", photo: still, depth: depth.url } : null;
+ if (!source) return null;
+ const ar = g.request.params?.aspectRatio;
+ return { generation: g, still, source, aspect: ar && IMAGE_ASPECTS.includes(ar) ? ar : "16:9" };
+}
+
+/** What a plan costs here: "Demo" when no provider of its model is connected and demo mode answers instead. */
+export function usePlanPrice(plan: CinemaPlan): { cost: number | null; label: string; demo: boolean } {
+ const status = useStatus().data;
+ const demo = !!status && status.demoMode !== "off" && !plan.model.routes.some((r) => status.providers[r.provider]?.configured);
+ const cost = demo ? 0 : plan.costUsd;
+ return { cost, demo, label: demo ? "Demo · free" : cost === 0 ? "Free" : cost != null ? `≈ ${formatCost(cost)}` : "Price unknown" };
+}
+
+const SKIP_KEY = "fuobe.cinema.sceneConfirm";
+
+export function skipSceneConfirm(): boolean {
+ try {
+ return localStorage.getItem(SKIP_KEY) === "skip";
+ } catch {
+ return false;
+ }
+}
+
+export interface ScenePlanContext {
+ engine: Engine;
+ settings: DirectorSettings;
+ context: { higgsfield: boolean; cloudAllowed: boolean };
+ brief: string;
+}
+
+/** The plan of "Create 3D scene" for one still (the menu shows its price, the dialog its notes). */
+export function useScenePlan(still: string | null, aspect: string | undefined, p: ScenePlanContext): CinemaPlan {
+ return useMemo(
+ () =>
+ planCinema(
+ { engine: p.engine, mode: "image", action: "scene", prompt: "", settings: p.settings, brief: p.brief, aspectRatio: aspect, source: still ? { url: still, kind: "image" } : undefined },
+ p.context,
+ ),
+ [still, aspect, p.engine, p.settings, p.brief, p.context],
+ );
+}
+
+export function SceneCreateDialog({
+ still,
+ aspect,
+ plan,
+ onOpenChange,
+ onConfirm,
+}: {
+ /** The still to build from (null = closed). */
+ still: string | null;
+ aspect?: string;
+ plan: CinemaPlan;
+ onOpenChange: (open: boolean) => void;
+ onConfirm: () => void;
+}) {
+ const price = usePlanPrice(plan);
+ const [skip, setSkip] = useState(false);
+ const skipId = useId();
+ const open = plan.model.engine === "open";
+ return (
+ <Dialog open={!!still} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2 font-heading text-[22px] font-normal">
+ <Box className="size-5 text-brand-text" /> Create a 3D scene?
+ </DialogTitle>
+ <DialogDescription>This turns your still into a 3D scene you can fly a camera through. Capture any view and it is re-rendered as a new take.</DialogDescription>
+ </DialogHeader>
+ {still && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={still} alt="The still to build from" className="max-h-48 w-full rounded-lg bg-muted object-contain" style={{ aspectRatio: aspect?.replace(":", "/") }} />
+ )}
+ <div className="space-y-1.5 rounded-lg bg-muted/60 p-3 text-[13px]">
+ <p>{plan.notes[0]}</p>
+ <p className="flex items-center justify-between gap-3 font-medium">
+ <span>{open ? "Open source · MoGe 2" : "Cloud · Marigold V2 depth"}</span>
+ <span className={price.cost === 0 ? "text-brand-text" : undefined}>{price.label}</span>
+ </p>
+ {!open && <p className="text-[12px] text-muted-foreground">Each re-render of a captured view is priced again before it runs.</p>}
+ </div>
+ <label htmlFor={skipId} className="flex items-center gap-2 text-[13px] text-muted-foreground">
+ <Checkbox id={skipId} checked={skip} onCheckedChange={(v) => setSkip(v === true)} /> Don&apos;t ask again
+ </label>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ disabled={!!plan.blocker}
+ onClick={() => {
+ if (skip)
+ try {
+ localStorage.setItem(SKIP_KEY, "skip");
+ } catch {}
+ onConfirm();
+ }}
+ >
+ <Box /> Build 3D scene · {price.label}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/cinema/scene-engine.ts b/src/components/cinema/scene-engine.ts
new file mode 100644
index 00000000..11cb61a1
--- /dev/null
+++ b/src/components/cinema/scene-engine.ts
@@ -0,0 +1,487 @@
+"use client";
+
+import * as THREE from "three";
+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
+import { FullScreenQuad } from "three/examples/jsm/postprocessing/Pass.js";
+import {
+ LENS,
+ blurScale,
+ buildPointCloud,
+ canvasFov,
+ dolly,
+ flySpeed,
+ flyStep,
+ focalForFov,
+ focusDistance,
+ keysToInput,
+ lensFov,
+ lookStep,
+ medianDepth,
+ objectStart,
+ sceneFov,
+ strafe,
+ type FlyPose,
+ type Pixels,
+ type Rect,
+} from "@/lib/scene3d";
+import type { SceneSource } from "./scene-actions";
+
+/**
+ * The 3D scene viewer's renderer (three.js, loaded only when a scene opens): a MoGe mesh (GLB) or a point cloud
+ * built from the still and its depth map, a fly camera, the frame-fitted lens, a depth-of-field pass, and the
+ * capture of exactly what the frame shows. The maths is in src/lib/scene3d.ts; this file only draws.
+ */
+
+export type { SceneSource };
+
+export interface SceneInfo {
+ kind: "mesh" | "points";
+ /** "scene": in the photo's camera space, so the start is the photo's view; "object": a model framed from the front. */
+ layout: "scene" | "object";
+ /** The lens (mm) that shows the photo's own view from the start. */
+ photoLens: number;
+ /** The subject distance: the orbit pivot for the re-shot angles. */
+ pivotDepth: number;
+ /** Points, or triangles, drawn. */
+ size: number;
+}
+
+export interface ViewSettings {
+ lens: number;
+ aperture: number;
+ aspect: number;
+ dof: boolean;
+ /** The frame, in CSS px of the canvas. */
+ frame: Rect;
+ /** Flying speed multiplier. */
+ speed: number;
+}
+
+const POINTS_VERT = /* glsl */ `
+attribute float size;
+attribute vec3 rgb;
+uniform float scale;
+varying vec3 vColor;
+vec3 toLinear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c)); }
+void main() {
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = clamp(size * scale / max(-mv.z, 1e-4), 1.0, 256.0);
+ vColor = toLinear(rgb);
+}`;
+
+const POINTS_FRAG = /* glsl */ `
+varying vec3 vColor;
+void main() { gl_FragColor = vec4(vColor, 1.0); }`;
+
+const POST_VERT = /* glsl */ `
+varying vec2 vUv;
+void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`;
+
+/** Thin-lens blur gathered over a golden-angle disc (a sample only counts where its own blur reaches), then sRGB. */
+const POST_FRAG = /* glsl */ `
+#include <packing>
+uniform sampler2D tColor;
+uniform sampler2D tDepth;
+uniform vec2 texel;
+uniform float cameraNear;
+uniform float cameraFar;
+uniform float focus;
+uniform float blur;
+uniform float framePx;
+uniform float maxRadius;
+varying vec2 vUv;
+float distAt(vec2 uv) { return -perspectiveDepthToViewZ(texture2D(tDepth, uv).x, cameraNear, cameraFar); }
+float coc(float d) { return min(maxRadius, 0.5 * blur * framePx * abs(d - focus) / max(d, 1e-4)); }
+vec3 toSRGB(vec3 c) { c = max(c, 0.0); return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); }
+void main() {
+ vec3 base = texture2D(tColor, vUv).rgb;
+ float r0 = blur > 0.0 ? coc(distAt(vUv)) : 0.0;
+ if (r0 > 0.75) {
+ vec3 acc = base;
+ float wsum = 1.0;
+ for (int i = 0; i < 40; i++) {
+ float fi = float(i) + 0.5;
+ float r = sqrt(fi / 40.0) * r0;
+ float a = fi * 2.39996323;
+ vec2 uv = vUv + vec2(cos(a), sin(a)) * r * texel;
+ float w = clamp(coc(distAt(uv)) / max(r, 0.5), 0.0, 1.0);
+ acc += texture2D(tColor, uv).rgb * w;
+ wsum += w;
+ }
+ base = acc / wsum;
+ }
+ gl_FragColor = vec4(toSRGB(base), 1.0);
+}`;
+
+const VOID = 0x0b0b0c;
+const START: FlyPose = { position: [0, 0, 0], yaw: 0, pitch: 0 };
+
+async function pixelsOf(url: string, maxSide: number, signal?: AbortSignal): Promise<Pixels> {
+ const img = new Image();
+ img.decoding = "async";
+ img.src = url;
+ await img.decode();
+ if (signal?.aborted) throw new DOMException("Closed", "AbortError");
+ const w0 = img.naturalWidth || 1024;
+ const h0 = img.naturalHeight || 1024;
+ const k = Math.min(1, maxSide / Math.max(w0, h0));
+ const width = Math.max(1, Math.round(w0 * k));
+ const height = Math.max(1, Math.round(h0 * k));
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d", { willReadFrequently: true })!;
+ ctx.drawImage(img, 0, 0, width, height);
+ return ctx.getImageData(0, 0, width, height);
+}
+
+/** Every vertex of the loaded model in world space, at most `max` of them (for the field of view, depth and focus). */
+function sampleVertices(root: THREE.Object3D, max = 80_000): Float32Array {
+ const meshes: THREE.Mesh[] = [];
+ root.traverse((o) => {
+ if ((o as THREE.Mesh).isMesh) meshes.push(o as THREE.Mesh);
+ });
+ const total = meshes.reduce((n, m) => n + (m.geometry.getAttribute("position")?.count ?? 0), 0);
+ const step = Math.max(1, Math.ceil(total / max));
+ const out: number[] = [];
+ const v = new THREE.Vector3();
+ for (const m of meshes) {
+ const pos = m.geometry.getAttribute("position");
+ if (!pos) continue;
+ for (let i = 0; i < pos.count; i += step) {
+ v.fromBufferAttribute(pos, i).applyMatrix4(m.matrixWorld);
+ out.push(v.x, v.y, v.z);
+ }
+ }
+ return Float32Array.from(out);
+}
+
+export class SceneEngine {
+ info: SceneInfo | null = null;
+ /** Called when the autofocus distance changes (scene units ≈ m). */
+ onFocus?: (distance: number) => void;
+
+ private renderer: THREE.WebGLRenderer;
+ private scene = new THREE.Scene();
+ private camera = new THREE.PerspectiveCamera(50, 1, 0.01, 1000);
+ private target: THREE.WebGLRenderTarget;
+ private postMat: THREE.ShaderMaterial;
+ private post: FullScreenQuad;
+ private pointsMat: THREE.ShaderMaterial | null = null;
+ private sample: Float32Array = new Float32Array(0);
+ /** The loaded model (mesh scenes), for focusing on the surface the frame's centre sees. */
+ private model: THREE.Object3D | null = null;
+ private raycaster = new THREE.Raycaster();
+ private pose: FlyPose = START;
+ private view: ViewSettings | null = null;
+ private keys = new Set<string>();
+ private boost = false;
+ private focus = 1;
+ private dirty = true;
+ private raf = 0;
+ private last = 0;
+ private focusTimer: ReturnType<typeof setTimeout> | undefined;
+ private size = { w: 1, h: 1, dpr: 1 };
+ private disposed = false;
+
+ constructor(canvas: HTMLCanvasElement) {
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: "high-performance" });
+ this.renderer.setClearColor(VOID, 1);
+ const ext = this.renderer.extensions;
+ const half = ext.has("EXT_color_buffer_float") || ext.has("EXT_color_buffer_half_float");
+ this.target = new THREE.WebGLRenderTarget(1, 1, { type: half ? THREE.HalfFloatType : THREE.UnsignedByteType, depthTexture: new THREE.DepthTexture(1, 1) });
+ this.postMat = new THREE.ShaderMaterial({
+ vertexShader: POST_VERT,
+ fragmentShader: POST_FRAG,
+ depthTest: false,
+ depthWrite: false,
+ uniforms: {
+ tColor: { value: null },
+ tDepth: { value: null },
+ texel: { value: new THREE.Vector2(1, 1) },
+ cameraNear: { value: 0.01 },
+ cameraFar: { value: 1000 },
+ focus: { value: 1 },
+ blur: { value: 0 },
+ framePx: { value: 1 },
+ maxRadius: { value: 0 },
+ },
+ });
+ this.post = new FullScreenQuad(this.postMat);
+ const tick = (t: number) => {
+ if (this.disposed) return;
+ this.raf = requestAnimationFrame(tick);
+ const dt = this.last ? (t - this.last) / 1000 : 0;
+ this.last = t;
+ this.step(dt);
+ };
+ this.raf = requestAnimationFrame(tick);
+ }
+
+ /** Load the scene; resolves with what the panel needs (the photo's lens, the scene's scale). */
+ async load(source: SceneSource, opts: { maxPoints: number; signal?: AbortSignal }): Promise<SceneInfo> {
+ let info: SceneInfo;
+ if (source.kind === "mesh") {
+ const gltf = await new GLTFLoader().loadAsync(source.url);
+ if (this.disposed || opts.signal?.aborted) throw new DOMException("Closed", "AbortError");
+ const root = gltf.scene;
+ let triangles = 0;
+ let lit = false;
+ root.traverse((o) => {
+ const mesh = o as THREE.Mesh;
+ if (!mesh.isMesh) return;
+ const geo = mesh.geometry;
+ triangles += (geo.index?.count ?? geo.getAttribute("position").count) / 3;
+ const mats = (Array.isArray(mesh.material) ? mesh.material : [mesh.material]) as THREE.MeshStandardMaterial[];
+ // A scanned scene carries its light in the texture: show it unlit. Untextured models keep their shading.
+ const next = mats.map((m) => {
+ if (m.map) {
+ const basic = new THREE.MeshBasicMaterial({ map: m.map, side: THREE.DoubleSide, vertexColors: !!geo.getAttribute("color") });
+ m.dispose();
+ return basic;
+ }
+ lit = true;
+ m.side = THREE.DoubleSide;
+ return m;
+ });
+ mesh.material = Array.isArray(mesh.material) ? next : next[0];
+ });
+ if (lit) {
+ this.scene.add(new THREE.HemisphereLight(0xffffff, 0x404048, 2.2));
+ const sun = new THREE.DirectionalLight(0xffffff, 2);
+ sun.position.set(2, 3, 4);
+ this.scene.add(sun);
+ }
+ root.updateMatrixWorld(true);
+ let sample = sampleVertices(root);
+ const fov = sceneFov(sample);
+ if (fov) {
+ const aspect = Math.tan((fov.h * Math.PI) / 360) / Math.tan((fov.v * Math.PI) / 360);
+ info = { kind: "mesh", layout: "scene", photoLens: focalForFov(fov.h, aspect), pivotDepth: medianDepth(sample), size: Math.round(triangles) };
+ } else {
+ // An object around its centre: move it so the camera starts at the origin, looking at it from the front.
+ const sphere = new THREE.Box3().setFromObject(root).getBoundingSphere(new THREE.Sphere());
+ const lens = 35;
+ const start = objectStart([sphere.center.x, sphere.center.y, sphere.center.z], sphere.radius, lensFov(lens, 16 / 9).v);
+ root.position.sub(new THREE.Vector3(...start.position));
+ root.updateMatrixWorld(true);
+ sample = sampleVertices(root);
+ info = { kind: "mesh", layout: "object", photoLens: lens, pivotDepth: start.position[2] - sphere.center.z, size: Math.round(triangles) };
+ }
+ this.sample = sample;
+ this.model = root;
+ this.scene.add(root);
+ } else {
+ const [photo, depth] = await Promise.all([pixelsOf(source.photo, 1600, opts.signal), pixelsOf(source.depth, 1600, opts.signal)]);
+ if (this.disposed) throw new DOMException("Closed", "AbortError");
+ // Built as a 24 mm view of the still, so the default lens starts on the photo.
+ const aspect = photo.width / photo.height;
+ const cloud = buildPointCloud(photo, depth, { hFov: lensFov(LENS.default, aspect).h, maxPoints: opts.maxPoints });
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute("position", new THREE.BufferAttribute(cloud.positions, 3));
+ geo.setAttribute("rgb", new THREE.BufferAttribute(cloud.colors, 3));
+ geo.setAttribute("size", new THREE.BufferAttribute(cloud.sizes, 1));
+ this.pointsMat = new THREE.ShaderMaterial({ vertexShader: POINTS_VERT, fragmentShader: POINTS_FRAG, uniforms: { scale: { value: 1 } } });
+ const points = new THREE.Points(geo, this.pointsMat);
+ points.frustumCulled = false;
+ this.scene.add(points);
+ this.sample = cloud.positions;
+ info = { kind: "points", layout: "scene", photoLens: LENS.default, pivotDepth: cloud.depth, size: cloud.count };
+ }
+ this.info = info;
+ this.camera.near = Math.max(0.005, info.pivotDepth * 0.01);
+ this.camera.far = info.pivotDepth * 80;
+ this.pose = START;
+ this.refocus(0);
+ this.dirty = true;
+ return info;
+ }
+
+ setView(view: ViewSettings) {
+ this.view = view;
+ this.dirty = true;
+ }
+
+ resize(w: number, h: number, dpr: number) {
+ this.size = { w: Math.max(1, w), h: Math.max(1, h), dpr };
+ this.renderer.setPixelRatio(dpr);
+ this.renderer.setSize(this.size.w, this.size.h, false);
+ this.target.setSize(Math.round(this.size.w * dpr), Math.round(this.size.h * dpr));
+ this.dirty = true;
+ }
+
+ // ---- Input
+
+ key(code: string, down: boolean) {
+ if (down) this.keys.add(code);
+ else this.keys.delete(code);
+ }
+
+ setBoost(on: boolean) {
+ this.boost = on;
+ }
+
+ releaseKeys() {
+ this.keys.clear();
+ this.boost = false;
+ }
+
+ /** Drag to look: across the frame's height turns by the lens's vertical field of view. */
+ look(dxPx: number, dyPx: number) {
+ if (!this.view) return;
+ const perPx = (lensFov(this.view.lens, this.view.aspect).v * Math.PI) / 180 / Math.max(100, this.view.frame.height);
+ this.move(lookStep(this.pose, dxPx, dyPx, perPx));
+ }
+
+ /** Turn by degrees (the arrow keys). */
+ turn(yawDeg: number, pitchDeg: number) {
+ this.move(lookStep(this.pose, -yawDeg, -pitchDeg, Math.PI / 180));
+ }
+
+ /** The wheel and pinches move along the view, in steps of the scene's size. */
+ dolly(amount: number) {
+ if (!this.info) return;
+ this.move(dolly(this.pose, amount * this.info.pivotDepth));
+ }
+
+ /** Two fingers: the scene follows them (px at the subject's distance). */
+ pan(dxPx: number, dyPx: number) {
+ if (!this.info || !this.view) return;
+ const perPx = (2 * Math.tan((lensFov(this.view.lens, this.view.aspect).v * Math.PI) / 360) * this.info.pivotDepth) / Math.max(100, this.view.frame.height);
+ this.move(strafe(this.pose, -dxPx * perPx, dyPx * perPx));
+ }
+
+ reset() {
+ this.move(START);
+ }
+
+ getPose(): FlyPose {
+ return this.pose;
+ }
+
+ private move(pose: FlyPose) {
+ this.pose = pose;
+ this.dirty = true;
+ this.refocus();
+ }
+
+ /** Focus on what the frame's centre sees once the camera settles. */
+ private refocus(delay = 120) {
+ clearTimeout(this.focusTimer);
+ this.focusTimer = setTimeout(() => {
+ if (this.disposed || !this.info) return;
+ const d = this.surfaceAhead() ?? focusDistance(this.sample, this.pose) ?? this.info.pivotDepth;
+ if (Math.abs(d - this.focus) > 1e-4) {
+ this.focus = d;
+ this.dirty = true;
+ this.onFocus?.(d);
+ }
+ }, delay);
+ }
+
+ /** A mesh's surface straight ahead (a low-poly model has too few vertices to sample). */
+ private surfaceAhead(): number | null {
+ if (!this.model) return null;
+ const cam = this.camera;
+ cam.position.set(...this.pose.position);
+ cam.rotation.set(this.pose.pitch, this.pose.yaw, 0, "YXZ");
+ cam.updateMatrixWorld();
+ this.raycaster.setFromCamera(new THREE.Vector2(0, 0), cam);
+ return this.raycaster.intersectObject(this.model, true)[0]?.distance ?? null;
+ }
+
+ // ---- Drawing
+
+ private step(dt: number) {
+ if (this.info && this.view && this.keys.size) {
+ const input = keysToInput(this.keys);
+ if (input.forward || input.right || input.up) {
+ this.pose = flyStep(this.pose, input, dt, flySpeed(this.info.pivotDepth) * this.view.speed, this.boost);
+ this.dirty = true;
+ this.refocus();
+ }
+ }
+ if (this.dirty && this.view && this.info) {
+ this.dirty = false;
+ this.draw(null, Math.round(this.size.w * this.size.dpr), Math.round(this.size.h * this.size.dpr), this.view.frame.width * this.size.dpr, this.view.frame.height * this.size.dpr);
+ }
+ }
+
+ /** Render into `out` (null = the screen) at w×h px; the frame is frameW×frameH px of it, centred. */
+ private draw(out: THREE.WebGLRenderTarget | null, w: number, h: number, frameW: number, frameH: number, color = this.target) {
+ const v = this.view!;
+ const cam = this.camera;
+ const frameFov = lensFov(v.lens, v.aspect).v;
+ cam.fov = canvasFov(frameFov, frameH, h);
+ cam.aspect = w / h;
+ cam.position.set(...this.pose.position);
+ cam.rotation.set(this.pose.pitch, this.pose.yaw, 0, "YXZ");
+ cam.updateProjectionMatrix();
+ cam.updateMatrixWorld();
+ if (this.pointsMat) this.pointsMat.uniforms.scale.value = h / 2 / Math.tan((cam.fov * Math.PI) / 360);
+ this.renderer.setRenderTarget(color);
+ this.renderer.clear();
+ this.renderer.render(this.scene, cam);
+ const u = this.postMat.uniforms;
+ u.tColor.value = color.texture;
+ u.tDepth.value = color.depthTexture;
+ u.texel.value.set(1 / w, 1 / h);
+ u.cameraNear.value = cam.near;
+ u.cameraFar.value = cam.far;
+ u.focus.value = this.focus;
+ u.blur.value = v.dof ? blurScale(v.lens, v.aperture, this.focus, v.aspect) : 0;
+ u.framePx.value = frameW;
+ u.maxRadius.value = Math.min(0.025 * frameW, 48);
+ this.renderer.setRenderTarget(out);
+ this.post.render(this.renderer);
+ }
+
+ /** What the frame shows, rendered at width×height (the frame's ratio), as a PNG. */
+ async capture(width: number, height: number): Promise<Blob> {
+ if (!this.view || !this.info) throw new Error("The scene isn't ready yet");
+ const color = new THREE.WebGLRenderTarget(width, height, { type: this.target.texture.type, depthTexture: new THREE.DepthTexture(width, height) });
+ const out = new THREE.WebGLRenderTarget(width, height);
+ try {
+ this.draw(out, width, height, width, height, color);
+ const buf = new Uint8Array(width * height * 4);
+ this.renderer.readRenderTargetPixels(out, 0, 0, width, height, buf);
+ const img = new ImageData(width, height);
+ // WebGL reads bottom-up.
+ for (let y = 0; y < height; y++) img.data.set(buf.subarray((height - 1 - y) * width * 4, (height - y) * width * 4), y * width * 4);
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ canvas.getContext("2d")!.putImageData(img, 0, 0);
+ const blob = await new Promise<Blob | null>((r) => canvas.toBlob(r, "image/png"));
+ if (!blob) throw new Error("Couldn't save the capture");
+ return blob;
+ } finally {
+ color.depthTexture?.dispose();
+ color.dispose();
+ out.dispose();
+ this.renderer.setRenderTarget(null);
+ this.dirty = true;
+ }
+ }
+
+ dispose() {
+ this.disposed = true;
+ cancelAnimationFrame(this.raf);
+ clearTimeout(this.focusTimer);
+ this.scene.traverse((o) => {
+ const m = o as THREE.Mesh;
+ m.geometry?.dispose();
+ for (const mat of (Array.isArray(m.material) ? m.material : m.material ? [m.material] : []) as THREE.MeshBasicMaterial[]) {
+ mat.map?.dispose();
+ mat.dispose();
+ }
+ });
+ this.target.depthTexture?.dispose();
+ this.target.dispose();
+ this.postMat.dispose();
+ this.post.dispose();
+ this.renderer.dispose();
+ this.renderer.forceContextLoss();
+ }
+}
diff --git a/src/components/cinema/scene-viewer.tsx b/src/components/cinema/scene-viewer.tsx
new file mode 100644
index 00000000..1c73fcd7
--- /dev/null
+++ b/src/components/cinema/scene-viewer.tsx
@@ -0,0 +1,542 @@
+"use client";
+
+import { Box, Camera, CircleHelp, Loader2, RotateCcw, SlidersHorizontal, X } from "lucide-react";
+import { useEffect, useId, 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 { Kbd } from "@/components/ui/kbd";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
+import { Slider } from "@/components/ui/slider";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { uploadFile } from "@/lib/api";
+import { getModel } from "@/lib/catalog";
+import { IMAGE_ASPECTS, RECOMPOSE_MODELS, planCinema, type CinemaGenerateInput, type DirectorSettings } from "@/lib/catalog/cinema";
+import type { Engine } from "@/lib/catalog/types";
+import { APERTURE, FLY_KEYS, F_STOPS, LENS, LENS_STOPS, captureSize, formatStop, frameRect, ratioOf, scenePose, twoFinger, type Rect } from "@/lib/scene3d";
+import { cn } from "@/lib/utils";
+import { useCinemaGenerate } from "./hooks";
+import { usePlanPrice, type SceneTake } from "./scene-actions";
+import type { SceneEngine, SceneInfo } from "./scene-engine";
+
+/**
+ * The full-screen 3D scene viewer (Higgsfield's "3D Scene", higgsfield-delta-4.md §4.4): fly with W A S D Q E
+ * (Shift faster), drag to look, scroll or pinch to move, two fingers to slide; a full-frame lens (18–300 mm),
+ * an aperture that previews the depth of field, the project's frame ratios, and Capture, which renders the
+ * frame to a PNG, uploads it and queues the recomposition as a new take next to the scene.
+ */
+
+export interface SceneViewerProps {
+ take: SceneTake;
+ projectId: string;
+ engine: Engine;
+ onEngine: (e: Engine) => void;
+ settings: DirectorSettings;
+ context: { higgsfield: boolean; cloudAllowed: boolean };
+ brief: string;
+ onClose: () => void;
+}
+
+const SPEEDS = [
+ { value: 0.4, label: "Slow" },
+ { value: 1, label: "Normal" },
+ { value: 2.5, label: "Fast" },
+];
+const LN_MIN = Math.log(LENS.min);
+const LN_MAX = Math.log(LENS.max);
+/** The lens slider is logarithmic, so 18–85 mm gets as much room as 85–300 mm. */
+const lensToPos = (mm: number) => Math.round(((Math.log(mm) - LN_MIN) / (LN_MAX - LN_MIN)) * 1000);
+const posToLens = (pos: number) => Math.round(Math.exp(LN_MIN + (pos / 1000) * (LN_MAX - LN_MIN)));
+const clampLens = (mm: number) => Math.max(LENS.min, Math.min(LENS.max, Math.round(mm)));
+/** What the planner needs to price a recomposition before anything is captured. */
+const PLACEHOLDER_CAPTURE = "/api/files/placeholder.png";
+
+const isTyping = (t: EventTarget | null) => {
+ const el = t as HTMLElement | null;
+ return !!el && (el.isContentEditable || !!el.closest?.("input,textarea,select,[contenteditable]"));
+};
+
+function errorText(e: unknown): string {
+ const m = (e as Error)?.message ?? "";
+ if (/webgl|context/i.test(m)) return "This browser can't show 3D here (WebGL is off or unavailable). Try another browser, or turn on hardware acceleration.";
+ return m || "Couldn't load the scene";
+}
+
+function Section({ title, value, children }: { title: string; value?: React.ReactNode; children: React.ReactNode }) {
+ return (
+ <section className="space-y-2.5">
+ <div className="flex items-baseline justify-between gap-2">
+ <h3 className="text-[12px] font-medium tracking-wide text-muted-foreground uppercase">{title}</h3>
+ {value !== undefined && <span className="font-mono text-[12.5px]">{value}</span>}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+export default function SceneViewer({ take, projectId, engine, onEngine, settings, context, brief, onClose }: 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);
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ const engineRef = useRef<SceneEngine | null>(null);
+ const sizeRef = useRef({ w: 0, h: 0 });
+ const pointers = useRef(new Map<number, { x: number; y: number }>());
+ const [coarse] = useState(() => typeof window !== "undefined" && window.matchMedia("(pointer: coarse)").matches);
+ const [status, setStatus] = useState<"loading" | "ready" | "error">("loading");
+ const [error, setError] = useState("");
+ const [attempt, setAttempt] = useState(0);
+ const [info, setInfo] = useState<SceneInfo | null>(null);
+ const [stage, setStage] = useState({ w: 0, h: 0 });
+ const [lens, setLens] = useState<number>(LENS.default);
+ const [aperture, setAperture] = useState<number>(APERTURE.default);
+ const [aspect, setAspect] = useState(take.aspect);
+ const [dof, setDof] = useState(true);
+ const [speed, setSpeed] = useState(1);
+ const [focus, setFocus] = useState<number | null>(null);
+ const [help, setHelp] = useState(true);
+ const [panelOpen, setPanelOpen] = useState(false);
+ const [picked, setPicked] = useState<string>(RECOMPOSE_MODELS[engine][0]);
+ const [note, setNote] = useState("");
+ const [capturing, setCapturing] = useState(false);
+ const [flash, setFlash] = useState(false);
+ const [queued, setQueued] = useState(0);
+ const generate = useCinemaGenerate(take.generation.projectId ?? projectId);
+ const noteId = useId();
+
+ const models = RECOMPOSE_MODELS[engine];
+ const modelId = models.includes(picked) ? picked : models[0];
+ const input: Omit<CinemaGenerateInput, "brief"> = useMemo(
+ () => ({ engine, mode: "image", action: "recompose", modelId, prompt: note, settings, source: { url: take.still, kind: "image" }, aspectRatio: aspect }),
+ [engine, modelId, note, settings, take.still, aspect],
+ );
+ const plan = useMemo(
+ () => planCinema({ ...input, brief, capture: { url: PLACEHOLDER_CAPTURE, lens, aperture, pose: { horizontal: 0, vertical: 0, zoom: 5 } } }, context),
+ [input, brief, context, lens, aperture],
+ );
+ const price = usePlanPrice(plan);
+
+ // The frame: the ratio's largest rectangle, centred, leaving room for the bars over the view.
+ const frame: Rect | null = useMemo(() => {
+ if (!stage.w || !stage.h) return null;
+ const mx = stage.w < 640 ? 12 : 32;
+ const my = stage.w < 640 ? 56 : 68;
+ const r = frameRect(stage.w - 2 * mx, stage.h - 2 * my, ratioOf(aspect));
+ return { ...r, x: r.x + mx, y: r.y + my };
+ }, [stage, aspect]);
+
+ // Load three.js and the scene (again on Try again, which mounts a fresh canvas).
+ useEffect(() => {
+ const canvas = canvasEl;
+ if (!canvas) return;
+ const ctl = new AbortController();
+ let eng: SceneEngine | null = null;
+ import("./scene-engine")
+ .then(async ({ SceneEngine }) => {
+ if (ctl.signal.aborted) return;
+ eng = new SceneEngine(canvas);
+ engineRef.current = eng;
+ eng.onFocus = setFocus;
+ const { w, h } = sizeRef.current;
+ if (w && h) eng.resize(w, h, Math.min(window.devicePixelRatio || 1, coarse ? 1.5 : 2));
+ const loaded = await eng.load(take.source, { maxPoints: coarse ? 150_000 : 400_000, signal: ctl.signal });
+ if (ctl.signal.aborted) return;
+ setInfo(loaded);
+ setLens(clampLens(loaded.photoLens));
+ setStatus("ready");
+ })
+ .catch((e) => {
+ if (ctl.signal.aborted) return;
+ setError(errorText(e));
+ setStatus("error");
+ });
+ return () => {
+ ctl.abort();
+ eng?.dispose();
+ engineRef.current = null;
+ };
+ }, [take.source, canvasEl, coarse]);
+
+ useEffect(() => {
+ const el = stageEl;
+ if (!el) return;
+ // Layout size, not getBoundingClientRect: the dialog opens with a zoom, which a transform-aware size would keep.
+ const measure = () => {
+ const r = { width: el.clientWidth, height: el.clientHeight };
+ sizeRef.current = { w: r.width, h: r.height };
+ setStage({ w: r.width, h: r.height });
+ engineRef.current?.resize(r.width, r.height, Math.min(window.devicePixelRatio || 1, coarse ? 1.5 : 2));
+ };
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ measure();
+ return () => ro.disconnect();
+ }, [stageEl, coarse]);
+
+ useEffect(() => {
+ if (frame && status === "ready") engineRef.current?.setView({ lens, aperture, aspect: ratioOf(aspect), dof, frame, speed });
+ }, [lens, aperture, aspect, dof, frame, speed, status]);
+
+ // W A S D Q E fly from anywhere in the viewer except a text field; arrows and R act on the focused view.
+ useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ const eng = engineRef.current;
+ if (!eng) return;
+ eng.setBoost(e.shiftKey);
+ if (e.metaKey || e.ctrlKey || e.altKey || isTyping(e.target)) return;
+ if (FLY_KEYS.has(e.code)) {
+ e.preventDefault();
+ eng.key(e.code, true);
+ return;
+ }
+ if (e.target !== canvasRef.current) return;
+ const turn: Record<string, [number, number]> = { ArrowLeft: [3, 0], ArrowRight: [-3, 0], ArrowUp: [0, 3], ArrowDown: [0, -3] };
+ if (turn[e.key]) {
+ e.preventDefault();
+ eng.turn(...turn[e.key]);
+ } else if (e.code === "KeyR") eng.reset();
+ };
+ const up = (e: KeyboardEvent) => {
+ engineRef.current?.key(e.code, false);
+ engineRef.current?.setBoost(e.shiftKey);
+ };
+ const release = () => engineRef.current?.releaseKeys();
+ window.addEventListener("keydown", down);
+ window.addEventListener("keyup", up);
+ window.addEventListener("blur", release);
+ document.addEventListener("visibilitychange", release);
+ return () => {
+ window.removeEventListener("keydown", down);
+ window.removeEventListener("keyup", up);
+ window.removeEventListener("blur", release);
+ document.removeEventListener("visibilitychange", release);
+ };
+ }, []);
+
+ const resetView = () => {
+ engineRef.current?.reset();
+ if (info) setLens(clampLens(info.photoLens));
+ };
+
+ const capture = async () => {
+ const eng = engineRef.current;
+ if (!eng || !info || capturing) return;
+ const blocker = plan.blocker && plan.blocker !== "Capture a view first" ? plan.blocker : undefined;
+ if (blocker) {
+ toast.error(blocker);
+ return;
+ }
+ setCapturing(true);
+ setFlash(true);
+ setTimeout(() => setFlash(false), 180);
+ try {
+ const { width, height } = captureSize(ratioOf(aspect));
+ const blob = await eng.capture(width, height);
+ const asset = await uploadFile(new File([blob], "capture.png", { type: "image/png" }));
+ const pose = scenePose(eng.getPose(), lens, info.photoLens, info.pivotDepth);
+ await generate.mutateAsync({ input: { ...input, capture: { url: asset.url, lens, aperture, pose } }, folderId: take.generation.folderId });
+ setQueued((n) => n + 1);
+ toast.success("Re-rendering this view — it lands next to the scene as a new take", { duration: 3000 });
+ } catch (e) {
+ toast.error((e as Error).message || "Couldn't capture this view");
+ } finally {
+ setCapturing(false);
+ }
+ };
+
+ const kind = info?.kind ?? take.source.kind;
+ const sizeText = info ? `${info.size >= 1000 ? `${Math.round(info.size / 1000)}k` : info.size} ${info.kind === "points" ? "points" : "triangles"}` : null;
+ const captureLabel = capturing ? "Capturing…" : "Capture";
+
+ const camera = (
+ <div className="space-y-6">
+ <Section title="Lens" value={`${lens} mm`}>
+ <Slider
+ min={0}
+ max={1000}
+ step={1}
+ value={[lensToPos(lens)]}
+ onValueChange={([v]) => setLens(clampLens(posToLens(v)))}
+ aria-label="Lens focal length"
+ aria-valuetext={`${lens} millimetres`}
+ />
+ <div className="flex flex-wrap gap-1" role="group" aria-label="Lens presets">
+ {LENS_STOPS.map((mm) => (
+ <button
+ key={mm}
+ type="button"
+ aria-pressed={lens === mm}
+ onClick={() => setLens(mm)}
+ className={cn("h-7 rounded-full px-2.5 font-mono text-[11.5px]", lens === mm ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}
+ >
+ {mm}
+ </button>
+ ))}
+ </div>
+ </Section>
+ <Section title="Aperture" value={`f/${formatStop(aperture)}`}>
+ <Slider
+ min={0}
+ max={F_STOPS.length - 1}
+ step={1}
+ value={[Math.max(0, F_STOPS.indexOf(aperture))]}
+ onValueChange={([i]) => setAperture(F_STOPS[i])}
+ aria-label="Aperture"
+ aria-valuetext={`f/${formatStop(aperture)}`}
+ />
+ <label className="flex items-center justify-between gap-3 text-[13px]">
+ <span>
+ Preview depth of field
+ <span className="block text-[11.5px] text-muted-foreground">{focus ? `Focused at ${focus.toFixed(1)} m, on the centre of the frame` : "Focuses on the centre of the frame"}</span>
+ </span>
+ <Switch checked={dof} onCheckedChange={setDof} aria-label="Preview depth of field" />
+ </label>
+ </Section>
+ <Section title="Frame" value={aspect}>
+ <div className="grid grid-cols-4 gap-1" role="radiogroup" aria-label="Frame ratio">
+ {IMAGE_ASPECTS.map((a) => (
+ <button
+ key={a}
+ type="button"
+ role="radio"
+ aria-checked={aspect === a}
+ onClick={() => setAspect(a)}
+ className={cn("h-8 rounded-lg font-mono text-[11.5px]", aspect === a ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}
+ >
+ {a}
+ </button>
+ ))}
+ </div>
+ </Section>
+ <Section title="Speed">
+ <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="radiogroup" aria-label="Flying speed">
+ {SPEEDS.map((s) => (
+ <button
+ key={s.label}
+ type="button"
+ role="radio"
+ aria-checked={speed === s.value}
+ onClick={() => setSpeed(s.value)}
+ className={cn("rounded-full px-3 text-[12.5px] font-medium", speed === s.value ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {s.label}
+ </button>
+ ))}
+ </div>
+ </Section>
+ </div>
+ );
+
+ const rerender = (
+ <div className="space-y-3">
+ <Section title="Re-render">
+ <EngineSwitch value={engine} onChange={onEngine} size="sm" />
+ {models.length > 1 ? (
+ <Select value={modelId} onValueChange={setPicked}>
+ <SelectTrigger className="w-full" aria-label="Re-render with">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {models.map((id) => (
+ <SelectItem key={id} value={id}>
+ {getModel(id)?.name ?? id}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <p className="text-[13px]">{getModel(modelId)?.name} + Multiple-Angles LoRA</p>
+ )}
+ <label htmlFor={noteId} className="sr-only">
+ Anything to change (optional)
+ </label>
+ <Textarea id={noteId} value={note} onChange={(e) => setNote(e.target.value)} placeholder="Anything to change? (optional) e.g. “golden hour”" className="min-h-16 text-[13px]" maxLength={2000} />
+ {plan.notes.map((n) => (
+ <p key={n} className="text-[12px] leading-snug text-muted-foreground">
+ {n}
+ </p>
+ ))}
+ </Section>
+ </div>
+ );
+
+ const captureButton = (className?: string) => (
+ <Button onClick={() => void capture()} disabled={status !== "ready" || capturing} className={cn("rounded-full", className)}>
+ {capturing ? <Loader2 className="animate-spin" /> : <Camera />} {captureLabel} <span className="opacity-80">· {price.label}</span>
+ </Button>
+ );
+
+ return (
+ <Dialog open onOpenChange={(v) => !v && onClose()}>
+ <DialogContent
+ showCloseButton={false}
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ canvasRef.current?.focus();
+ }}
+ 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"
+ >
+ <DialogTitle className="sr-only">3D scene</DialogTitle>
+ <DialogDescription className="sr-only">Fly the camera through the scene, frame a view and capture it to re-render it as a new take.</DialogDescription>
+ <div ref={setStageEl} className="relative min-h-0 min-w-0 flex-1 overflow-hidden bg-[#0b0b0c]">
+ <canvas
+ key={attempt}
+ ref={(el) => {
+ canvasRef.current = el;
+ setCanvasEl(el);
+ }}
+ tabIndex={0}
+ role="application"
+ aria-roledescription="3D view"
+ aria-label="3D scene. W A S D to move, Q and E to go down and up, Shift to go faster, arrow keys to look around, R to reset the view."
+ className="absolute inset-0 size-full cursor-grab touch-none outline-none active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
+ onPointerDown={(e) => {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ }}
+ onPointerMove={(e) => {
+ const map = pointers.current;
+ const prev = map.get(e.pointerId);
+ const eng = engineRef.current;
+ if (!prev || !eng) return;
+ // The scene follows the pointer: drag right and the view turns left.
+ if (map.size === 1) {
+ map.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ eng.look(-(e.clientX - prev.x), -(e.clientY - prev.y));
+ return;
+ }
+ const ids = [...map.keys()].slice(0, 2);
+ if (!ids.includes(e.pointerId)) return;
+ const before = ids.map((id) => map.get(id)!) as [{ x: number; y: number }, { x: number; y: number }];
+ map.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ const after = ids.map((id) => map.get(id)!) as [{ x: number; y: number }, { x: number; y: number }];
+ const g = twoFinger(before, after);
+ eng.pan(g.dx, g.dy);
+ if (g.scale !== 1) eng.dolly(Math.log(g.scale) * 0.8);
+ }}
+ onPointerUp={(e) => pointers.current.delete(e.pointerId)}
+ onPointerCancel={(e) => pointers.current.delete(e.pointerId)}
+ onWheel={(e) => engineRef.current?.dolly(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0015))}
+ />
+ {frame && (
+ <div
+ aria-hidden
+ className={cn("pointer-events-none absolute rounded-[2px] border border-white/70 transition-[background-color] duration-150", flash && "bg-white/60")}
+ style={{ left: frame.x, top: frame.y, width: frame.width, height: frame.height, boxShadow: "0 0 0 100vmax rgba(0,0,0,0.55)" }}
+ >
+ <span className="absolute top-1.5 left-1.5 rounded bg-black/45 px-1.5 py-0.5 font-mono text-[11px] whitespace-nowrap text-white/90">
+ {aspect} · {lens} mm · f/{formatStop(aperture)}
+ </span>
+ </div>
+ )}
+
+ <div className="absolute inset-x-0 top-0 flex items-center gap-2 bg-gradient-to-b from-black/70 to-transparent px-3 pt-2.5 pb-6 text-white sm:px-4">
+ <Box className="size-4 shrink-0" aria-hidden />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[14px] font-medium">3D scene</p>
+ <p className="truncate text-[11.5px] text-white/70">
+ {kind === "points" ? "Point cloud from a depth map" : info?.layout === "object" ? "3D model" : "MoGe 2 mesh"}
+ {sizeText ? ` · ${sizeText}` : ""}
+ {queued ? ` · ${queued} re-render${queued > 1 ? "s" : ""} queued` : ""}
+ </p>
+ </div>
+ <button type="button" onClick={() => setHelp((v) => !v)} aria-pressed={help} aria-label="Controls" className="grid size-9 place-items-center rounded-full hover:bg-white/15">
+ <CircleHelp className="size-[18px]" />
+ </button>
+ <button type="button" onClick={resetView} aria-label="Reset the view to the still" className="grid size-9 place-items-center rounded-full hover:bg-white/15">
+ <RotateCcw className="size-[18px]" />
+ </button>
+ <button type="button" onClick={onClose} aria-label="Close the 3D scene" className="grid size-9 place-items-center rounded-full hover:bg-white/15">
+ <X className="size-5" />
+ </button>
+ </div>
+
+ {help && status === "ready" && (
+ <div className="absolute bottom-3 left-3 max-w-[calc(100%-1.5rem)] rounded-xl bg-black/65 px-3 py-2 text-[12px] leading-relaxed text-white/90 backdrop-blur">
+ {coarse ? (
+ <p>Drag to look · two fingers to move · pinch to go forward or back</p>
+ ) : (
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span>
+ <Kbd>W</Kbd> <Kbd>A</Kbd> <Kbd>S</Kbd> <Kbd>D</Kbd> move
+ </span>
+ <span>
+ <Kbd>Q</Kbd> <Kbd>E</Kbd> down / up
+ </span>
+ <span>
+ <Kbd>Shift</Kbd> faster
+ </span>
+ <span>drag to look · scroll to go forward</span>
+ </p>
+ )}
+ </div>
+ )}
+
+ {status !== "ready" && (
+ <div className="absolute inset-0 grid place-items-center p-6 text-center text-white" role="status">
+ {status === "loading" ? (
+ <p className="flex items-center gap-2 text-[14px]">
+ <Loader2 className="size-4 animate-spin" /> {take.source.kind === "points" ? "Building the point cloud from the depth map…" : "Loading the 3D scene…"}
+ </p>
+ ) : (
+ <div className="max-w-sm space-y-3">
+ <p className="text-[14px]">{error}</p>
+ <div className="flex justify-center gap-2">
+ <Button
+ variant="secondary"
+ onClick={() => {
+ setStatus("loading");
+ setInfo(null);
+ setAttempt((n) => n + 1);
+ }}
+ >
+ Try again
+ </Button>
+ <Button variant="ghost" className="text-white hover:bg-white/15 hover:text-white" onClick={onClose}>
+ Close
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Phones: the capture stays in reach; the camera and re-render settings open in a sheet. */}
+ <div className="flex shrink-0 items-center gap-2 border-t border-white/10 bg-[#0b0b0c] px-3 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] md:hidden">
+ <Button variant="secondary" className="rounded-full" onClick={() => setPanelOpen(true)}>
+ <SlidersHorizontal /> Camera
+ </Button>
+ {captureButton("min-w-0 flex-1")}
+ </div>
+ <Sheet open={panelOpen} onOpenChange={setPanelOpen}>
+ <SheetContent side="bottom" className="max-h-[75svh] gap-0 overflow-y-auto rounded-t-2xl p-0 md:hidden">
+ <SheetHeader className="border-b px-4 py-3">
+ <SheetTitle className="font-heading text-[20px] font-normal">Camera</SheetTitle>
+ <SheetDescription className="sr-only">Lens, aperture, frame and how the capture is re-rendered</SheetDescription>
+ </SheetHeader>
+ <div className="space-y-6 p-4">
+ {camera}
+ {rerender}
+ {captureButton("w-full")}
+ </div>
+ </SheetContent>
+ </Sheet>
+
+ <aside className="hidden w-[320px] shrink-0 flex-col border-l bg-background md:flex" aria-label="Camera and re-render">
+ <div className="min-h-0 flex-1 space-y-6 overflow-y-auto p-4">
+ {camera}
+ {rerender}
+ </div>
+ <div className="space-y-1.5 border-t p-4">
+ {captureButton("w-full")}
+ <p className="text-center text-[11.5px] text-muted-foreground">Renders the frame, then re-renders it as a new take next to the scene</p>
+ </div>
+ </aside>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsx
index 3f278285..ab661f18 100644
--- a/src/components/cinema/workspace.tsx
+++ b/src/components/cinema/workspace.tsx
@@ -2,6 +2,7 @@
import { Bot, ChevronLeft, Clapperboard, Copy, FileText, Folder, FolderOpen, FolderTree, Heart, Library, MoreHorizontal, Pin, PinOff, Settings2, Upload } from "lucide-react";
import { nanoid } from "nanoid";
+import dynamic from "next/dynamic";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
@@ -25,13 +26,24 @@ import { initialDraft, type CinemaDraft } from "./draft";
import { ElementsPanel } from "./elements-panel";
import { FolderSidebar, subtree, viewKey, type CinemaView } from "./folder-sidebar";
import { formatUsd } from "./money";
-import { useAutosave, useCinemaItems, useCinemaProject, useItemActions, useStudioGenerations, useUpdateProject, type CinemaGeneration, type ProjectView } from "./hooks";
+import { foreign, useAutosave, useCinemaGenerate, useCinemaItems, useCinemaProject, useItemActions, useStudioGenerations, useUpdateProject, type CinemaGeneration, type ProjectView } from "./hooks";
import { cutGrid } from "./media";
import { ProjectDialog } from "./project-settings";
import { PromptBar, useAddRefs } from "./prompt-bar";
+import { SceneCreateDialog, sceneTake, skipSceneConfirm, usePlanPrice, useScenePlan, type SceneTake } from "./scene-actions";
import { SidePanel } from "./side-panel";
import { SoulCastDialog, SoulLocationDialog } from "./soul-builders";
+/** The 3D viewer (and three.js inside it) loads when a scene is opened. */
+const SceneViewer = dynamic(() => import("./scene-viewer"), {
+ ssr: false,
+ loading: () => (
+ <div className="fixed inset-0 z-50 grid place-items-center bg-[#0b0b0c] text-[14px] text-white" role="status">
+ Opening the 3D scene…
+ </div>
+ ),
+});
+
function useMedia(query: string): boolean {
return useSyncExternalStore(
(cb) => {
@@ -69,6 +81,9 @@ function nameFrom(prompt: string | undefined, fallback: string): string {
return words.slice(0, 3).map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join(" ") || fallback;
}
+/** Any still prices "Create 3D scene" the same: the menu shows it before one is picked. */
+const ANY_STILL = "/api/files/placeholder.png";
+
const DRAFT_KEY = (id: string) => `fuobe.cinema.draft.${id}`;
const KEPT = ["mode", "imageTool", "prompt", "moves", "models", "duration", "resolution", "aspect", "batch", "audio", "multiShot", "grid"] as const;
@@ -191,6 +206,41 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
const addRefs = useAddRefs((fn) => setDraft(fn));
useGridTiles(id, items);
+ // 3D scenes: "Create 3D scene" on a still (priced, asks first), the viewer, and a toast when one is built.
+ const generate = useCinemaGenerate(id);
+ const [sceneFrom, setSceneFrom] = useState<{ g: CinemaGeneration; url: string } | null>(null);
+ const [openScene, setOpenScene] = useState<SceneTake | null>(null);
+ const sceneCtx = useMemo(() => ({ engine, settings, context, brief: project.brief.body }), [engine, settings, context, project.brief.body]);
+ const scenePrice = usePlanPrice(useScenePlan(ANY_STILL, undefined, sceneCtx)).label;
+ const scenePlan = useScenePlan(sceneFrom?.url ?? null, sceneFrom?.g.request.params?.aspectRatio, sceneCtx);
+ const building = useRef(new Set<string>());
+ const createScene = (g: CinemaGeneration, url: string) => {
+ setSceneFrom(null);
+ generate.mutate(
+ {
+ input: { engine, mode: "image", action: "scene", prompt: "", settings, source: { url, kind: "image" }, aspectRatio: g.request.params?.aspectRatio },
+ folderId: foreign(g, id) ? null : g.folderId,
+ },
+ {
+ onSuccess: (r) => {
+ r.items.forEach((x) => building.current.add(x.id));
+ toast(engine === "open" ? "Building the 3D scene on your ComfyUI…" : "Building the 3D scene…", { description: "It appears next to the still; you'll get a note when it's ready.", duration: 3000 });
+ },
+ onError: (e) => toast.error((e as Error).message),
+ },
+ );
+ };
+ useEffect(() => {
+ for (const gid of [...building.current]) {
+ const g = items.find((x) => x.id === gid);
+ if (!g || g.status === "queued" || g.status === "running") continue;
+ building.current.delete(gid);
+ const t = sceneTake(g);
+ if (t) toast.success("Your 3D scene is ready", { action: { label: "Open", onClick: () => setOpenScene(t) }, duration: 8000 });
+ else toast.error(`The 3D scene couldn't be built${g.error ? `: ${g.error}` : ""}`);
+ }
+ }, [items]);
+
const currentView: CinemaView = useMemo(() => (view.kind === "folder" && !folders.some((f) => f.id === view.id) ? { kind: "home" } : view), [view, folders]);
const folderId = currentView.kind === "folder" ? currentView.id : null;
const shown = useMemo(() => {
@@ -250,6 +300,13 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
onError: (e) => toast.error((e as Error).message),
},
),
+ onCreateScene: (g, url) => (skipSceneConfirm() ? createScene(g, url) : setSceneFrom({ g, url })),
+ onOpenScene: (g) => {
+ const t = sceneTake(g);
+ if (t) setOpenScene(t);
+ else toast("This 3D scene isn't ready yet");
+ },
+ scenePrice,
};
const onLoadShot = (shot: DirectorShot) => {
setDraft({ mode: "video", prompt: shot.prompt, moves: shot.moves, duration: shot.duration, source: null, action: "generate", multiShot: { mode: "off", shots: [] } });
@@ -505,6 +562,25 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
</SheetContent>
</Sheet>
+ <SceneCreateDialog
+ still={sceneFrom?.url ?? null}
+ aspect={sceneFrom?.g.request.params?.aspectRatio}
+ plan={scenePlan}
+ onOpenChange={(o) => !o && setSceneFrom(null)}
+ onConfirm={() => sceneFrom && createScene(sceneFrom.g, sceneFrom.url)}
+ />
+ {openScene && (
+ <SceneViewer
+ take={openScene}
+ projectId={id}
+ engine={engine}
+ onEngine={setEngine}
+ settings={settings}
+ context={context}
+ brief={project.brief.body}
+ onClose={() => setOpenScene(null)}
+ />
+ )}
<SoulCastDialog open={castOpen} onOpenChange={setCastOpen} {...builderProps} />
<SoulLocationDialog open={locationOpen} onOpenChange={setLocationOpen} {...builderProps} />
<ProjectDialog open={settingsOpen} onOpenChange={setSettingsOpen} project={project} spentUsd={spentUsd} onDone={() => setSettingsOpen(false)} onDeleted={() => router.push("/cinema")} />