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 3D scene: lens, frame, fly-camera and point-cloud maths

Claude099f1325f4bd
diff --git a/src/lib/scene3d.ts b/src/lib/scene3d.ts
new file mode 100644
index 00000000..93dfa5be
--- /dev/null
+++ b/src/lib/scene3d.ts
@@ -0,0 +1,512 @@
+/**
+ * Cinema Studio's 3D scene (gap R4-08): the pure maths behind the viewer and the recomposition request,
+ * shared by the browser (components/cinema/scene-*) and the planner (catalog/cinema.ts).
+ *
+ * Both engines put the scene in the photo's own camera space with glTF axes: the photo was taken from the
+ * origin looking down -Z, +Y is up. On the open engine that is MoGe 2's mesh (metres); on the cloud it is a
+ * point cloud built here from the photo and a depth map (research: paid-model-apis-4.md §8, comfyui-oss-4.md §i).
+ *
+ * The camera follows Higgsfield's viewer (higgsfield-delta-4.md §4.4): W A S D Q E to fly, Shift faster, a lens
+ * in mm on a full-frame body, an aperture that sets the depth of field, and a frame in the project's ratio.
+ */
+
+export type Vec3 = [number, number, number];
+
+/** Lens range in mm (Higgsfield's 3D Angles: 24–300; 18 for a wider establishing view). */
+export const LENS = { min: 18, max: 300, default: 24 } as const;
+/** Quick picks on the lens slider. */
+export const LENS_STOPS = [18, 24, 35, 50, 85, 135, 200, 300];
+/** Whole and half stops from f/1.4 to f/16. */
+export const F_STOPS = [1.4, 2, 2.8, 4, 5.6, 8, 11, 16];
+export const APERTURE = { min: 1.4, max: 16, default: 5.6 } as const;
+/** A full-frame sensor, in mm: the frame lines of every ratio sit inside it. */
+export const SENSOR = { width: 36, height: 24 } as const;
+
+const DEG = Math.PI / 180;
+const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));
+const round = (n: number, step = 0.1) => Math.round(n / step) * step;
+
+/** "16:9" → 1.777…; anything unreadable is square. */
+export function ratioOf(aspect: string): number {
+ const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(aspect.trim());
+ const r = m ? Number(m[1]) / Number(m[2]) : 1;
+ return Number.isFinite(r) && r > 0 ? r : 1;
+}
+
+/** The frame of this ratio inside the full-frame sensor (mm): as wide as the sensor, or as tall for narrower frames. */
+export function frameSensor(aspect: number): { width: number; height: number } {
+ const full = SENSOR.width / SENSOR.height;
+ return aspect >= full ? { width: SENSOR.width, height: SENSOR.width / aspect } : { width: SENSOR.height * aspect, height: SENSOR.height };
+}
+
+/** Horizontal and vertical field of view (degrees) of a lens on a frame of this ratio. */
+export function lensFov(focalMm: number, aspect: number): { h: number; v: number } {
+ const f = Math.max(1, focalMm);
+ const s = frameSensor(aspect);
+ return { h: (2 * Math.atan(s.width / (2 * f))) / DEG, v: (2 * Math.atan(s.height / (2 * f))) / DEG };
+}
+
+/** The focal length (mm) whose horizontal field of view on this frame is `hFovDeg` (the inverse of lensFov). */
+export function focalForFov(hFovDeg: number, aspect: number): number {
+ const half = clamp(hFovDeg, 1, 179) * DEG * 0.5;
+ return frameSensor(aspect).width / (2 * Math.tan(half));
+}
+
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/** Where the frame of this ratio sits in a viewport: the largest such rectangle inside `margin` px, centred. */
+export function frameRect(viewW: number, viewH: number, aspect: number, margin = 0): Rect {
+ const w = Math.max(1, viewW - 2 * margin);
+ const h = Math.max(1, viewH - 2 * margin);
+ const width = Math.min(w, h * aspect);
+ const height = width / aspect;
+ return { x: (viewW - width) / 2, y: (viewH - height) / 2, width, height };
+}
+
+/**
+ * The vertical field of view to give the camera of the whole canvas so that the frame rectangle (its height
+ * in px) shows exactly the lens's vertical field of view.
+ */
+export function canvasFov(frameVFovDeg: number, frameHeightPx: number, canvasHeightPx: number): number {
+ const t = Math.tan(frameVFovDeg * DEG * 0.5) * (canvasHeightPx / Math.max(1, frameHeightPx));
+ return (2 * Math.atan(t)) / DEG;
+}
+
+/** The captured PNG's size: the frame's ratio, its longer edge `long` px, both sides multiples of 16. */
+export function captureSize(aspect: number, long = 1536): { width: number; height: number } {
+ const m16 = (n: number) => Math.max(16, Math.round(n / 16) * 16);
+ return aspect >= 1 ? { width: m16(long), height: m16(long / aspect) } : { width: m16(long * aspect), height: m16(long) };
+}
+
+// ---------------------------------------------------------------------------
+// Flying
+
+/** A fly camera: where it is and where it looks. yaw 0 looks down -Z and grows turning left; pitch grows looking up. */
+export interface FlyPose {
+ position: Vec3;
+ yaw: number;
+ pitch: number;
+}
+
+/** Each axis -1…1: forward (W/S), right (D/A), up (E/Q). */
+export interface FlyInput {
+ forward: number;
+ right: number;
+ up: number;
+}
+
+export const PITCH_LIMIT = Math.PI / 2 - 0.01;
+
+export function forwardOf(yaw: number, pitch: number): Vec3 {
+ return [-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)];
+}
+
+export function rightOf(yaw: number): Vec3 {
+ return [Math.cos(yaw), 0, -Math.sin(yaw)];
+}
+
+/** Keys held → the axes (KeyboardEvent.code, so the keys keep their place on any layout). */
+export function keysToInput(codes: Iterable<string>): FlyInput {
+ const held = new Set(codes);
+ const axis = (plus: string, minus: string) => (held.has(plus) ? 1 : 0) - (held.has(minus) ? 1 : 0);
+ return { forward: axis("KeyW", "KeyS"), right: axis("KeyD", "KeyA"), up: axis("KeyE", "KeyQ") };
+}
+
+export const FLY_KEYS = new Set(["KeyW", "KeyA", "KeyS", "KeyD", "KeyQ", "KeyE"]);
+/** Shift flies this much faster. */
+export const BOOST = 3;
+
+/**
+ * Move for `dt` seconds at `speed` units per second (×BOOST with Shift): forward along the view (so looking
+ * down and pressing W flies down), sideways level with the ground, Q/E straight down/up. Diagonals are not faster.
+ */
+export function flyStep(pose: FlyPose, input: FlyInput, dt: number, speed: number, boost = false): FlyPose {
+ const f = forwardOf(pose.yaw, pose.pitch);
+ const r = rightOf(pose.yaw);
+ const v: Vec3 = [0, 1, 2].map((i) => f[i] * input.forward + r[i] * input.right + (i === 1 ? input.up : 0)) as Vec3;
+ const len = Math.hypot(...v);
+ if (!len || dt <= 0) return pose;
+ const step = (speed * (boost ? BOOST : 1) * Math.min(dt, 0.1)) / Math.max(1, len);
+ return { ...pose, position: [pose.position[0] + v[0] * step, pose.position[1] + v[1] * step, pose.position[2] + v[2] * step] };
+}
+
+/** Mouse or finger look: dragging right turns right, dragging up looks up (`perPx` radians per pixel). */
+export function lookStep(pose: FlyPose, dxPx: number, dyPx: number, perPx = 0.004): FlyPose {
+ return { ...pose, yaw: pose.yaw - dxPx * perPx, pitch: clamp(pose.pitch - dyPx * perPx, -PITCH_LIMIT, PITCH_LIMIT) };
+}
+
+/** Move along the view by `dist` units (the mouse wheel, a pinch). */
+export function dolly(pose: FlyPose, dist: number): FlyPose {
+ const f = forwardOf(pose.yaw, pose.pitch);
+ return { ...pose, position: [pose.position[0] + f[0] * dist, pose.position[1] + f[1] * dist, pose.position[2] + f[2] * dist] };
+}
+
+/** Move sideways and up by (right, up) units in the view's plane (a two-finger drag). */
+export function strafe(pose: FlyPose, right: number, up: number): FlyPose {
+ const r = rightOf(pose.yaw);
+ return { ...pose, position: [pose.position[0] + r[0] * right, pose.position[1] + up, pose.position[2] + r[2] * right] };
+}
+
+export interface Touch2 {
+ x: number;
+ y: number;
+}
+
+/** Two fingers from `a` to `b`: how far their midpoint moved (px) and how much they spread apart (>1 = pinch out). */
+export function twoFinger(a: [Touch2, Touch2], b: [Touch2, Touch2]): { dx: number; dy: number; scale: number } {
+ const mid = (p: [Touch2, Touch2]) => ({ x: (p[0].x + p[1].x) / 2, y: (p[0].y + p[1].y) / 2 });
+ const span = (p: [Touch2, Touch2]) => Math.hypot(p[0].x - p[1].x, p[0].y - p[1].y);
+ const m0 = mid(a);
+ const m1 = mid(b);
+ const s0 = span(a);
+ return { dx: m1.x - m0.x, dy: m1.y - m0.y, scale: s0 > 0 ? span(b) / s0 : 1 };
+}
+
+/** Flying speed for a scene whose typical depth is `depth` units: about a third of it per second. */
+export function flySpeed(depth: number): number {
+ return Math.max(0.05, depth * 0.35);
+}
+
+// ---------------------------------------------------------------------------
+// Scenes: where the camera starts
+
+/**
+ * The photo's field of view, read from a scene in its camera space (vertices in front of the origin): the
+ * frustum through the outermost points (the 99.5th percentile of |x|/-z and |y|/-z, so a few stray points don't
+ * widen it). Null when the model isn't such a scene (an object around the origin, like the demo mesh).
+ */
+export function sceneFov(positions: ArrayLike<number>, maxSamples = 60_000): { h: number; v: number } | null {
+ const n = Math.floor(positions.length / 3);
+ if (!n) return null;
+ const step = Math.max(1, Math.floor(n / maxSamples));
+ const xs: number[] = [];
+ const ys: number[] = [];
+ let behind = 0;
+ let seen = 0;
+ for (let i = 0; i < n; i += step) {
+ const z = positions[i * 3 + 2];
+ seen++;
+ if (!(z < 0)) {
+ behind++;
+ continue;
+ }
+ xs.push(Math.abs(positions[i * 3] / z));
+ ys.push(Math.abs(positions[i * 3 + 1] / z));
+ }
+ if (behind > seen * 0.02 || xs.length < 3) return null;
+ const p = (a: number[]) => a.sort((x, y) => x - y)[Math.min(a.length - 1, Math.floor(a.length * 0.995))];
+ return { h: (2 * Math.atan(p(xs))) / DEG, v: (2 * Math.atan(p(ys))) / DEG };
+}
+
+/** The median distance of the points along -Z (the photo's subject distance): where the orbit pivot sits. */
+export function medianDepth(positions: ArrayLike<number>, maxSamples = 60_000): number {
+ const n = Math.floor(positions.length / 3);
+ const step = Math.max(1, Math.floor(n / maxSamples));
+ const zs: number[] = [];
+ for (let i = 0; i < n; i += step) {
+ const z = -positions[i * 3 + 2];
+ if (Number.isFinite(z)) zs.push(Math.abs(z));
+ }
+ if (!zs.length) return 1;
+ zs.sort((a, b) => a - b);
+ return zs[Math.floor(zs.length / 2)] || 1;
+}
+
+/** An object around a centre (not a camera-space scene): start in front of it, far enough to see all of it. */
+export function objectStart(center: Vec3, radius: number, vFovDeg: number): FlyPose {
+ const d = (Math.max(radius, 1e-3) / Math.sin(Math.max(5, vFovDeg) * DEG * 0.5)) * 1.1;
+ return { position: [center[0], center[1], center[2] + d], yaw: 0, pitch: 0 };
+}
+
+// ---------------------------------------------------------------------------
+// The point cloud (cloud engine): the photo + a depth map → points in the photo's camera space
+
+/** RGBA pixels, as ImageData has them. */
+export interface Pixels {
+ width: number;
+ height: number;
+ data: ArrayLike<number>;
+}
+
+export interface PointCloudOptions {
+ /** The photo's horizontal field of view (degrees). */
+ hFov: number;
+ /** At most this many points (the sampling stride follows). */
+ maxPoints?: number;
+ /** Depth maps differ: bright = near (disparity) or dark = near (depth). Undefined = read it from the map. */
+ nearIsBright?: boolean;
+ /** Distance of the nearest and the farthest points (scene units ≈ metres). */
+ near?: number;
+ far?: number;
+ /** Points whose depth jumps more than this fraction from a neighbour's are dropped (the smeared edges). */
+ edge?: number;
+}
+
+export interface PointCloud {
+ /** xyz per point. */
+ positions: Float32Array;
+ /** rgb 0–1 per point (sRGB, as in the photo). */
+ colors: Float32Array;
+ /** Each point's diameter in scene units: it covers its share of the photo, seen from where it was taken. */
+ sizes: Float32Array;
+ count: number;
+ stride: number;
+ /** Median distance (the orbit pivot). */
+ depth: number;
+}
+
+/** Bilinear grey value (0–1, the red channel) of a depth map at normalised (u, v). */
+function greyAt(px: Pixels, u: number, v: number): number {
+ const x = clamp(u * px.width - 0.5, 0, px.width - 1);
+ const y = clamp(v * px.height - 0.5, 0, px.height - 1);
+ const x0 = Math.floor(x);
+ const y0 = Math.floor(y);
+ const x1 = Math.min(px.width - 1, x0 + 1);
+ const y1 = Math.min(px.height - 1, y0 + 1);
+ const g = (xx: number, yy: number) => px.data[(yy * px.width + xx) * 4];
+ const fx = x - x0;
+ const fy = y - y0;
+ return ((g(x0, y0) * (1 - fx) + g(x1, y0) * fx) * (1 - fy) + (g(x0, y1) * (1 - fx) + g(x1, y1) * fx) * fy) / 255;
+}
+
+/**
+ * Which way a depth map runs: in a photo the bottom of the frame (the floor, the street) is nearly always nearer
+ * than the top, so the map is "bright = near" when its bottom quarter is brighter than its top quarter.
+ */
+export function nearIsBright(depth: Pixels): boolean {
+ const band = Math.max(1, Math.floor(depth.height / 4));
+ const mean = (y0: number) => {
+ let s = 0;
+ let n = 0;
+ for (let y = y0; y < y0 + band; y++)
+ for (let x = 0; x < depth.width; x += Math.max(1, Math.floor(depth.width / 64))) {
+ s += depth.data[(y * depth.width + x) * 4];
+ n++;
+ }
+ return s / Math.max(1, n);
+ };
+ return mean(depth.height - band) >= mean(0);
+}
+
+/**
+ * The photo as points: every `stride`-th pixel, pushed back to its distance along its own ray from the origin.
+ * Bright-near maps are read as disparity (1/z), dark-near maps as depth (z), each spread between the map's 1st and
+ * 99th percentile so every map fills the near–far range.
+ */
+export function buildPointCloud(photo: Pixels, depthMap: Pixels, opts: PointCloudOptions): PointCloud {
+ const W = photo.width;
+ const H = photo.height;
+ const near = opts.near ?? 1;
+ const far = Math.max(near * 1.05, opts.far ?? 6);
+ const bright = opts.nearIsBright ?? nearIsBright(depthMap);
+ const stride = Math.max(1, Math.ceil(Math.sqrt((W * H) / Math.max(1, opts.maxPoints ?? 300_000))));
+ const cols = Math.ceil(W / stride);
+ const rows = Math.ceil(H / stride);
+
+ // Nearness 0 (far) … 1 (near) per sample, spread between the percentiles.
+ const nearness = new Float32Array(cols * rows);
+ for (let r = 0; r < rows; r++)
+ for (let c = 0; c < cols; c++) {
+ const g = greyAt(depthMap, (Math.min(W - 1, c * stride) + 0.5) / W, (Math.min(H - 1, r * stride) + 0.5) / H);
+ nearness[r * cols + c] = bright ? g : 1 - g;
+ }
+ const sorted = Float32Array.from(nearness).sort();
+ const lo = sorted[Math.floor(sorted.length * 0.01)];
+ const hi = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.99))];
+ const span = hi - lo > 1e-6 ? hi - lo : 1;
+ const z = new Float32Array(cols * rows);
+ for (let i = 0; i < z.length; i++) {
+ const s = clamp((nearness[i] - lo) / span, 0, 1);
+ z[i] = bright ? 1 / (1 / far + s * (1 / near - 1 / far)) : far - s * (far - near);
+ }
+
+ const fx = W / 2 / Math.tan(clamp(opts.hFov, 1, 179) * DEG * 0.5);
+ const edge = opts.edge ?? 0.06;
+ const keep: number[] = [];
+ for (let r = 0; r < rows; r++)
+ for (let c = 0; c < cols; c++) {
+ const i = r * cols + c;
+ if (edge > 0) {
+ let jump = 0;
+ if (c + 1 < cols) jump = Math.max(jump, Math.abs(z[i + 1] - z[i]));
+ if (c > 0) jump = Math.max(jump, Math.abs(z[i - 1] - z[i]));
+ if (r + 1 < rows) jump = Math.max(jump, Math.abs(z[i + cols] - z[i]));
+ if (r > 0) jump = Math.max(jump, Math.abs(z[i - cols] - z[i]));
+ // A jump counts against the nearer side, so the front edge of a subject stays and the smear behind goes.
+ if (jump / z[i] > edge && jump > 0 && !isFrontOf(z, i, cols, rows)) continue;
+ }
+ keep.push(i);
+ }
+
+ const count = keep.length;
+ const positions = new Float32Array(count * 3);
+ const colors = new Float32Array(count * 3);
+ const sizes = new Float32Array(count);
+ keep.forEach((i, k) => {
+ const c = i % cols;
+ const r = (i - c) / cols;
+ const px = Math.min(W - 1, c * stride);
+ const py = Math.min(H - 1, r * stride);
+ const d = z[i];
+ positions[k * 3] = ((px + 0.5 - W / 2) / fx) * d;
+ positions[k * 3 + 1] = (-(py + 0.5 - H / 2) / fx) * d;
+ positions[k * 3 + 2] = -d;
+ const o = (py * W + px) * 4;
+ colors[k * 3] = photo.data[o] / 255;
+ colors[k * 3 + 1] = photo.data[o + 1] / 255;
+ colors[k * 3 + 2] = photo.data[o + 2] / 255;
+ sizes[k] = ((stride * d) / fx) * 1.5;
+ });
+ return { positions, colors, sizes, count, stride, depth: medianDepth(positions) };
+}
+
+/** Whether sample i is the nearest of itself and its four neighbours (the front of an edge). */
+function isFrontOf(z: Float32Array, i: number, cols: number, rows: number): boolean {
+ const c = i % cols;
+ const r = (i - c) / cols;
+ const n = [c + 1 < cols ? z[i + 1] : Infinity, c > 0 ? z[i - 1] : Infinity, r + 1 < rows ? z[i + cols] : Infinity, r > 0 ? z[i - cols] : Infinity];
+ return n.every((v) => z[i] <= v);
+}
+
+// ---------------------------------------------------------------------------
+// Depth of field (a hint: the thin-lens blur of a full-frame camera)
+
+/**
+ * The blur scale A of a thin lens focused at `focus` (scene units ≈ m): a point at distance d is blurred into a
+ * disc of A·|d − focus|/d of the frame's width. 50 mm at f/1.4 focused at 2 m blurs a wall 6 m away by ~1.7%.
+ */
+export function blurScale(lensMm: number, fNumber: number, focus: number, aspect = 16 / 9): number {
+ const f = lensMm / 1000;
+ const s = Math.max(focus, f * 1.01);
+ return (f * f) / (Math.max(0.5, fNumber) * (s - f) * (frameSensor(aspect).width / 1000));
+}
+
+/**
+ * What the frame's centre is looking at: the nearest surfaces in a narrow cone around the view (the 10th
+ * percentile of the sampled points' distances inside it). Null when nothing is there.
+ */
+export function focusDistance(positions: ArrayLike<number>, pose: FlyPose, coneDeg = 2.5, maxSamples = 80_000): number | null {
+ const n = Math.floor(positions.length / 3);
+ const step = Math.max(1, Math.floor(n / maxSamples));
+ const f = forwardOf(pose.yaw, pose.pitch);
+ const cos = Math.cos(coneDeg * DEG);
+ const [ox, oy, oz] = pose.position;
+ const hits: number[] = [];
+ for (let i = 0; i < n; i += step) {
+ const dx = positions[i * 3] - ox;
+ const dy = positions[i * 3 + 1] - oy;
+ const dz = positions[i * 3 + 2] - oz;
+ const along = dx * f[0] + dy * f[1] + dz * f[2];
+ if (along <= 0) continue;
+ if (along / Math.hypot(dx, dy, dz) >= cos) hits.push(along);
+ }
+ if (!hits.length) return null;
+ hits.sort((a, b) => a - b);
+ return hits[Math.floor(hits.length * 0.1)];
+}
+
+// ---------------------------------------------------------------------------
+// The captured view → a recomposition request
+
+/** The camera of a capture: what the Multiple-Angles LoRA and its fal / ComfyUI routes take. */
+export interface ScenePose {
+ /** 0–360°: 0 = from the front (where the photo was taken), 90 = moved round to the right. */
+ horizontal: number;
+ /** −30…90°: below eye level up to a bird's-eye view. */
+ vertical: number;
+ /** 0 (wide) … 5 (as framed in the photo) … 10 (close-up). */
+ zoom: number;
+}
+
+/**
+ * The flown camera as angles around the scene's pivot (the photo's centre at its median depth `pivotDepth`),
+ * averaging where the camera went with where it looks (each says half of a re-shot angle), and the zoom from how
+ * much tighter the frame is than the photo's (lens and distance), as Qwen Multiple Angles reads them.
+ */
+export function scenePose(pose: FlyPose, lensMm: number, photoLensMm: number, pivotDepth: number): ScenePose {
+ const pivot: Vec3 = [0, 0, -pivotDepth];
+ const dx = pose.position[0] - pivot[0];
+ const dy = pose.position[1] - pivot[1];
+ const dz = pose.position[2] - pivot[2];
+ const orbit = Math.atan2(dx, dz) / DEG;
+ const level = Math.hypot(dx, dz);
+ const elevation = Math.atan2(dy, Math.max(level, 1e-6)) / DEG;
+ const yaw = pose.yaw / DEG;
+ const pitch = pose.pitch / DEG;
+ const horizontal = (((orbit + wrap180(yaw)) / 2) % 360 + 360) % 360;
+ const vertical = clamp((elevation - pitch) / 2, -30, 90);
+ const distance = Math.max(1e-3, Math.hypot(dx, dy, dz));
+ const tighter = (lensMm / Math.max(1, photoLensMm)) * (pivotDepth / distance);
+ const zoom = clamp(5 + 5 * Math.log2(tighter), 0, 10);
+ return { horizontal: round(horizontal, 1) % 360, vertical: round(vertical, 1), zoom: round(zoom, 0.1) };
+}
+
+const wrap180 = (deg: number) => ((((deg + 180) % 360) + 360) % 360) - 180;
+
+/** The Multiple-Angles LoRA's own words for a pose (the same lists as the Angles app). */
+export const POSE_WORDS = {
+ horizontal: [
+ [0, "front view"],
+ [45, "front-right quarter view"],
+ [90, "right side view"],
+ [135, "back-right quarter view"],
+ [180, "back view"],
+ [225, "back-left quarter view"],
+ [270, "left side view"],
+ [315, "front-left quarter view"],
+ ] as [number, string][],
+ vertical: [
+ [-30, "low-angle shot"],
+ [0, "eye-level shot"],
+ [30, "elevated shot"],
+ [60, "high-angle shot"],
+ ] as [number, string][],
+};
+
+export function poseWords(p: ScenePose): string {
+ const nearest = (list: [number, string][], v: number, circular = false) =>
+ list.reduce((best, cur) => {
+ const d = (x: number) => (circular ? Math.min(Math.abs(x - v), 360 - Math.abs(x - v)) : Math.abs(x - v));
+ return d(cur[0]) < d(best[0]) ? cur : best;
+ })[1];
+ const distance = p.zoom >= 7.5 ? "close-up" : p.zoom <= 2.5 ? "wide shot" : "medium shot";
+ return `${nearest(POSE_WORDS.horizontal, p.horizontal, true)} ${nearest(POSE_WORDS.vertical, p.vertical)} ${distance}`;
+}
+
+/** The lens and aperture in a director's words ("a 24 mm wide-angle lens at f/5.6, moderate depth of field"). */
+export function cameraWords(lensMm: number, fNumber: number): string {
+ const lens = lensMm <= 28 ? "wide-angle" : lensMm <= 60 ? "standard" : lensMm <= 135 ? "portrait telephoto" : "long telephoto";
+ const dof = fNumber <= 2 ? "very shallow depth of field, the background melting into soft bokeh" : fNumber <= 4 ? "shallow depth of field, a soft background" : fNumber <= 8 ? "moderate depth of field" : "deep focus, everything sharp";
+ return `a ${Math.round(lensMm)} mm ${lens} lens at f/${formatStop(fNumber)}, ${dof}`;
+}
+
+export const formatStop = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(1));
+
+/**
+ * The recomposition instruction. Research (higgsfield-delta-4.md §4.4): "Re-render this view photorealistically,
+ * keep composition and camera exactly, fix holes and stretched textures." Image 1 is the capture, image 2 the photo.
+ */
+export function recomposePrompt(lensMm: number, fNumber: number, note?: string): string {
+ const extra = note?.trim().replace(/[.\s]+$/, "");
+ return [
+ "Re-render this exact camera view of the scene photorealistically.",
+ "Image 1 is a rough 3D render of the new camera view: keep its composition, camera position, angle and framing exactly.",
+ "Image 2 is the original photo: take the people, objects, materials, colours and light from it, so everything looks the same as there.",
+ "Fill holes, gaps and stretched textures with what belongs there.",
+ `Shot on ${cameraWords(lensMm, fNumber)}.`,
+ extra ? `${extra}.` : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+/** What Qwen Multiple Angles adds to its own camera words on the cloud (it gets the photo and the angles). */
+export function anglesNote(lensMm: number, fNumber: number, note?: string): string {
+ const extra = note?.trim().replace(/[.\s]+$/, "");
+ return `Keep the same subjects, identity, outfits, lighting and environment. Shot on ${cameraWords(lensMm, fNumber)}.${extra ? ` ${extra}.` : ""}`;
+}
diff --git a/tests/scene3d.test.ts b/tests/scene3d.test.ts
new file mode 100644
index 00000000..6b4ea4eb
--- /dev/null
+++ b/tests/scene3d.test.ts
@@ -0,0 +1,246 @@
+import { describe, expect, it } from "vitest";
+import {
+ BOOST,
+ blurScale,
+ buildPointCloud,
+ canvasFov,
+ captureSize,
+ dolly,
+ flyStep,
+ focalForFov,
+ focusDistance,
+ forwardOf,
+ frameRect,
+ frameSensor,
+ keysToInput,
+ lensFov,
+ lookStep,
+ medianDepth,
+ nearIsBright,
+ objectStart,
+ poseWords,
+ ratioOf,
+ recomposePrompt,
+ sceneFov,
+ scenePose,
+ strafe,
+ twoFinger,
+ type FlyPose,
+ type Pixels,
+} from "@/lib/scene3d";
+
+const start: FlyPose = { position: [0, 0, 0], yaw: 0, pitch: 0 };
+const close = (a: number[], b: number[], digits = 4) => a.forEach((v, i) => expect(v).toBeCloseTo(b[i], digits));
+
+describe("lens → field of view", () => {
+ it("puts every ratio's frame inside the full-frame sensor", () => {
+ expect(frameSensor(16 / 9)).toEqual({ width: 36, height: 20.25 });
+ expect(frameSensor(3 / 2)).toEqual({ width: 36, height: 24 });
+ expect(frameSensor(1)).toEqual({ width: 24, height: 24 });
+ expect(frameSensor(9 / 16).height).toBe(24);
+ expect(frameSensor(9 / 16).width).toBeCloseTo(13.5);
+ });
+
+ it("gives the classic angles (24 mm ≈ 74° across, 50 mm ≈ 40°) and inverts", () => {
+ const wide = lensFov(24, 16 / 9);
+ expect(wide.h).toBeCloseTo(73.74, 1);
+ expect(wide.v).toBeCloseTo(45.7, 1);
+ expect(lensFov(50, 3 / 2).h).toBeCloseTo(39.6, 1);
+ expect(lensFov(300, 16 / 9).h).toBeLessThan(7);
+ for (const f of [18, 24, 35, 85, 300]) expect(focalForFov(lensFov(f, 21 / 9).h, 21 / 9)).toBeCloseTo(f, 6);
+ });
+
+ it("reads ratios and sizes the capture in multiples of 16", () => {
+ expect(ratioOf("16:9")).toBeCloseTo(16 / 9);
+ expect(ratioOf("2.39:1")).toBeCloseTo(2.39);
+ expect(ratioOf("auto")).toBe(1);
+ expect(captureSize(16 / 9)).toEqual({ width: 1536, height: 864 });
+ expect(captureSize(9 / 16)).toEqual({ width: 864, height: 1536 });
+ expect(captureSize(21 / 9, 1024)).toEqual({ width: 1024, height: 432 });
+ });
+
+ it("lays the frame into the viewport and widens the canvas camera to match", () => {
+ expect(frameRect(1600, 900, 16 / 9)).toEqual({ x: 0, y: 0, width: 1600, height: 900 });
+ const tall = frameRect(390, 800, 16 / 9, 15);
+ expect(tall.width).toBe(360);
+ expect(tall.x).toBe(15);
+ expect(tall.height).toBeCloseTo(202.5);
+ // The frame is a quarter of the canvas height: the canvas camera sees four times the tangent.
+ const v = lensFov(24, 16 / 9).v;
+ const fov = canvasFov(v, 200, 800);
+ expect(Math.tan((fov * Math.PI) / 360)).toBeCloseTo(4 * Math.tan((v * Math.PI) / 360), 6);
+ expect(canvasFov(v, 800, 800)).toBeCloseTo(v, 6);
+ });
+});
+
+describe("flying", () => {
+ it("maps W A S D Q E by key position", () => {
+ expect(keysToInput(["KeyW"])).toEqual({ forward: 1, right: 0, up: 0 });
+ expect(keysToInput(["KeyS", "KeyA", "KeyQ"])).toEqual({ forward: -1, right: -1, up: -1 });
+ expect(keysToInput(["KeyW", "KeyS", "KeyE"])).toEqual({ forward: 0, right: 0, up: 1 });
+ });
+
+ it("flies down -Z at the start, sideways level, and no faster on a diagonal", () => {
+ close(flyStep(start, { forward: 1, right: 0, up: 0 }, 0.05, 20).position, [0, 0, -1]);
+ close(flyStep(start, { forward: 0, right: 1, up: 0 }, 0.05, 20).position, [1, 0, 0]);
+ close(flyStep(start, { forward: 0, right: 0, up: -1 }, 0.05, 20).position, [0, -1, 0]);
+ const diag = flyStep(start, { forward: 1, right: 1, up: 0 }, 0.05, 20).position;
+ expect(Math.hypot(...diag)).toBeCloseTo(1);
+ close(flyStep(start, { forward: 1, right: 0, up: 0 }, 0.05, 20, true).position, [0, 0, -BOOST]);
+ // A long frame (a hidden tab) never jumps more than 0.1 s.
+ close(flyStep(start, { forward: 1, right: 0, up: 0 }, 5, 1).position, [0, 0, -0.1]);
+ expect(flyStep(start, { forward: 0, right: 0, up: 0 }, 1, 1)).toBe(start);
+ });
+
+ it("looks with the mouse: right turns right, up looks up, never over the top", () => {
+ const turned = lookStep(start, 100, 0, 0.01);
+ expect(turned.yaw).toBeCloseTo(-1);
+ close(forwardOf(turned.yaw, 0), [Math.sin(1), 0, -Math.cos(1)]);
+ expect(lookStep(start, 0, -100, 0.01).pitch).toBeCloseTo(1);
+ expect(lookStep(start, 0, -10_000).pitch).toBeLessThan(Math.PI / 2);
+ // Looking straight down, W flies down.
+ const down = { ...start, pitch: -Math.PI / 2 + 0.01 };
+ expect(flyStep(down, { forward: 1, right: 0, up: 0 }, 0.1, 10).position[1]).toBeLessThan(-0.99);
+ });
+
+ it("reads two fingers as a move and a pinch, and moves along and across the view", () => {
+ const g = twoFinger([{ x: 0, y: 0 }, { x: 100, y: 0 }], [{ x: 10, y: 20 }, { x: 210, y: 20 }]);
+ expect(g).toEqual({ dx: 60, dy: 20, scale: 2 });
+ close(dolly(start, 2).position, [0, 0, -2]);
+ close(strafe({ ...start, yaw: Math.PI / 2 }, 1, 0.5).position, [0, 0.5, -1]);
+ });
+});
+
+describe("where the camera starts", () => {
+ it("reads the photo's field of view and subject distance from a camera-space scene", () => {
+ const fov = sceneFov(new Float32Array([-1, -0.5, -2, 1, 0.5, -2, 0, 0, -4]))!;
+ expect(fov.h).toBeCloseTo(53.13, 1);
+ expect(fov.v).toBeCloseTo(28.07, 1);
+ expect(medianDepth(new Float32Array([0, 0, -1, 0, 0, -3, 0, 0, -9]))).toBe(3);
+ });
+
+ it("frames an object around the origin from the front instead", () => {
+ // The demo crystal has points behind the origin: it is an object, not a scene.
+ expect(sceneFov(new Float32Array([0, 1, 0.5, 0, -1, -0.5, 0.6, 0, 0.6]))).toBeNull();
+ const pose = objectStart([0, 0, 0], 1, 60);
+ expect(pose.position[2]).toBeCloseTo(2.2);
+ expect(pose.yaw).toBe(0);
+ });
+});
+
+function pixels(width: number, height: number, fill: (x: number, y: number) => [number, number, number]): Pixels {
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let y = 0; y < height; y++)
+ for (let x = 0; x < width; x++) {
+ const [r, g, b] = fill(x, y);
+ data.set([r, g, b, 255], (y * width + x) * 4);
+ }
+ return { width, height, data };
+}
+
+describe("point cloud from a photo and a depth map", () => {
+ const photo = pixels(40, 20, (x) => [x * 6, 100, 200]);
+ // Bright = near: the bottom rows are nearest (a floor), the top far (a wall).
+ const depthMap = pixels(20, 10, (_x, y) => [Math.round((y / 9) * 255), 0, 0]);
+
+ it("tells which way a map runs from its top and bottom", () => {
+ expect(nearIsBright(depthMap)).toBe(true);
+ const flipped = pixels(20, 10, (_x, y) => [255 - Math.round((y / 9) * 255), 0, 0]);
+ expect(nearIsBright(flipped)).toBe(false);
+ });
+
+ it("puts each pixel on its ray, between near and far, nearest at the bottom", () => {
+ const cloud = buildPointCloud(photo, depthMap, { hFov: 90, near: 1, far: 5, edge: 0 });
+ expect(cloud.stride).toBe(1);
+ expect(cloud.count).toBe(800);
+ const z = (k: number) => -cloud.positions[k * 3 + 2];
+ const at = (x: number, y: number) => y * 40 + x;
+ expect(z(at(5, 19))).toBeCloseTo(1, 5);
+ expect(z(at(5, 0))).toBeCloseTo(5, 5);
+ // 90° across: the left edge pixel's ray leaves at ~45°, so x ≈ −z there.
+ const k = at(0, 10);
+ expect(cloud.positions[k * 3] / -cloud.positions[k * 3 + 2]).toBeCloseTo(-(20 - 0.5) / 20, 5);
+ // Up is +Y: the top half has positive y.
+ expect(cloud.positions[at(20, 2) * 3 + 1]).toBeGreaterThan(0);
+ // Colours come from the photo, sizes grow with distance.
+ expect(cloud.colors[at(10, 5) * 3]).toBeCloseTo(60 / 255);
+ expect(cloud.sizes[at(5, 0)]).toBeGreaterThan(cloud.sizes[at(5, 19)] * 4);
+ });
+
+ it("reads a dark-near map as depth, the same way round", () => {
+ const depth = pixels(20, 10, (_x, y) => [255 - Math.round((y / 9) * 255), 0, 0]);
+ const cloud = buildPointCloud(photo, depth, { hFov: 60, near: 1, far: 5, edge: 0 });
+ expect(-cloud.positions[(19 * 40 + 3) * 3 + 2]).toBeCloseTo(1, 4);
+ expect(-cloud.positions[3 * 3 + 2]).toBeCloseTo(5, 4);
+ });
+
+ it("samples big photos under the point budget and drops the smear behind an edge", () => {
+ const big = pixels(1000, 500, () => [10, 20, 30]);
+ const flat = pixels(100, 50, () => [128, 0, 0]);
+ const cloud = buildPointCloud(big, flat, { hFov: 60, maxPoints: 10_000 });
+ expect(cloud.stride).toBe(8);
+ expect(cloud.count).toBeLessThanOrEqual(10_000);
+ // A near square in the middle of a far wall: the wall right next to it goes, the square stays whole.
+ const box = pixels(40, 20, (x, y) => (x >= 10 && x < 30 && y >= 5 && y < 15 ? [255, 0, 0] : [0, 0, 0]));
+ const cut = buildPointCloud(photo, box, { hFov: 60, near: 1, far: 5, nearIsBright: true });
+ const all = buildPointCloud(photo, box, { hFov: 60, near: 1, far: 5, nearIsBright: true, edge: 0 });
+ expect(cut.count).toBeLessThan(all.count);
+ const nearPts = (c: typeof cut) => Array.from({ length: c.count }, (_, k) => -c.positions[k * 3 + 2]).filter((d) => d < 1.5).length;
+ expect(nearPts(cut)).toBe(nearPts(all));
+ });
+});
+
+describe("depth of field and focus", () => {
+ it("blurs like a thin lens: more with a longer lens, a wider aperture and a closer focus", () => {
+ const a = blurScale(50, 1.4, 2, 3 / 2);
+ expect(a * (4 / 6)).toBeCloseTo(0.017, 3);
+ expect(blurScale(85, 1.4, 2)).toBeGreaterThan(blurScale(24, 1.4, 2));
+ expect(blurScale(50, 1.4, 2)).toBeGreaterThan(blurScale(50, 16, 2) * 10);
+ expect(blurScale(50, 4, 1)).toBeGreaterThan(blurScale(50, 4, 5));
+ });
+
+ it("focuses on the nearest thing at the centre of the frame", () => {
+ const pts = new Float32Array([0, 0, -2, 0.01, 0, -2.02, 0, 0, -6, 3, 0, -1]);
+ expect(focusDistance(pts, start)).toBeCloseTo(2, 1);
+ expect(focusDistance(pts, { ...start, yaw: Math.PI })).toBeNull();
+ });
+});
+
+describe("the captured camera → a recomposition", () => {
+ it("is the photo's own view (front, eye level, as framed) before moving", () => {
+ expect(scenePose({ position: [0, 0, 0], yaw: 0, pitch: 0 }, 24, 24, 3)).toEqual({ horizontal: 0, vertical: 0, zoom: 5 });
+ expect(poseWords({ horizontal: 0, vertical: 0, zoom: 5 })).toBe("front view eye-level shot medium shot");
+ });
+
+ it("orbits right and up, aimed at the subject, into a front-right elevated view", () => {
+ // 3 m from the pivot, swung 45° right and raised 30°, looking back at it.
+ const d = 3;
+ const pos: [number, number, number] = [Math.sin(Math.PI / 4) * Math.cos(Math.PI / 6) * d, Math.sin(Math.PI / 6) * d, -3 + Math.cos(Math.PI / 4) * Math.cos(Math.PI / 6) * d];
+ const p = scenePose({ position: pos, yaw: Math.PI / 4, pitch: -Math.PI / 6 }, 24, 24, 3);
+ expect(p.horizontal).toBeCloseTo(45, 0);
+ expect(p.vertical).toBeCloseTo(30, 0);
+ expect(p.zoom).toBeCloseTo(5, 1);
+ expect(poseWords(p)).toBe("front-right quarter view elevated shot medium shot");
+ // Swung round to the left: 315°.
+ expect(scenePose({ position: [-3, 0, -3], yaw: -Math.PI / 2, pitch: 0 }, 24, 24, 3).horizontal).toBeCloseTo(270, 0);
+ });
+
+ it("zooms with the lens and the distance, within 0–10", () => {
+ expect(scenePose(start, 48, 24, 3).zoom).toBeCloseTo(10);
+ expect(scenePose({ ...start, position: [0, 0, -1.5] }, 24, 24, 3).zoom).toBeCloseTo(10);
+ expect(scenePose({ ...start, position: [0, 0, 3] }, 24, 24, 3).zoom).toBeCloseTo(0);
+ expect(scenePose(start, 300, 24, 3).zoom).toBe(10);
+ expect(poseWords({ horizontal: 200, vertical: -25, zoom: 1 })).toBe("back view low-angle shot wide shot");
+ });
+
+ it("asks to re-render the exact view with the photo's look, the lens and the user's note", () => {
+ const p = recomposePrompt(85, 1.4, "make it dusk.");
+ expect(p).toMatch(/^Re-render this exact camera view of the scene photorealistically\./);
+ expect(p).toContain("Image 1 is a rough 3D render");
+ expect(p).toContain("Image 2 is the original photo");
+ expect(p).toMatch(/holes, gaps and stretched textures/);
+ expect(p).toContain("Shot on a 85 mm portrait telephoto lens at f/1.4, very shallow depth of field");
+ expect(p.endsWith("make it dusk.")).toBe(true);
+ expect(recomposePrompt(24, 11)).toContain("f/11, deep focus");
+ });
+});