The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Cinema: every frame of a path filmed with a prop is sorted for its own camera, and a prop that can't go in the scene says so
Claudef8cb42df784a
diff --git a/src/components/cinema/scene-engine.ts b/src/components/cinema/scene-engine.tsindex a8598ab1..f57f0a0f 100644--- a/src/components/cinema/scene-engine.ts+++ b/src/components/cinema/scene-engine.ts@@ -245,6 +245,11 @@ export class SceneEngine {private disposed = false;/** A path preview or recording owns the camera. */private playing = false;+ /**+ * A path is being recorded: the screen isn't drawn meanwhile. Drawing it would make Spark sort the props for the+ * on-screen camera while a path frame waits for its own sort, and the frame would be drawn in the wrong order.+ */+ private recording = false;/** 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;@@ -516,7 +521,7 @@ export class SceneEngine {this.refocus();}}- if (this.dirty && this.view && this.info) {+ if (this.dirty && this.view && this.info && !this.recording) {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);}@@ -574,6 +579,8 @@ export class SceneEngine {async addProp(p: SceneProp, o: { signal?: AbortSignal; maxBytes?: number } = {}): Promise<number> {if (!this.splatsLoading) {const loading = import("../model3d/splat-engine").then(({ SceneSplats }) => {+ // The viewer closed while Spark was loading: make nothing for it.+ if (this.disposed) throw new DOMException("Closed", "AbortError");const splats = new SceneSplats(this.renderer, () => (this.dirty = true));this.scene.add(splats.root);this.splats = splats;@@ -764,6 +771,7 @@ export class SceneEngine {if (o.signal?.aborted || this.disposed) throw new DOMException("Stopped", "AbortError");};this.playing = true;+ this.recording = true;try {// Blockout to film: the render as the cloud models read it (MP4 where the browser encodes H.264).if (o.mp4 && !mask) {@@ -804,6 +812,7 @@ export class SceneEngine {out.dispose();this.renderer.setRenderTarget(null);this.playing = false;+ this.recording = false;this.dirty = true;}}diff --git a/src/components/cinema/scene-props.tsx b/src/components/cinema/scene-props.tsxindex 4be8fbd1..9914aa8a 100644--- a/src/components/cinema/scene-props.tsx+++ b/src/components/cinema/scene-props.tsx@@ -51,7 +51,7 @@ export function AddPropDialog({</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} />}+ {full ? <p className="rounded-lg bg-muted/60 p-3 text-[13px]">This scene holds {MAX_PROPS} props at most, counting any still being made. Remove one to add another.</p> : open && <AddPropBody onPlace={onPlace} onMaking={onMaking} />}</DialogContent></Dialog>);@@ -117,7 +117,8 @@ function MakeFromPicture({ onMaking }: { onMaking: (generationId: string) => voi? 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";+ // No price until the preview has one (not while it loads, or when it failed).+ const price = priceLine(preview.data);const make = () => {if (!req) return;create.mutate(req, {@@ -160,7 +161,7 @@ function MakeFromPicture({ onMaking }: { onMaking: (generationId: string) => voi</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}+ {create.isPending ? <Loader2 className="animate-spin" /> : <Plus />} Make the prop{price ? ` · ${price}` : ""}</Button></>)}diff --git a/src/components/cinema/scene-viewer.tsx b/src/components/cinema/scene-viewer.tsxindex 48c4d8d0..23eab58f 100644--- a/src/components/cinema/scene-viewer.tsx+++ b/src/components/cinema/scene-viewer.tsx@@ -320,15 +320,21 @@ export default function SceneViewer({ take, projectId, engine, onEngine, settingif (status === "ready") engineRef.current?.pickProp(pickedReady ? pickedProp : null, handle);}, [pickedProp, pickedReady, handle, status]);+ /** Place a Library splat in the scene; says why not when it can't (the scene isn't ready, or it is full). */const placeCandidate = useCallback(- (c: PropCandidate & { name: string }) => {+ (c: PropCandidate & { name: string }): "placed" | "not-ready" | "full" => {const eng = engineRef.current;- if (!eng || !info) return;+ if (!eng || !info) return "not-ready";+ const ps = propsRef.current;+ if (ps.length >= MAX_PROPS) return "full";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)]));+ const next = [...ps, placeProp(c, eng.getPose(), info.pivotDepth, ps.length, id)];+ propsRef.current = next;+ setProps(next);setPickedProp(id);setHandle("translate");setAddOpen(false);+ return "placed";},[info],);@@ -338,8 +344,10 @@ export default function SceneViewer({ take, projectId, engine, onEngine, settingsetMaking((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");+ const placed = placeCandidate({ ...c, name: propName(c.modelId) });+ if (placed === "placed") toast.success("Your prop is in the scene");+ else if (placed === "full") toast.info(`Your prop is ready in your Library. The scene holds ${MAX_PROPS} props: remove one, then add it from Add a prop`);+ else toast.info("Your prop is ready in your Library. Add it to the scene from Add a prop");} else toast.error("Couldn't make the prop from that picture. Try another picture, with one object on a plain background");},[placeCandidate],@@ -976,7 +984,7 @@ export default function SceneViewer({ take, projectId, engine, onEngine, settingsetAddOpen(false);toast.success("Making your prop — it lands in the scene when it's ready", { duration: 3000 });}}- full={props.length >= MAX_PROPS}+ full={props.length + making.length >= MAX_PROPS}/>{making.length > 0 && <MakingWatch ids={making} onDone={madeProp} />}</DialogContent>diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsxindex 565c6b4a..2e475c17 100644--- a/src/components/cinema/workspace.tsx+++ b/src/components/cinema/workspace.tsx@@ -634,6 +634,7 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG/>{openScene && (<SceneViewer+ key={openScene.generation.id}take={openScene}projectId={id}engine={engine}diff --git a/src/lib/scene-props.ts b/src/lib/scene-props.tsindex d38090c0..f7596d4d 100644--- a/src/lib/scene-props.ts+++ b/src/lib/scene-props.ts@@ -139,7 +139,7 @@ function parseProp(v: unknown): SceneProp | null {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;+ 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);diff --git a/tests/e2e/cinema-props.mjs b/tests/e2e/cinema-props.mjsindex ddb4f81b..cac4c053 100644--- a/tests/e2e/cinema-props.mjs+++ b/tests/e2e/cinema-props.mjs@@ -51,13 +51,32 @@ const hideDevBadge = (ctx) =>const noSideScroll = async (page, what) => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth), 0, `${what}: nothing scrolls sideways`);const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-props-"));-/** The first frame of a path render as raw RGB (ffmpeg), with its size. */-async function firstFrame(url, name) {+/** The first and last frames of a path render as raw RGB (ffmpeg), with their size. */+async function ends(url, name) {const file = path.join(tmp, `${name}${path.extname(url)}`);fs.writeFileSync(file, Buffer.from(await (await (await api).fetch(app + url)).body()));const probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "json", file]).toString()).streams[0];- const rgb = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 64 << 20 });- return { width: probe.width, height: probe.height, rgb };+ const first = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 64 << 20 });+ // The last half second, then its last frame.+ const tail = execFileSync("ffmpeg", ["-v", "error", "-sseof", "-0.5", "-i", file, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 256 << 20 });+ const n = probe.width * probe.height * 3;+ return { width: probe.width, height: probe.height, first, last: tail.subarray(tail.length - n) };+}++/** How one frame differs from the same frame without the prop: changed pixels, the splat's violet, the handle's colours. */+function compare(a, b) {+ let changed = 0;+ let violet = 0;+ let handle = 0;+ for (let i = 0; i < a.length; i += 3) {+ const d = Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]);+ if (d < 60) continue;+ changed++;+ const [r, g, bl] = [b[i], b[i + 1], b[i + 2]];+ if (bl > r + 25 && bl > g + 25) violet++;+ if ((r > 180 && g < 90 && bl < 90) || (g > 180 && r < 90 && bl < 90)) handle++;+ }+ return { changed, violet, handle };}const status = await call("/api/status");@@ -124,8 +143,11 @@ try {await aside.getByRole("button", { name: "Add a prop" }).click();const dialog = page.getByRole("dialog", { name: "Add a prop" });await dialog.getByRole("heading", { name: "From a picture" }).waitFor();- // The owner on placeholder results may make one from a picture (Idol 3D on the GPU), priced before it runs.- await dialog.getByRole("button", { name: /^Make the prop · / }).waitFor();+ // The owner on placeholder results may make one from a picture (Idol 3D on the GPU). No price shows until a picture+ // is picked and priced (never a "Free" guessed before the preview).+ const makeButton = dialog.getByRole("button", { name: /^Make the prop/ });+ await makeButton.waitFor();+ assert.equal((await makeButton.textContent()).trim(), "Make the prop", "no price before a picture is picked");await shoot(page, "props-add-dialog-dark");await dialog.getByRole("button", { name: /^Place Idol 3D/ }).first().click();await dialog.waitFor({ state: "detached" });@@ -169,26 +191,22 @@ try {// The prop stays picked: its handle shows on screen, and must not reach the render.await page.mouse.move(1300, 20);const withProp = await filmOpen(page, seen);- const a = await firstFrame(plain.request.inputs.video, "plain");- const b = await firstFrame(withProp.request.inputs.video, "prop");+ const a = await ends(plain.request.inputs.video, "plain");+ const b = await ends(withProp.request.inputs.video, "prop");assert.equal(a.width, b.width);assert.equal(a.height, b.height);- let changed = 0;- let violet = 0;- let handle = 0;- for (let i = 0; i < a.rgb.length; i += 3) {- const d = Math.abs(a.rgb[i] - b.rgb[i]) + Math.abs(a.rgb[i + 1] - b.rgb[i + 1]) + Math.abs(a.rgb[i + 2] - b.rgb[i + 2]);- if (d < 60) continue;- changed++;- const [r, g, bl] = [b.rgb[i], b.rgb[i + 1], b.rgb[i + 2]];- if (bl > r + 25 && bl > g + 25) violet++;- if ((r > 180 && g < 90 && bl < 90) || (g > 180 && r < 90 && bl < 90)) handle++;- }const total = a.width * a.height;+ const { changed, violet, handle } = compare(a.first, b.first);console.log(` first frame ${a.width}x${a.height}: ${changed} px changed (${((changed / total) * 100).toFixed(1)}%), ${violet} violet, ${handle} handle-coloured`);assert.ok(changed > total * 0.01, "the prop changes the render's first frame");assert.ok(violet > changed * 0.5, "what changed is the prop's violet");assert.ok(handle < changed * 0.01, "the handle isn't in the render");+ // The last frame, the furthest from where the screen's camera stayed, shows the prop too, and only the prop.+ const late = compare(a.last, b.last);+ console.log(` last frame: ${late.changed} px changed (${((late.changed / total) * 100).toFixed(1)}%), ${late.violet} violet, ${late.handle} handle-coloured`);+ assert.ok(late.changed > total * 0.01, "the prop is in the render's last frame");+ assert.ok(late.violet > late.changed * 0.5, "what changed in the last frame is the prop's violet");+ assert.ok(late.handle < late.changed * 0.01, "the handle isn't in the last frame");step("the prop is kept for the scene after a reload");await page.reload({ waitUntil: "load" });diff --git a/tests/scene-props.test.ts b/tests/scene-props.test.tsindex e9aa0830..7a674b0d 100644--- a/tests/scene-props.test.ts+++ b/tests/scene-props.test.ts@@ -128,6 +128,7 @@ describe("the scene state round trip", () => {const bad = [{ ...good, id: "" },{ ...good, id: "u", url: "javascript:alert(1)" },+ { ...good, id: "pr", url: "//elsewhere.example/x.spz" },{ ...good, id: "f", format: "glb" },{ ...good, id: "n", position: [0, Number.NaN, 0] },{ ...good, id: "s", size: -1 },@@ -189,4 +190,37 @@ describe("the scene draws props in its own render", () => {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/);});++ it("doesn't draw the screen while a path records, so every path frame keeps its own camera's sort", () => {+ const engine = read("src/components/cinema/scene-engine.ts");+ // step() draws only when not recording (a screen draw would start a sort for the on-screen camera mid-frame).+ expect(engine).toMatch(/if \(this\.dirty && this\.view && this\.info && !this\.recording\)/);+ const record = engine.slice(engine.indexOf("async recordPath("), engine.indexOf("dispose() {"));+ expect(record).toMatch(/this\.recording = true;/);+ // ...and gives the screen back however the recording ends.+ expect(record.slice(record.indexOf("} finally {"))).toMatch(/this\.recording = false;/);+ });++ it("makes no Spark renderer for a viewer that closed while Spark was loading", () => {+ const engine = read("src/components/cinema/scene-engine.ts");+ const add = engine.slice(engine.indexOf("async addProp("), engine.indexOf("updateProp(p: SceneProp)"));+ expect(add.indexOf("if (this.disposed)")).toBeGreaterThan(-1);+ expect(add.indexOf("if (this.disposed)")).toBeLessThan(add.indexOf("new SceneSplats("));+ });++ it("a prop made from a picture says so when it couldn't go in the scene, and props being made count towards the most", () => {+ const viewer = read("src/components/cinema/scene-viewer.tsx");+ const made = viewer.slice(viewer.indexOf("const madeProp"), viewer.indexOf("const changeProp"));+ expect(made).toMatch(/if \(placed === "placed"\) toast\.success\("Your prop is in the scene"\)/);+ expect(made).toMatch(/placed === "full"/);+ expect(viewer).toMatch(/full=\{props\.length \+ making\.length >= MAX_PROPS\}/);+ // A new scene opened in place starts from its own props.+ expect(read("src/components/cinema/workspace.tsx")).toMatch(/<SceneViewer\s+key=\{openScene\.generation\.id\}/);+ });++ it("the Make the prop button shows no price until the preview has one", () => {+ const ui = read("src/components/cinema/scene-props.tsx");+ expect(ui).not.toMatch(/priceLine\(preview\.data\) \?\? "Free"/);+ expect(ui).toMatch(/Make the prop\{price \? ` · \$\{price\}` : ""\}/);+ });});