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.

Fly around: exact orbits by numbers, a server render of the path, and /api/fly-around

Claude84f952fb932f
diff --git a/src/app/api/fly-around/route.ts b/src/app/api/fly-around/route.ts
new file mode 100644
index 00000000..44eb17b4
--- /dev/null
+++ b/src/app/api/fly-around/route.ts
@@ -0,0 +1,22 @@
+import { body, handle, once } from "@/server/shorts-schemas";
+import { createFlyAround, FlyAroundSchema, previewFlyAround } from "@/server/fly-around";
+import { priceAs } from "@/server/visitor";
+
+/**
+ * Fly around (build plan N7-7): a still filmed along an exact camera path (an orbit's numbers, a preset or keys), on either
+ * engine. `?preview=1` plans and prices it without running it. Fuobe DoP, Image to 3D, Canvas and Assist call it.
+ */
+async function post(request: Request) {
+ return handle(async () => {
+ const { requestId, ...input } = await body(request, FlyAroundSchema, "Pick the engine, the still and the path");
+ if (new URL(request.url).searchParams.get("preview")) return Response.json(previewFlyAround(input));
+ // A plan that can't run (FlyAroundError) is a 422 with its reason, as any planner's error is.
+ const result = await once("fly-around", requestId, () => createFlyAround(input));
+ return Response.json(result, { status: 201 });
+ }, request);
+}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/lib/catalog/fly-around.ts b/src/lib/catalog/fly-around.ts
new file mode 100644
index 00000000..52c23705
--- /dev/null
+++ b/src/lib/catalog/fly-around.ts
@@ -0,0 +1,182 @@
+/**
+ * Fly around (build plan N7-7; research new-models-7.md §3.10 rows 3-5): a still filmed along an exact camera path, with no
+ * browser view of its scene. Fuobe DoP's and Cinema's exact orbits, Image to 3D's "Film it photoreal", Canvas's "Fly
+ * around" node and Assist's fly_around tool all plan through here, on N7-5's models:
+ *
+ * - Open engine: MoGe 2 (oss-scene-moge) makes the still's depth, the server renders the path through that depth as a point
+ * cloud (src/server/path-render.ts, ChainSlot.render "path"), and Wan 2.1 + Uni3C (oss-uni3c-path) films the still along
+ * it. With a render already made (Image to 3D records its model along the path in the browser), the depth step is skipped.
+ * - Cloud: H3 Max camera-controls with the path as its keyframes. With reference views (Canvas "Fly around" with views),
+ * MiniMax H3 Max reference-to-video takes the still and the views, and the path goes in words (N7-6's References route).
+ *
+ * Pure: the browser prices it, the server runs the same steps (src/server/fly-around.ts).
+ */
+
+import { DEFAULT_MOTION, MAX_KEYS, PATH_FPS, PATH_FRAMES, normalizeKeys, presetKeys, toH3MaxTrajectory, type CameraKey } from "@/lib/camera-path";
+import { exactOrbitKeys, exactSummary, exactWords, type ExactOrbit } from "@/lib/exact-orbit";
+import { getModel, getPreset } from "./index";
+import { onEngine } from "./engines";
+import { estimateCost, planGeneration } from "./plan";
+import type { Engine, GenerationRequest, GenParams, ModelDef } from "./types";
+
+/** What films a path on each engine (N7-5's), what makes the depth on the open engine, and the cloud's route with views. */
+export const FLY_MODELS = { open: "oss-uni3c-path", cloud: "minimax-h3-max-camera", depth: "oss-scene-moge", views: "minimax-h3-max" } as const;
+/** The cloud's lengths; the open engine always makes 81 frames at 16 fps (about 5 s). */
+export const FLY_DURATIONS = [3, 5, 8, 10, 15];
+export const FLY_VIEWS_MAX = 8;
+/** MoGe's scene for a render only needs its depth picture: a lighter mesh. */
+const DEPTH_DECIMATION = 4;
+
+export interface FlyAroundInput {
+ engine: Engine;
+ /** The still to film (the first frame). */
+ image?: string;
+ /** Other views of the subject (cloud: references; the open engine films from the still alone). */
+ views?: string[];
+ /** The path: an exact orbit, a preset id (camera-path PATH_PRESETS, orbit_<N>_cw…) or keys. The first that is given wins. */
+ orbit?: Partial<ExactOrbit>;
+ preset?: string;
+ keys?: CameraKey[];
+ /** A render of the path made already (Image to 3D's model recorded in the browser): the open engine's guide. */
+ render?: string;
+ prompt?: string;
+ duration?: number;
+ resolution?: string;
+ feature?: string;
+ title?: string;
+ seed?: number;
+}
+
+export interface FlyStep {
+ key: string;
+ request: GenerationRequest;
+ after?: string[];
+}
+
+export interface FlyAroundPlan {
+ engine: Engine;
+ model: ModelDef;
+ keys: CameraKey[];
+ /** The path in words, for the result's caption ("360° counter-clockwise · level"). */
+ label: string;
+ steps: FlyStep[];
+ notes: string[];
+ blocker?: string;
+ costUsd: number | null;
+ /** Seconds of film. */
+ duration: number;
+}
+
+/** The keys a request asks for: an orbit's numbers, a preset or keys, from the photo's pose. Empty when none is given. */
+export function flyKeys(input: Pick<FlyAroundInput, "orbit" | "preset" | "keys">): { keys: CameraKey[]; label: string } {
+ if (input.orbit) return { keys: exactOrbitKeys(input.orbit), label: exactSummary(input.orbit) };
+ const fromPreset = input.preset ? presetKeys(input.preset) : null;
+ if (fromPreset) return { keys: fromPreset, label: input.preset!.replace(/_/g, " ") };
+ const keys = input.keys?.length ? normalizeKeys(input.keys).slice(0, MAX_KEYS) : [];
+ return { keys, label: keys.length > 1 ? `${keys.length} keyframes` : "" };
+}
+
+const tidy = (p: string | undefined) => (p ?? "").trim();
+
+function stepCost(req: GenerationRequest, engine: Engine): number | null {
+ const lookup = (id: string) => {
+ const m = getModel(id);
+ return m && onEngine(m, engine);
+ };
+ // Chained inputs are priced with stand-ins (the render a step makes first).
+ const filled: GenerationRequest = req.chain?.some((c) => c.slot === "video") ? { ...req, inputs: { ...req.inputs, video: "/api/files/placeholder.mp4" } } : req;
+ const p = planGeneration(filled, lookup, getPreset);
+ return estimateCost(p.model, p.params, 1, p.op);
+}
+
+/** Plan a fly-around: the steps each engine runs, priced (free on the open engine), and what it still needs. */
+export function planFlyAround(input: FlyAroundInput): FlyAroundPlan {
+ const { engine } = input;
+ const feature = input.feature ?? "fly-around";
+ const { keys, label } = flyKeys(input);
+ const views = (input.views ?? []).filter(Boolean).slice(0, FLY_VIEWS_MAX);
+ const notes: string[] = [];
+ const seed = input.seed !== undefined ? { seed: input.seed } : {};
+ const title = input.title ? { title: input.title } : {};
+ const steps: FlyStep[] = [];
+ let model: ModelDef;
+ let duration: number;
+ const image = input.image;
+ if (engine === "open") {
+ model = getModel(FLY_MODELS.open)!;
+ duration = Math.round((PATH_FRAMES / PATH_FPS) * 10) / 10;
+ const resolution = model.options.resolutions?.find((r) => r.toLowerCase() === input.resolution?.toLowerCase()) ?? "480p";
+ const params: GenParams = { numOutputs: 1, aspectRatio: "auto", resolution, cameraPath: keys, ...seed };
+ const prompt = tidy(input.prompt) || DEFAULT_MOTION;
+ if (input.render) {
+ notes.push(`Wan 2.1 starts from the still and Uni3C keeps its camera on your render of the path — ${PATH_FRAMES} frames at ${PATH_FPS} fps (${duration} s) on your GPU`);
+ steps.push({ key: "main", request: { feature, modelId: model.id, op: "camera-path", prompt, ...title, inputs: image ? { images: [image], video: input.render } : undefined, params } });
+ } else {
+ const depth = getModel(FLY_MODELS.depth)!;
+ notes.push(
+ `MoGe 2 measures the still's depth, the studio renders the path through it, then Wan 2.1 films the still along that render with Uni3C — ${PATH_FRAMES} frames at ${PATH_FPS} fps (${duration} s) on your GPU, which needs about 48 GB`,
+ );
+ steps.push({
+ key: "depth",
+ request: { feature, modelId: depth.id, op: "scene-3d", prompt: "", inputs: image ? { images: [image] } : undefined, params: { numOutputs: 1, extra: { decimation: DEPTH_DECIMATION } }, step: { label: "Depth of the still", index: 0, of: 2 } },
+ });
+ steps.push({
+ key: "main",
+ request: { feature, modelId: model.id, op: "camera-path", prompt, ...title, inputs: image ? { images: [image] } : undefined, chain: [{ slot: "video", render: "path" }], params, step: { label: "Film along the path", index: 1, of: 2 } },
+ after: ["depth"],
+ });
+ }
+ if (views.length) notes.push("Your other views aren't used on your GPU: it films from the still alone");
+ } else if (views.length) {
+ model = getModel(FLY_MODELS.views)!;
+ duration = nearest(model.options.durations ?? FLY_DURATIONS, input.duration ?? 5);
+ const resolution = model.options.resolutions?.find((r) => r.toLowerCase() === input.resolution?.toLowerCase()) ?? model.defaults?.resolution;
+ const max = model.options.maxImages ?? 9;
+ const images = image ? [image, ...views].slice(0, max) : views.slice(0, max);
+ if (1 + views.length > max) notes.push(`${model.name} takes up to ${max} pictures: the rest are left out`);
+ const words = input.orbit ? exactWords(input.orbit) : "The camera flies around the subject";
+ steps.push({
+ key: "main",
+ request: {
+ feature,
+ modelId: model.id,
+ op: "ref2v",
+ prompt: `${words}. Image 1 is the first frame; the other images show the same subject from other sides. ${tidy(input.prompt) || DEFAULT_MOTION}`,
+ ...title,
+ inputs: { images },
+ params: { numOutputs: 1, duration, ...(resolution ? { resolution } : {}), ...seed },
+ },
+ });
+ notes.push(`${model.name} takes the still and your ${views.length} view${views.length === 1 ? "" : "s"} as references and turns the camera from the words: the sides hold, the path is loose`);
+ } else {
+ model = getModel(FLY_MODELS.cloud)!;
+ const range = model.routes[0]?.map?.ranges?.duration;
+ duration = Math.min(range?.max ?? 15, Math.max(Math.max(1, range?.min ?? 1), Math.round((input.duration ?? 5) * 10) / 10));
+ const resolution = model.options.resolutions?.find((r) => r.toLowerCase() === input.resolution?.toLowerCase()) ?? model.defaults?.resolution;
+ if (keys.length > 1) {
+ const cam = toH3MaxTrajectory(keys);
+ notes.push("trajectory" in cam ? `H3 Max follows the ${cam.trajectory.length} keyframes from the still, with prompt expansion off` : cam.notes[0]);
+ if ("trajectory" in cam) notes.push(...cam.notes);
+ }
+ steps.push({
+ key: "main",
+ request: { feature, modelId: model.id, op: "camera-path", prompt: tidy(input.prompt) || DEFAULT_MOTION, ...title, inputs: image ? { images: [image] } : undefined, params: { numOutputs: 1, duration, ...(resolution ? { resolution } : {}), cameraPath: keys, ...seed } },
+ });
+ }
+ let blocker = !image ? "Add the still to film" : keys.length < 2 && !(engine === "cloud" && views.length) ? "Pick a path first" : undefined;
+ let cost: number | null = 0;
+ for (const s of steps) {
+ try {
+ const priced: GenerationRequest = s.request.inputs?.images?.length ? s.request : { ...s.request, inputs: { ...s.request.inputs, images: ["/api/files/placeholder.png"] } };
+ const c = stepCost(priced, engine);
+ cost = c === null || cost === null ? null : cost + c;
+ } catch (e) {
+ blocker ??= (e as Error).message;
+ }
+ }
+ return { engine, model, keys, label, steps, notes, ...(blocker && { blocker }), costUsd: cost === null ? null : Math.round(cost * 1000) / 1000, duration };
+}
+
+function nearest(list: number[], n: number): number {
+ return list.reduce((best, x) => (Math.abs(x - n) < Math.abs(best - n) ? x : best), list[0] ?? n);
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index ac15098f..9195c30d 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1154,6 +1154,12 @@ export interface ChainSlot {
* with a look makes each next frame from the previous one, and every frame gets the look's grade on its own.
*/
raw?: boolean;
+ /**
+ * "path" (build plan N7-7, a video slot): the server renders the step's camera path (params.cameraPath) through the
+ * scene the dependency made from the step's still (MoGe 2's depth picture), and that render is the input: Uni3C's guide
+ * when no browser has drawn one (Canvas, Assist, Fuobe DoP, Cinema's exact orbits). src/server/path-render.ts.
+ */
+ render?: "path";
}
/** How many outputs a planned list (ChainSlot.of) may be short of before the steps reading it fail. */
diff --git a/src/lib/exact-orbit.ts b/src/lib/exact-orbit.ts
new file mode 100644
index 00000000..2308e3b6
--- /dev/null
+++ b/src/lib/exact-orbit.ts
@@ -0,0 +1,110 @@
+/**
+ * Exact orbits (build plan N7-7; research new-models-7.md §3.10 rows 3-5): an orbit move picked in Fuobe DoP, Cinema's
+ * Director or Image to 3D, set by numbers instead of a LoRA's or a prompt's idea of an orbit: how far round (30-360°),
+ * which way (seen from above), a height tilt (0-20°, a ring tilted like the camera path library's Tilted ring) and a
+ * radius pulse (none or 25% in, twice). The numbers become the camera path library's keys (src/lib/camera-path.ts), so
+ * both engines film them the way N7-5's Fly path does: H3 Max camera-controls on the cloud, Uni3C on your GPU.
+ *
+ * Pure: no DOM, no server.
+ */
+
+import { PHOTO_KEY, type CameraKey } from "./camera-path";
+
+export type OrbitDirection = "cw" | "ccw";
+
+export interface ExactOrbit {
+ /** Degrees round the subject, 30-360. */
+ degrees: number;
+ /** Seen from above: counter-clockwise moves the camera round to the right (camera-path's + azimuth). */
+ direction: OrbitDirection;
+ /** Degrees the ring is tilted (0 = level): it rises on the way round and comes back level. */
+ tilt: number;
+ /** How far the camera moves in and out on the way round (0 or 0.25 = 25% closer, twice). */
+ pulse: number;
+}
+
+export const EXACT_LIMITS = { degrees: { min: 30, max: 360, step: 5 }, tilt: { min: 0, max: 20, step: 1 }, pulses: [0, 0.25] } as const;
+
+export const DIRECTION_NAMES: Record<OrbitDirection, string> = { cw: "Clockwise", ccw: "Counter-clockwise" };
+
+const DEG = Math.PI / 180;
+const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));
+const tidy = (n: number, digits = 3) => Number(n.toFixed(digits)) + 0;
+
+/**
+ * The orbit moves that take the Exact switch, by Fuobe DoP preset id and by Cinema move slug, with the numbers each starts
+ * from. Arc Left moves the camera round to the left (clockwise from above), Arc Right to the right.
+ */
+export const EXACT_DEFAULTS: Readonly<Record<string, ExactOrbit>> = {
+ // Fuobe DoP / Motions (src/lib/catalog/motions.ts, Orbit)
+ "motion-360-orbit": { degrees: 360, direction: "ccw", tilt: 0, pulse: 0 },
+ "motion-arc-left": { degrees: 90, direction: "cw", tilt: 0, pulse: 0 },
+ "motion-arc-right": { degrees: 90, direction: "ccw", tilt: 0, pulse: 0 },
+ "motion-lazy-orbit": { degrees: 60, direction: "ccw", tilt: 5, pulse: 0 },
+ // Cinema's Director (src/lib/catalog/cinema.ts CAMERA_MOVES)
+ "drone-orbit": { degrees: 360, direction: "ccw", tilt: 15, pulse: 0 },
+ "arc-left": { degrees: 90, direction: "cw", tilt: 0, pulse: 0 },
+ "arc-right": { degrees: 90, direction: "ccw", tilt: 0, pulse: 0 },
+ "bullet-time": { degrees: 180, direction: "ccw", tilt: 0, pulse: 0 },
+};
+
+/** Whether a DoP preset or a Cinema move takes the Exact switch. */
+export const takesExact = (id: string | null | undefined): boolean => !!id && Object.hasOwn(EXACT_DEFAULTS, id);
+
+/** The numbers a move starts from (360° counter-clockwise, level, for anything else). */
+export function exactDefaults(id?: string | null): ExactOrbit {
+ return { ...(id && Object.hasOwn(EXACT_DEFAULTS, id) ? EXACT_DEFAULTS[id] : { degrees: 360, direction: "ccw" as const, tilt: 0, pulse: 0 }) };
+}
+
+/** The numbers inside their ranges: degrees 30-360 in 5° steps, tilt 0-20°, pulse 0 or 25%. */
+export function normalizeExact(o: Partial<ExactOrbit> | undefined, fallback: ExactOrbit = exactDefaults()): ExactOrbit {
+ const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) ? v : d);
+ const { degrees, tilt } = EXACT_LIMITS;
+ return {
+ degrees: clamp(Math.round(num(o?.degrees, fallback.degrees) / degrees.step) * degrees.step, degrees.min, degrees.max),
+ direction: o?.direction === "cw" || o?.direction === "ccw" ? o.direction : fallback.direction,
+ tilt: clamp(Math.round(num(o?.tilt, fallback.tilt)), tilt.min, tilt.max),
+ pulse: num(o?.pulse, fallback.pulse) >= 0.125 ? 0.25 : 0,
+ };
+}
+
+/** The most keys an exact orbit has: 12, all of which H3 Max takes, so both engines follow the same keys. */
+export const EXACT_MAX_KEYS = 12;
+
+/**
+ * The orbit as camera-path keys, evenly spaced in time from the photo's pose: a key at least every 30° (at least 5 keys,
+ * so a tilt and a pulse show on a short arc). The tilt is a ring tilted about the photo's line of sight (elevation =
+ * asin(sin tilt · sin turned)), rising first whichever way it turns; the pulse takes the camera 25% in and out twice.
+ */
+export function exactOrbitKeys(input: Partial<ExactOrbit>): CameraKey[] {
+ const o = normalizeExact(input);
+ const n = clamp(Math.ceil(o.degrees / 30 - 1e-9), 4, EXACT_MAX_KEYS - 1);
+ const sign = o.direction === "ccw" ? 1 : -1;
+ return Array.from({ length: n + 1 }, (_, i) => {
+ const f = i / n;
+ const turned = o.degrees * f;
+ if (i === 0) return { ...PHOTO_KEY };
+ return {
+ t: tidy(f, 4),
+ azimuth: tidy(sign * turned, 2),
+ elevation: tidy(Math.asin(Math.sin(o.tilt * DEG) * Math.sin(turned * DEG)) / DEG, 2),
+ distance: tidy(1 - o.pulse * Math.sin(2 * Math.PI * f) ** 2, 4),
+ };
+ });
+}
+
+/** The numbers in a few words: "360° counter-clockwise · tilt 10° · pulse 25%". */
+export function exactSummary(input: Partial<ExactOrbit>): string {
+ const o = normalizeExact(input);
+ return [`${o.degrees}° ${DIRECTION_NAMES[o.direction].toLowerCase()}`, o.tilt ? `tilt ${o.tilt}°` : "level", ...(o.pulse ? [`pulse ${Math.round(o.pulse * 100)}%`] : [])].join(" · ");
+}
+
+/** Words for a model that reads the path from the prompt (the cloud's reference route): where the camera goes. */
+export function exactWords(input: Partial<ExactOrbit>): string {
+ const o = normalizeExact(input);
+ const way = o.direction === "ccw" ? "to the right" : "to the left";
+ const how = o.degrees >= 360 ? "a full 360-degree orbit" : `a ${o.degrees}-degree arc`;
+ const tilt = o.tilt ? `, the ring tilted ${o.tilt} degrees so the camera rises and comes back to eye level` : ", at a constant height";
+ const pulse = o.pulse ? ", moving in and out twice on the way" : "";
+ return `The camera makes ${how} around the subject, moving ${way}${tilt}${pulse}, keeping the subject centered`;
+}
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index c09b412f..674d52c9 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -97,7 +97,7 @@ export function guestRead(pathname: string): GuestRead {
* The run routes whose `?preview=1` only plans and prices (any other route would ignore the flag and run). AI
* Influencer, Fashion Factory and Character Sheet price on load, with synchronous price functions.
*/
-const PREVIEWS = [/^\/api\/(generations|audio-tools|dub|katana|turnaround|influencer|photodump|photodump\/fashion|photodump\/character)$/, /^\/api\/dub\/[^/]+\/voice$/];
+const PREVIEWS = [/^\/api\/(generations|audio-tools|dub|katana|turnaround|fly-around|influencer|photodump|photodump\/fashion|photodump\/character)$/, /^\/api\/dub\/[^/]+\/voice$/];
/** The estimate routes (named: a dynamic segment called "estimate" on another route must not pass for one). */
const ESTIMATES =
diff --git a/src/lib/path-splat.ts b/src/lib/path-splat.ts
new file mode 100644
index 00000000..5d34a089
--- /dev/null
+++ b/src/lib/path-splat.ts
@@ -0,0 +1,63 @@
+/**
+ * A headless point-cloud renderer (build plan N7-7, option B): the frames of a camera path drawn through a still's point
+ * cloud (scene3d buildPointCloud) with no browser and no GPU, for the server's path render (src/server/path-render.ts).
+ * It draws what the browser's recordPath draws for Uni3C: the points seen from each camera, nearest in front, black where
+ * nothing was seen.
+ *
+ * Pure: typed arrays in, typed arrays out.
+ */
+
+import type { Mat3, Mat4 } from "./camera-path";
+import type { PointCloud } from "./scene3d";
+
+/** The widest a point is drawn (pixels), so a point right in front of the camera doesn't paint the whole frame. */
+export const MAX_SPLAT_PX = 6;
+
+/**
+ * One frame, RGB (3 bytes a pixel, rows top-down), of `cloud` (glTF axes: x right, y up, the photo looking down −Z) seen by
+ * a camera-to-world `pose` in OpenCV axes (x right, y down, z forward; the world is the photo camera's own frame, as
+ * camera-path framePoses makes them) with pixel intrinsic `k`. Each point is a square as wide as its size at its distance.
+ */
+export function splatFrame(cloud: Pick<PointCloud, "positions" | "colors" | "sizes" | "count">, pose: Mat4, k: Mat3, width: number, height: number, out?: Uint8Array): Uint8Array {
+ const rgb = out ?? new Uint8Array(width * height * 3);
+ rgb.fill(0);
+ const zbuf = new Float32Array(width * height).fill(Infinity);
+ const [fx, fy, cx, cy] = [k[0][0], k[1][1], k[0][2], k[1][2]];
+ // World → camera: R^T (p − eye), R's columns being the camera's right, down and forward.
+ const ex = pose[0][3];
+ const ey = pose[1][3];
+ const ez = pose[2][3];
+ const r = [0, 1, 2].map((c) => [pose[0][c], pose[1][c], pose[2][c]]);
+ const { positions: P, colors: C, sizes: S } = cloud;
+ for (let i = 0; i < cloud.count; i++) {
+ // glTF → OpenCV: y and z flip.
+ const px = P[i * 3] - ex;
+ const py = -P[i * 3 + 1] - ey;
+ const pz = -P[i * 3 + 2] - ez;
+ const zc = r[2][0] * px + r[2][1] * py + r[2][2] * pz;
+ if (zc <= 1e-4) continue;
+ const xc = r[0][0] * px + r[0][1] * py + r[0][2] * pz;
+ const yc = r[1][0] * px + r[1][1] * py + r[1][2] * pz;
+ const u = (fx * xc) / zc + cx;
+ const v = (fy * yc) / zc + cy;
+ const half = Math.min(MAX_SPLAT_PX, Math.max(1, (fx * S[i]) / zc)) / 2;
+ const x0 = Math.max(0, Math.floor(u - half));
+ const x1 = Math.min(width - 1, Math.ceil(u + half) - 1);
+ const y0 = Math.max(0, Math.floor(v - half));
+ const y1 = Math.min(height - 1, Math.ceil(v + half) - 1);
+ if (x0 > x1 || y0 > y1) continue;
+ const red = Math.round(C[i * 3] * 255);
+ const green = Math.round(C[i * 3 + 1] * 255);
+ const blue = Math.round(C[i * 3 + 2] * 255);
+ for (let y = y0; y <= y1; y++)
+ for (let x = x0; x <= x1; x++) {
+ const o = y * width + x;
+ if (zc >= zbuf[o]) continue;
+ zbuf[o] = zc;
+ rgb[o * 3] = red;
+ rgb[o * 3 + 1] = green;
+ rgb[o * 3 + 2] = blue;
+ }
+ }
+ return rgb;
+}
diff --git a/src/server/fly-around.ts b/src/server/fly-around.ts
new file mode 100644
index 00000000..44a2ae58
--- /dev/null
+++ b/src/server/fly-around.ts
@@ -0,0 +1,150 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import { DISTANCE, MAX_KEYS } from "@/lib/camera-path";
+import { EXACT_LIMITS } from "@/lib/exact-orbit";
+import { FLY_VIEWS_MAX, planFlyAround, type FlyAroundInput, type FlyAroundPlan, type FlyStep } from "@/lib/catalog/fly-around";
+import type { Generation } from "@/lib/catalog/types";
+import { cancelGeneration, createGenerations, previewChained, previewGeneration } from "./generations";
+import { isOffered } from "./model-access";
+
+/**
+ * Fly around (build plan N7-7): the plan from src/lib/catalog/fly-around.ts, checked step by step on this install (keys,
+ * demo mode, Settings → Models & licences, the engine mode) and run as one batch. Fuobe DoP's exact orbits, Image to 3D's
+ * "Film it photoreal", Canvas's Fly around node and Assist's fly_around tool call it (/api/fly-around).
+ */
+
+const FileRef = z.string().startsWith("/api/files/").max(500);
+
+export const CameraKeySchema = z.object({
+ t: z.number().min(0).max(1),
+ azimuth: z.number().min(-360 * 32).max(360 * 32),
+ elevation: z.number().min(-90).max(90),
+ distance: z.number().min(DISTANCE.min).max(DISTANCE.max),
+ truck: z.number().min(-4).max(4).optional(),
+});
+
+export const ExactOrbitSchema = z.object({
+ degrees: z.number().min(EXACT_LIMITS.degrees.min).max(EXACT_LIMITS.degrees.max),
+ direction: z.enum(["cw", "ccw"]),
+ tilt: z.number().min(EXACT_LIMITS.tilt.min).max(EXACT_LIMITS.tilt.max).default(0),
+ pulse: z.number().min(0).max(0.25).default(0),
+});
+
+/** What /api/fly-around takes. */
+export const FlyAroundSchema = z.object({
+ engine: z.enum(["cloud", "open"]),
+ image: FileRef.optional(),
+ views: z.array(FileRef).max(FLY_VIEWS_MAX).optional(),
+ orbit: ExactOrbitSchema.optional(),
+ preset: z.string().max(40).optional(),
+ keys: z.array(CameraKeySchema).min(1).max(MAX_KEYS).optional(),
+ render: FileRef.optional(),
+ prompt: z.string().max(1500).optional(),
+ duration: z.number().min(1).max(15).optional(),
+ resolution: z.string().max(10).optional(),
+ /** Where the run is filed: Fuobe DoP's move, Image to 3D or Canvas (default "fly-around"). */
+ feature: z.enum(["fly-around", "motion", "model3d", "canvas", "assist"]).optional(),
+ title: z.string().max(80).optional(),
+ seed: z.number().int().min(0).max(4_294_967_295).optional(),
+ requestId: z.string().max(80).optional(),
+});
+
+export class FlyAroundError extends Error {
+ constructor(
+ message: string,
+ public status = 422,
+ ) {
+ super(message);
+ }
+}
+
+export interface FlyAroundPreview {
+ engine: FlyAroundPlan["engine"];
+ model: { id: string; name: string };
+ label: string;
+ keys: FlyAroundPlan["keys"];
+ duration: number;
+ steps: number;
+ notes: string[];
+ blocker?: string;
+ costUsd: number | null;
+ demo: boolean;
+}
+
+/** The plan as this install runs it: a model switched off in Settings → Models & licences is a blocker. */
+function plan(input: FlyAroundInput): FlyAroundPlan {
+ const p = planFlyAround(input);
+ const off = p.steps.find((s) => !isOffered(s.request.modelId));
+ return off && !p.blocker ? { ...p, blocker: "This move is switched off on this studio" } : p;
+}
+
+/** The run as the server would make it, priced, without running it. */
+export function previewFlyAround(input: FlyAroundInput): FlyAroundPreview {
+ const p = plan(input);
+ let blocker = p.blocker;
+ let cost: number | null = p.costUsd;
+ let demo = false;
+ const notes = [...p.notes];
+ if (!blocker) {
+ cost = 0;
+ try {
+ for (const s of p.steps) {
+ const r = s.after?.length ? previewChained(s.request, s.after.length) : previewGeneration(s.request);
+ demo ||= r.demo;
+ cost = r.costUsd === null || cost === null ? null : cost + r.costUsd;
+ for (const n of r.notes ?? []) if (!notes.includes(n)) notes.push(n);
+ }
+ } catch (e) {
+ blocker = (e as Error).message;
+ cost = p.costUsd;
+ }
+ }
+ return {
+ engine: p.engine,
+ model: { id: p.model.id, name: p.model.name },
+ label: p.label,
+ keys: p.keys,
+ duration: p.duration,
+ steps: p.steps.length,
+ notes,
+ ...(blocker && { blocker }),
+ costUsd: demo ? 0 : cost === null ? null : Math.round(cost * 1000) / 1000,
+ demo,
+ };
+}
+
+/** Run the steps in order as one batch (each waits for the steps it names). The film first. */
+export function runFlySteps(steps: FlyStep[], batchId = nanoid(10)): Generation[] {
+ const made: Record<string, Generation[]> = {};
+ const all: Generation[] = [];
+ try {
+ for (const s of steps) {
+ const deps = s.after?.map((k) => made[k]?.[0]?.id).filter((x): x is string => !!x) ?? [];
+ const created = createGenerations(s.request, { batchId, ...(deps.length && { dependsOn: deps }) });
+ made[s.key] = created;
+ all.push(...created);
+ }
+ } catch (e) {
+ for (const g of all) void cancelGeneration(g.id);
+ throw new FlyAroundError((e as Error).message);
+ }
+ const film = made.main?.[0];
+ return film ? [film, ...all.filter((g) => g.id !== film.id)] : all;
+}
+
+export interface FlyAroundResult {
+ final: Generation;
+ items: Generation[];
+ batchId: string;
+ plan: FlyAroundPreview;
+}
+
+/** Plan, check every step, then run them. */
+export function createFlyAround(input: FlyAroundInput): FlyAroundResult {
+ const preview = previewFlyAround(input);
+ if (preview.blocker) throw new FlyAroundError(preview.blocker);
+ const batchId = nanoid(10);
+ const items = runFlySteps(plan(input).steps, batchId);
+ return { final: items[0], items, batchId, plan: preview };
+}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index f8c0ffc4..9d2d2f98 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -81,6 +81,7 @@ import { offeredLoras, offeredRoutes, requireOffered } from "./model-access";
import { llmBackends, llmLabel, llmMissing, llmUsesClaude, probeLocal } from "./providers/llm";
import type { PollContext, PollResult, ProviderAdapter, RemoteOutput } from "./providers/types";
import { mediaFacts } from "./media-facts";
+import { renderPathVideo } from "./path-render";
import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";
import { cropPicture, isCropWindow } from "./crop-picture";
import { convertMask, decodePng, encodePng } from "./png";
@@ -1039,6 +1040,8 @@ const SOUNDTRACK_SLOTS = new Set<ChainSlot["slot"]>(["audio", "audio2"]);
export function pickOutput(outputs: OutputFile[], s: ChainSlot): OutputFile | undefined {
// A mask: the output made as one (meta.role "mask": a painted window's last tracked frame), else a mask video, else a still.
if (s.slot === "mask") return outputs.find((o) => o.meta?.role === "mask") ?? outputs.find((o) => o.kind === "video") ?? outputs.find((o) => o.kind === "image");
+ // A path render (ChainSlot.render "path") is drawn from the depth picture the scene step made (MoGe 2: a GLB and a depth PNG).
+ if (s.render === "path") return outputs.find((o) => o.kind === "image");
const ofKind = outputs.filter((o) => o.kind === SLOT_KIND[s.slot]);
if (s.index !== undefined) {
if (!ofKind.length) return undefined;
@@ -1325,9 +1328,21 @@ async function advanceDependents(): Promise<void> {
const values = await asRun(() => Promise.all(outputs.map((o, i) => chainValue(pickOutput(o, slots[i]), slots[i], r.op))));
const missing = values.findIndex((u) => !u);
if (missing >= 0) {
- fail(`${earlier} has no ${slotNoun(slots[missing])} to use`);
+ fail(`${earlier} has no ${slots[missing].render ? "depth picture" : slotNoun(slots[missing])} to use`);
continue;
}
+ // A camera path drawn through the still's depth on this server (Uni3C's guide where no browser drew one); a demo
+ // depth step hands on a demo render.
+ for (let i = 0; i < slots.length; i++) {
+ if (slots[i].render !== "path") continue;
+ const photo = request.inputs?.images?.[0];
+ const keys = request.params?.cameraPath ?? [];
+ if (deps[i]!.provider === "mock" || !photo) values[i] = placeholderFor(slots[i]);
+ else {
+ update(r.id, { message: "Rendering the camera path" });
+ values[i] = await asRun(() => renderPathVideo({ photo, depth: values[i]!, keys }, r.id));
+ }
+ }
// Routing reads cached reachability: make sure it's fresh for local engines. An Original counts with the routes of
// the engine it runs on, ComfyUI taken as answering: one on the cloud doesn't use it, so doesn't wait for it.
const model = getModel(request.modelId);
diff --git a/src/server/path-render.ts b/src/server/path-render.ts
new file mode 100644
index 00000000..ba0db3fd
--- /dev/null
+++ b/src/server/path-render.ts
@@ -0,0 +1,98 @@
+import "server-only";
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { nanoid } from "nanoid";
+import sharp from "sharp";
+import { PATH_FPS, PATH_FRAMES, framePoses, renderSize, type CameraKey } from "@/lib/camera-path";
+import { splatFrame } from "@/lib/path-splat";
+import { LENS, buildPointCloud, lensFov } from "@/lib/scene3d";
+import { adoptFile, readRef, scratchDir } from "./storage";
+
+/**
+ * The server's path render (build plan N7-7, option B: a small headless point-cloud renderer, no node pack): a still and
+ * its depth picture (MoGe 2's, from the depth step) become a point cloud the way Cinema's 3D scene builds one (scene3d
+ * buildPointCloud, the photo taken with the scene's default lens), drawn along the camera path at 81 frames, 16 fps (the
+ * Uni3C graph's length), black where nothing was seen, and encoded to an MP4 by ffmpeg. Canvas, Assist, Fuobe DoP and
+ * Cinema's exact orbits use it, since none of them has a browser view of the scene; Cinema's 3D scene and Image to 3D
+ * still record theirs in the browser.
+ *
+ * It runs inside the step's run (generations.ts advanceDependents): an account's step reads only its own files
+ * (readRef) and the render is stored as its file.
+ */
+
+/** At most this many points (every second pixel of an 832 px render): a few seconds of CPU for 81 frames. */
+const MAX_POINTS = 300_000;
+
+export class PathRenderError extends Error {}
+
+/** Raw RGBA pixels of a picture at exactly `size`. */
+async function pixels(data: Buffer, size: { width: number; height: number }) {
+ const img = sharp(data, { failOn: "none" }).rotate().removeAlpha().ensureAlpha().resize(size.width, size.height, { fit: "fill" });
+ const { data: raw, info } = await img.raw().toBuffer({ resolveWithObject: true });
+ return { width: info.width, height: info.height, data: raw };
+}
+
+/** Frames as RGB into ffmpeg's stdin, an H.264 MP4 out (yuv420p, so every reader plays it), written to `file`. */
+function encode(file: string, frames: number, width: number, height: number, fps: number, frame: (i: number) => Uint8Array): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const args = ["-hide_banner", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", `${width}x${height}`, "-r", String(fps), "-i", "pipe:0"];
+ args.push("-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-f", "mp4", "-y", file);
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(process.env.FFMPEG_PATH || "ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });
+ } catch {
+ reject(new PathRenderError("Rendering the camera path needs ffmpeg on the studio's server"));
+ return;
+ }
+ let err = "";
+ child.stderr!.on("data", (b: Buffer) => (err += b.toString()));
+ child.on("error", () => reject(new PathRenderError("Rendering the camera path needs ffmpeg on the studio's server")));
+ child.on("close", (code) => (code === 0 ? resolve() : reject(new PathRenderError(`The camera path couldn't be encoded${err ? `: ${err.trim().split("\n").pop()}` : ""}`))));
+ child.stdin!.on("error", () => undefined);
+ (async () => {
+ for (let i = 0; i < frames; i++) {
+ if (!child.stdin!.write(frame(i))) await new Promise((r) => child.stdin!.once("drain", r));
+ }
+ child.stdin!.end();
+ })().catch(() => child.kill());
+ });
+}
+
+export interface PathRenderInput {
+ /** The still (the clip's first frame). */
+ photo: string;
+ /** Its depth picture (MoGe 2's depth render; any grey or Spectral depth map scene3d reads). */
+ depth: string;
+ keys: CameraKey[];
+ frames?: number;
+ fps?: number;
+}
+
+/** The path through the still's scene: its frame size and a renderer for frame i (RGB, rows top-down). */
+export async function pathScene(input: Omit<PathRenderInput, "fps">): Promise<{ width: number; height: number; count: number; frame: (i: number) => Uint8Array }> {
+ const [photoFile, depthFile] = await Promise.all([readRef(input.photo), readRef(input.depth)]);
+ const meta = await sharp(photoFile.data, { failOn: "none" }).metadata();
+ const aspect = (meta.autoOrient?.width ?? meta.width ?? 1) / (meta.autoOrient?.height ?? meta.height ?? 1);
+ // Read at the render's own size, so every point covers about its pixel there.
+ const size = renderSize(aspect);
+ const photo = await pixels(photoFile.data, size);
+ const depth = await pixels(depthFile.data, size);
+ const hFov = lensFov(LENS.default, aspect).h;
+ const cloud = buildPointCloud(photo, depth, { hFov, maxPoints: MAX_POINTS });
+ const poses = framePoses(input.keys, input.frames ?? PATH_FRAMES, cloud.depth, hFov, size);
+ // A new buffer a frame: the encoder's pipe may still hold the last one.
+ return { ...size, count: poses.poses.length, frame: (i) => splatFrame(cloud, poses.poses[i], poses.intrinsic, size.width, size.height) };
+}
+
+/** Render the path and store it (an MP4, as the generation's derived file): its URL, for the step's `video`. */
+export async function renderPathVideo(input: PathRenderInput, generationId?: string): Promise<string> {
+ const scene = await pathScene(input);
+ const file = path.join(scratchDir(), `path-${nanoid(10)}.mp4`);
+ try {
+ await encode(file, scene.count, scene.width, scene.height, input.fps ?? PATH_FPS, scene.frame);
+ return adoptFile({ from: file, contentType: "video/mp4", name: "path-render.mp4", source: "derived", ...(generationId && { generationId }) }).url;
+ } finally {
+ fs.rmSync(file, { force: true });
+ }
+}
diff --git a/tests/fly-around.test.ts b/tests/fly-around.test.ts
new file mode 100644
index 00000000..9d01d760
--- /dev/null
+++ b/tests/fly-around.test.ts
@@ -0,0 +1,201 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+/**
+ * Exact orbits and Fly around (build plan N7-7): the orbit's numbers as camera-path keys, the plan on both engines, the
+ * server's headless path render (option B) and its chain slot, and /api/fly-around.
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-fly-around-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { saveFile, readRef } = await import("@/server/storage");
+const { encodePng } = await import("@/server/png");
+const gens = await import("@/server/generations");
+const exact = await import("@/lib/exact-orbit");
+const fly = await import("@/lib/catalog/fly-around");
+const { PHOTO_KEY, PATH_FRAMES, toH3MaxTrajectory, H3_LIMITS, framePoses, renderSize } = await import("@/lib/camera-path");
+const { splatFrame } = await import("@/lib/path-splat");
+const { buildPointCloud, lensFov, LENS } = await import("@/lib/scene3d");
+const { pathScene, renderPathVideo } = await import("@/server/path-render");
+const route = await import("@/app/api/fly-around/route");
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+});
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+/** A 64 × 48 still: a red square in the middle of a blue field, and its depth (the square near, bright). */
+function scene() {
+ const w = 64;
+ const h = 48;
+ const photo = Buffer.alloc(w * h * 4);
+ const depth = Buffer.alloc(w * h * 4);
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const o = (y * w + x) * 4;
+ const inside = x > 20 && x < 44 && y > 12 && y < 36;
+ photo.set(inside ? [220, 30, 30, 255] : [30, 60, 200, 255], o);
+ const g = inside ? 230 : 40 + Math.round((y / h) * 60);
+ depth.set([g, g, g, 255], o);
+ }
+ const save = (data: Buffer, name: string) => saveFile({ data: encodePng({ width: w, height: h, data }), contentType: "image/png", name, source: "upload" }).url;
+ return { photo: save(photo, "still.png"), depth: save(depth, "depth.png") };
+}
+
+describe("exact orbit settings → keys", () => {
+ it("starts at the photo, turns the asked degrees the asked way, and stays within H3 Max's 12 keys", () => {
+ const keys = exact.exactOrbitKeys({ degrees: 360, direction: "ccw", tilt: 0, pulse: 0 });
+ expect(keys[0]).toEqual(PHOTO_KEY);
+ expect(keys.at(-1)).toMatchObject({ t: 1, azimuth: 360, elevation: 0, distance: 1 });
+ expect(keys.length).toBeLessThanOrEqual(exact.EXACT_MAX_KEYS);
+ const cam = toH3MaxTrajectory(keys);
+ expect("trajectory" in cam && cam.trajectory.length).toBe(keys.length);
+ expect(cam.notes).toEqual([]);
+ expect(keys.length).toBeLessThanOrEqual(H3_LIMITS.max);
+ const cw = exact.exactOrbitKeys({ degrees: 90, direction: "cw" });
+ expect(cw.at(-1)!.azimuth).toBe(-90);
+ expect(cw.length).toBe(5);
+ expect(cw.every((k, i) => i === 0 || k.azimuth < cw[i - 1].azimuth)).toBe(true);
+ });
+
+ it("tilts the ring (rising first, either way) and pulses the radius 25% in twice", () => {
+ for (const direction of ["cw", "ccw"] as const) {
+ const keys = exact.exactOrbitKeys({ degrees: 360, direction, tilt: 20, pulse: 0.25 });
+ const top = Math.max(...keys.map((k) => k.elevation));
+ expect(top).toBeCloseTo(20, 0);
+ expect(keys.find((k) => k.t === 0.25 || Math.abs(k.t - 0.2727) < 0.01)!.elevation).toBeGreaterThan(0);
+ expect(Math.min(...keys.map((k) => k.distance))).toBeCloseTo(0.75, 1);
+ expect(keys.at(-1)!.distance).toBeCloseTo(1, 3);
+ }
+ });
+
+ it("keeps the numbers in range and knows which moves take the switch", () => {
+ expect(exact.normalizeExact({ degrees: 5, tilt: 99, pulse: 0.2, direction: "x" as never })).toEqual({ degrees: 30, direction: "ccw", tilt: 20, pulse: 0.25 });
+ expect(exact.normalizeExact({ degrees: 412 }).degrees).toBe(360);
+ for (const id of ["motion-360-orbit", "motion-arc-left", "motion-arc-right", "motion-lazy-orbit", "drone-orbit", "arc-left", "arc-right", "bullet-time"]) expect(exact.takesExact(id), id).toBe(true);
+ expect(exact.takesExact("dolly-in")).toBe(false);
+ expect(exact.exactDefaults("arc-left")).toMatchObject({ degrees: 90, direction: "cw" });
+ expect(exact.exactSummary({ degrees: 180, direction: "cw", tilt: 10, pulse: 0.25 })).toBe("180° clockwise · tilt 10° · pulse 25%");
+ });
+});
+
+describe("the fly-around plan", () => {
+ const image = "/api/files/uploads/still.png";
+ const orbit = { degrees: 360, direction: "ccw" as const, tilt: 0, pulse: 0 };
+
+ it("on your GPU: MoGe's depth, then Uni3C along the server's render of the path, free", () => {
+ const p = fly.planFlyAround({ engine: "open", image, orbit });
+ expect(p.blocker).toBeUndefined();
+ expect(p.steps.map((s) => [s.key, s.request.modelId, s.request.op])).toEqual([
+ ["depth", "oss-scene-moge", "scene-3d"],
+ ["main", "oss-uni3c-path", "camera-path"],
+ ]);
+ expect(p.steps[1].after).toEqual(["depth"]);
+ expect(p.steps[1].request.chain).toEqual([{ slot: "video", render: "path" }]);
+ expect(p.steps[1].request.params?.cameraPath).toEqual(exact.exactOrbitKeys(orbit));
+ expect(p.costUsd).toBe(0);
+ expect(p.duration).toBeCloseTo(5.1, 1);
+ });
+
+ it("with a render already made (Image to 3D), skips the depth", () => {
+ const p = fly.planFlyAround({ engine: "open", image, preset: "orbit_360", render: "/api/files/uploads/r.webm" });
+ expect(p.steps).toHaveLength(1);
+ expect(p.steps[0].request.inputs).toEqual({ images: [image], video: "/api/files/uploads/r.webm" });
+ });
+
+ it("in the cloud: H3 Max camera-controls with the keys, 5 s at 768P = $0.40 at list", () => {
+ const p = fly.planFlyAround({ engine: "cloud", image, orbit, duration: 5 });
+ expect(p.steps).toHaveLength(1);
+ expect(p.steps[0].request).toMatchObject({ modelId: "minimax-h3-max-camera", op: "camera-path", params: { duration: 5, resolution: "768P" } });
+ expect(p.costUsd).toBeCloseTo(0.4, 3);
+ });
+
+ it("in the cloud with views: H3 Max reference-to-video with the still first and the path in words", () => {
+ const p = fly.planFlyAround({ engine: "cloud", image, views: ["/api/files/uploads/back.png"], orbit: { ...orbit, direction: "cw", degrees: 180 } });
+ expect(p.steps[0].request).toMatchObject({ modelId: "minimax-h3-max", op: "ref2v", inputs: { images: [image, "/api/files/uploads/back.png"] } });
+ expect(p.steps[0].request.prompt).toMatch(/180-degree arc around the subject, moving to the left/);
+ });
+
+ it("asks for the still and a path", () => {
+ expect(fly.planFlyAround({ engine: "cloud", orbit }).blocker).toBe("Add the still to film");
+ expect(fly.planFlyAround({ engine: "open", image }).blocker).toBe("Pick a path first");
+ });
+});
+
+describe("the server's path render (option B)", () => {
+ it("draws the photo's own view on frame 0 and turns away from it later", () => {
+ const w = 32;
+ const h = 24;
+ const photo = { width: w, height: h, data: new Uint8Array(w * h * 4).map((_, i) => (i % 4 === 0 ? 200 : i % 4 === 3 ? 255 : 40)) };
+ const depth = { width: w, height: h, data: new Uint8Array(w * h * 4).fill(128) };
+ const hFov = lensFov(LENS.default, w / h).h;
+ const cloud = buildPointCloud(photo, depth, { hFov });
+ const size = { width: w, height: h };
+ const poses = framePoses(exact.exactOrbitKeys({ degrees: 90, direction: "ccw" }), 3, cloud.depth, hFov, size);
+ const first = splatFrame(cloud, poses.poses[0], poses.intrinsic, w, h);
+ const lit = (f: Uint8Array) => f.filter((_, i) => i % 3 === 0 && f[i] > 100).length;
+ expect(lit(first)).toBe(w * h);
+ // A quarter turn round a flat picture sees it edge-on: most of the frame is a hole (black).
+ expect(lit(splatFrame(cloud, poses.poses[2], poses.intrinsic, w, h))).toBeLessThan(w * h * 0.5);
+ });
+
+ it("reads the still and its depth, renders 81 frames of the still's shape and stores an MP4", async () => {
+ const { photo, depth } = scene();
+ const s = await pathScene({ photo, depth, keys: exact.exactOrbitKeys({ degrees: 60, direction: "cw" }) });
+ expect(s.count).toBe(PATH_FRAMES);
+ expect({ width: s.width, height: s.height }).toEqual(renderSize(64 / 48));
+ const f0 = s.frame(0);
+ const mid = ((s.height / 2) * s.width + s.width / 2) * 3;
+ expect(f0[mid]).toBeGreaterThan(150); // the red square in the middle
+ if (spawnSync("ffmpeg", ["-version"]).status !== 0) return;
+ const url = await renderPathVideo({ photo, depth, keys: exact.exactOrbitKeys({ degrees: 60, direction: "cw" }) });
+ const file = await readRef(url);
+ expect(file.contentType).toBe("video/mp4");
+ expect(file.data.subarray(4, 8).toString()).toBe("ftyp");
+ }, 60_000);
+
+ it("takes the depth picture of the scene step for a path slot", () => {
+ const outputs = [
+ { url: "/api/files/outputs/scene.glb", kind: "model3d" as const },
+ { url: "/api/files/outputs/depth.png", kind: "image" as const },
+ ];
+ expect(gens.pickOutput(outputs, { slot: "video", render: "path" })?.url).toBe("/api/files/outputs/depth.png");
+ });
+});
+
+describe("/api/fly-around", () => {
+ const post = (url: string, body: unknown) => route.POST(new Request(`http://localhost:3000${url}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
+
+ it("prices a preview on both engines and refuses a body without a path's numbers in range", async () => {
+ const { photo } = scene();
+ const open = await post("/api/fly-around?preview=1", { engine: "open", image: photo, orbit: { degrees: 180, direction: "cw" } });
+ expect(open.status).toBe(200);
+ expect(await open.json()).toMatchObject({ engine: "open", steps: 2, costUsd: 0, label: "180° clockwise · level" });
+ const cloud = await post("/api/fly-around?preview=1", { engine: "cloud", image: photo, preset: "orbit_90_cw" });
+ expect(await cloud.json()).toMatchObject({ engine: "cloud", model: { id: "minimax-h3-max-camera" }, steps: 1 });
+ expect((await post("/api/fly-around?preview=1", { engine: "open", image: photo, orbit: { degrees: 720, direction: "cw" } })).status).toBe(400);
+ });
+
+ it("runs a demo on the open engine as two chained steps, the film waiting for the depth with a path slot", async () => {
+ const { photo } = scene();
+ setSetting("demoMode", "on");
+ try {
+ const r = await post("/api/fly-around", { engine: "open", image: photo, orbit: { degrees: 90, direction: "ccw" } });
+ expect(r.status).toBe(201);
+ const out = await r.json();
+ expect(out.items).toHaveLength(2);
+ expect(out.final.modelId).toBe("oss-uni3c-path");
+ expect(out.final.request.chain).toEqual([{ slot: "video", render: "path" }]);
+ } finally {
+ setSetting("demoMode", "auto");
+ }
+ });
+});