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: add a prop to the 3D scene, an object made from a picture, with move, turn and size handles

Claude4a8090b88193
diff --git a/src/components/cinema/scene-engine.ts b/src/components/cinema/scene-engine.ts
index 92b57919..8a06a7a8 100644
--- a/src/components/cinema/scene-engine.ts
+++ b/src/components/cinema/scene-engine.ts
@@ -1,6 +1,7 @@
"use client";
import * as THREE from "three";
+import { TransformControls } from "three/examples/jsm/controls/TransformControls.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { FullScreenQuad } from "three/examples/jsm/postprocessing/Pass.js";
import { flyPoseOf, type FramePoses } from "@/lib/camera-path";
@@ -25,6 +26,8 @@ import {
type Pixels,
type Rect,
} from "@/lib/scene3d";
+import type { SceneProp } from "@/lib/scene-props";
+import type { SceneSplats } from "../model3d/splat-engine";
import type { SceneSource } from "./scene-actions";
import { encodeFrames, encodeVp8, pathVideoType, recordWithMediaRecorder, vp8Supported } from "./video-encode";
@@ -33,6 +36,10 @@ import { encodeFrames, encodeVp8, pathVideoType, recordWithMediaRecorder, vp8Sup
* built from the still and its depth map, a fly camera, the frame-fitted lens, a depth-of-field pass, the capture
* of exactly what the frame shows, and (Fly path, N7-5) a preview flight and a recording of the scene along a camera
* path. The maths is in src/lib/scene3d.ts and src/lib/camera-path.ts; this file only draws.
+ *
+ * Props (idol-9): splats placed in the scene (src/lib/scene-props.ts), drawn by idol-4's renderer (Spark, loaded only
+ * when the first prop is added) in the same scene graph, so the capture, the path render and the blockout show them.
+ * A move / turn / size handle (three's TransformControls) is drawn over the finished frame on screen only.
*/
export type { SceneSource };
@@ -182,6 +189,12 @@ async function pixelsOf(url: string, maxSide: number, signal?: AbortSignal): Pro
return ctx.getImageData(0, 0, width, height);
}
+/** How a prop's handle moves it. */
+export type PropHandle = "translate" | "rotate" | "scale";
+
+/** A prop's place, turn (degrees, Euler "YXZ") and size, as the handle left it. */
+export type PropTransform = Pick<SceneProp, "position" | "rotation" | "size">;
+
/** 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[] = [];
@@ -232,8 +245,19 @@ export class SceneEngine {
private disposed = false;
/** A path preview or recording owns the camera. */
private playing = false;
-
- constructor(canvas: HTMLCanvasElement) {
+ /** Props: their splats (Spark, once the first is added) and their groups by id. */
+ private splats: SceneSplats | null = null;
+ private splatsLoading: Promise<SceneSplats> | null = null;
+ private props = new Map<string, THREE.Group>();
+ /** The handle on the picked prop, drawn after the frame (never in a capture or a path render). */
+ private gizmo: TransformControls | null = null;
+ private overlay = new THREE.Scene();
+ /** A prop's size when the handle took it (sizes stay uniform). */
+ private sizeAtGrab = 1;
+ /** The handle moved, turned or sized a prop. */
+ onPropChange?: (id: string, t: PropTransform) => void;
+
+ constructor(private 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;
@@ -505,13 +529,7 @@ export class SceneEngine {
private draw(out: THREE.WebGLRenderTarget | null, w: number, h: number, frameW: number, frameH: number, color = this.target, shot?: { pose: FlyPose; vFov: number }) {
const v = this.view!;
const cam = this.camera;
- const pose = shot?.pose ?? this.pose;
- cam.fov = shot ? shot.vFov : canvasFov(lensFov(v.lens, v.aspect).v, frameH, h);
- cam.aspect = w / h;
- cam.position.set(...pose.position);
- cam.rotation.set(pose.pitch, pose.yaw, 0, "YXZ");
- cam.updateProjectionMatrix();
- cam.updateMatrixWorld();
+ this.poseCamera(shot?.pose ?? this.pose, shot ? shot.vFov : canvasFov(lensFov(v.lens, v.aspect).v, frameH, h), w / h);
if (this.pointsMat) this.pointsMat.uniforms.scale.value = h / 2 / Math.tan((cam.fov * Math.PI) / 360);
this.renderer.setRenderTarget(color);
this.renderer.clear();
@@ -531,6 +549,121 @@ export class SceneEngine {
u.holeRadius.value = Math.max(2, frameW / 70);
this.renderer.setRenderTarget(out);
this.post.render(this.renderer);
+ // The prop's handle, over the finished frame on screen only.
+ if (!out && !shot && this.gizmo?.object) {
+ this.renderer.autoClear = false;
+ this.renderer.clearDepth();
+ this.renderer.render(this.overlay, cam);
+ this.renderer.autoClear = true;
+ }
+ }
+
+ private poseCamera(pose: FlyPose, vFov: number, aspect: number) {
+ const cam = this.camera;
+ cam.fov = vFov;
+ cam.aspect = aspect;
+ cam.position.set(...pose.position);
+ cam.rotation.set(pose.pitch, pose.yaw, 0, "YXZ");
+ cam.updateProjectionMatrix();
+ cam.updateMatrixWorld();
+ }
+
+ // ---- Props
+
+ /** Load a prop's splat into the scene (Spark comes in with the first one); resolves with its Gaussian count. */
+ async addProp(p: SceneProp, o: { signal?: AbortSignal; maxBytes?: number } = {}): Promise<number> {
+ if (!this.splatsLoading) {
+ const loading = import("../model3d/splat-engine").then(({ SceneSplats }) => {
+ const splats = new SceneSplats(this.renderer, () => (this.dirty = true));
+ this.scene.add(splats.root);
+ this.splats = splats;
+ return splats;
+ });
+ // A failed load (offline, a chunk that didn't arrive) is tried again with the next prop.
+ loading.catch(() => (this.splatsLoading = null));
+ this.splatsLoading = loading;
+ }
+ const splats = await this.splatsLoading;
+ if (this.disposed) throw new DOMException("Closed", "AbortError");
+ const { group, splats: count } = await splats.add(p.id, p.url, p.format, { cutoff: p.cutoff, signal: o.signal, maxBytes: o.maxBytes });
+ if (this.disposed) throw new DOMException("Closed", "AbortError");
+ this.props.set(p.id, group);
+ this.updateProp(p);
+ return count;
+ }
+
+ /** Put a prop where the state says (place, turn, size, haze cut-off). */
+ updateProp(p: SceneProp) {
+ const g = this.props.get(p.id);
+ if (!g) return;
+ g.position.set(...p.position);
+ g.rotation.set(THREE.MathUtils.degToRad(p.rotation[0]), THREE.MathUtils.degToRad(p.rotation[1]), THREE.MathUtils.degToRad(p.rotation[2]), "YXZ");
+ g.scale.setScalar(p.size);
+ g.updateMatrixWorld(true);
+ this.splats?.setCutoff(p.id, p.cutoff);
+ this.dirty = true;
+ }
+
+ removeProp(id: string) {
+ const g = this.props.get(id);
+ if (!g) return;
+ if (this.gizmo?.object === g) this.gizmo.detach();
+ this.props.delete(id);
+ this.splats?.remove(id);
+ this.dirty = true;
+ }
+
+ hasProp(id: string) {
+ return this.props.has(id);
+ }
+
+ /** Put the handle on a prop (null: none), in a mode. */
+ pickProp(id: string | null, mode: PropHandle) {
+ const g = id ? this.props.get(id) : undefined;
+ if (!g) {
+ this.gizmo?.detach();
+ this.dirty = true;
+ return;
+ }
+ const gizmo = this.ensureGizmo();
+ gizmo.setMode(mode);
+ if (gizmo.object !== g) gizmo.attach(g);
+ this.dirty = true;
+ }
+
+ /** The pointer is on the handle or dragging it (the view's own drag-to-look waits). */
+ handleActive(): boolean {
+ return !!this.gizmo?.object && (this.gizmo.dragging || this.gizmo.axis !== null);
+ }
+
+ private propIdOf(g: THREE.Object3D | undefined): string | undefined {
+ for (const [id, v] of this.props) if (v === g) return id;
+ return undefined;
+ }
+
+ private ensureGizmo(): TransformControls {
+ if (this.gizmo) return this.gizmo;
+ const gizmo = new TransformControls(this.camera, this.canvas);
+ gizmo.setSpace("world");
+ gizmo.addEventListener("change", () => (this.dirty = true));
+ gizmo.addEventListener("mouseDown", () => (this.sizeAtGrab = gizmo.object?.scale.x ?? 1));
+ gizmo.addEventListener("objectChange", () => {
+ const g = gizmo.object;
+ const id = this.propIdOf(g);
+ if (!g || !id) return;
+ // Sizes stay uniform: whichever axis the handle moved most sets all three.
+ const s = g.scale;
+ const from = this.sizeAtGrab;
+ const size = Math.max(1e-3, Math.abs([s.x, s.y, s.z].reduce((a, b) => (Math.abs(b - from) > Math.abs(a - from) ? b : a), s.x)));
+ g.scale.setScalar(size);
+ const r = new THREE.Euler().setFromQuaternion(g.quaternion, "YXZ");
+ const deg = (x: number) => Math.round(THREE.MathUtils.radToDeg(x) * 10) / 10;
+ const r4 = (x: number) => Math.round(x * 1e4) / 1e4;
+ this.onPropChange?.(id, { position: [r4(g.position.x), r4(g.position.y), r4(g.position.z)], rotation: [deg(r.x), deg(r.y), deg(r.z)], size: r4(size) });
+ });
+ this.overlay.add(gizmo.getHelper());
+ this.gizmo = gizmo;
+ return gizmo;
}
/** What the frame shows, rendered at width×height (the frame's ratio), as a PNG. */
@@ -585,9 +718,18 @@ export class SceneEngine {
const render = new ImageData(width, height);
const mask = o.mask ? new ImageData(width, height) : null;
const images = mask ? [render, mask] : [render];
- /** Frame i into `render` (and `mask`): WebGL reads bottom-up, and a pixel nothing covered is transparent black. */
- const frame = (i: number) => {
- this.draw(out, width, height, width, height, color, { pose: flyPoseOf(poses[i]), vFov });
+ /**
+ * Frame i into `render` (and `mask`): WebGL reads bottom-up, and a pixel nothing covered is transparent black. With
+ * props, their splats are sorted for this frame's camera first.
+ */
+ const frame = async (i: number) => {
+ const pose = flyPoseOf(poses[i]);
+ if (this.splats?.size) {
+ this.poseCamera(pose, vFov, width / height);
+ await this.splats.settle(this.scene, this.camera);
+ stop();
+ }
+ this.draw(out, width, height, width, height, color, { pose, vFov });
this.renderer.readRenderTargetPixels(out, 0, 0, width, height, buf);
for (let y = 0; y < height; y++) {
const src = (height - 1 - y) * width * 4;
@@ -614,21 +756,33 @@ export class SceneEngine {
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);
+ const out = await encodeFrames(
+ poses.length,
+ width,
+ height,
+ o.fps,
+ async (i) => {
+ stop();
+ await frame(i);
+ o.onProgress?.((i + 1) / poses.length);
+ return 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) => {
+ const [a, b] = await encodeVp8(poses.length, width, height, o.fps, images.length, async (i) => {
stop();
- frame(i);
+ await frame(i);
o.onProgress?.((i + 1) / poses.length);
return images;
});
return { render: new Blob([a as BlobPart], { type }), ...(b ? { mask: new Blob([b as BlobPart], { type }) } : {}), type, frames: poses.length };
}
- const [r, m] = await recordWithMediaRecorder(type, poses.length, width, height, o.fps, images.length, (i) => {
+ const [r, m] = await recordWithMediaRecorder(type, poses.length, width, height, o.fps, images.length, async (i) => {
stop();
- frame(i);
+ await frame(i);
o.onProgress?.((i + 1) / poses.length);
return images;
});
@@ -647,6 +801,14 @@ export class SceneEngine {
this.disposed = true;
cancelAnimationFrame(this.raf);
clearTimeout(this.focusTimer);
+ if (this.gizmo) {
+ this.gizmo.detach();
+ this.gizmo.getHelper().removeFromParent();
+ this.gizmo.dispose();
+ }
+ // Spark's objects dispose themselves (before the generic sweep below).
+ this.splats?.dispose();
+ this.props.clear();
this.scene.traverse((o) => {
const m = o as THREE.Mesh;
m.geometry?.dispose();
diff --git a/src/components/cinema/scene-props.tsx b/src/components/cinema/scene-props.tsx
new file mode 100644
index 00000000..4be8fbd1
--- /dev/null
+++ b/src/components/cinema/scene-props.tsx
@@ -0,0 +1,334 @@
+"use client";
+
+import { ArrowDownToDot, Box, FlipVertical2, Loader2, Move3d, Plus, Rotate3d, Scaling, Trash2 } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Slider } from "@/components/ui/slider";
+import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { priceLine, useRunPreview } from "@/components/model3d/hooks";
+import { useCreateGeneration, useGenerations, useStatus } from "@/lib/api";
+import { IDOL_MODELS, IDOL_QUALITIES, MODEL3D_FEATURE, model3dRequest, type IdolQuality } from "@/lib/av/model3d";
+import { getModel } from "@/lib/catalog";
+import type { Generation } from "@/lib/catalog/types";
+import { offered } from "@/lib/model-access";
+import { toastError } from "@/lib/refusals";
+import { MAX_PROPS, propCandidate, propMakerBlocker, wrapDeg, type PropCandidate, type SceneProp } from "@/lib/scene-props";
+import { cn } from "@/lib/utils";
+import type { PropHandle } from "./scene-engine";
+
+/**
+ * Props in Cinema's 3D scene (idol-9): "Add a prop" (a splat from the Library, Idol 3D and TripoSplat on either engine,
+ * or a picture made into one with Idol 3D on your GPU), and the list of placed props with their handles.
+ */
+
+export const propName = (modelId: string | undefined) => (modelId && getModel(modelId)?.name) || "3D prop";
+
+/** The features whose results can hold a splat (Image to 3D, and its app). */
+const PROP_FEATURES = [MODEL3D_FEATURE, "app:app-image-to-3d"];
+
+export function AddPropDialog({
+ open,
+ onOpenChange,
+ onPlace,
+ onMaking,
+ full,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onPlace: (c: PropCandidate & { name: string }) => void;
+ /** An Idol 3D run started from a picture: the viewer places its splat when it lands. */
+ onMaking: (generationId: string) => void;
+ /** The scene holds MAX_PROPS already. */
+ full: boolean;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[90svh] overflow-y-auto sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2 font-heading text-[22px] font-normal">
+ <Box className="size-5 text-brand-text" /> Add a prop
+ </DialogTitle>
+ <DialogDescription>Place an object made from a picture in the scene, then move, turn and size it. It shows in captures and in paths filmed on your GPU.</DialogDescription>
+ </DialogHeader>
+ {full ? <p className="rounded-lg bg-muted/60 p-3 text-[13px]">This scene has {MAX_PROPS} props, the most it holds. Remove one to add another.</p> : open && <AddPropBody onPlace={onPlace} onMaking={onMaking} />}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function AddPropBody({ onPlace, onMaking }: { onPlace: (c: PropCandidate & { name: string }) => void; onMaking: (generationId: string) => void }) {
+ const results = useGenerations({ features: PROP_FEATURES, limit: 48 });
+ const candidates = (results.data ?? []).map((g) => ({ g, c: propCandidate(g) })).filter((x): x is { g: Generation; c: PropCandidate } => !!x.c);
+ return (
+ <div className="space-y-5">
+ <section className="space-y-2" aria-labelledby="prop-library">
+ <h3 id="prop-library" className="text-[12px] font-medium tracking-wide text-muted-foreground uppercase">
+ From your Library
+ </h3>
+ {results.isLoading ? (
+ <p className="flex items-center gap-2 text-[13px] text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" /> Looking for 3D splats…
+ </p>
+ ) : candidates.length ? (
+ <ul className="grid grid-cols-3 gap-2 sm:grid-cols-4">
+ {candidates.map(({ g, c }) => {
+ const name = propName(c.modelId);
+ return (
+ <li key={g.id}>
+ <button
+ type="button"
+ onClick={() => onPlace({ ...c, name })}
+ aria-label={`Place ${name}${g.createdAt ? `, made ${new Date(g.createdAt).toLocaleDateString()}` : ""}`}
+ className="group block w-full overflow-hidden rounded-lg border bg-muted text-left outline-none hover:border-ring focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {c.poster ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={c.poster} alt="" className="aspect-square w-full object-cover" />
+ ) : (
+ <span className="grid aspect-square w-full place-items-center text-muted-foreground">
+ <Box className="size-6" aria-hidden />
+ </span>
+ )}
+ <span className="block truncate px-2 py-1 text-[11.5px]">{name}</span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <p className="text-[13px] text-muted-foreground">No 3D splats yet. Make one from a picture below, or in Image to 3D → Splat.</p>
+ )}
+ </section>
+ <MakeFromPicture onMaking={onMaking} />
+ </div>
+ );
+}
+
+function MakeFromPicture({ onMaking }: { onMaking: (generationId: string) => void }) {
+ const status = useStatus().data;
+ const create = useCreateGeneration();
+ const [photo, setPhoto] = useState<SlotValue | null>(null);
+ const [quality, setQuality] = useState<IdolQuality>("best");
+ const blocker = propMakerBlocker(status && { ...status, idolOn: offered(status.access, IDOL_MODELS.open, "open") });
+ // Idol's looser photo crop for an upload; a picture made here is framed already (idol-1's rule).
+ const req =
+ !blocker && photo && !photo.uploading
+ ? model3dRequest({ engine: "open", mode: "splat", modelId: IDOL_MODELS.open, photo: photo.ref, quality, photoCrop: photo.source !== "generation" })
+ : null;
+ const preview = useRunPreview(req);
+ const price = priceLine(preview.data) ?? "Free";
+ const make = () => {
+ if (!req) return;
+ create.mutate(req, {
+ onSuccess: (items) => {
+ const g = items[0];
+ if (g) onMaking(g.id);
+ setPhoto(null);
+ },
+ onError: (e) => toastError(e, "Couldn't start the prop"),
+ });
+ };
+ return (
+ <section className="space-y-2.5" aria-labelledby="prop-picture">
+ <h3 id="prop-picture" className="text-[12px] font-medium tracking-wide text-muted-foreground uppercase">
+ From a picture
+ </h3>
+ {blocker ? (
+ <p className="rounded-lg bg-muted/60 p-3 text-[13px]">{blocker}</p>
+ ) : (
+ <>
+ <div className="flex items-start gap-3">
+ <MediaSlot label="Picture" kind="image" value={photo} onChange={setPhoto} />
+ <div className="min-w-0 flex-1 space-y-2 text-[13px]">
+ <p>One object, whole, on a plain background works best. Idol 3D makes it on your GPU (open source), and it lands in the scene when it&apos;s ready.</p>
+ <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="radiogroup" aria-label="Idol 3D quality">
+ {IDOL_QUALITIES.map((q) => (
+ <button
+ key={q.id}
+ type="button"
+ role="radio"
+ aria-checked={quality === q.id}
+ title={q.hint}
+ onClick={() => setQuality(q.id)}
+ className={cn("rounded-full px-3 text-[12.5px] font-medium", quality === q.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {q.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ <Button className="w-full rounded-full" disabled={!req || create.isPending} onClick={make}>
+ {create.isPending ? <Loader2 className="animate-spin" /> : <Plus />} Make the prop · {price}
+ </Button>
+ </>
+ )}
+ </section>
+ );
+}
+
+/** Places the splat of each Idol 3D run started from a picture once it lands (and says so when one fails). */
+export function MakingWatch({ ids, onDone }: { ids: string[]; onDone: (id: string, g: Generation | null) => void }) {
+ const results = useGenerations({ features: PROP_FEATURES, limit: 24 });
+ const seen = useRef(new Set<string>());
+ useEffect(() => {
+ for (const g of results.data ?? []) {
+ if (!ids.includes(g.id) || seen.current.has(g.id)) continue;
+ if (g.status === "succeeded" || g.status === "failed" || g.status === "canceled") {
+ seen.current.add(g.id);
+ onDone(g.id, g.status === "succeeded" ? g : null);
+ }
+ }
+ }, [results.data, ids, onDone]);
+ return null;
+}
+
+const HANDLES: { id: PropHandle; label: string; icon: typeof Move3d }[] = [
+ { id: "translate", label: "Move", icon: Move3d },
+ { id: "rotate", label: "Turn", icon: Rotate3d },
+ { id: "scale", label: "Size", icon: Scaling },
+];
+
+/** The placed props: pick one to put the handle on it, its handle mode, size and turn, and the ways to fix it. */
+export function PropsPanel({
+ props,
+ picked,
+ onPick,
+ handle,
+ onHandle,
+ loading,
+ making,
+ sizeRange,
+ onChange,
+ onRemove,
+ onBring,
+ onTurnOver,
+ onAdd,
+ disabled,
+ note,
+}: {
+ props: SceneProp[];
+ picked: string | null;
+ onPick: (id: string | null) => void;
+ handle: PropHandle;
+ onHandle: (h: PropHandle) => void;
+ loading: Record<string, "loading" | "error">;
+ making: number;
+ sizeRange: { min: number; max: number };
+ onChange: (p: SceneProp) => void;
+ onRemove: (id: string) => void;
+ onBring: (id: string) => void;
+ onTurnOver: (id: string) => void;
+ onAdd: () => void;
+ disabled?: boolean;
+ /** What the engine films of the props (the cloud follows the still itself). */
+ note?: string;
+}) {
+ const current = props.find((p) => p.id === picked);
+ // The size slider is logarithmic over its range.
+ const lnMin = Math.log(sizeRange.min);
+ const lnMax = Math.log(sizeRange.max);
+ const toPos = (s: number) => Math.round(((Math.log(Math.min(sizeRange.max, Math.max(sizeRange.min, s))) - lnMin) / (lnMax - lnMin)) * 1000);
+ const fromPos = (pos: number) => Math.exp(lnMin + (pos / 1000) * (lnMax - lnMin));
+ return (
+ <div className="space-y-3">
+ {props.length ? (
+ <ul className="space-y-1" aria-label="Props in the scene">
+ {props.map((p, i) => {
+ const state = loading[p.id];
+ return (
+ <li key={p.id} className={cn("flex items-center gap-2 rounded-lg border p-1.5", picked === p.id && "border-ring bg-accent/40")}>
+ <button
+ type="button"
+ onClick={() => onPick(picked === p.id ? null : p.id)}
+ aria-pressed={picked === p.id}
+ aria-label={`Prop ${i + 1}: ${p.name}`}
+ className="flex min-w-0 flex-1 items-center gap-2 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {p.poster ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={p.poster} alt="" className="size-8 shrink-0 rounded object-cover" />
+ ) : (
+ <span className="grid size-8 shrink-0 place-items-center rounded bg-muted">
+ <Box className="size-4" aria-hidden />
+ </span>
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px]">{p.name}</span>
+ <span className="block truncate text-[11.5px] text-muted-foreground">
+ {state === "loading" ? "Loading…" : state === "error" ? "Couldn't load it" : picked === p.id ? "Drag the handle in the view" : "Pick to move it"}
+ </span>
+ </span>
+ {state === "loading" && <Loader2 className="size-4 shrink-0 animate-spin" aria-hidden />}
+ </button>
+ <Button variant="ghost" size="icon" className="size-8 shrink-0" onClick={() => onRemove(p.id)} aria-label={`Remove ${p.name}`} disabled={disabled}>
+ <Trash2 />
+ </Button>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <p className="text-[12.5px] text-muted-foreground">Place an object made from a picture, then film it with the scene.</p>
+ )}
+ {making > 0 && (
+ <p className="flex items-center gap-2 text-[12.5px] text-muted-foreground" role="status">
+ <Loader2 className="size-3.5 animate-spin" /> Making {making > 1 ? `${making} props` : "a prop"} on your GPU — {making > 1 ? "they land" : "it lands"} here when ready
+ </p>
+ )}
+ {current && !loading[current.id] && (
+ <div className="space-y-3 rounded-lg bg-muted/50 p-2.5">
+ <div className="grid grid-cols-3 gap-1" role="radiogroup" aria-label="Handle">
+ {HANDLES.map((h) => (
+ <button
+ key={h.id}
+ type="button"
+ role="radio"
+ aria-checked={handle === h.id}
+ onClick={() => onHandle(h.id)}
+ className={cn("flex h-8 items-center justify-center gap-1.5 rounded-lg text-[12.5px] font-medium", handle === h.id ? "bg-primary text-primary-foreground" : "bg-background hover:bg-accent")}
+ >
+ <h.icon className="size-3.5" aria-hidden /> {h.label}
+ </button>
+ ))}
+ </div>
+ <label className="block space-y-1.5 text-[12.5px]">
+ <span className="flex justify-between">
+ <span>Size</span>
+ <span className="font-mono">{current.size < 1 ? current.size.toFixed(2) : current.size.toFixed(1)} m</span>
+ </span>
+ <Slider min={0} max={1000} step={1} value={[toPos(current.size)]} onValueChange={([v]) => onChange({ ...current, size: Math.round(fromPos(v) * 1e4) / 1e4 })} aria-label="Prop size" disabled={disabled} />
+ </label>
+ <label className="block space-y-1.5 text-[12.5px]">
+ <span className="flex justify-between">
+ <span>Turn</span>
+ <span className="font-mono">{Math.round(current.rotation[1])}°</span>
+ </span>
+ <Slider
+ min={-180}
+ max={180}
+ step={1}
+ value={[Math.round(current.rotation[1])]}
+ onValueChange={([v]) => onChange({ ...current, rotation: [current.rotation[0], wrapDeg(v), current.rotation[2]] })}
+ aria-label="Prop turn"
+ disabled={disabled}
+ />
+ </label>
+ <div className="flex flex-wrap gap-1.5">
+ <Button variant="secondary" size="sm" className="rounded-full" onClick={() => onBring(current.id)} disabled={disabled}>
+ <ArrowDownToDot /> In front of the camera
+ </Button>
+ <Button variant="secondary" size="sm" className="rounded-full" onClick={() => onTurnOver(current.id)} disabled={disabled}>
+ <FlipVertical2 /> Turn over
+ </Button>
+ </div>
+ </div>
+ )}
+ {note && props.length > 0 && <p className="text-[12px] leading-snug text-muted-foreground">{note}</p>}
+ <Button variant="secondary" className="w-full rounded-full" onClick={onAdd} disabled={disabled || props.length >= MAX_PROPS}>
+ <Plus /> Add a prop
+ </Button>
+ </div>
+ );
+}
diff --git a/src/components/cinema/scene-viewer.tsx b/src/components/cinema/scene-viewer.tsx
index d431ce57..48c4d8d0 100644
--- a/src/components/cinema/scene-viewer.tsx
+++ b/src/components/cinema/scene-viewer.tsx
@@ -1,7 +1,7 @@
"use client";
-import { Box, Camera, CircleHelp, Loader2, Route, RotateCcw, SlidersHorizontal, X } from "lucide-react";
-import { useEffect, useEffectEvent, useId, useMemo, useRef, useState } from "react";
+import { Box, Camera, CircleHelp, Loader2, Package, Route, RotateCcw, SlidersHorizontal, X } from "lucide-react";
+import { useCallback, useEffect, useEffectEvent, 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";
@@ -16,16 +16,19 @@ import { uploadFile, useDeleteUpload, useModelAccess, useStatus } from "@/lib/ap
import { getModel } from "@/lib/catalog";
import { IMAGE_ASPECTS, PATH_MODELS, PATH_RENDER_FIRST, RECOMPOSE_MODELS, planCinema, type CinemaGenerateInput, type DirectorSettings } from "@/lib/catalog/cinema";
import { PATH_FPS, PATH_FRAMES, PHOTO_KEY, addKey, flyPoseOf, framePoses, fromScenePose, keyAt, keyPose, presetKeys, removeKey, renderSize, type CameraKey } from "@/lib/camera-path";
-import type { Engine } from "@/lib/catalog/types";
+import type { Engine, Generation } from "@/lib/catalog/types";
import { ACCESS_PLACE, offered } from "@/lib/model-access";
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 { toastError } from "@/lib/refusals";
+import { SPLAT_MAX_BYTES } from "@/lib/av/splat-view";
+import { MAX_PROPS, bringToCamera, parseSceneState, placeProp, propCandidate as propCandidateOf, sceneStateKey, serializeSceneState, sizeRange, turnOver, type PropCandidate, type SceneProp } from "@/lib/scene-props";
import { useCinemaGenerate } from "./hooks";
import { usePlanPrice, type SceneTake } from "./scene-actions";
import { FilmButton, OPEN_SECONDS, PathKeys, PathOptions } from "./scene-path";
import { WORLDCAST_SECONDS } from "@/lib/catalog/worldcast-plan";
-import type { SceneEngine, SceneInfo } from "./scene-engine";
+import type { PropHandle, SceneEngine, SceneInfo } from "./scene-engine";
+import { AddPropDialog, MakingWatch, PropsPanel, propName } from "./scene-props";
/**
* The full-screen 3D scene viewer (Higgsfield's "3D Scene", higgsfield-delta-4.md §4.4): fly with W A S D Q E
@@ -36,6 +39,11 @@ import type { SceneEngine, SceneInfo } from "./scene-engine";
* Fly path (build plan N7-5): keyframe the camera (or pick a move), preview the flight, and "Film this path" films the
* still along it as a new take: H3 Max camera-controls on the cloud; on the open engine the browser first records the
* scene along the path, which guides Wan 2.1 through Uni3C on the user's GPU.
+ *
+ * Props (idol-9): "Add a prop" places a splat (an Idol 3D or TripoSplat result from the Library, or a picture made into
+ * one with Idol 3D on your GPU) in the scene with move, turn and size handles. The props are part of the scene's own
+ * render, so a capture, a blockout and the open engine's path render (Uni3C's guide) show them; they are kept per
+ * scene in this browser.
*/
export interface SceneViewerProps {
@@ -128,6 +136,26 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
const [filming, setFilming] = useState<"render" | "send" | null>(null);
const [progress, setProgress] = useState(0);
const previewRef = useRef<AbortController | null>(null);
+ // Props: kept per scene in this browser; `loaded` is what the current engine holds.
+ const stateKey = sceneStateKey(take.generation.id);
+ const [props, setProps] = useState<SceneProp[]>(() => {
+ try {
+ return parseSceneState(localStorage.getItem(stateKey)).props;
+ } catch {
+ return [];
+ }
+ });
+ const [pickedProp, setPickedProp] = useState<string | null>(null);
+ const [handle, setHandle] = useState<PropHandle>("translate");
+ const [propLoading, setPropLoading] = useState<Record<string, "loading" | "error">>({});
+ const [addOpen, setAddOpen] = useState(false);
+ const [propsOpen, setPropsOpen] = useState(false);
+ const [making, setMaking] = useState<string[]>([]);
+ const loadedRef = useRef(new Set<string>());
+ const propsRef = useRef(props);
+ useEffect(() => {
+ propsRef.current = props;
+ }, [props]);
const generate = useCinemaGenerate(take.generation.projectId ?? projectId);
const noteId = useId();
@@ -202,7 +230,9 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
if (ctl.signal.aborted) return;
eng = new SceneEngine(canvas);
engineRef.current = eng;
+ loadedRef.current = new Set();
eng.onFocus = setFocus;
+ eng.onPropChange = (id, t) => setProps((ps) => ps.map((p) => (p.id === id ? { ...p, ...t } : p)));
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 });
@@ -243,6 +273,87 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
if (frame && status === "ready") engineRef.current?.setView({ lens, aperture, aspect: ratioOf(aspect), dof, frame, speed });
}, [lens, aperture, aspect, dof, frame, speed, status]);
+ // Props into the engine: new ones load (Spark comes with the first), changed ones move, removed ones go.
+ useEffect(() => {
+ const eng = engineRef.current;
+ if (!eng || status !== "ready") return;
+ const loaded = loadedRef.current;
+ for (const p of props) {
+ if (loaded.has(p.id)) {
+ eng.updateProp(p);
+ continue;
+ }
+ loaded.add(p.id);
+ setPropLoading((m) => ({ ...m, [p.id]: "loading" }));
+ eng
+ .addProp(p, { maxBytes: coarse ? SPLAT_MAX_BYTES.coarse : SPLAT_MAX_BYTES.fine })
+ .then(() => {
+ if (engineRef.current !== eng) return;
+ // The latest state of it (a slider may have moved while it loaded).
+ const now = propsRef.current.find((x) => x.id === p.id);
+ if (now) eng.updateProp(now);
+ else eng.removeProp(p.id);
+ setPropLoading((m) => Object.fromEntries(Object.entries(m).filter(([k]) => k !== p.id)));
+ })
+ .catch((e) => {
+ if (engineRef.current !== eng || (e as Error).name === "AbortError") return;
+ setPropLoading((m) => ({ ...m, [p.id]: "error" }));
+ });
+ }
+ for (const id of [...loaded]) {
+ if (props.some((p) => p.id === id)) continue;
+ loaded.delete(id);
+ eng.removeProp(id);
+ }
+ }, [props, status, coarse]);
+
+ useEffect(() => {
+ try {
+ if (props.length) localStorage.setItem(stateKey, serializeSceneState({ version: 1, props }));
+ else localStorage.removeItem(stateKey);
+ } catch {}
+ }, [props, stateKey]);
+
+ // The handle sits on the picked prop once it has loaded.
+ const pickedReady = !!pickedProp && props.some((p) => p.id === pickedProp) && !propLoading[pickedProp];
+ useEffect(() => {
+ if (status === "ready") engineRef.current?.pickProp(pickedReady ? pickedProp : null, handle);
+ }, [pickedProp, pickedReady, handle, status]);
+
+ const placeCandidate = useCallback(
+ (c: PropCandidate & { name: string }) => {
+ const eng = engineRef.current;
+ if (!eng || !info) return;
+ const id = `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
+ setProps((ps) => (ps.length >= MAX_PROPS ? ps : [...ps, placeProp(c, eng.getPose(), info.pivotDepth, ps.length, id)]));
+ setPickedProp(id);
+ setHandle("translate");
+ setAddOpen(false);
+ },
+ [info],
+ );
+
+ const madeProp = useCallback(
+ (id: string, g: Generation | null) => {
+ setMaking((m) => m.filter((x) => x !== id));
+ const c = g && propCandidateOf(g);
+ if (c) {
+ placeCandidate({ ...c, name: propName(c.modelId) });
+ toast.success("Your prop is in the scene");
+ } else toast.error("Couldn't make the prop from that picture. Try another picture, with one object on a plain background");
+ },
+ [placeCandidate],
+ );
+
+ const changeProp = (id: string, f: (p: SceneProp) => SceneProp) => setProps((ps) => ps.map((p) => (p.id === id ? f(p) : p)));
+ const propSizes = sizeRange(info?.pivotDepth ?? 1);
+ const propNote =
+ engine === "cloud"
+ ? "Props show in captures and blockouts. Filming on the cloud follows the still itself, so they don't show there; film on your GPU to keep them."
+ : context.worldcast
+ ? "Props show in captures and blockouts. WorldCast films from the still's depth, so they don't show there."
+ : "Props show in captures, blockouts and the path filmed on your GPU.";
+
// The camera of a key as the path films it: the still's own lens (a key's distance already counts the lens it was set with).
const goTo = (i: number) => {
const eng = engineRef.current;
@@ -550,6 +661,32 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
</div>
);
+ const propsPanel = (
+ <PropsPanel
+ props={props}
+ picked={pickedProp}
+ onPick={setPickedProp}
+ handle={handle}
+ onHandle={setHandle}
+ loading={propLoading}
+ making={making.length}
+ sizeRange={propSizes}
+ onChange={(p) => changeProp(p.id, () => p)}
+ onRemove={(id) => {
+ setProps((ps) => ps.filter((p) => p.id !== id));
+ if (pickedProp === id) setPickedProp(null);
+ }}
+ onBring={(id) => {
+ const eng = engineRef.current;
+ if (eng && info) changeProp(id, (p) => bringToCamera(p, eng.getPose(), info.pivotDepth));
+ }}
+ onTurnOver={(id) => changeProp(id, turnOver)}
+ onAdd={() => setAddOpen(true)}
+ disabled={status !== "ready" || pathBusy}
+ note={propNote}
+ />
+ );
+
const pathKeys = (tone: "overlay" | "panel") => (
<PathKeys
keys={keys}
@@ -627,6 +764,8 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
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) => {
+ // The prop's handle takes this drag.
+ if (engineRef.current?.handleActive()) return;
e.currentTarget.setPointerCapture(e.pointerId);
pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
}}
@@ -673,6 +812,7 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
<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}` : ""}
+ {props.length ? ` · ${props.length} prop${props.length > 1 ? "s" : ""}` : ""}
{queued ? ` · ${queued} new take${queued > 1 ? "s" : ""} queued` : ""}
</p>
</div>
@@ -758,6 +898,18 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
<Button variant="secondary" size="icon" className="shrink-0 rounded-full" onClick={() => setPanelOpen(true)} aria-label="Camera" title="Camera: lens, aperture, frame">
<SlidersHorizontal />
</Button>
+ <Button
+ variant="secondary"
+ size="icon"
+ className="relative shrink-0 rounded-full"
+ onClick={() => setPropsOpen(true)}
+ disabled={status !== "ready"}
+ aria-label={`Props, ${props.length} in the scene`}
+ title="Props: objects in the scene"
+ >
+ <Package />
+ {props.length > 0 && <span className="absolute -top-1 -right-1 grid size-4 place-items-center rounded-full bg-primary text-[10px] text-primary-foreground">{props.length}</span>}
+ </Button>
<Button variant="secondary" className="shrink-0 rounded-full px-3" onClick={() => setPathOpen(true)} disabled={status !== "ready"} aria-label={`Path, ${keys.length - 1} keyframe${keys.length === 2 ? "" : "s"}`}>
{filming ? <Loader2 className="animate-spin" /> : <Route />} Path{keys.length > 1 ? ` · ${keys.length - 1}` : ""}
</Button>
@@ -776,6 +928,15 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
</div>
</SheetContent>
</Sheet>
+ <Sheet open={propsOpen} onOpenChange={setPropsOpen}>
+ <SheetContent side="bottom" className="max-h-[80svh] 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">Props</SheetTitle>
+ <SheetDescription className="text-[12.5px]">Objects made from pictures, placed in the scene. Pick one, close this and drag its handle in the view.</SheetDescription>
+ </SheetHeader>
+ <div className="p-4">{propsPanel}</div>
+ </SheetContent>
+ </Sheet>
<Sheet open={pathOpen} onOpenChange={setPathOpen}>
<SheetContent side="bottom" className="max-h-[80svh] gap-0 overflow-y-auto rounded-t-2xl p-0 md:hidden">
<SheetHeader className="border-b px-4 py-3">
@@ -795,6 +956,7 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
<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}
+ <Section title="Props">{propsPanel}</Section>
{rerender}
<Section title="Fly path">{pathOptions}</Section>
</div>
@@ -805,6 +967,18 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting
<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>
+ <AddPropDialog
+ open={addOpen}
+ onOpenChange={setAddOpen}
+ onPlace={placeCandidate}
+ onMaking={(id) => {
+ setMaking((m) => [...m, id]);
+ setAddOpen(false);
+ toast.success("Making your prop — it lands in the scene when it's ready", { duration: 3000 });
+ }}
+ full={props.length >= MAX_PROPS}
+ />
+ {making.length > 0 && <MakingWatch ids={making} onDone={madeProp} />}
</DialogContent>
</Dialog>
);
diff --git a/src/components/cinema/video-encode.ts b/src/components/cinema/video-encode.ts
index 59f2a6ba..0f539758 100644
--- a/src/components/cinema/video-encode.ts
+++ b/src/components/cinema/video-encode.ts
@@ -28,10 +28,10 @@ export async function vp8Supported(width: number, height: number, fps: number):
}
/**
- * `count` frames of two streams (`draw(i)` gives frame i of each) encoded with WebCodecs and written as two WebM files:
+ * `count` frames of two streams (`draw(i)` gives frame i of each, or a promise of them: a frame may wait for a splat's sort) encoded with WebCodecs and written as two WebM files:
* every frame kept, frame i at i / fps, a keyframe each second.
*/
-export async function encodeVp8(count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[]): Promise<Uint8Array[]> {
+export async function encodeVp8(count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[] | Promise<ImageData[]>): Promise<Uint8Array[]> {
const chunks: EncodedFrame[][] = Array.from({ length: outputs }, () => []);
let failure: unknown;
const encoders = chunks.map((_, k) => {
@@ -49,7 +49,7 @@ export async function encodeVp8(count: number, width: number, height: number, fp
try {
const step = 1e6 / fps;
for (let i = 0; i < count; i++) {
- const images = draw(i);
+ const images = await draw(i);
images.forEach((img, k) => {
const f = new VideoFrame(img.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp: Math.round(i * step), duration: Math.round(step) });
encoders[k].encode(f, { keyFrame: i % Math.max(1, Math.round(fps)) === 0 });
@@ -71,7 +71,7 @@ export async function encodeVp8(count: number, width: number, height: number, fp
}
/** The fallback: a canvas per stream recorded with MediaRecorder, each frame handed over 1/fps apart. */
-export async function recordWithMediaRecorder(type: string, count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[]): Promise<Blob[]> {
+export async function recordWithMediaRecorder(type: string, count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[] | Promise<ImageData[]>): Promise<Blob[]> {
const canvases = Array.from({ length: outputs }, () => Object.assign(document.createElement("canvas"), { width, height }));
const ctxs = canvases.map((c) => c.getContext("2d")!);
const streams = canvases.map((c) => c.captureStream(0));
@@ -89,7 +89,7 @@ export async function recordWithMediaRecorder(type: string, count: number, width
await wait(step);
const t0 = performance.now();
for (let i = 0; i < count; i++) {
- draw(i).forEach((img, k) => ctxs[k].putImageData(img, 0, 0));
+ (await draw(i)).forEach((img, k) => ctxs[k].putImageData(img, 0, 0));
tracks.forEach((t) => t.requestFrame?.());
await wait(Math.max(0, t0 + (i + 1) * step - performance.now()));
}
@@ -119,7 +119,7 @@ export async function avcCodec(width: number, height: number, fps: number): Prom
}
/** `count` frames (`draw(i)` gives frame i) encoded with WebCodecs H.264 and written as one MP4: every frame kept. */
-export async function encodeMp4(codec: string, count: number, width: number, height: number, fps: number, draw: (i: number) => ImageData): Promise<Uint8Array> {
+export async function encodeMp4(codec: string, count: number, width: number, height: number, fps: number, draw: (i: number) => ImageData | Promise<ImageData>): Promise<Uint8Array> {
const frames: EncodedFrame[] = [];
let avcC: Uint8Array | null = null;
let failure: unknown;
@@ -137,7 +137,7 @@ export async function encodeMp4(codec: string, count: number, width: number, hei
try {
const step = 1e6 / fps;
for (let i = 0; i < count; i++) {
- const img = draw(i);
+ const img = await draw(i);
const f = new VideoFrame(img.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp: Math.round(i * step), duration: Math.round(step) });
e.encode(f, { keyFrame: i % Math.max(1, Math.round(fps)) === 0 });
f.close();
@@ -159,15 +159,15 @@ export async function encodeMp4(codec: string, count: number, width: number, hei
* One stream of `count` frames as the best video this browser makes: MP4 (H.264) when `preferMp4` and WebCodecs can,
* else WebM (VP8), else MediaRecorder's own type. Frame-exact except on the MediaRecorder fallback.
*/
-export async function encodeFrames(count: number, width: number, height: number, fps: number, draw: (i: number) => ImageData, preferMp4 = false): Promise<{ blob: Blob; type: string; exact: boolean }> {
+export async function encodeFrames(count: number, width: number, height: number, fps: number, draw: (i: number) => ImageData | Promise<ImageData>, preferMp4 = false): Promise<{ blob: Blob; type: string; exact: boolean }> {
const avc = preferMp4 ? await avcCodec(width, height, fps) : null;
if (avc) return { blob: new Blob([(await encodeMp4(avc, count, width, height, fps, draw)) as BlobPart], { type: "video/mp4" }), type: "video/mp4", exact: true };
if (await vp8Supported(width, height, fps)) {
- const [a] = await encodeVp8(count, width, height, fps, 1, (i) => [draw(i)]);
+ const [a] = await encodeVp8(count, width, height, fps, 1, async (i) => [await draw(i)]);
return { blob: new Blob([a as BlobPart], { type: "video/webm" }), type: "video/webm", exact: true };
}
const type = pathVideoType();
if (!type) throw new Error("This browser can't record video — try Chrome or Edge, or upload a render from your 3D app");
- const [b] = await recordWithMediaRecorder(type, count, width, height, fps, 1, (i) => [draw(i)]);
+ const [b] = await recordWithMediaRecorder(type, count, width, height, fps, 1, async (i) => [await draw(i)]);
return { blob: b, type: type.split(";")[0], exact: false };
}
diff --git a/src/components/model3d/splat-engine.ts b/src/components/model3d/splat-engine.ts
index 76132377..ccd19c04 100644
--- a/src/components/model3d/splat-engine.ts
+++ b/src/components/model3d/splat-engine.ts
@@ -57,26 +57,13 @@ export class SplatEngine {
/** Fetch the file (abortable, its size checked against maxBytes first), then build the splat. */
async load(url: string, format: string, { signal, maxBytes, onProgress }: { signal?: AbortSignal; maxBytes?: number; onProgress?: (p: number) => void } = {}): Promise<SplatLoadInfo> {
- const res = await fetch(url, { signal });
- if (!res.ok) throw new Error(`The splat didn't load (${res.status})`);
- const length = Number(res.headers.get("content-length")) || 0;
- if (maxBytes && length > maxBytes) throw new SplatTooBigError(length);
- const bytes = await readAll(res, length, maxBytes, onProgress);
+ const bytes = await fetchSplat(url, { signal, maxBytes, onProgress });
if (this.disposed || signal?.aborted) throw new DOMException("Aborted", "AbortError");
- const mesh = new SplatMesh({ fileBytes: bytes, fileType: FILE_TYPES[format], fileName: `splat.${format}` });
- await mesh.initialized;
+ const mesh = await buildSplatMesh(bytes, format, this.cutoff);
if (this.disposed || signal?.aborted) {
mesh.dispose();
throw new DOMException("Aborted", "AbortError");
}
- // The haze cut-off: a Gaussian fainter than the slider's value isn't drawn (its opacity goes to 0).
- const cutoff = this.cutoff;
- mesh.objectModifier = dyno.dynoBlock({ gsplat: dyno.Gsplat }, { gsplat: dyno.Gsplat }, ({ gsplat }) => {
- if (!gsplat) throw new Error("no splat");
- const { opacity } = dyno.splitGsplat(gsplat).outputs;
- return { gsplat: dyno.combineGsplat({ gsplat, opacity: dyno.select(dyno.lessThan(opacity, cutoff), dyno.dynoConst("float", 0), opacity) }) };
- });
- mesh.updateGenerator();
this.mesh = mesh;
this.scene.add(mesh);
this.frameObject(mesh.getBoundingBox(true));
@@ -195,6 +182,112 @@ export class SplatEngine {
}
}
+/** Fetch a splat file (abortable; refused past maxBytes, by its length or as it streams). */
+export async function fetchSplat(url: string, { signal, maxBytes, onProgress }: { signal?: AbortSignal; maxBytes?: number; onProgress?: (p: number) => void } = {}): Promise<Uint8Array> {
+ const res = await fetch(url, { signal });
+ if (!res.ok) throw new Error(`The splat didn't load (${res.status})`);
+ const length = Number(res.headers.get("content-length")) || 0;
+ if (maxBytes && length > maxBytes) throw new SplatTooBigError(length);
+ return readAll(res, length, maxBytes, onProgress);
+}
+
+/** A splat built from its file, with the haze cut-off: a Gaussian fainter than `cutoff`'s value isn't drawn (its opacity goes to 0). */
+export async function buildSplatMesh(bytes: Uint8Array, format: string, cutoff: dyno.DynoFloat<string>): Promise<SplatMesh> {
+ const mesh = new SplatMesh({ fileBytes: bytes, fileType: FILE_TYPES[format], fileName: `splat.${format}` });
+ await mesh.initialized;
+ mesh.objectModifier = dyno.dynoBlock({ gsplat: dyno.Gsplat }, { gsplat: dyno.Gsplat }, ({ gsplat }) => {
+ if (!gsplat) throw new Error("no splat");
+ const { opacity } = dyno.splitGsplat(gsplat).outputs;
+ return { gsplat: dyno.combineGsplat({ gsplat, opacity: dyno.select(dyno.lessThan(opacity, cutoff), dyno.dynoConst("float", 0), opacity) }) };
+ });
+ mesh.updateGenerator();
+ return mesh;
+}
+
+/**
+ * Splats inside another engine's three.js scene: Cinema Studio's 3D scene props (idol-9). One SparkRenderer draws
+ * every prop in the scene's own render pass, depth-tested against the MoGe mesh or point cloud and sorted with it.
+ * Unlike the viewer's, it writes depth: the scene's post pass reads depth to tell a surface from a hole (what the path
+ * render leaves transparent for Uni3C), so a splat that wrote none would vanish from the render. Spark sorts back to
+ * front, so writing depth hides nothing behind a nearer Gaussian; the faintest edges (under minAlpha) are dropped so
+ * they don't mark a hole as seen. Each prop sits in a group whose scale is its longest side (the splat is centred and
+ * fitted to 1 inside), so the scene sets a prop's place, turn and size on the group.
+ */
+export class SceneSplats {
+ readonly root = new THREE.Group();
+ private spark: SparkRenderer;
+ private props = new Map<string, { group: THREE.Group; mesh: SplatMesh; cutoff: dyno.DynoFloat<string> }>();
+ private disposed = false;
+
+ constructor(renderer: THREE.WebGLRenderer, onDirty: () => void) {
+ this.spark = new SparkRenderer({ renderer, onDirty, depthWrite: true, minAlpha: 1 / 16 });
+ this.root.add(this.spark);
+ }
+
+ /** Load a prop's splat into a new group under `root`; resolves with the group (its transform is the scene's to set). */
+ async add(id: string, url: string, format: string, o: { cutoff: number; signal?: AbortSignal; maxBytes?: number }): Promise<{ group: THREE.Group; splats: number }> {
+ const bytes = await fetchSplat(url, { signal: o.signal, maxBytes: o.maxBytes });
+ if (this.disposed || o.signal?.aborted) throw new DOMException("Aborted", "AbortError");
+ const cutoff = dyno.dynoFloat(o.cutoff);
+ const mesh = await buildSplatMesh(bytes, format, cutoff);
+ if (this.disposed || o.signal?.aborted) {
+ mesh.dispose();
+ throw new DOMException("Aborted", "AbortError");
+ }
+ const box = mesh.getBoundingBox(true);
+ const center = box.isEmpty() ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
+ const longest = box.isEmpty() ? 1 : Math.max(...box.getSize(new THREE.Vector3()).toArray(), 1e-3);
+ const fit = new THREE.Group();
+ fit.scale.setScalar(1 / longest);
+ mesh.position.copy(center).multiplyScalar(-1);
+ fit.add(mesh);
+ const group = new THREE.Group();
+ group.name = `prop:${id}`;
+ group.add(fit);
+ this.remove(id);
+ this.props.set(id, { group, mesh, cutoff });
+ this.root.add(group);
+ return { group, splats: mesh.packedSplats?.numSplats ?? 0 };
+ }
+
+ setCutoff(id: string, value: number) {
+ const p = this.props.get(id);
+ if (!p || p.cutoff.value === value) return;
+ p.cutoff.value = value;
+ p.mesh.updateVersion();
+ }
+
+ remove(id: string) {
+ const p = this.props.get(id);
+ if (!p) return;
+ this.props.delete(id);
+ p.group.removeFromParent();
+ p.mesh.dispose();
+ }
+
+ get size() {
+ return this.props.size;
+ }
+
+ /**
+ * Bring the splats up to date for `camera` and wait for their sort (a path render draws each frame once, so the
+ * order must be this frame's, not the last one's). Spark sorts on a worker: wait out a sort already running first.
+ */
+ async settle(scene: THREE.Scene, camera: THREE.Camera) {
+ if (!this.props.size) return;
+ for (let i = 0; this.spark.sorting && i < 200; i++) await new Promise((r) => setTimeout(r, 5));
+ await this.spark.update({ scene, camera });
+ for (let i = 0; this.spark.sorting && i < 200; i++) await new Promise((r) => setTimeout(r, 5));
+ }
+
+ dispose() {
+ this.disposed = true;
+ for (const id of [...this.props.keys()]) this.remove(id);
+ this.root.removeFromParent();
+ this.spark.dispose();
+ }
+}
+
export class SplatTooBigError extends Error {
constructor(readonly bytes: number) {
super("This splat is too big to open on this device");
diff --git a/src/lib/scene-props.ts b/src/lib/scene-props.ts
new file mode 100644
index 00000000..d38090c0
--- /dev/null
+++ b/src/lib/scene-props.ts
@@ -0,0 +1,208 @@
+import { isIdol, model3dView, splatFormatOf } from "@/lib/av/model3d";
+import { HAZE_MAX, hazeCutoffFor } from "@/lib/av/splat-view";
+import type { Generation } from "@/lib/catalog/types";
+import { forwardOf, type FlyPose, type Vec3 } from "@/lib/scene3d";
+
+/**
+ * Props in Cinema Studio's 3D scene (idol-9, docs/research/idol-9.md §8–9): an object made from a picture (an Idol 3D
+ * splat, or any splat result in the Library, a cloud TripoSplat .ply included) placed in the MoGe scene, moved, turned
+ * and sized, and filmed with it. The scene viewer draws them with idol-4's splat renderer
+ * (src/components/model3d/splat-engine.ts) inside the scene's own three.js graph, so captures, path renders and
+ * blockouts show them. Pure, so the tests can check the state and the placing.
+ */
+
+/** At most this many props in one scene (each is a splat the browser sorts every time the camera moves). */
+export const MAX_PROPS = 4;
+/** A prop's size: its longest side, as a share of the scene's subject distance, from this to that. */
+export const PROP_SIZE = { min: 0.02, max: 4, start: 0.35 } as const;
+
+export interface SceneProp {
+ id: string;
+ /** The splat file (.spz, .ply, .ksplat or .splat). */
+ url: string;
+ format: string;
+ /** What the list calls it ("Idol 3D", "TripoSplat"). */
+ name: string;
+ /** The Library result it came from. */
+ generationId?: string;
+ modelId?: string;
+ /** A still of it for the list (the result's preview or poster). */
+ poster?: string;
+ /** Where its centre is, in scene units (the scene's camera space). */
+ position: Vec3;
+ /** Its turn in degrees about x, y and z (three.js Euler order "YXZ": yaw first, as the fly camera turns). */
+ rotation: Vec3;
+ /** Its longest side, in scene units. */
+ size: number;
+ /** The opacity it hides Gaussians under (Idol 3D's faint haze; idol-4's cut-off). */
+ cutoff: number;
+}
+
+/** What the viewer keeps for one scene take: its props (in this browser, next to the scene they were placed in). */
+export interface SceneState {
+ version: 1;
+ props: SceneProp[];
+}
+
+export const EMPTY_SCENE: SceneState = { version: 1, props: [] };
+
+/** Where a scene's state is kept in this browser. */
+export const sceneStateKey = (sceneId: string) => `fuobe.cinema.scene.${sceneId}`;
+
+/** A Library result that can be placed as a prop: a finished 3D result whose file is a splat. */
+export interface PropCandidate {
+ url: string;
+ format: string;
+ generationId: string;
+ modelId: string;
+ poster?: string;
+}
+
+export function propCandidate(g: Pick<Generation, "id" | "status" | "outputs" | "request">): PropCandidate | null {
+ if (g.status !== "succeeded") return null;
+ const view = model3dView(g);
+ if (!view.splat) return null;
+ return { url: view.splat.url, format: view.splat.format, generationId: g.id, modelId: g.request.modelId, ...(view.poster ? { poster: view.poster } : {}) };
+}
+
+const add = (a: Vec3, b: Vec3, k: number): Vec3 => [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k];
+
+/**
+ * A new prop where the camera looks, facing it: `pivotDepth` × 0.7 ahead (a little in front of the subject), its
+ * longest side 0.35 × pivotDepth, turned so its front (+z in its own file, the side Idol saw in the picture) faces the
+ * camera. A second or third prop lands a little to the side, so they don't stack.
+ */
+export function placeProp(c: PropCandidate & { name: string }, pose: FlyPose, pivotDepth: number, taken: number, id: string): SceneProp {
+ const d = Math.max(pivotDepth, 0.05);
+ const ahead = add(pose.position, forwardOf(pose.yaw, 0), d * 0.7);
+ const side: Vec3 = [Math.cos(pose.yaw), 0, -Math.sin(pose.yaw)];
+ const shift = taken === 0 ? 0 : (taken % 2 ? 1 : -1) * Math.ceil(taken / 2) * 0.3 * d;
+ return {
+ id,
+ url: c.url,
+ format: c.format,
+ name: c.name,
+ generationId: c.generationId,
+ modelId: c.modelId,
+ ...(c.poster ? { poster: c.poster } : {}),
+ position: round3(add(ahead, side, shift)),
+ rotation: [0, round(deg(pose.yaw), 1), 0],
+ size: round(d * PROP_SIZE.start, 4),
+ cutoff: hazeCutoffFor(c.modelId),
+ };
+}
+
+/** Put a prop back in front of the camera, keeping its size and its turn relative to the view. */
+export function bringToCamera(p: SceneProp, pose: FlyPose, pivotDepth: number): SceneProp {
+ const ahead = add(pose.position, forwardOf(pose.yaw, 0), Math.max(pivotDepth, 0.05) * 0.7);
+ return { ...p, position: round3(ahead), rotation: [p.rotation[0], round(deg(pose.yaw), 1), p.rotation[2]] };
+}
+
+/** Turn it over (a file saved upside down): half a turn about its own x. */
+export const turnOver = (p: SceneProp): SceneProp => ({ ...p, rotation: [wrapDeg(p.rotation[0] + 180), p.rotation[1], wrapDeg(p.rotation[2])] });
+
+/** The size slider's range for a scene, in scene units. */
+export const sizeRange = (pivotDepth: number) => ({ min: Math.max(pivotDepth, 0.05) * PROP_SIZE.min, max: Math.max(pivotDepth, 0.05) * PROP_SIZE.max });
+
+export function serializeSceneState(s: SceneState): string {
+ return JSON.stringify({ version: 1, props: s.props.slice(0, MAX_PROPS) });
+}
+
+/**
+ * A kept state read back: anything that isn't a well-formed prop is dropped (an edited or older entry never breaks
+ * the viewer), numbers are kept finite, sizes positive, cut-offs in the slider's range, at most MAX_PROPS.
+ */
+export function parseSceneState(text: string | null | undefined): SceneState {
+ if (!text) return EMPTY_SCENE;
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ return EMPTY_SCENE;
+ }
+ const list = raw && typeof raw === "object" && Array.isArray((raw as { props?: unknown }).props) ? ((raw as { props: unknown[] }).props as unknown[]) : [];
+ const props: SceneProp[] = [];
+ const ids = new Set<string>();
+ for (const item of list) {
+ const p = parseProp(item);
+ if (!p || ids.has(p.id)) continue;
+ ids.add(p.id);
+ props.push(p);
+ if (props.length >= MAX_PROPS) break;
+ }
+ return { version: 1, props };
+}
+
+function parseProp(v: unknown): SceneProp | null {
+ if (!v || typeof v !== "object") return null;
+ const o = v as Record<string, unknown>;
+ const str = (x: unknown) => (typeof x === "string" && x.length > 0 && x.length <= 2048 ? x : undefined);
+ const id = str(o.id);
+ const url = str(o.url);
+ if (!id || !url || !/^(\/|https?:\/\/)/.test(url)) return null;
+ const format = typeof o.format === "string" ? splatFormatOf({ url: `x.${o.format}` }) : undefined;
+ if (!format) return null;
+ const vec = (x: unknown): Vec3 | null => (Array.isArray(x) && x.length === 3 && x.every((n) => typeof n === "number" && Number.isFinite(n)) ? [x[0], x[1], x[2]] : null);
+ const position = vec(o.position);
+ const rotation = vec(o.rotation);
+ const size = typeof o.size === "number" && Number.isFinite(o.size) && o.size > 0 ? o.size : null;
+ if (!position || !rotation || !size) return null;
+ const cutoff = typeof o.cutoff === "number" && Number.isFinite(o.cutoff) ? Math.min(HAZE_MAX, Math.max(0, o.cutoff)) : 0;
+ const modelId = str(o.modelId);
+ return {
+ id,
+ url,
+ format,
+ name: str(o.name)?.slice(0, 80) ?? "Prop",
+ ...(str(o.generationId) ? { generationId: str(o.generationId) } : {}),
+ ...(modelId ? { modelId } : {}),
+ ...(str(o.poster) ? { poster: str(o.poster) } : {}),
+ position,
+ rotation: [wrapDeg(rotation[0]), wrapDeg(rotation[1]), wrapDeg(rotation[2])],
+ size,
+ cutoff,
+ };
+}
+
+/** Whether a prop came from Idol 3D (its haze cut-off starts at 0.05). */
+export const isIdolProp = (p: Pick<SceneProp, "modelId">) => isIdol(p.modelId);
+
+function deg(rad: number) {
+ return (rad * 180) / Math.PI;
+}
+/** Degrees into -180…180. */
+export function wrapDeg(d: number): number {
+ const w = ((((d + 180) % 360) + 360) % 360) - 180;
+ return w === -180 ? 180 : Object.is(w, -0) ? 0 : w;
+}
+function round(n: number, places: number) {
+ const k = 10 ** places;
+ return Math.round(n * k) / k;
+}
+const round3 = (v: Vec3): Vec3 => [round(v[0], 4), round(v[1], 4), round(v[2], 4)];
+
+/** What the status says about who is looking and what runs here (src/lib/connections.ts ConnectionState, loosely). */
+export interface PropMakerStatus {
+ viewer?: unknown;
+ engineMode?: string;
+ demoMode?: string;
+ providers?: Record<string, { configured?: boolean } | undefined>;
+ ownerGpu?: unknown;
+ /** Idol 3D on the open engine is switched on in Settings → Models & licences. */
+ idolOn: boolean;
+}
+
+/**
+ * Why "Make a prop from a picture" (Idol 3D on your GPU, open source; Idol has no hosted route for this) can't run
+ * here, or null when it can. The same rule as Make it 3D on image results (src/lib/connections.ts make3dOffered):
+ * visitors make no 3D yet, Paid APIs only leaves the open engine out, the model can be off, and the GPU must be
+ * connected (or placeholder results on). A splat already in the Library can be placed either way.
+ */
+export function propMakerBlocker(s: PropMakerStatus | undefined): string | null {
+ if (!s) return "Checking what runs here…";
+ if (s.viewer) return "Making a prop from a picture isn't available on your account yet. You can place 3D results you already have.";
+ if (s.engineMode === "cloud") return "Making a prop from a picture runs Idol 3D on your GPU (open source), which Paid APIs only leaves out. You can still place splats from your Library.";
+ if (!s.idolOn) return "Idol 3D is turned off in Settings → Models & licences. Turn it on there to make props from pictures.";
+ if (s.demoMode !== "on" && !s.providers?.comfyui?.configured && !s.ownerGpu) return "Connect ComfyUI in Settings to make props from pictures on your GPU.";
+ return null;
+}
diff --git a/tests/scene-props.test.ts b/tests/scene-props.test.ts
new file mode 100644
index 00000000..15767791
--- /dev/null
+++ b/tests/scene-props.test.ts
@@ -0,0 +1,186 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+import { forwardOf, type FlyPose } from "@/lib/scene3d";
+import {
+ EMPTY_SCENE,
+ MAX_PROPS,
+ PROP_SIZE,
+ bringToCamera,
+ parseSceneState,
+ placeProp,
+ propCandidate,
+ propMakerBlocker,
+ sceneStateKey,
+ serializeSceneState,
+ sizeRange,
+ turnOver,
+ wrapDeg,
+ type SceneProp,
+} from "@/lib/scene-props";
+
+/**
+ * Props in Cinema's 3D scene (idol-9): which Library results can be placed, where a new prop lands and how it faces
+ * the camera, the scene state's round trip through this browser's storage, the transforms, and who may make one from
+ * a picture. The pixel check (a path render shows the prop) is in tests/e2e/cinema-props.mjs.
+ */
+
+const gen = (over: Partial<Generation> & { outputs: Generation["outputs"] }): Pick<Generation, "id" | "status" | "outputs" | "request"> => ({
+ id: "g1",
+ status: "succeeded",
+ request: { feature: "image-to-3d", modelId: "oss-idol", op: "splat", inputs: { images: ["/api/files/uploads/cup.png"] } },
+ ...over,
+});
+
+const START: FlyPose = { position: [0, 0, 0], yaw: 0, pitch: 0 };
+const close = (a: number[], b: number[], eps = 1e-3) => a.forEach((x, i) => expect(x).toBeCloseTo(b[i], -Math.log10(eps)));
+
+describe("what can be placed", () => {
+ it("a finished splat result from either engine (Idol 3D's .spz, cloud TripoSplat's .ply), with its still", () => {
+ const idol = propCandidate(
+ gen({
+ outputs: [
+ { url: "/api/files/g1/splat.spz", kind: "model3d", meta: { format: "spz", role: "splat" } },
+ { url: "/api/files/g1/orbit.mp4", kind: "video", meta: { role: "turntable" } },
+ { url: "/api/files/g1/seen.png", kind: "image", meta: { role: "preview" } },
+ ],
+ }),
+ );
+ expect(idol).toEqual({ url: "/api/files/g1/splat.spz", format: "spz", generationId: "g1", modelId: "oss-idol", poster: "/api/files/g1/seen.png" });
+ const tripo = propCandidate(gen({ id: "g2", request: { feature: "image-to-3d", modelId: "triposplat", op: "splat" }, outputs: [{ url: "/api/files/g2/model.ply", kind: "model3d" }] }));
+ expect(tripo).toMatchObject({ url: "/api/files/g2/model.ply", format: "ply", modelId: "triposplat" });
+ });
+
+ it("not a GLB, an unfinished run or a failed one", () => {
+ expect(propCandidate(gen({ outputs: [{ url: "/api/files/g1/model.glb", kind: "model3d", meta: { format: "glb" } }] }))).toBeNull();
+ expect(propCandidate(gen({ status: "running", outputs: [] }))).toBeNull();
+ expect(propCandidate(gen({ status: "failed", outputs: [{ url: "/api/files/g1/splat.spz", kind: "model3d" }] }))).toBeNull();
+ });
+});
+
+describe("placing a prop", () => {
+ const c = { url: "/api/files/g1/splat.spz", format: "spz", generationId: "g1", modelId: "oss-idol", name: "Idol 3D" };
+
+ it("lands ahead of the camera, a little before the subject, sized to the scene and facing the camera", () => {
+ const p = placeProp(c, START, 4, 0, "a");
+ close(p.position, [0, 0, -2.8]);
+ expect(p.size).toBeCloseTo(4 * PROP_SIZE.start);
+ expect(p.rotation).toEqual([0, 0, 0]);
+ // Idol 3D starts with its faint haze hidden (idol-4's 0.05); TripoSplat draws everything.
+ expect(p.cutoff).toBe(0.05);
+ expect(placeProp({ ...c, modelId: "triposplat" }, START, 4, 0, "b").cutoff).toBe(0);
+ });
+
+ it("follows the camera's turn: its front (+z) points back at the camera, level whatever the pitch", () => {
+ const pose: FlyPose = { position: [1, 0.5, 2], yaw: Math.PI / 2, pitch: 0.4 };
+ const p = placeProp(c, pose, 2, 0, "a");
+ close(p.position, [1 + forwardOf(pose.yaw, 0)[0] * 1.4, 0.5, 2 + forwardOf(pose.yaw, 0)[2] * 1.4]);
+ expect(p.rotation[1]).toBe(90);
+ // The prop's +z after a 90° yaw is +x, from the prop towards the camera.
+ const front = [Math.sin(Math.PI / 2), 0, Math.cos(Math.PI / 2)];
+ const toCamera = [pose.position[0] - p.position[0], 0, pose.position[2] - p.position[2]];
+ expect(front[0] * toCamera[0] + front[2] * toCamera[2]).toBeGreaterThan(0);
+ });
+
+ it("puts a second and third prop to either side, not on top of the first", () => {
+ const xs = [0, 1, 2].map((n) => placeProp(c, START, 4, n, `p${n}`).position[0]);
+ expect(new Set(xs).size).toBe(3);
+ expect(xs[1] * xs[2]).toBeLessThan(0);
+ });
+
+ it("brings a prop back in front of the camera, keeping its size and tilt", () => {
+ const p: SceneProp = { ...placeProp(c, START, 4, 0, "a"), position: [9, 9, 9], rotation: [180, 10, 5], size: 0.5 };
+ const back = bringToCamera(p, { position: [0, 0, 0], yaw: Math.PI, pitch: 0 }, 4);
+ close(back.position, [0, 0, 2.8]);
+ expect(back.rotation).toEqual([180, 180, 5]);
+ expect(back.size).toBe(0.5);
+ });
+
+ it("turns over about its own x, and keeps degrees within -180…180", () => {
+ const p = placeProp(c, START, 4, 0, "a");
+ expect(turnOver(p).rotation).toEqual([180, 0, 0]);
+ expect(turnOver(turnOver(p)).rotation).toEqual([0, 0, 0]);
+ expect([wrapDeg(190), wrapDeg(-190), wrapDeg(540), wrapDeg(-180), wrapDeg(-0)]).toEqual([-170, 170, 180, 180, 0]);
+ });
+
+ it("sizes within 2% to 4× the subject distance", () => {
+ expect(sizeRange(5)).toEqual({ min: 5 * PROP_SIZE.min, max: 5 * PROP_SIZE.max });
+ });
+});
+
+describe("the scene state round trip", () => {
+ const c = { url: "/api/files/g1/splat.spz", format: "spz", generationId: "g1", modelId: "oss-idol", name: "Idol 3D", poster: "/api/files/g1/seen.png" };
+
+ it("keeps a moved, turned and sized prop exactly", () => {
+ const moved: SceneProp = { ...placeProp(c, START, 3, 0, "a"), position: [0.25, -0.4, -1.75], rotation: [180, -35.5, 12], size: 0.42, cutoff: 0.12 };
+ const state = { version: 1 as const, props: [moved, placeProp({ ...c, url: "/api/files/g2/model.ply", format: "ply", modelId: "triposplat", name: "TripoSplat" }, START, 3, 1, "b")] };
+ const back = parseSceneState(serializeSceneState(state));
+ expect(back).toEqual(state);
+ expect(sceneStateKey("gen-1")).toBe("fuobe.cinema.scene.gen-1");
+ });
+
+ it("drops what isn't a well-formed prop and never throws", () => {
+ expect(parseSceneState(null)).toEqual(EMPTY_SCENE);
+ expect(parseSceneState("{not json")).toEqual(EMPTY_SCENE);
+ expect(parseSceneState(JSON.stringify({ props: "x" }))).toEqual(EMPTY_SCENE);
+ const good = placeProp(c, START, 3, 0, "ok");
+ const bad = [
+ { ...good, id: "" },
+ { ...good, id: "u", url: "javascript:alert(1)" },
+ { ...good, id: "f", format: "glb" },
+ { ...good, id: "n", position: [0, Number.NaN, 0] },
+ { ...good, id: "s", size: -1 },
+ { ...good, id: "r", rotation: [0, 0] },
+ "a string",
+ null,
+ ];
+ const back = parseSceneState(JSON.stringify({ version: 1, props: [...bad, good, { ...good }] }));
+ expect(back.props.map((p) => p.id)).toEqual(["ok"]);
+ });
+
+ it("keeps cut-offs in the slider's range, angles wrapped, and at most MAX_PROPS", () => {
+ const p = placeProp(c, START, 3, 0, "a");
+ const back = parseSceneState(JSON.stringify({ props: [{ ...p, cutoff: 2, rotation: [0, 270, -540] }] }));
+ expect(back.props[0].cutoff).toBe(0.3);
+ expect(back.props[0].rotation).toEqual([0, -90, 180]);
+ const many = Array.from({ length: MAX_PROPS + 3 }, (_, i) => ({ ...p, id: `p${i}` }));
+ expect(parseSceneState(JSON.stringify({ props: many })).props).toHaveLength(MAX_PROPS);
+ expect(JSON.parse(serializeSceneState({ version: 1, props: many })).props).toHaveLength(MAX_PROPS);
+ });
+});
+
+describe("making a prop from a picture (Idol 3D on your GPU only)", () => {
+ const owner = { engineMode: "both", demoMode: "off", providers: { comfyui: { configured: true } }, idolOn: true };
+
+ it("runs for the owner with a GPU connected, or with placeholder results on", () => {
+ expect(propMakerBlocker(owner)).toBeNull();
+ expect(propMakerBlocker({ ...owner, providers: {}, demoMode: "on" })).toBeNull();
+ expect(propMakerBlocker({ ...owner, providers: {}, ownerGpu: { device: "x" } })).toBeNull();
+ });
+
+ it("says why not otherwise: visitors, Paid APIs only, Idol 3D switched off, no GPU", () => {
+ expect(propMakerBlocker({ ...owner, viewer: { account: "a" } })).toMatch(/isn't available on your account yet/);
+ expect(propMakerBlocker({ ...owner, engineMode: "cloud" })).toMatch(/your GPU \(open source\), which Paid APIs only leaves out/);
+ expect(propMakerBlocker({ ...owner, idolOn: false })).toMatch(/turned off in Settings → Models & licences/);
+ expect(propMakerBlocker({ ...owner, providers: {} })).toMatch(/Connect ComfyUI in Settings/);
+ // Visitor copy names no files, codes or engines' internals.
+ expect(propMakerBlocker({ ...owner, viewer: { account: "a" } })).not.toMatch(/ComfyUI|GPU|Idol|owner|install/i);
+ });
+});
+
+describe("the scene draws props in its own render", () => {
+ const read = (f: string) => fs.readFileSync(path.join(process.cwd(), f), "utf8");
+
+ it("the path render sorts the splats for each frame before drawing it, and the handle never reaches a render", () => {
+ const engine = read("src/components/cinema/scene-engine.ts");
+ const record = engine.slice(engine.indexOf("async recordPath("));
+ expect(record).toMatch(/await this\.splats\.settle\(this\.scene, this\.camera\)/);
+ // The handle is drawn only on screen (out === null) and never for a shot.
+ expect(engine).toMatch(/if \(!out && !shot && this\.gizmo\?\.object\)/);
+ });
+
+ it("props write depth, so the post pass doesn't take them for holes (Uni3C's transparent black)", () => {
+ expect(read("src/components/model3d/splat-engine.ts")).toMatch(/new SparkRenderer\(\{ renderer, onDirty, depthWrite: true/);
+ });
+});
diff --git a/tests/splat-view.test.ts b/tests/splat-view.test.ts
index 73e4f36d..424ee041 100644
--- a/tests/splat-view.test.ts
+++ b/tests/splat-view.test.ts
@@ -122,9 +122,10 @@ describe("Spark loads only with the splat viewer", () => {
for (const f of engineUsers) {
const text = fs.readFileSync(f, "utf8");
// Type imports vanish from the bundle; anything else must be import("./splat-engine").
- expect(text.replace(/import type [^;]+;/g, "").replace(/import\("\.\/splat-engine"\)/g, ""), path.relative(process.cwd(), f)).not.toMatch(/splat-engine/);
+ expect(text.replace(/import type [^;]+;/g, "").replace(/import\("(\.\/|\.\.\/model3d\/)splat-engine"\)/g, ""), path.relative(process.cwd(), f)).not.toMatch(/splat-engine/);
}
- expect(engineUsers.map((f) => path.relative(process.cwd(), f))).toEqual(["src/components/model3d/splat-viewer.tsx"]);
+ // The splat viewer, and Cinema's 3D scene for its props (idol-9; itself loaded only when a scene opens).
+ expect(engineUsers.map((f) => path.relative(process.cwd(), f)).sort()).toEqual(["src/components/cinema/scene-engine.ts", "src/components/model3d/splat-viewer.tsx"]);
});
});