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
3D results: every one shows its model, turning on hover
Adarsh164d20701b20
diff --git a/bin/lib/worker/finish.mjs b/bin/lib/worker/finish.mjsindex 9b56a407..845425fd 100644--- a/bin/lib/worker/finish.mjs+++ b/bin/lib/worker/finish.mjs@@ -7,6 +7,8 @@// GLB; then scripts/model3d/render-turntable.mjs renders the turntable and its poster (CPU only). With no browser or// ffmpeg for the turntable here, the model goes back without one ("skipped").// - "path": path-child.mjs draws the camera path through the still and its depth picture, and ffmpeg encodes it.+// - "preview3d": scripts/model3d/render-preview.mjs draws a 3D result's turntable and its stills on the CPU (no browser,+// no GPU), and ffmpeg encodes them.import { spawn } from "node:child_process";import fs from "node:fs";import os from "node:os";@@ -19,6 +21,16 @@ const ROOT = path.resolve(here, "../../..");/** Exit code 3 of the 3D scripts: the GLB isn't self-contained (finish-glb.mjs), or no browser or ffmpeg (render-turntable.mjs). */const REFUSED = 3;+/** A preview's files by role (src/lib/finish-ticket.ts PREVIEW_FILES; tests/preview3d.test.ts keeps the two the same). */+export const PREVIEW_FILES = {+ posterLight: { file: "poster-light.webp", contentType: "image/webp" },+ posterDark: { file: "poster-dark.webp", contentType: "image/webp" },+ clipLight: { file: "turntable-light.mp4", contentType: "video/mp4" },+ clipDark: { file: "turntable-dark.mp4", contentType: "video/mp4" },+ webmLight: { file: "turntable-light.webm", contentType: "video/webm" },+ webmDark: { file: "turntable-dark.webm", contentType: "video/webm" },+};+/** The variables the scripts read (and what Node, a browser and ffmpeg need to start): nothing else of this PC's. */const PASS = ["PATH", "Path", "SYSTEMROOT", "SystemRoot", "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "LANG", "CHROMIUM_PATH", "FUOBE_CHROMIUM", "PLAYWRIGHT_BROWSERS_PATH"];@@ -96,11 +108,14 @@ export function finishers(o) {const root = o.root ?? ROOT;const finishGlb = o.scripts?.finishGlb ?? path.join(root, "scripts/model3d/finish-glb.mjs");const turntableScript = o.scripts?.turntable ?? path.join(root, "scripts/model3d/render-turntable.mjs");+ const previewScript = o.scripts?.preview ?? path.join(root, "scripts/model3d/render-preview.mjs");const dist = o.distDir ?? path.join(here, "dist");const env = scriptEnv(o.env ?? process.env, o.ffmpeg);const kinds = [];if (hasPackage("@gltf-transform/core") && hasPackage("sharp")) kinds.push("model3d");if (o.ffmpeg && ["camera-path.mjs", "path-splat.mjs", "scene3d.mjs"].every((f) => fs.existsSync(path.join(dist, f))) && hasPackage("sharp")) kinds.push("path");+ // A 3D result's preview: drawn on the CPU (no browser), encoded by ffmpeg.+ if (o.ffmpeg && fs.existsSync(previewScript) && hasPackage("sharp")) kinds.push("preview3d");async function finish(t, inputs, { signal, progress }) {const kind = t.finish?.kind;@@ -147,6 +162,29 @@ export function finishers(o) {const stat = { material: stats.material, triangles: stats.triangles, bytesIn: stats.bytesIn, bytesOut: stats.bytesOut };return { files, stats: stat, ...(turntable && { turntable }) };}+ if (kind === "preview3d") {+ const s = t.finish.settings;+ const model = put(`model.${s.format}`, inputs.model);+ const out = path.join(dir, "preview");+ const args = ["--in", model, "--out-dir", out, "--format", String(s.format), "--front-yaw", String(s.frontYaw), "--cutoff", String(s.cutoff), ...(s.yDown ? ["--y-down"] : [])];+ const r = await runScript(previewScript, args, {+ cwd: dir,+ signal,+ env,+ timeoutMs,+ onLine: (line) => {+ const m = /^frame (\d+)\/(\d+)$/.exec(line.trim());+ if (m) progress(Number(m[1]) / Number(m[2]));+ },+ });+ if (r.code === REFUSED) return { refused: "unsafe-model" };+ if (r.code !== 0) return { refused: "finish-failed" };+ const files = Object.entries(PREVIEW_FILES)+ .filter(([, f]) => fs.existsSync(path.join(out, f.file)))+ .map(([role, f]) => ({ role, name: f.file, data: fs.readFileSync(path.join(out, f.file)), contentType: f.contentType }));+ if (!["posterLight", "posterDark", "clipLight", "clipDark"].every((role) => files.some((f) => f.role === role))) return { refused: "finish-failed" };+ return { files };+ }// "path"const photo = put("photo.png", inputs.photo);const depth = put("depth.png", inputs.depth);diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 766806ad..709abf38 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -761,10 +761,18 @@ Set `"cpuSlot": true` in `worker.json` (setup asks) and the worker runs one CPUbrowser or ffmpeg for the turntable, the model comes back without one. This needs `pnpm install` in its checkout.- `path`, a camera path drawn through a still and its depth picture (the guide of a camera move), encoded by ffmpeg.This needs ffmpeg.+ - `preview3d`, the preview of any finished 3D result: a GLB mesh, or a Gaussian splat as `.spz` or `.ply`, from any+ run (the owner's, an account's, a provider's). `scripts/model3d/render-preview.mjs` draws one turn of the model (120+ frames, 5 s, a loop with no seam) on the CPU, with no browser and no GPU, on a light and a dark studio backdrop, and+ ffmpeg encodes each as H.264 (and AV1 when its ffmpeg has an AV1 encoder); the stills are the first frame. This needs+ ffmpeg and sharp. The studio follows these jobs in `src/server/model3d-preview.ts`: every finished 3D result without+ a preview gets one, newest first, a few at a time; an older result's job goes after everyone's runs. Without a+ worker that draws previews, a server that runs ComfyUI itself draws them; one with workers draws only a provider's+ result of the owner's, and an account's waits for a worker.A finishing job comes as a finish ticket (`src/lib/finish-ticket.ts`): its kind, typed settings, and its inputfiles by slot, name and SHA-256. The worker checks it the same way the studio does, and sends back only the files its- kind makes (`web`, `turntable` and `poster`; or `path`). The studio stores them, and checks the web GLB is+ kind makes (`web`, `turntable` and `poster`; `path`; or the preview's stills and clips). The studio stores them, and checks the web GLB isself-contained again before it keeps it. The owner's own runs, and runs on an account's own GPU or keys, keep thestudio's own finish, as before.@@ -935,7 +943,7 @@ its target), at most once an hour each.- `protocol` is 2 for a worker that says which inputs it takes, makes clips and sound again, and keeps its ComfyUIbehind the guard. It is 3 for a worker that also makes an account's pictures again (see "Pictures of an account'srun") and may have a CPU slot.- - `cpuSlot` (optional) says its CPU slot and the finishing jobs it runs (`{ finishes: ["model3d", "path"] }`), and+ - `cpuSlot` (optional) says its CPU slot and the finishing jobs it runs (`{ finishes: ["model3d", "path", "preview3d"] }`), and`cpuRunning` the task that slot works on, as `running` does for its GPU's. With no `cpuSlot`, it has none.- `held` (optional) names the jobs whose finished results the worker keeps on its disk. A pause now sends thosejobs back in line only when the worker doesn't name them.diff --git a/scripts/model3d/preview3d-core.mjs b/scripts/model3d/preview3d-core.mjsnew file mode 100644index 00000000..f2b283fa--- /dev/null+++ b/scripts/model3d/preview3d-core.mjs@@ -0,0 +1,1049 @@+// The preview of a 3D result, drawn on the CPU with no browser and no GPU: a still and a turntable of a GLB mesh or a+// Gaussian splat (.spz / .ply). scripts/model3d/render-preview.mjs reads the files (pictures through sharp) and+// encodes the frames with ffmpeg; this file is pure (typed arrays in, typed arrays out), so a test can run it as it is.+//+// - Meshes: a z-buffered rasterizer at 2x (each output pixel is the mean of four), shaded once per visible pixel:+// glTF metallic-roughness with the base colour, metallic-roughness, normal and occlusion textures, lit by the studio+// HDR the server's turntable uses (irradiance from 9 spherical harmonics, reflections from blurred copies of the+// HDR picked by roughness, Karis' analytic split-sum term), exposure, Khronos PBR Neutral tone mapping. The+// materials get the same roughness floors as the web GLB (scripts/model3d/finish-glb.mjs), so the still matches+// what the viewer shows. A soft contact shadow sits under the model.+// - Splats: each Gaussian projected to a 2D ellipse (the 3DGS EWA projection), sorted back to front and blended,+// after the pose the viewer gives it (src/lib/av/splat-view.ts splatPose: ComfyUI's splats are y down and face +x).+//+// The model turns about the vertical axis through the middle of its box; the camera and the light stay put. One turn+// is `frames` frames, so frame `frames` would be frame 0 again: the clip loops with no seam. The framing is fixed for+// the whole turn (the model fits in every frame) and centred.++// ---------------------------------------------------------------------------------------------------------------------+// Files++/** A binary glTF: its JSON, its binary chunk, and its pictures as bytes (`images[i]`: { mime, bytes }). */+export function readGlb(buf) {+ const u8 = buf instanceof Uint8Array ? buf : new Uint8Array(buf);+ const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);+ if (u8.byteLength < 20 || dv.getUint32(0, true) !== 0x46546c67) throw new Error("not a binary glTF");+ let at = 12;+ let json = null;+ let bin = null;+ while (at + 8 <= u8.byteLength) {+ const len = dv.getUint32(at, true);+ const type = dv.getUint32(at + 4, true);+ const body = u8.subarray(at + 8, at + 8 + len);+ if (type === 0x4e4f534a) json = JSON.parse(new TextDecoder().decode(body));+ else if (type === 0x004e4942) bin = body;+ at += 8 + len + ((4 - (len % 4)) % 4);+ }+ if (!json) throw new Error("the glTF has no JSON");+ const used = [...(json.extensionsRequired ?? []), ...(json.extensionsUsed ?? [])];+ const packed = used.find((e) => e === "KHR_draco_mesh_compression" || e === "EXT_meshopt_compression" || e === "KHR_mesh_quantization");+ if (packed && (json.extensionsRequired ?? []).includes(packed)) throw new Unsupported(`the model uses ${packed}`);+ const bufferOf = (i) => {+ const b = json.buffers?.[i];+ if (!b) throw new Error("a buffer is missing");+ if (b.uri !== undefined) {+ // Only data inside the file: a buffer named by a URI is never fetched or read from disk.+ const m = /^data:[^;,]*;base64,(.*)$/.exec(b.uri);+ if (!m) throw new Unsupported("a buffer names another file");+ return Uint8Array.from(Buffer.from(m[1], "base64"));+ }+ if (!bin) throw new Error("the glTF has no binary chunk");+ return bin;+ };+ const viewBytes = (vi) => {+ const v = json.bufferViews[vi];+ const b = bufferOf(v.buffer);+ return { bytes: b.subarray(v.byteOffset ?? 0, (v.byteOffset ?? 0) + v.byteLength), stride: v.byteStride ?? 0 };+ };+ const images = (json.images ?? []).map((img) => {+ if (img.bufferView !== undefined) return { mime: img.mimeType ?? "", bytes: viewBytes(img.bufferView).bytes };+ const m = typeof img.uri === "string" ? /^data:([^;,]*);base64,(.*)$/.exec(img.uri) : null;+ return m ? { mime: m[1], bytes: Uint8Array.from(Buffer.from(m[2], "base64")) } : null;+ });+ return { json, viewBytes, images };+}++/** A model that this drawer can't read (a compressed or split glTF): the preview falls back. */+export class Unsupported extends Error {}++const COMPONENTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16 };+const SIZES = { 5120: 1, 5121: 1, 5122: 2, 5123: 2, 5125: 4, 5126: 4 };++/** An accessor as floats (normalized integers scaled to 0..1 / -1..1), `n` per element. */+function accessor(glb, index) {+ const a = glb.json.accessors[index];+ const n = COMPONENTS[a.type];+ const out = new Float32Array(a.count * n);+ if (a.bufferView === undefined) return { data: out, n, count: a.count };+ const { bytes, stride } = glb.viewBytes(a.bufferView);+ const size = SIZES[a.componentType];+ const step = stride || size * n;+ const dv = new DataView(bytes.buffer, bytes.byteOffset + (a.byteOffset ?? 0), bytes.byteLength - (a.byteOffset ?? 0));+ const norm = !!a.normalized;+ for (let i = 0; i < a.count; i++) {+ const base = i * step;+ for (let k = 0; k < n; k++) {+ const o = base + k * size;+ let v;+ switch (a.componentType) {+ case 5126: v = dv.getFloat32(o, true); break;+ case 5125: v = dv.getUint32(o, true); break;+ case 5123: v = dv.getUint16(o, true); if (norm) v /= 65535; break;+ case 5122: v = dv.getInt16(o, true); if (norm) v = Math.max(v / 32767, -1); break;+ case 5121: v = dv.getUint8(o); if (norm) v /= 255; break;+ default: v = dv.getInt8(o); if (norm) v = Math.max(v / 127, -1);+ }+ out[i * n + k] = v;+ }+ }+ return { data: out, n, count: a.count };+}++function indices(glb, index) {+ const a = glb.json.accessors[index];+ const { bytes, stride } = glb.viewBytes(a.bufferView);+ const size = SIZES[a.componentType];+ const dv = new DataView(bytes.buffer, bytes.byteOffset + (a.byteOffset ?? 0), bytes.byteLength - (a.byteOffset ?? 0));+ const out = new Uint32Array(a.count);+ const step = stride || size;+ for (let i = 0; i < a.count; i++) out[i] = size === 4 ? dv.getUint32(i * step, true) : size === 2 ? dv.getUint16(i * step, true) : dv.getUint8(i * step);+ return out;+}++// 4x4 matrices, column-major as glTF writes them.+const mat4 = () => new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+function mul4(a, b) {+ const o = new Float64Array(16);+ for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) o[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];+ return o;+}+function nodeMatrix(node) {+ if (node.matrix) return Float64Array.from(node.matrix);+ const [tx, ty, tz] = node.translation ?? [0, 0, 0];+ const [x, y, z, w] = node.rotation ?? [0, 0, 0, 1];+ const [sx, sy, sz] = node.scale ?? [1, 1, 1];+ return new Float64Array([+ (1 - 2 * (y * y + z * z)) * sx, 2 * (x * y + z * w) * sx, 2 * (x * z - y * w) * sx, 0,+ 2 * (x * y - z * w) * sy, (1 - 2 * (x * x + z * z)) * sy, 2 * (y * z + x * w) * sy, 0,+ 2 * (x * z + y * w) * sz, 2 * (y * z - x * w) * sz, (1 - 2 * (x * x + y * y)) * sz, 0,+ tx, ty, tz, 1,+ ]);+}++/**+ * The triangles of a glTF in world space, merged: positions, normals, tangents (xyzw), UVs, and per triangle its+ * material. `pictures[i]` is the decoded picture i ({ width, height, data: RGBA bytes }) or null.+ */+export function meshOf(glb, pictures, { maxTriangles = 4_000_000 } = {}) {+ const { json } = glb;+ const parts = [];+ let tris = 0;+ const visit = (ni, parent) => {+ const node = json.nodes[ni];+ const m = mul4(parent, nodeMatrix(node));+ if (node.mesh !== undefined) {+ for (const p of json.meshes[node.mesh].primitives) {+ if ((p.mode ?? 4) !== 4 || p.attributes.POSITION === undefined) continue;+ if (p.extensions?.KHR_draco_mesh_compression) throw new Unsupported("the model uses Draco compression");+ const pos = accessor(glb, p.attributes.POSITION);+ const idx = p.indices !== undefined ? indices(glb, p.indices) : Uint32Array.from({ length: pos.count }, (_, i) => i);+ tris += idx.length / 3;+ if (tris > maxTriangles) throw new Unsupported("the model has too many triangles to draw");+ parts.push({ m, pos, idx, nrm: p.attributes.NORMAL !== undefined ? accessor(glb, p.attributes.NORMAL) : null, tan: p.attributes.TANGENT !== undefined ? accessor(glb, p.attributes.TANGENT) : null, uv: p.attributes.TEXCOORD_0 !== undefined ? accessor(glb, p.attributes.TEXCOORD_0) : null, material: p.material ?? -1 });+ }+ }+ for (const c of node.children ?? []) visit(c, m);+ };+ const scene = json.scenes?.[json.scene ?? 0];+ const roots = scene?.nodes ?? (json.nodes ?? []).map((_, i) => i).filter((i) => !(json.nodes ?? []).some((n) => n.children?.includes(i)));+ for (const r of roots) visit(r, mat4());+ if (!parts.length) throw new Unsupported("the model has no triangles");++ const vCount = parts.reduce((s, p) => s + p.pos.count, 0);+ const P = new Float32Array(vCount * 3);+ const N = new Float32Array(vCount * 3);+ const T = new Float32Array(vCount * 4);+ const UV = new Float32Array(vCount * 2);+ const I = new Uint32Array(tris * 3);+ const triMat = new Int16Array(tris);+ const hasTangent = new Uint8Array(tris);+ const materials = (json.materials ?? []).map((mt) => materialOf(json, mt, pictures));+ let vo = 0;+ let to = 0;+ for (const part of parts) {+ const { m } = part;+ // The normal matrix: the inverse transpose of the upper 3x3.+ const nm = normalMatrix(m);+ for (let i = 0; i < part.pos.count; i++) {+ const x = part.pos.data[i * 3], y = part.pos.data[i * 3 + 1], z = part.pos.data[i * 3 + 2];+ const o = (vo + i) * 3;+ P[o] = m[0] * x + m[4] * y + m[8] * z + m[12];+ P[o + 1] = m[1] * x + m[5] * y + m[9] * z + m[13];+ P[o + 2] = m[2] * x + m[6] * y + m[10] * z + m[14];+ if (part.nrm) {+ const a = part.nrm.data[i * 3], b = part.nrm.data[i * 3 + 1], c = part.nrm.data[i * 3 + 2];+ N[o] = nm[0] * a + nm[3] * b + nm[6] * c;+ N[o + 1] = nm[1] * a + nm[4] * b + nm[7] * c;+ N[o + 2] = nm[2] * a + nm[5] * b + nm[8] * c;+ norm3(N, o);+ }+ if (part.tan) {+ const a = part.tan.data[i * 4], b = part.tan.data[i * 4 + 1], c = part.tan.data[i * 4 + 2];+ const q = (vo + i) * 4;+ T[q] = m[0] * a + m[4] * b + m[8] * c;+ T[q + 1] = m[1] * a + m[5] * b + m[9] * c;+ T[q + 2] = m[2] * a + m[6] * b + m[10] * c;+ const l = Math.hypot(T[q], T[q + 1], T[q + 2]) || 1;+ T[q] /= l; T[q + 1] /= l; T[q + 2] /= l;+ T[q + 3] = part.tan.data[i * 4 + 3] < 0 ? -1 : 1;+ }+ if (part.uv) {+ UV[(vo + i) * 2] = part.uv.data[i * 2];+ UV[(vo + i) * 2 + 1] = part.uv.data[i * 2 + 1];+ }+ }+ for (let t = 0; t < part.idx.length / 3; t++) {+ I[(to + t) * 3] = part.idx[t * 3] + vo;+ I[(to + t) * 3 + 1] = part.idx[t * 3 + 1] + vo;+ I[(to + t) * 3 + 2] = part.idx[t * 3 + 2] + vo;+ triMat[to + t] = part.material;+ hasTangent[to + t] = part.tan ? 1 : 0;+ }+ if (!part.nrm) flatNormals(P, N, I, to, part.idx.length / 3);+ vo += part.pos.count;+ to += part.idx.length / 3;+ }+ return { P, N, T, UV, I, triMat, hasTangent, materials, triangles: tris, vertices: vCount };+}++function normalMatrix(m) {+ const a = m[0], b = m[1], c = m[2], d = m[4], e = m[5], f = m[6], g = m[8], h = m[9], i = m[10];+ const A = e * i - f * h, B = -(d * i - f * g), C = d * h - e * g;+ const det = a * A + b * B + c * C || 1;+ // Inverse transpose, row-major 3x3 as used above: n' = M * n with M[r*3+c]... kept column-major like m.+ return [A / det, B / det, C / det, -(b * i - c * h) / det, (a * i - c * g) / det, -(a * h - b * g) / det, (b * f - c * e) / det, -(a * f - c * d) / det, (a * e - b * d) / det];+}+function norm3(a, o) {+ const l = Math.hypot(a[o], a[o + 1], a[o + 2]) || 1;+ a[o] /= l; a[o + 1] /= l; a[o + 2] /= l;+}+/** Area-weighted vertex normals for a part that came without them. */+function flatNormals(P, N, I, from, count) {+ for (let t = from; t < from + count; t++) {+ const i0 = I[t * 3] * 3, i1 = I[t * 3 + 1] * 3, i2 = I[t * 3 + 2] * 3;+ const ux = P[i1] - P[i0], uy = P[i1 + 1] - P[i0 + 1], uz = P[i1 + 2] - P[i0 + 2];+ const vx = P[i2] - P[i0], vy = P[i2 + 1] - P[i0 + 1], vz = P[i2 + 2] - P[i0 + 2];+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;+ for (const i of [i0, i1, i2]) { N[i] += nx; N[i + 1] += ny; N[i + 2] += nz; }+ }+ for (let t = from; t < from + count; t++) for (let k = 0; k < 3; k++) norm3(N, I[t * 3 + k] * 3);+}++// ---------------------------------------------------------------------------------------------------------------------+// Materials and pictures++const SRGB = new Float32Array(256).map((_, i) => { const c = i / 255; return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); });++function textureOf(json, info, pictures) {+ if (!info) return null;+ const tex = json.textures?.[info.index];+ const src = tex?.source ?? tex?.extensions?.EXT_texture_webp?.source;+ const pic = src !== undefined ? pictures[src] : null;+ return pic && pic.width && pic.height ? pic : null;+}++/**+ * A material as the drawer uses it, with the web GLB's roughness floors (finish-glb.mjs): mostly metal keeps its+ * metal; almost none is matte (roughness >= 0.8, no metal); anything else "mixed" (roughness >= 0.45 off the metal).+ * A material still at the glTF defaults with no metallic-roughness picture is a matte dielectric.+ */+function materialOf(json, mt, pictures) {+ const pbr = mt.pbrMetallicRoughness ?? {};+ const base = textureOf(json, pbr.baseColorTexture, pictures);+ const mr = textureOf(json, pbr.metallicRoughnessTexture, pictures);+ const normal = textureOf(json, mt.normalTexture, pictures);+ const occ = textureOf(json, mt.occlusionTexture, pictures);+ let metallic = pbr.metallicFactor ?? 1;+ let roughness = pbr.roughnessFactor ?? 1;+ let kind = "mixed";+ if (mr) {+ let metalTexels = 0, sum = 0;+ const n = mr.width * mr.height;+ for (let i = 0; i < n; i += 7) { const b = (mr.data[i * 4 + 2] / 255) * metallic; sum += b; if (b >= 0.5) metalTexels++; }+ const samples = Math.ceil(n / 7);+ const frac = metalTexels / samples;+ kind = frac >= 0.25 ? "metal" : frac < 0.02 && sum / samples < 0.05 ? "matte" : "mixed";+ } else if (metallic === 1 && roughness === 1) {+ metallic = 0;+ roughness = 0.8;+ kind = "plain";+ }+ return {+ color: pbr.baseColorFactor ?? [1, 1, 1, 1],+ base, mr, normal, occ,+ normalScale: mt.normalTexture?.scale ?? 1,+ occStrength: mt.occlusionTexture?.strength ?? 1,+ metallic, roughness, kind,+ emissive: mt.emissiveFactor ?? [0, 0, 0],+ emissiveTex: textureOf(json, mt.emissiveTexture, pictures),+ doubleSided: !!mt.doubleSided,+ blend: mt.alphaMode === "MASK" ? "mask" : "opaque",+ cutoff: mt.alphaCutoff ?? 0.5,+ };+}++/** Bilinear lookup of a picture (wrapping), into out[0..3] as 0..1. */+function sample(pic, u, v, out) {+ const w = pic.width, h = pic.height, d = pic.data;+ let x = (u - Math.floor(u)) * w - 0.5;+ let y = (v - Math.floor(v)) * h - 0.5;+ if (x < 0) x += w;+ if (y < 0) y += h;+ const x0 = Math.floor(x), y0 = Math.floor(y);+ const fx = x - x0, fy = y - y0;+ const x1 = (x0 + 1) % w, y1 = (y0 + 1) % h;+ const a = (y0 * w + x0) * 4, b = (y0 * w + x1) * 4, c = (y1 * w + x0) * 4, e = (y1 * w + x1) * 4;+ for (let k = 0; k < 4; k++) out[k] = ((d[a + k] * (1 - fx) + d[b + k] * fx) * (1 - fy) + (d[c + k] * (1 - fx) + d[e + k] * fx) * fy) / 255;+}+/** Same, with each colour channel from sRGB to linear. */+function sampleSrgb(pic, u, v, out) {+ const w = pic.width, h = pic.height, d = pic.data;+ let x = (u - Math.floor(u)) * w - 0.5;+ let y = (v - Math.floor(v)) * h - 0.5;+ if (x < 0) x += w;+ if (y < 0) y += h;+ const x0 = Math.floor(x), y0 = Math.floor(y);+ const fx = x - x0, fy = y - y0;+ const x1 = (x0 + 1) % w, y1 = (y0 + 1) % h;+ const a = (y0 * w + x0) * 4, b = (y0 * w + x1) * 4, c = (y1 * w + x0) * 4, e = (y1 * w + x1) * 4;+ for (let k = 0; k < 3; k++) out[k] = (SRGB[d[a + k]] * (1 - fx) + SRGB[d[b + k]] * fx) * (1 - fy) + (SRGB[d[c + k]] * (1 - fx) + SRGB[d[e + k]] * fx) * fy;+ out[3] = ((d[a + 3] * (1 - fx) + d[b + 3] * fx) * (1 - fy) + (d[c + 3] * (1 - fx) + d[e + 3] * fx) * fy) / 255;+}++// ---------------------------------------------------------------------------------------------------------------------+// The studio light: a Radiance HDR, its irradiance (9 spherical harmonics) and blurred copies for reflections.++/** A Radiance .hdr (RGBE, flat or run-length encoded) as linear RGB floats. */+export function readHdr(buf) {+ const u8 = buf instanceof Uint8Array ? buf : new Uint8Array(buf);+ let at = 0;+ const line = () => { let s = ""; while (at < u8.length && u8[at] !== 10) s += String.fromCharCode(u8[at++]); at++; return s; };+ if (!line().startsWith("#?")) throw new Error("not a Radiance HDR");+ for (let l = line(); l !== ""; l = line()) if (at >= u8.length) throw new Error("HDR header has no end");+ const m = /-Y (\d+) \+X (\d+)/.exec(line());+ if (!m) throw new Error("HDR size line not understood");+ const h = Number(m[1]), w = Number(m[2]);+ const data = new Float32Array(w * h * 3);+ const row = new Uint8Array(w * 4);+ for (let y = 0; y < h; y++) {+ if (w >= 8 && w < 32768 && u8[at] === 2 && u8[at + 1] === 2 && ((u8[at + 2] << 8) | u8[at + 3]) === w) {+ at += 4;+ for (let c = 0; c < 4; c++) {+ for (let x = 0; x < w; ) {+ let n = u8[at++];+ if (n > 128) { n -= 128; const v = u8[at++]; while (n--) row[(x++) * 4 + c] = v; }+ else while (n--) row[(x++) * 4 + c] = u8[at++];+ }+ }+ } else {+ row.set(u8.subarray(at, at + w * 4));+ at += w * 4;+ }+ for (let x = 0; x < w; x++) {+ const e = row[x * 4 + 3];+ const f = e ? Math.pow(2, e - 136) : 0;+ const o = (y * w + x) * 3;+ data[o] = row[x * 4] * f; data[o + 1] = row[x * 4 + 1] * f; data[o + 2] = row[x * 4 + 2] * f;+ }+ }+ return { width: w, height: h, data };+}++/** Direction (y up) of an equirect texel centre: u across from -z through +x, v from the top. */+function dirOf(u, v, out) {+ const phi = u * 2 * Math.PI - Math.PI;+ const th = v * Math.PI;+ out[0] = Math.sin(th) * Math.sin(phi);+ out[1] = Math.cos(th);+ out[2] = -Math.sin(th) * Math.cos(phi);+}+function uvOf(x, y, z) {+ const u = (Math.atan2(x, -z) + Math.PI) / (2 * Math.PI);+ const v = Math.acos(Math.max(-1, Math.min(1, y))) / Math.PI;+ return [u, v];+}++function downsample(env, w, h) {+ const out = new Float32Array(w * h * 3);+ const sx = env.width / w, sy = env.height / h;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ let r = 0, g = 0, b = 0, n = 0;+ for (let j = Math.floor(y * sy); j < Math.floor((y + 1) * sy); j++) for (let i = Math.floor(x * sx); i < Math.floor((x + 1) * sx); i++) {+ const o = (j * env.width + i) * 3; r += env.data[o]; g += env.data[o + 1]; b += env.data[o + 2]; n++;+ }+ const o = (y * w + x) * 3; out[o] = r / n; out[o + 1] = g / n; out[o + 2] = b / n;+ }+ return { width: w, height: h, data: out };+}++/**+ * The light from an HDR: `sh` (9 x RGB irradiance coefficients) and `levels`: copies blurred for roughness 0, 0.2,+ * 0.4, 0.6, 0.8 and 1 (a cosine-power lobe, wider as it gets rougher). `yaw` turns the light about the vertical axis.+ */+export function studioLight(hdr, { yaw = 0 } = {}) {+ const src = downsample(hdr, 128, 64);+ const d = [0, 0, 0];+ // Each texel's solid angle and direction.+ const n = src.width * src.height;+ const dirs = new Float32Array(n * 3);+ const area = new Float32Array(n);+ for (let y = 0; y < src.height; y++) for (let x = 0; x < src.width; x++) {+ const i = y * src.width + x;+ dirOf((x + 0.5) / src.width + yaw / (2 * Math.PI), (y + 0.5) / src.height, d);+ dirs[i * 3] = d[0]; dirs[i * 3 + 1] = d[1]; dirs[i * 3 + 2] = d[2];+ area[i] = (2 * Math.PI / src.width) * (Math.PI / src.height) * Math.sin(((y + 0.5) / src.height) * Math.PI);+ }+ // Irradiance SH (Ramamoorthi & Hanrahan).+ const sh = new Float64Array(27);+ for (let i = 0; i < n; i++) {+ const x = dirs[i * 3], y = dirs[i * 3 + 1], z = dirs[i * 3 + 2];+ const basis = [0.282095, 0.488603 * y, 0.488603 * z, 0.488603 * x, 1.092548 * x * y, 1.092548 * y * z, 0.315392 * (3 * z * z - 1), 1.092548 * x * z, 0.546274 * (x * x - y * y)];+ for (let k = 0; k < 9; k++) for (let c = 0; c < 3; c++) sh[k * 3 + c] += src.data[i * 3 + c] * basis[k] * area[i];+ }+ const band = [Math.PI, (2 * Math.PI) / 3, (2 * Math.PI) / 3, (2 * Math.PI) / 3, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4];+ for (let k = 0; k < 9; k++) for (let c = 0; c < 3; c++) sh[k * 3 + c] *= band[k];+ // Reflection copies.+ const roughs = [0, 0.2, 0.4, 0.6, 0.8, 1];+ const levels = roughs.map((r) => {+ if (r === 0) return { ...hdr, yaw };+ const W = r < 0.3 ? 64 : 32, H = W / 2;+ const out = new Float32Array(W * H * 3);+ const power = 2 / Math.pow(Math.max(r, 0.05), 4) - 2;+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {+ dirOf((x + 0.5) / W + yaw / (2 * Math.PI), (y + 0.5) / H, d);+ let rr = 0, gg = 0, bb = 0, ww = 0;+ for (let i = 0; i < n; i++) {+ const c = d[0] * dirs[i * 3] + d[1] * dirs[i * 3 + 1] + d[2] * dirs[i * 3 + 2];+ if (c <= 0) continue;+ const wgt = Math.pow(c, power) * area[i];+ if (wgt < 1e-7) continue;+ rr += src.data[i * 3] * wgt; gg += src.data[i * 3 + 1] * wgt; bb += src.data[i * 3 + 2] * wgt; ww += wgt;+ }+ const o = (y * W + x) * 3;+ out[o] = rr / ww; out[o + 1] = gg / ww; out[o + 2] = bb / ww;+ }+ return { width: W, height: H, data: out, yaw };+ });+ return { sh, levels, roughs };+}++function envLookup(level, x, y, z, out) {+ let [u, v] = uvOf(x, y, z);+ u -= level.yaw / (2 * Math.PI);+ const w = level.width, h = level.height, d = level.data;+ let fx = (u - Math.floor(u)) * w - 0.5;+ const fy = Math.min(h - 1, Math.max(0, v * h - 0.5));+ if (fx < 0) fx += w;+ const x0 = Math.floor(fx), y0 = Math.floor(fy);+ const ax = fx - x0, ay = fy - y0;+ const x1 = (x0 + 1) % w, y1 = Math.min(h - 1, y0 + 1);+ const a = (y0 * w + x0) * 3, b = (y0 * w + x1) * 3, c = (y1 * w + x0) * 3, e = (y1 * w + x1) * 3;+ for (let k = 0; k < 3; k++) out[k] = (d[a + k] * (1 - ax) + d[b + k] * ax) * (1 - ay) + (d[c + k] * (1 - ax) + d[e + k] * ax) * ay;+}++// ---------------------------------------------------------------------------------------------------------------------+// The camera and the framing++/**+ * Where the camera stands to keep a turning subject in frame for the whole turn: the subject's cylinder (radius `r`+ * about the axis, from `y0` to `y1`) seen from `elevation` degrees above, through a lens of `fov` degrees, filling+ * `fill` of the frame at most. Returns the distance and the height the camera looks at (the cylinder centred).+ */+export function frameCylinder({ r, y0, y1 }, { fov = 24, elevation = 14, fill = 0.82, aspect = 1 } = {}) {+ const t = Math.tan((fov * Math.PI) / 360);+ const el = (elevation * Math.PI) / 180;+ const pts = [];+ for (let k = 0; k < 48; k++) {+ const a = (k / 48) * 2 * Math.PI;+ pts.push([r * Math.cos(a), y0, r * Math.sin(a)], [r * Math.cos(a), y1, r * Math.sin(a)]);+ }+ const project = (dist, lookY) => {+ // Camera on +z, raised by `el`, looking at (0, lookY, 0).+ const cy = lookY + dist * Math.sin(el), cz = dist * Math.cos(el);+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ for (const [x, y, z] of pts) {+ const dy = y - cy, dz = z - cz;+ // View axes: forward f = (0, -sin el, -cos el), up u = (0, cos el, -sin el).+ const depth = -dy * Math.sin(el) - dz * Math.cos(el);+ const vy = dy * Math.cos(el) - dz * Math.sin(el);+ const sx = x / (depth * t * aspect), sy = vy / (depth * t);+ minX = Math.min(minX, sx); maxX = Math.max(maxX, sx); minY = Math.min(minY, sy); maxY = Math.max(maxY, sy);+ }+ return { minX, maxX, minY, maxY };+ };+ let lookY = (y0 + y1) / 2;+ let lo = r * 0.5 + 1e-6, hi = (Math.max(r, y1 - y0) * 40) / t + 1;+ for (let it = 0; it < 60; it++) {+ const mid = (lo + hi) / 2;+ const p = project(mid, lookY);+ if (Math.max(p.maxX, -p.minX, p.maxY, -p.minY) <= fill) hi = mid;+ else lo = mid;+ // Centred vertically as the distance settles.+ const q = project(hi, lookY);+ lookY += ((q.maxY + q.minY) / 2) * hi * t * 0.5;+ }+ return { distance: hi, lookY, fov, elevation };+}++// ---------------------------------------------------------------------------------------------------------------------+// Meshes++const PBR_NEUTRAL = (c) => {+ // Khronos PBR Neutral tone mapping, per pixel on [r, g, b].+ const startCompression = 0.8 - 0.04, desaturation = 0.15;+ const x = Math.min(c[0], c[1], c[2]);+ const offset = x < 0.08 ? x - 6.25 * x * x : 0.04;+ c[0] -= offset; c[1] -= offset; c[2] -= offset;+ const peak = Math.max(c[0], c[1], c[2]);+ if (peak < startCompression) return;+ const d = 1 - startCompression;+ const newPeak = 1 - (d * d) / (peak + d - startCompression);+ for (let k = 0; k < 3; k++) c[k] *= newPeak / peak;+ const g = 1 - 1 / (desaturation * (peak - newPeak) + 1);+ for (let k = 0; k < 3; k++) c[k] = c[k] * (1 - g) + newPeak * g;+};+const toSrgb = (v) => (v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055);+const SRGB_OUT = new Uint8Array(4096).map((_, i) => Math.round(Math.max(0, Math.min(1, toSrgb(i / 4095))) * 255));+const enc = (v) => SRGB_OUT[v <= 0 ? 0 : v >= 1 ? 4095 : (v * 4095) | 0];++/** The subject's turning axis and size from a mesh: the box's middle (x, z), and the cylinder it turns in. */+export function meshCylinder(mesh) {+ const { P } = mesh;+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity, minZ = Infinity, maxZ = -Infinity;+ for (let i = 0; i < P.length; i += 3) {+ if (P[i] < minX) minX = P[i]; if (P[i] > maxX) maxX = P[i];+ if (P[i + 1] < minY) minY = P[i + 1]; if (P[i + 1] > maxY) maxY = P[i + 1];+ if (P[i + 2] < minZ) minZ = P[i + 2]; if (P[i + 2] > maxZ) maxZ = P[i + 2];+ }+ const cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;+ let r2 = 0;+ for (let i = 0; i < P.length; i += 3) { const dx = P[i] - cx, dz = P[i + 2] - cz; const d = dx * dx + dz * dz; if (d > r2) r2 = d; }+ return { cx, cz, r: Math.sqrt(r2), y0: minY, y1: maxY };+}++/**+ * A mesh turned `angle` radians (about its axis, plus `frontYaw` degrees so the first frame faces its front), drawn at+ * `size` x `size` (`ss` x supersampled), as straight RGBA bytes: the model opaque, its contact shadow as black with+ * alpha, nothing else.+ */+export function drawMesh(mesh, light, view, angle, { size = 720, ss = 2, exposure = 1.15, shadow = 0.5 } = {}) {+ const S = size * ss;+ const { P, N, T, UV, I, triMat, hasTangent, materials } = mesh;+ const { cx, cz, y0 } = view.cyl;+ const t = Math.tan((view.frame.fov * Math.PI) / 360);+ const el = (view.frame.elevation * Math.PI) / 180;+ const ce = Math.cos(el), se = Math.sin(el);+ const ca = Math.cos(angle), sa = Math.sin(angle);+ const camY = view.frame.lookY + view.frame.distance * se, camZ = view.frame.distance * ce;+ const vCount = P.length / 3;+ // Per vertex: screen x, y (pixels), 1/depth; world position after the turn (for the view vector), normal, tangent.+ const sx = new Float32Array(vCount), sy = new Float32Array(vCount), iw = new Float32Array(vCount);+ const wn = new Float32Array(vCount * 3), wt = new Float32Array(vCount * 3), wp = new Float32Array(vCount * 3);+ const half = S / 2, f = half / t;+ for (let i = 0; i < vCount; i++) {+ const x = P[i * 3] - cx, y = P[i * 3 + 1], z = P[i * 3 + 2] - cz;+ const rx = ca * x + sa * z, rz = -sa * x + ca * z;+ wp[i * 3] = rx; wp[i * 3 + 1] = y; wp[i * 3 + 2] = rz;+ const dy = y - camY, dz = rz - camZ;+ const depth = -dy * se - dz * ce;+ const vy = dy * ce - dz * se;+ iw[i] = 1 / depth;+ sx[i] = half + (rx * f) / depth;+ sy[i] = half - (vy * f) / depth;+ const nx = N[i * 3], nz = N[i * 3 + 2];+ wn[i * 3] = ca * nx + sa * nz; wn[i * 3 + 1] = N[i * 3 + 1]; wn[i * 3 + 2] = -sa * nx + ca * nz;+ const tx = T[i * 4], tz = T[i * 4 + 2];+ wt[i * 3] = ca * tx + sa * tz; wt[i * 3 + 1] = T[i * 4 + 1]; wt[i * 3 + 2] = -sa * tx + ca * tz;+ }+ // Visibility: the nearest triangle per pixel (largest 1/depth), with its perspective-correct barycentrics.+ const zb = new Float32Array(S * S);+ const tri = new Int32Array(S * S).fill(-1);+ const bA = new Float32Array(S * S), bB = new Float32Array(S * S);+ const triCount = I.length / 3;+ const sampleOut = [0, 0, 0, 0];+ for (let k = 0; k < triCount; k++) {+ const a = I[k * 3], b = I[k * 3 + 1], c = I[k * 3 + 2];+ const ax = sx[a], ay = sy[a], bx = sx[b], by = sy[b], cxv = sx[c], cy = sy[c];+ if (iw[a] <= 0 || iw[b] <= 0 || iw[c] <= 0) continue;+ const area = (bx - ax) * (cy - ay) - (by - ay) * (cxv - ax);+ if (area === 0) continue;+ const mat = materials[triMat[k]];+ // Single-sided materials: only the faces toward the camera (screen y runs down, so front faces have area < 0).+ if (area > 0 && mat && !mat.doubleSided) continue;+ let x0 = Math.max(0, Math.floor(Math.min(ax, bx, cxv))), x1 = Math.min(S - 1, Math.ceil(Math.max(ax, bx, cxv)));+ let y0p = Math.max(0, Math.floor(Math.min(ay, by, cy))), y1p = Math.min(S - 1, Math.ceil(Math.max(ay, by, cy)));+ if (x0 > x1 || y0p > y1p) continue;+ const inv = 1 / area;+ for (let py = y0p; py <= y1p; py++) {+ const qy = py + 0.5;+ for (let px = x0; px <= x1; px++) {+ const qx = px + 0.5;+ const w0 = ((bx - qx) * (cy - qy) - (by - qy) * (cxv - qx)) * inv;+ const w1 = ((cxv - qx) * (ay - qy) - (cy - qy) * (ax - qx)) * inv;+ const w2 = 1 - w0 - w1;+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;+ const z = w0 * iw[a] + w1 * iw[b] + w2 * iw[c];+ const p = py * S + px;+ if (z <= zb[p]) continue;+ // Alpha-masked materials: the cut-out parts let what is behind through.+ if (mat && mat.blend === "mask") {+ const pb = (w1 * iw[b]) / z, pc = (w2 * iw[c]) / z, pa = 1 - pb - pc;+ let alpha = mat.color[3];+ if (mat.base) { sample(mat.base, pa * UV[a * 2] + pb * UV[b * 2] + pc * UV[c * 2], pa * UV[a * 2 + 1] + pb * UV[b * 2 + 1] + pc * UV[c * 2 + 1], sampleOut); alpha *= sampleOut[3]; }+ if (alpha < mat.cutoff) continue;+ }+ zb[p] = z;+ tri[p] = k;+ bA[p] = (w1 * iw[b]) / z;+ bB[p] = (w2 * iw[c]) / z;+ }+ }+ }+ // Shading, once per covered pixel.+ const out = new Uint8ClampedArray(size * size * 4);+ const acc = new Float32Array(size * size * 4);+ const col = [0, 0, 0, 0], mr = [0, 0, 0, 0], nm = [0, 0, 0, 0], oc = [0, 0, 0, 0], em = [0, 0, 0, 0];+ const env = [0, 0, 0], env2 = [0, 0, 0];+ const { sh, levels, roughs } = light;+ for (let py = 0; py < S; py++) {+ for (let px = 0; px < S; px++) {+ const p = py * S + px;+ const k = tri[p];+ if (k < 0) continue;+ const pb = bA[p], pc = bB[p], pa = 1 - pb - pc;+ const a = I[k * 3], b = I[k * 3 + 1], c = I[k * 3 + 2];+ const mat = materials[triMat[k]] ?? DEFAULT_MATERIAL;+ const u = pa * UV[a * 2] + pb * UV[b * 2] + pc * UV[c * 2];+ const v = pa * UV[a * 2 + 1] + pb * UV[b * 2 + 1] + pc * UV[c * 2 + 1];+ let nx = pa * wn[a * 3] + pb * wn[b * 3] + pc * wn[c * 3];+ let ny = pa * wn[a * 3 + 1] + pb * wn[b * 3 + 1] + pc * wn[c * 3 + 1];+ let nz = pa * wn[a * 3 + 2] + pb * wn[b * 3 + 2] + pc * wn[c * 3 + 2];+ let l = Math.hypot(nx, ny, nz) || 1;+ nx /= l; ny /= l; nz /= l;+ const px3 = pa * wp[a * 3] + pb * wp[b * 3] + pc * wp[c * 3];+ const py3 = pa * wp[a * 3 + 1] + pb * wp[b * 3 + 1] + pc * wp[c * 3 + 1];+ const pz3 = pa * wp[a * 3 + 2] + pb * wp[b * 3 + 2] + pc * wp[c * 3 + 2];+ let vx = -px3, vy = camY - py3, vz = camZ - pz3;+ l = Math.hypot(vx, vy, vz) || 1;+ vx /= l; vy /= l; vz /= l;+ // A back face of a double-sided material: its normal turned to the camera.+ let flip = nx * vx + ny * vy + nz * vz < 0 ? -1 : 1;+ if (mat.normal && hasTangent[k]) {+ sample(mat.normal, u, v, nm);+ const tx0 = pa * wt[a * 3] + pb * wt[b * 3] + pc * wt[c * 3];+ const ty0 = pa * wt[a * 3 + 1] + pb * wt[b * 3 + 1] + pc * wt[c * 3 + 1];+ const tz0 = pa * wt[a * 3 + 2] + pb * wt[b * 3 + 2] + pc * wt[c * 3 + 2];+ const sign = T[a * 4 + 3];+ const bx = (ny * tz0 - nz * ty0) * sign, by2 = (nz * tx0 - nx * tz0) * sign, bz = (nx * ty0 - ny * tx0) * sign;+ const mx = (nm[0] * 2 - 1) * mat.normalScale, my = (nm[1] * 2 - 1) * mat.normalScale, mz = nm[2] * 2 - 1;+ const qx = tx0 * mx + bx * my + nx * mz, qy = ty0 * mx + by2 * my + ny * mz, qz = tz0 * mx + bz * my + nz * mz;+ l = Math.hypot(qx, qy, qz);+ if (l > 1e-6) { nx = qx / l; ny = qy / l; nz = qz / l; }+ }+ nx *= flip; ny *= flip; nz *= flip;+ let ndv = nx * vx + ny * vy + nz * vz;+ if (ndv < 1e-3) {+ // A normal map that points away: bend it back toward the camera.+ nx += vx * (1e-3 - ndv); ny += vy * (1e-3 - ndv); nz += vz * (1e-3 - ndv);+ l = Math.hypot(nx, ny, nz) || 1; nx /= l; ny /= l; nz /= l;+ ndv = Math.max(1e-3, nx * vx + ny * vy + nz * vz);+ }+ // Material.+ let r = mat.color[0], g = mat.color[1], bl = mat.color[2];+ if (mat.base) { sampleSrgb(mat.base, u, v, col); r *= col[0]; g *= col[1]; bl *= col[2]; }+ let metal = mat.metallic, rough = mat.roughness;+ if (mat.mr) { sample(mat.mr, u, v, mr); metal *= mr[2]; rough *= mr[1]; }+ if (mat.kind === "matte") { metal = 0; rough = Math.max(rough, 0.8); }+ else if (mat.kind === "mixed" && metal < 0.5) rough = Math.max(rough, 0.45);+ rough = Math.min(1, Math.max(0.04, rough));+ let ao = 1;+ if (mat.occ) { sample(mat.occ, u, v, oc); ao = 1 + mat.occStrength * (oc[0] - 1); }+ // Diffuse: irradiance from the harmonics.+ const B = [0.282095, 0.488603 * ny, 0.488603 * nz, 0.488603 * nx, 1.092548 * nx * ny, 1.092548 * ny * nz, 0.315392 * (3 * nz * nz - 1), 1.092548 * nx * nz, 0.546274 * (nx * nx - ny * ny)];+ let er = 0, eg = 0, eb = 0;+ for (let q = 0; q < 9; q++) { er += sh[q * 3] * B[q]; eg += sh[q * 3 + 1] * B[q]; eb += sh[q * 3 + 2] * B[q]; }+ er = Math.max(0, er) / Math.PI; eg = Math.max(0, eg) / Math.PI; eb = Math.max(0, eb) / Math.PI;+ // Reflection: the HDR copy for this roughness, along the mirrored view.+ const rx = 2 * ndv * nx - vx, ry = 2 * ndv * ny - vy, rz = 2 * ndv * nz - vz;+ const lv = rough * (roughs.length - 1);+ const l0 = Math.min(roughs.length - 1, Math.floor(lv)), l1 = Math.min(roughs.length - 1, l0 + 1), lf = lv - l0;+ envLookup(levels[l0], rx, ry, rz, env);+ if (lf > 0) { envLookup(levels[l1], rx, ry, rz, env2); for (let q = 0; q < 3; q++) env[q] = env[q] * (1 - lf) + env2[q] * lf; }+ // Karis' analytic environment BRDF.+ const c0x = -1, c0y = -0.0275, c0z = -0.572, c0w = 0.022, c1x = 1, c1y = 0.0425, c1z = 1.04, c1w = -0.04;+ const rrx = rough * c0x + c1x, rry = rough * c0y + c1y, rrz = rough * c0z + c1z, rrw = rough * c0w + c1w;+ const a004 = Math.min(rrx * rrx, Math.pow(2, -9.28 * ndv)) * rrx + rry;+ const A = a004 * -1.04 + rrz, Bb = a004 * 1.04 + rrw;+ const f0r = 0.04 * (1 - metal) + r * metal, f0g = 0.04 * (1 - metal) + g * metal, f0b = 0.04 * (1 - metal) + bl * metal;+ const so = Math.min(1, ao + 0.15);+ col[0] = (r * (1 - metal) * er * ao + env[0] * (f0r * A + Bb) * so) * exposure;+ col[1] = (g * (1 - metal) * eg * ao + env[1] * (f0g * A + Bb) * so) * exposure;+ col[2] = (bl * (1 - metal) * eb * ao + env[2] * (f0b * A + Bb) * so) * exposure;+ if (mat.emissiveTex || mat.emissive[0] || mat.emissive[1] || mat.emissive[2]) {+ let e0 = mat.emissive[0], e1 = mat.emissive[1], e2 = mat.emissive[2];+ if (mat.emissiveTex) { sampleSrgb(mat.emissiveTex, u, v, em); e0 *= em[0]; e1 *= em[1]; e2 *= em[2]; }+ col[0] += e0; col[1] += e1; col[2] += e2;+ }+ PBR_NEUTRAL(col);+ const o = ((py / ss) | 0) * size + ((px / ss) | 0);+ acc[o * 4] += enc(col[0]); acc[o * 4 + 1] += enc(col[1]); acc[o * 4 + 2] += enc(col[2]); acc[o * 4 + 3] += 1;+ }+ }+ const per = ss * ss;+ for (let i = 0; i < size * size; i++) {+ const n = acc[i * 4 + 3];+ if (!n) continue;+ out[i * 4] = acc[i * 4] / n; out[i * 4 + 1] = acc[i * 4 + 1] / n; out[i * 4 + 2] = acc[i * 4 + 2] / n;+ out[i * 4 + 3] = Math.round((255 * n) / per);+ }+ if (shadow > 0) {+ // The contact shadow: the model seen from straight above, blurred, laid on the floor under it.+ const G = 160;+ const ext = view.cyl.r * 1.5;+ const top = new Float32Array(G * G);+ for (let i = 0; i < vCount; i++) {+ const h = (wp[i * 3 + 1] - y0) / Math.max(1e-6, view.cyl.y1 - y0);+ if (h > 0.6) continue;+ const gx = Math.floor(((wp[i * 3] / ext) * 0.5 + 0.5) * G), gz = Math.floor(((wp[i * 3 + 2] / ext) * 0.5 + 0.5) * G);+ if (gx >= 0 && gx < G && gz >= 0 && gz < G) top[gz * G + gx] = Math.max(top[gz * G + gx], 1 - h / 0.6);+ }+ let soft = blur(blur(blur(top, G, 3), G, 3), G, 3);+ let peak = 0;+ for (const x of soft) if (x > peak) peak = x;+ if (peak > 0) for (let i = 0; i < soft.length; i++) soft[i] = Math.min(1, (soft[i] / peak) * 1.4);+ drawFloor(out, size, soft, G, ext, { camY, camZ, ce, se, t, floorY: y0, strength: shadow });+ }+ return out;+}++const DEFAULT_MATERIAL = { color: [0.8, 0.8, 0.8, 1], base: null, mr: null, normal: null, occ: null, normalScale: 1, occStrength: 1, metallic: 0, roughness: 0.8, kind: "plain", emissive: [0, 0, 0], emissiveTex: null, doubleSided: true, blend: "opaque", cutoff: 0.5 };++function blur(src, G, r) {+ const tmp = new Float32Array(G * G), out = new Float32Array(G * G);+ for (let y = 0; y < G; y++) for (let x = 0; x < G; x++) { let s = 0, n = 0; for (let k = -r; k <= r; k++) { const xx = x + k; if (xx >= 0 && xx < G) { s += src[y * G + xx]; n++; } } tmp[y * G + x] = s / n; }+ for (let y = 0; y < G; y++) for (let x = 0; x < G; x++) { let s = 0, n = 0; for (let k = -r; k <= r; k++) { const yy = y + k; if (yy >= 0 && yy < G) { s += tmp[yy * G + x]; n++; } } out[y * G + x] = s / n; }+ return out;+}++/** Lay a floor shadow map (G x G over +-ext around the axis) under what is drawn: black with alpha where nothing is. */+function drawFloor(out, size, map, G, ext, { camY, camZ, ce, se, t, floorY, strength }) {+ const half = size / 2, f = half / t;+ for (let py = 0; py < size; py++) {+ for (let px = 0; px < size; px++) {+ const o = (py * size + px) * 4;+ if (out[o + 3] === 255) continue;+ // The view ray through this pixel, from the camera, in world space.+ const vx = (px + 0.5 - half) / f, vyv = -(py + 0.5 - half) / f;+ const dx = vx, dy = -se + vyv * ce, dz = -ce - vyv * se;+ if (dy >= -1e-6) continue;+ const k = (floorY - camY) / dy;+ const wx = dx * k, wz = camZ + dz * k;+ const gx = (wx / ext) * 0.5 + 0.5, gz = (wz / ext) * 0.5 + 0.5;+ if (gx <= 0 || gx >= 1 || gz <= 0 || gz >= 1) continue;+ const s = map[Math.floor(gz * G) * G + Math.floor(gx * G)] * strength;+ if (s <= 0.004) continue;+ // Under a partly covered edge pixel the shadow shows through the rest.+ const a = out[o + 3] / 255;+ const sa = s * (1 - a);+ const na = a + sa;+ out[o] = (out[o] * a) / na; out[o + 1] = (out[o + 1] * a) / na; out[o + 2] = (out[o + 2] * a) / na;+ out[o + 3] = Math.round(na * 255);+ }+ }+}++// ---------------------------------------------------------------------------------------------------------------------+// Gaussian splats++const SH_C0 = 0.28209479177387814;++/** A .spz (Niantic's packed splats, versions 2 and 3) as centres, scales, rotations (x y z w), opacities and colours. */+export function readSpz(raw, gunzip) {+ const b = gunzip(raw);+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);+ if (dv.getUint32(0, true) !== 0x5053474e) throw new Error("not a .spz");+ const version = dv.getUint32(4, true);+ const n = dv.getUint32(8, true);+ const shDegree = b[12];+ const fractional = b[13];+ if (version < 2 || version > 3) throw new Unsupported(`.spz version ${version}`);+ let at = 16;+ const pos = new Float32Array(n * 3);+ const scale = 1 / (1 << fractional);+ for (let i = 0; i < n * 3; i++) {+ let v = b[at] | (b[at + 1] << 8) | (b[at + 2] << 16);+ if (v & 0x800000) v |= ~0xffffff;+ pos[i] = v * scale;+ at += 3;+ }+ const opacity = new Float32Array(n);+ for (let i = 0; i < n; i++) opacity[i] = b[at++] / 255;+ const color = new Float32Array(n * 3);+ for (let i = 0; i < n * 3; i++) color[i] = Math.min(1, Math.max(0, 0.5 + SH_C0 * ((b[at++] / 255 - 0.5) / 0.15)));+ const scales = new Float32Array(n * 3);+ for (let i = 0; i < n * 3; i++) scales[i] = Math.exp(b[at++] / 16 - 10);+ const rot = new Float32Array(n * 4);+ for (let i = 0; i < n; i++) {+ if (version >= 3) {+ // Smallest three: 2 bits for the largest's index, then three 10-bit signed values of the others.+ const word = b[at] | (b[at + 1] << 8) | (b[at + 2] << 16) | (b[at + 3] << 24);+ at += 4;+ const largest = word >>> 30;+ let rest = word;+ const q = [0, 0, 0, 0];+ let sum = 0;+ for (let k = 3; k >= 0; k--) {+ if (k === largest) continue;+ const mag = rest & 0x1ff, neg = (rest >>> 9) & 1;+ rest >>>= 10;+ q[k] = (Math.SQRT1_2 * mag) / 511 * (neg ? -1 : 1);+ sum += q[k] * q[k];+ }+ q[largest] = Math.sqrt(Math.max(0, 1 - sum));+ rot.set(q, i * 4);+ } else {+ const x = b[at] / 127.5 - 1, y = b[at + 1] / 127.5 - 1, z = b[at + 2] / 127.5 - 1;+ at += 3;+ rot[i * 4] = x; rot[i * 4 + 1] = y; rot[i * 4 + 2] = z; rot[i * 4 + 3] = Math.sqrt(Math.max(0, 1 - x * x - y * y - z * z));+ }+ }+ void shDegree;+ return { n, pos, scales, rot, opacity, color };+}++/** A 3DGS .ply (binary little-endian: x y z, f_dc_0..2, opacity as a logit, scale_0..2 as logs, rot_0..3 as w x y z). */+export function readPly(raw) {+ const u8 = raw instanceof Uint8Array ? raw : new Uint8Array(raw);+ const headEnd = Buffer.from(u8.subarray(0, Math.min(u8.length, 65536))).indexOf("end_header\n");+ if (headEnd < 0) throw new Error("not a .ply");+ const head = new TextDecoder().decode(u8.subarray(0, headEnd)).split("\n");+ if (!head.some((l) => l.startsWith("format binary_little_endian"))) throw new Unsupported("only binary little-endian .ply");+ let n = 0;+ const props = [];+ let inVertex = false;+ for (const l of head) {+ const w = l.trim().split(/\s+/);+ if (w[0] === "element") { inVertex = w[1] === "vertex"; if (inVertex) n = Number(w[2]); }+ else if (w[0] === "property" && inVertex) props.push({ type: w[1], name: w[2] });+ }+ const SZ = { float: 4, float32: 4, double: 8, uchar: 1, uint8: 1, int: 4, uint: 4, short: 2, ushort: 2 };+ let stride = 0;+ const off = {};+ for (const p of props) { off[p.name] = { at: stride, type: p.type }; stride += SZ[p.type] ?? 4; }+ for (const k of ["x", "y", "z", "opacity", "scale_0", "scale_1", "scale_2", "rot_0", "rot_1", "rot_2", "rot_3"]) if (!off[k]) throw new Unsupported(`the .ply has no ${k}`);+ const base = headEnd + "end_header\n".length;+ const dv = new DataView(u8.buffer, u8.byteOffset + base, n * stride);+ const get = (i, k) => { const o = off[k]; const at = i * stride + o.at; return o.type === "double" ? dv.getFloat64(at, true) : o.type === "uchar" || o.type === "uint8" ? dv.getUint8(at) / 255 : dv.getFloat32(at, true); };+ const pos = new Float32Array(n * 3), scales = new Float32Array(n * 3), rot = new Float32Array(n * 4), opacity = new Float32Array(n), color = new Float32Array(n * 3);+ const hasDc = !!off.f_dc_0, hasRgb = !!off.red;+ for (let i = 0; i < n; i++) {+ pos[i * 3] = get(i, "x"); pos[i * 3 + 1] = get(i, "y"); pos[i * 3 + 2] = get(i, "z");+ opacity[i] = 1 / (1 + Math.exp(-get(i, "opacity")));+ for (let k = 0; k < 3; k++) scales[i * 3 + k] = Math.exp(get(i, `scale_${k}`));+ const w = get(i, "rot_0"), x = get(i, "rot_1"), y = get(i, "rot_2"), z = get(i, "rot_3");+ const l = Math.hypot(w, x, y, z) || 1;+ rot[i * 4] = x / l; rot[i * 4 + 1] = y / l; rot[i * 4 + 2] = z / l; rot[i * 4 + 3] = w / l;+ for (let k = 0; k < 3; k++) color[i * 3 + k] = hasDc ? Math.min(1, Math.max(0, 0.5 + SH_C0 * get(i, `f_dc_${k}`))) : hasRgb ? get(i, ["red", "green", "blue"][k]) : 0.7;+ }+ return { n, pos, scales, rot, opacity, color };+}++/**+ * A splat made ready to draw: stood upright (y down: half a turn about x, as the viewer does), the haze under `cutoff`+ * and the strays far outside the subject's box left out, each Gaussian's 3D covariance worked out once.+ */+export function prepareSplat(s, { yDown = false, cutoff = 0, frontYaw = 0 } = {}) {+ const keep = [];+ for (let i = 0; i < s.n; i++) if (s.opacity[i] > Math.max(cutoff, 1 / 255)) keep.push(i);+ // The subject's box from the solid Gaussians (src/lib/av/splat-view.ts subjectBounds), trimmed of 0.5 % each end.+ const solid = keep.filter((i) => s.opacity[i] >= 0.1);+ const use = solid.length >= Math.max(8, keep.length * 0.02) ? solid : keep;+ const ys = yDown ? -1 : 1;+ const axis = (a, sign) => Float64Array.from(use, (i) => s.pos[i * 3 + a] * sign).sort();+ const q = (arr, f) => arr[Math.min(arr.length - 1, Math.max(0, Math.round(f * (arr.length - 1))))];+ const X = axis(0, 1), Y = axis(1, ys), Z = axis(2, ys);+ const box = { min: [q(X, 0.005), q(Y, 0.005), q(Z, 0.005)], max: [q(X, 0.995), q(Y, 0.995), q(Z, 0.995)] };+ const pad = [0, 1, 2].map((k) => (box.max[k] - box.min[k]) * 0.25);+ const cx = (box.min[0] + box.max[0]) / 2, cz = (box.min[2] + box.max[2]) / 2;+ const inside = keep.filter((i) => {+ const p = [s.pos[i * 3], s.pos[i * 3 + 1] * ys, s.pos[i * 3 + 2] * ys];+ return p.every((v, k) => v >= box.min[k] - pad[k] && v <= box.max[k] + pad[k]);+ });+ const n = inside.length;+ const pos = new Float32Array(n * 3), cov = new Float32Array(n * 6), opacity = new Float32Array(n), color = new Float32Array(n * 3);+ // The subject's front faces the camera at the first frame: turn it by -frontYaw about y.+ const fy = (-frontYaw * Math.PI) / 180, cf = Math.cos(fy), sf = Math.sin(fy);+ let r2 = 0;+ inside.forEach((i, j) => {+ const x0 = s.pos[i * 3] - cx, y = s.pos[i * 3 + 1] * ys, z0 = s.pos[i * 3 + 2] * ys - cz;+ const x = cf * x0 + sf * z0, z = -sf * x0 + cf * z0;+ pos[j * 3] = x; pos[j * 3 + 1] = y; pos[j * 3 + 2] = z;+ if (s.opacity[i] >= 0.1) r2 = Math.max(r2, x * x + z * z);+ opacity[j] = s.opacity[i];+ color.set(s.color.subarray(i * 3, i * 3 + 3), j * 3);+ // R from the quaternion; y down turns it half a turn about x: R' = Fx R Fx with Fx = diag(1, -1, -1).+ let qx = s.rot[i * 4], qy = s.rot[i * 4 + 1], qz = s.rot[i * 4 + 2], qw = s.rot[i * 4 + 3];+ const l = Math.hypot(qx, qy, qz, qw) || 1;+ qx /= l; qy /= l; qz /= l; qw /= l;+ const R = [+ 1 - 2 * (qy * qy + qz * qz), 2 * (qx * qy - qz * qw), 2 * (qx * qz + qy * qw),+ 2 * (qx * qy + qz * qw), 1 - 2 * (qx * qx + qz * qz), 2 * (qy * qz - qx * qw),+ 2 * (qx * qz - qy * qw), 2 * (qy * qz + qx * qw), 1 - 2 * (qx * qx + qy * qy),+ ];+ if (yDown) for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) R[r * 3 + c] *= (r === 0 ? 1 : -1) * (c === 0 ? 1 : -1);+ // The front turn: Ry R.+ const M = [0, 0, 0, 0, 0, 0, 0, 0, 0];+ const Ry = [cf, 0, sf, 0, 1, 0, -sf, 0, cf];+ for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) M[r * 3 + c] = Ry[r * 3] * R[c] + Ry[r * 3 + 1] * R[3 + c] + Ry[r * 3 + 2] * R[6 + c];+ const sx = s.scales[i * 3], sy = s.scales[i * 3 + 1], sz = s.scales[i * 3 + 2];+ // Sigma = M S S M^T+ const m = (r, c) => M[r * 3 + c];+ const sig = (r, c) => m(r, 0) * m(c, 0) * sx * sx + m(r, 1) * m(c, 1) * sy * sy + m(r, 2) * m(c, 2) * sz * sz;+ cov[j * 6] = sig(0, 0); cov[j * 6 + 1] = sig(0, 1); cov[j * 6 + 2] = sig(0, 2); cov[j * 6 + 3] = sig(1, 1); cov[j * 6 + 4] = sig(1, 2); cov[j * 6 + 5] = sig(2, 2);+ });+ return { n, pos, cov, opacity, color, cyl: { cx: 0, cz: 0, r: Math.sqrt(r2), y0: box.min[1], y1: box.max[1] } };+}++/** A prepared splat turned `angle` radians, as straight RGBA bytes (the subject over nothing, with a soft floor shadow). */+export function drawSplat(sp, view, angle, { size = 720, shadow = 0.35 } = {}) {+ const t = Math.tan((view.frame.fov * Math.PI) / 360);+ const el = (view.frame.elevation * Math.PI) / 180;+ const ce = Math.cos(el), se = Math.sin(el);+ const ca = Math.cos(angle), sa = Math.sin(angle);+ const camY = view.frame.lookY + view.frame.distance * se, camZ = view.frame.distance * ce;+ const half = size / 2, f = half / t;+ const { n, pos, cov, opacity, color } = sp;+ const depth = new Float32Array(n);+ const order = new Uint32Array(n);+ const proj = new Float32Array(n * 5); // x, y, conic a, b, c+ const rad = new Float32Array(n);+ // W: the view (rows right, up, back; the camera looks along -back) times the turn Ry(angle).+ const W = [ca, 0, sa, se * sa, ce, -se * ca, -ce * sa, se, ce * ca];+ let m = 0;+ for (let i = 0; i < n; i++) {+ const x = pos[i * 3], y = pos[i * 3 + 1] - camY, z = pos[i * 3 + 2];+ // In camera space: turn the subject, then view (camera at (0, camY, camZ) after the turn: subtract before viewing).+ const rx = ca * x + sa * z, rz = -sa * x + ca * z - camZ;+ const vx = rx, vy = ce * y - se * rz, vz = se * y + ce * rz; // vz < 0 in front+ const d = -vz;+ if (d <= 0.01) continue;+ // Sigma in camera space: W Sigma W^T.+ const s00 = cov[i * 6], s01 = cov[i * 6 + 1], s02 = cov[i * 6 + 2], s11 = cov[i * 6 + 3], s12 = cov[i * 6 + 4], s22 = cov[i * 6 + 5];+ const Sm = [s00, s01, s02, s01, s11, s12, s02, s12, s22];+ const WS = [0, 0, 0, 0, 0, 0, 0, 0, 0];+ for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) WS[r * 3 + c] = W[r * 3] * Sm[c] + W[r * 3 + 1] * Sm[3 + c] + W[r * 3 + 2] * Sm[6 + c];+ const C = (r, c) => WS[r * 3] * W[c * 3] + WS[r * 3 + 1] * W[c * 3 + 1] + WS[r * 3 + 2] * W[c * 3 + 2];+ // Jacobian of the projection (screen y down).+ const j00 = f / d, j02 = (f * vx) / (d * d), j11 = -f / d, j12 = (-f * vy) / (d * d);+ // J for (vx, vy, vz) with d = -vz: dx/dvz = f vx / d^2, dy/dvz = -f vy / d^2.+ const c00 = C(0, 0), c01 = C(0, 1), c02 = C(0, 2), c11 = C(1, 1), c12 = C(1, 2), c22 = C(2, 2);+ const a = j00 * j00 * c00 + 2 * j00 * j02 * c02 + j02 * j02 * c22 + 0.3;+ const b = j00 * j11 * c01 + j00 * j12 * c02 + j02 * j11 * c12 + j02 * j12 * c22;+ const c = j11 * j11 * c11 + 2 * j11 * j12 * c12 + j12 * j12 * c22 + 0.3;+ const det = a * c - b * b;+ if (det <= 0) continue;+ const mid = (a + c) / 2;+ const lam = mid + Math.sqrt(Math.max(0.1, mid * mid - det));+ const r = Math.ceil(3 * Math.sqrt(lam));+ const sxp = half + (vx * f) / d, syp = half - (vy * f) / d;+ if (sxp + r < 0 || sxp - r >= size || syp + r < 0 || syp - r >= size) continue;+ proj[i * 5] = sxp; proj[i * 5 + 1] = syp;+ proj[i * 5 + 2] = c / det; proj[i * 5 + 3] = -b / det; proj[i * 5 + 4] = a / det;+ rad[i] = Math.min(r, size / 3);+ depth[i] = d;+ order[m++] = i;+ }+ const idx = order.subarray(0, m);+ // Back to front.+ const sorted = Array.from(idx).sort((p, q) => depth[q] - depth[p]);+ const rgb = new Float32Array(size * size * 3);+ const alpha = new Float32Array(size * size);+ for (const i of sorted) {+ const x = proj[i * 5], y = proj[i * 5 + 1], A = proj[i * 5 + 2], B = proj[i * 5 + 3], Cc = proj[i * 5 + 4];+ const r = rad[i];+ const x0 = Math.max(0, Math.floor(x - r)), x1 = Math.min(size - 1, Math.ceil(x + r));+ const y0 = Math.max(0, Math.floor(y - r)), y1 = Math.min(size - 1, Math.ceil(y + r));+ const op = opacity[i], cr = color[i * 3], cg = color[i * 3 + 1], cb = color[i * 3 + 2];+ for (let py = y0; py <= y1; py++) {+ const dy = py + 0.5 - y;+ for (let px = x0; px <= x1; px++) {+ const dx = px + 0.5 - x;+ const power = -0.5 * (A * dx * dx + Cc * dy * dy) - B * dx * dy;+ if (power > 0 || power < -4.5) continue;+ const al = Math.min(0.99, op * Math.exp(power));+ if (al < 1 / 255) continue;+ const p = py * size + px;+ // "Over", back to front.+ rgb[p * 3] = cr * al + rgb[p * 3] * (1 - al);+ rgb[p * 3 + 1] = cg * al + rgb[p * 3 + 1] * (1 - al);+ rgb[p * 3 + 2] = cb * al + rgb[p * 3 + 2] * (1 - al);+ alpha[p] = al + alpha[p] * (1 - al);+ }+ }+ }+ const out = new Uint8ClampedArray(size * size * 4);+ for (let p = 0; p < size * size; p++) {+ const a = alpha[p];+ if (a <= 0) continue;+ out[p * 4] = (rgb[p * 3] / a) * 255; out[p * 4 + 1] = (rgb[p * 3 + 1] / a) * 255; out[p * 4 + 2] = (rgb[p * 3 + 2] / a) * 255;+ out[p * 4 + 3] = a * 255;+ }+ if (shadow > 0) {+ const G = 128;+ const ext = sp.cyl.r * 1.5;+ const top = new Float32Array(G * G);+ const span = Math.max(1e-6, sp.cyl.y1 - sp.cyl.y0);+ for (let i = 0; i < n; i++) {+ if (opacity[i] < 0.3) continue;+ const h = (pos[i * 3 + 1] - sp.cyl.y0) / span;+ if (h > 0.3) continue;+ const x = pos[i * 3], z = pos[i * 3 + 2];+ const rx = ca * x + sa * z, rz = -sa * x + ca * z;+ const gx = Math.floor(((rx / ext) * 0.5 + 0.5) * G), gz = Math.floor(((rz / ext) * 0.5 + 0.5) * G);+ if (gx >= 0 && gx < G && gz >= 0 && gz < G) top[gz * G + gx] = Math.max(top[gz * G + gx], 1 - h / 0.3);+ }+ const soft = blur(blur(blur(top, G, 3), G, 3), G, 3);+ let peak = 0;+ for (const x of soft) if (x > peak) peak = x;+ if (peak > 0) for (let i = 0; i < soft.length; i++) soft[i] = Math.min(1, (soft[i] / peak) * 1.3);+ drawFloor(out, size, soft, G, ext, { camY, camZ, ce, se, t, floorY: sp.cyl.y0, strength: shadow });+ }+ return out;+}++// ---------------------------------------------------------------------------------------------------------------------+// Backdrops++/** The studio backdrops behind a preview: a soft sweep, light (the light theme) or dark (the dark theme), RGB bytes. */+export function backdrop(size, tone) {+ const [c0, c1] = tone === "dark" ? [[44, 44, 48], [20, 20, 23]] : [[246, 245, 243], [218, 216, 212]];+ const px = new Uint8Array(size * size * 3);+ const cx = size / 2, cy = size * 0.42, r = size * 0.78;+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {+ const tt = Math.pow(Math.min(1, Math.hypot(x - cx, (y - cy) * 1.15) / r), 1.5);+ const o = (y * size + x) * 3;+ for (let k = 0; k < 3; k++) px[o + k] = c0[k] + (c1[k] - c0[k]) * tt;+ }+ return px;+}++/** Straight RGBA over an RGB backdrop, into RGB bytes. */+export function over(rgba, plate) {+ const n = plate.length / 3;+ const out = new Uint8Array(plate.length);+ for (let i = 0; i < n; i++) {+ const a = rgba[i * 4 + 3] / 255;+ for (let k = 0; k < 3; k++) out[i * 3 + k] = rgba[i * 4 + k] * a + plate[i * 3 + k] * (1 - a);+ }+ return out;+}diff --git a/scripts/model3d/render-preview.mjs b/scripts/model3d/render-preview.mjsnew file mode 100644index 00000000..e04ef02a--- /dev/null+++ b/scripts/model3d/render-preview.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+// The preview of a 3D result, made once when the run finishes: a turntable clip (one full turn that loops with no+// seam) and a still from its first frame, each on a light and a dark studio backdrop (the site's two themes). Drawn on+// the CPU by scripts/model3d/preview3d-core.mjs: no browser and no GPU, so it runs on a worker's CPU slot or a server+// with only Node, sharp and ffmpeg.+//+// node scripts/model3d/render-preview.mjs --in model.glb|splat.spz|splat.ply --out-dir dir [options]+//+// Options (defaults in brackets):+// --format auto glb | spz | ply (auto: from the file's name)+// --y-down the splat is in the 3DGS frame (y down; ComfyUI's): stood upright first+// --front-yaw 0 degrees from +z toward +x where the subject's front is: the first frame faces it+// --cutoff 0 splats: leave out Gaussians fainter than this (haze)+// --frames 120 --fps 24 one turn = 120 frames = 5 s+// --size 720 the clip and the stills are size x size+// --ffmpeg <exe> default: $FFMPEG_PATH, else ffmpeg on the PATH+// --no-webm skip the AV1 .webm copies (they are made only when this ffmpeg has an AV1 encoder)+//+// Writes poster-light.webp, poster-dark.webp, turntable-light.mp4, turntable-dark.mp4 and, when it can,+// turntable-light.webm and turntable-dark.webm. Prints "frame i/N" after each frame, then one JSON line:+// { kind, frames, fps, seconds, size, webm, triangles?, splats?, ms }. Exit code 3: a model this can't draw (a+// compressed glTF, an unknown splat) or no ffmpeg; the caller keeps the result without a preview.+import { spawn } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";+import zlib from "node:zlib";+import sharp from "sharp";+import { backdrop, drawMesh, drawSplat, frameCylinder, meshCylinder, meshOf, over, prepareSplat, readGlb, readHdr, readPly, readSpz, studioLight, Unsupported } from "./preview3d-core.mjs";++const here = path.dirname(fileURLToPath(import.meta.url));+const { values: a } = parseArgs({+ options: {+ in: { type: "string" },+ "out-dir": { type: "string" },+ format: { type: "string", default: "auto" },+ "y-down": { type: "boolean", default: false },+ "front-yaw": { type: "string", default: "0" },+ cutoff: { type: "string", default: "0" },+ frames: { type: "string", default: "120" },+ fps: { type: "string", default: "24" },+ size: { type: "string", default: "720" },+ ffmpeg: { type: "string" },+ "no-webm": { type: "boolean", default: false },+ },+});+if (!a.in || !a["out-dir"]) {+ console.error("usage: render-preview.mjs --in model.glb --out-dir dir [options]");+ process.exit(2);+}+const unavailable = (msg) => {+ console.error(msg);+ process.exit(3);+};+// Run by a parent that may go away (the worker, the server): stop when its end of stdin closes.+if (process.env.FUOBE_PARENT_PIPE === "1") {+ process.stdin.on("end", () => process.exit(1));+ process.stdin.on("error", () => process.exit(1));+ process.stdin.resume();+ process.stdin.unref?.();+}+for (const sig of ["SIGTERM", "SIGINT"]) process.on(sig, () => process.exit(1));++const SIZE = Math.max(64, Math.min(1440, Math.round(Number(a.size)) || 720));+const FRAMES = Math.max(2, Math.min(480, Math.round(Number(a.frames)) || 120));+const FPS = Math.max(1, Math.min(60, Math.round(Number(a.fps)) || 24));+const ffmpeg = a.ffmpeg || process.env.FFMPEG_PATH || "ffmpeg";+const out = a["out-dir"];+fs.mkdirSync(out, { recursive: true });+const t0 = Date.now();++function run(cmd, args, { input, collect } = {}) {+ return new Promise((resolve, reject) => {+ const p = spawn(cmd, args, { stdio: [input ? "pipe" : "ignore", collect ? "pipe" : "ignore", "pipe"], windowsHide: true });+ let err = "";+ let stdout = "";+ p.stderr.on("data", (d) => (err = (err + d).slice(-4000)));+ if (collect) p.stdout.on("data", (d) => (stdout += d));+ p.on("error", reject);+ p.on("close", (code) => (code === 0 ? resolve(stdout) : reject(new Error(`${path.basename(cmd)} exited ${code}: ${err.trim().split("\n").slice(-2).join(" | ")}`))));+ if (input) input(p.stdin);+ });+}++let encoders = "";+try {+ encoders = await run(ffmpeg, ["-hide_banner", "-encoders"], { collect: true });+} catch {+ unavailable("ffmpeg not found (set FFMPEG_PATH)");+}+if (!/\blibx264\b/.test(encoders)) unavailable("this ffmpeg has no H.264 encoder");+const av1 = a["no-webm"] ? null : /\blibsvtav1\b/.test(encoders) ? "libsvtav1" : null;++const format = a.format !== "auto" ? a.format : (/\.(\w+)$/.exec(a.in)?.[1] ?? "").toLowerCase();+const raw = fs.readFileSync(a.in);++// The subject, ready to draw, and how to draw one frame of it.+let draw;+let view;+let stats = {};+try {+ if (format === "glb") {+ const glb = readGlb(raw);+ // Pictures decoded once, at most 1024 px a side (plenty for a 720 px frame), checked from their headers first.+ const pictures = await Promise.all(+ glb.images.map(async (img) => {+ if (!img || !/^image\/(png|jpeg|webp)$/.test(img.mime || "image/png")) return null;+ try {+ const meta = await sharp(img.bytes, { limitInputPixels: 64 * 2 ** 20 }).metadata();+ if (!meta.width || !meta.height) return null;+ const { data, info } = await sharp(img.bytes, { limitInputPixels: 64 * 2 ** 20 }).resize(1024, 1024, { fit: "inside", withoutEnlargement: true }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ return { width: info.width, height: info.height, data };+ } catch {+ return null;+ }+ }),+ );+ const mesh = meshOf(glb, pictures);+ const light = studioLight(readHdr(fs.readFileSync(path.join(here, "studio_small_08-1k.hdr"))));+ const cyl = meshCylinder(mesh);+ view = { cyl, frame: frameCylinder(cyl) };+ const yaw = (Number(a["front-yaw"]) * Math.PI) / 180 || 0;+ draw = (angle) => drawMesh(mesh, light, view, angle - yaw, { size: SIZE });+ stats = { triangles: mesh.triangles };+ } else if (format === "spz" || format === "ply") {+ const s = format === "spz" ? readSpz(raw, zlib.gunzipSync) : readPly(raw);+ const sp = prepareSplat(s, { yDown: a["y-down"], cutoff: Number(a.cutoff) || 0, frontYaw: Number(a["front-yaw"]) || 0 });+ if (sp.n < 16) throw new Unsupported("the splat is empty");+ view = { cyl: sp.cyl, frame: frameCylinder(sp.cyl) };+ draw = (angle) => drawSplat(sp, view, angle, { size: SIZE });+ stats = { splats: sp.n };+ } else throw new Unsupported(`no preview for .${format}`);+} catch (e) {+ if (e instanceof Unsupported) unavailable(e.message);+ throw e;+}++const plates = { light: backdrop(SIZE, "light"), dark: backdrop(SIZE, "dark") };+const tones = ["light", "dark"];+// One encoder per clip, each fed the same frames.+const outputs = [];+for (const tone of tones) {+ outputs.push({ tone, file: path.join(out, `turntable-${tone}.mp4`), args: ["-c:v", "libx264", "-preset", "slow", "-crf", "25", "-g", String(FRAMES), "-pix_fmt", "yuv420p", "-movflags", "+faststart"] });+ if (av1) outputs.push({ tone, file: path.join(out, `turntable-${tone}.webm`), args: ["-c:v", av1, "-preset", "8", "-crf", "40", "-g", String(FRAMES), "-pix_fmt", "yuv420p"] });+}+const encoders$ = outputs.map((o) => {+ let feed;+ const fed = new Promise((r) => (feed = r));+ const done = run(+ ffmpeg,+ [+ "-hide_banner", "-v", "error", "-y",+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", `${SIZE}x${SIZE}`, "-framerate", String(FPS), "-i", "-",+ "-frames:v", String(FRAMES), ...o.args,+ "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv", "-an", o.file,+ ],+ { input: (stdin) => feed(stdin) },+ );+ return { ...o, fed, done };+});+const pipes = await Promise.all(encoders$.map((e) => e.fed));+for (const p of pipes) p.on("error", () => {});+const write = (stdin, buf) => (stdin.write(buf) ? Promise.resolve() : new Promise((r) => stdin.once("drain", r)));++let first;+for (let i = 0; i < FRAMES; i++) {+ const rgba = draw((2 * Math.PI * i) / FRAMES);+ if (i === 0) first = rgba;+ const frames = { light: over(rgba, plates.light), dark: over(rgba, plates.dark) };+ await Promise.all(encoders$.map((e, k) => write(pipes[k], frames[e.tone])));+ console.log(`frame ${i + 1}/${FRAMES}`);+}+for (const p of pipes) p.end();+const ended = await Promise.allSettled(encoders$.map((e) => e.done));+for (const [k, r] of ended.entries()) {+ if (r.status === "rejected") {+ // A .webm that didn't encode is left out; an .mp4 that didn't is a failure.+ if (encoders$[k].file.endsWith(".mp4")) throw r.reason;+ fs.rmSync(encoders$[k].file, { force: true });+ }+}+for (const tone of tones) {+ await sharp(Buffer.from(over(first, plates[tone])), { raw: { width: SIZE, height: SIZE, channels: 3 } }).webp({ quality: 86 }).toFile(path.join(out, `poster-${tone}.webp`));+}+const webm = tones.every((tone) => fs.existsSync(path.join(out, `turntable-${tone}.webm`)));+console.log(JSON.stringify({ kind: format === "glb" ? "mesh" : "splat", frames: FRAMES, fps: FPS, seconds: FRAMES / FPS, size: SIZE, webm, ...stats, ms: Date.now() - t0 }));diff --git a/src/app/s/share-page.tsx b/src/app/s/share-page.tsxindex e1e2d03f..c4667a2f 100644--- a/src/app/s/share-page.tsx+++ b/src/app/s/share-page.tsx@@ -211,21 +211,39 @@ function Media({ media: m, alt, fit, short }: { media: PublicMedia; alt: string;);default:return (- <div className="flex items-center gap-3 p-4">- <span className="grid size-10 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">- <Box className="size-5" />- </span>- <div className="min-w-0 text-[13px]">- <p className="font-medium break-all">{m.download}</p>- <a href={`${m.url}?download=${encodeURIComponent(m.download)}`} download={m.download} className="text-brand-text underline underline-offset-2">- Download the 3D file- </a>+ <>+ {m.turntable && <Turntable media={m} alt={alt} box={box} />}+ <div className="flex items-center gap-3 p-4">+ <span className="grid size-10 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">+ <Box className="size-5" />+ </span>+ <div className="min-w-0 text-[13px]">+ <p className="font-medium break-all">{m.download}</p>+ <a href={`${m.url}?download=${encodeURIComponent(m.download)}`} download={m.download} className="text-brand-text underline underline-offset-2">+ Download the 3D file+ </a>+ </div></div>- </div>+ </>);}}+/**+ * A 3D model's turntable: one turn that loops, muted, on the studio of the page's theme, over its still (so there is no+ * blank frame while it loads).+ */+function Turntable({ media: m, alt, box }: { media: PublicMedia; alt: string; box: string }) {+ const t = m.turntable!;+ const video = "block aspect-square h-auto object-contain";+ return (+ <figure className="bg-[#dad8d4] dark:bg-[#141417]" aria-label={`${alt}, turning`}>+ <video src={t.light} poster={m.poster} autoPlay muted loop playsInline preload="metadata" className={cn(video, box, "dark:hidden")} />+ <video src={t.dark} poster={t.posterDark} autoPlay muted loop playsInline preload="metadata" className={cn(video, box, "hidden dark:block")} />+ </figure>+ );+}+function Nothing() {return (<div className="rounded-2xl border border-primary/10 bg-brand-faint px-6 py-14 text-center">diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex 6091609d..3d62a6fa 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -65,6 +65,8 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport { LanguageChip, SliderControls } from "@/components/studio/audio-controls";import { downloadName } from "@/components/studio/feed";import { RunAura, RunRing } from "@/components/studio/run-visuals";+import { ModelTile } from "@/components/model3d/model-tile";+import { preview3dOf } from "@/lib/preview3d";import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";import { ControlsChip } from "@/components/studio/model-controls";import { ModelPicker } from "@/components/studio/model-picker";@@ -517,6 +519,15 @@ function OutputThumb({ o, onOpen, className, large }: { o: OutputFile; onOpen: ();}if (o.kind === "model3d") {+ // Its preview: the still, turning on hover (the viewer loads the model when it is opened).+ const ready = preview3dOf(o);+ if (ready) {+ return (+ <button onClick={onOpen} className={cn("block aspect-square w-full overflow-hidden rounded-lg", large ? "max-h-80" : "max-h-44", NO_DRAG, className)} aria-label="Open the 3D model">+ <ModelTile preview={ready} fit />+ </button>+ );+ }return (<button onClick={onOpen} className={cn("flex h-20 w-full items-center justify-center gap-2 rounded-lg bg-muted text-[12px] font-medium text-muted-foreground hover:text-foreground", NO_DRAG, className)}><Box className="size-4" /> 3D modeldiff --git a/src/components/home-view.tsx b/src/components/home-view.tsxindex e9685b2a..1a878d5c 100644--- a/src/components/home-view.tsx+++ b/src/components/home-view.tsx@@ -1,7 +1,7 @@"use client";import Link from "next/link";-import { ArrowRight, CircleAlert, ImageIcon, Loader2, MessageCircle, Video, Wand2, Zap } from "lucide-react";+import { ArrowRight, CircleAlert, ImageIcon, MessageCircle, Video, Wand2, Zap } from "lucide-react";import { useRouter, useSearchParams } from "next/navigation";import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";import { GetStarted } from "@/components/get-started";@@ -13,6 +13,9 @@ import { HadItemsScript, useHadItems } from "@/components/use-had-items";import { IntentLink } from "@/components/intent-link";import { useFadeEdges } from "@/components/use-fade-edges";import { MediaThumb } from "@/components/studio/result-media";+import { RunAura, RunRing } from "@/components/studio/run-visuals";+import { pendingWords } from "@/lib/pending-words";+import { runStage, STAGE_WORDS } from "@/lib/run-stage";import { CONNECT_GPU_EVENT, signInHref, useEngine, useGenerations, useHydrated, useIsOwner, useStatus } from "@/lib/api";import { EngineSwitch } from "@/components/studio/engine-switch";import type { Generation } from "@/lib/catalog/types";@@ -65,14 +68,7 @@ function RecentStrip({ items }: { items: Generation[] }) {<MediaThumb output={g.outputs[0]} g={g} /></button>) : (- <Link- href="/library"- title={title}- aria-label={`${failed ? "Failed" : "Rendering"}: “${title}” — open the Library`}- className="grid aspect-square w-full place-items-center rounded-xl border border-dashed bg-muted/40 text-muted-foreground"- >- {failed ? <CircleAlert className="size-5" /> : <Loader2 className="size-5 animate-spin" />}- </Link>+ <RecentWaiting g={g} title={title} failed={failed} />)}</li>);@@ -93,6 +89,39 @@ function RecentStrip({ items }: { items: Generation[] }) {);}+/**+ * A recent run that has no result to show: on its way, the living fill and ring the run cards have, with its stage+ * ("In line", "Creating") and what it is (its title, else its model or app); stopped, what happened. A tap opens the+ * Library, where it is followed.+ */+function RecentWaiting({ g, title, failed }: { g: Generation; title: string; failed: boolean }) {+ const st = runStage(g);+ const { label, place } = pendingWords(g);+ // "In line" for a run waiting its turn, whatever its last message said; else the run's own words.+ const words = failed ? (g.status === "canceled" ? "Canceled" : "Couldn't generate this one") : st?.stage === "in-line" && g.place !== "pool" ? STAGE_WORDS["in-line"] : label;+ const what = g.request.title?.trim() || g.modelName || title;+ return (+ <Link+ href="/library"+ title={title}+ aria-label={`${words}: “${what}”. Open the Library`}+ data-stage={failed ? g.status : st?.stage}+ className={cn(+ "relative flex aspect-square w-full flex-col justify-end overflow-hidden rounded-xl p-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",+ failed ? "border bg-muted/40" : "bg-muted",+ )}+ >+ {!failed && <RunAura />}+ <span className="relative flex min-w-0 items-start gap-1.5 text-[12px] leading-snug font-medium">+ {failed ? <CircleAlert className="mt-px size-4 shrink-0 text-muted-foreground" aria-hidden /> : <RunRing fraction={st?.stage === "in-line" ? null : (st?.fraction ?? null)} stage={st?.stage ?? "creating"} />}+ <span className="line-clamp-2">{words}</span>+ </span>+ <span className="relative mt-0.5 line-clamp-2 pl-[22px] text-[11px] leading-snug text-muted-foreground">{what}</span>+ {!failed && place && <span className="relative line-clamp-1 pl-[22px] text-[11px] text-muted-foreground">{place}</span>}+ </Link>+ );+}+function Row({ title, href, children, className }: { title: string; href: string; children: React.ReactNode; className?: string }) {return (<section className={cn("space-y-3", className)}>diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsxindex 36268c0d..5c18ecd9 100644--- a/src/components/model3d/model-card.tsx+++ b/src/components/model3d/model-card.tsx@@ -15,6 +15,8 @@ import type { Generation } from "@/lib/catalog/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { loadModelViewer, TURNTABLE_BACKDROP, useViewerSrc, viewerLook } from "./model-viewer";+import { ModelTile } from "./model-tile";+import { preview3dOf } from "@/lib/preview3d";import { RetextureDialog } from "./retexture-dialog";import { RigDialog } from "./rig-dialog";import { PrintDialog } from "./print-dialog";@@ -137,6 +139,8 @@ export function ModelCard({useEffect(() => () => void (recordedUrl && URL.revokeObjectURL(recordedUrl)), [recordedUrl]);// The turntable the server rendered (open models), TripoSplat's orbit or the demo's, or the one recorded here.const clip = view.turntable ?? recordedUrl;+ // Its preview (src/lib/preview3d.ts): the still and the turntable on a light and a dark studio.+ const shown = preview3dOf(g.outputs[modelAt(g)]);// What the card shows while the viewer is closed: the poster, else the photo it was made from. An Idol 3D clean splat// shows its orbit's first frame instead (view.stillClip), so the turntable shows its own.const still = view.stillClip ? undefined : (view.poster ?? view.photo);@@ -330,7 +334,16 @@ export function ModelCard({/>) : !open3d ? (<>- {clip && show === "preview" ? <TurntableLoop src={clip} poster={still} label={`Turntable of the ${label} model`} /> : placeholder}+ {/* Its preview turns on the studio of the page's theme; else the turntable it came with, or one recorded here. */}+ {shown && show === "preview" ? (+ <div className="absolute inset-0" role="img" aria-label={`Turntable of the ${label} model`}>+ <ModelTile preview={shown} fit autoPlay />+ </div>+ ) : clip && show === "preview" ? (+ <TurntableLoop src={clip} poster={still} label={`Turntable of the ${label} model`} />+ ) : (+ placeholder+ )}{(view.glb || canLook) && (<Buttonsize="sm"diff --git a/src/components/model3d/model-tile.tsx b/src/components/model3d/model-tile.tsxnew file mode 100644index 00000000..49931a56--- /dev/null+++ b/src/components/model3d/model-tile.tsx@@ -0,0 +1,222 @@+"use client";++import { Box } from "lucide-react";+import { createElement, useEffect, useLayoutEffect, useRef, useState } from "react";+import { viewerGlb } from "@/lib/av/model3d";+import type { OutputFile } from "@/lib/catalog/types";+import { releaseVideo } from "@/lib/media-release";+import type { ReadyPreview3d } from "@/lib/preview3d";+import { reducedMotion } from "@/lib/ui-motion";+import { cn } from "@/lib/utils";+import { loadModelViewer } from "./model-viewer";++/** How long a mouse stays on a tile before its model turns (ms): one passing over on its way elsewhere starts nothing. */+const TURN_AFTER = 120;++/** The one turntable playing: a grid plays only the tile under the pointer (or, on a touch screen, the one in view). */+let playing: HTMLVideoElement | null = null;++/** Turntables play unless the viewer asks for less motion or to save data. */+function turnsAllowed(): boolean {+ if (reducedMotion()) return false;+ const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection;+ return !conn?.saveData;+}++/** The studio colour behind a preview's backdrop (its edges), so a letterboxed tile has no seam. */+const STUDIO_FILL = "bg-[#dad8d4] dark:bg-[#141417]";++/**+ * A 3D result as a tile: its preview's still (the light or the dark studio, with the theme), and its turntable playing+ * muted and looped over it while a mouse rests on the tile or the keys focus it (on a touch screen: while the tile is+ * in view). The clip shows only once its first frame is drawn, and fades back to the still: never a blank frame. The+ * 3D file itself is never loaded here; the viewer loads it when the result is opened.+ */+export function ModelTile({ preview, fit, autoPlay, className }: { preview: ReadyPreview3d; fit?: boolean; autoPlay?: boolean; className?: string }) {+ const root = useRef<HTMLDivElement>(null);+ const [on, setOn] = useState(false);+ const object = fit ? "object-contain" : "object-cover";+ useEffect(() => {+ const el = root.current;+ if (!el) return;+ // The tile's own button or link takes the pointer and the focus.+ const host = (el.closest("a,button,[tabindex]") as HTMLElement | null) ?? el;+ let timer = 0;+ const start = (delay: number) => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => turnsAllowed() && setOn(true), delay);+ };+ const stop = () => {+ window.clearTimeout(timer);+ setOn(false);+ };+ const enter = (e: PointerEvent) => e.pointerType === "mouse" && start(TURN_AFTER);+ const leave = (e: PointerEvent) => e.pointerType === "mouse" && stop();+ const focus = () => host.matches(":focus-visible") && start(0);+ host.addEventListener("pointerenter", enter);+ host.addEventListener("pointerleave", leave);+ host.addEventListener("focus", focus);+ host.addEventListener("blur", stop);+ // A touch screen has no hover: the tile turns while most of it is in view.+ let io: IntersectionObserver | null = null;+ if (autoPlay || (typeof window.matchMedia === "function" && window.matchMedia("(hover: none)").matches)) {+ io = new IntersectionObserver(([e]) => (e.intersectionRatio >= 0.6 ? start(autoPlay ? 0 : 250) : stop()), { threshold: [0, 0.6] });+ io.observe(el);+ }+ return () => {+ window.clearTimeout(timer);+ host.removeEventListener("pointerenter", enter);+ host.removeEventListener("pointerleave", leave);+ host.removeEventListener("focus", focus);+ host.removeEventListener("blur", stop);+ io?.disconnect();+ };+ }, [autoPlay]);+ const { mounted, leaving } = usePresence(on);+ return (+ <div ref={root} className={cn("relative size-full overflow-hidden", STUDIO_FILL, className)} data-model-tile="">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={preview.poster.light} alt="" loading="lazy" decoding="async" className={cn("absolute inset-0 size-full dark:hidden", object)} />+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={preview.poster.dark} alt="" loading="lazy" decoding="async" className={cn("absolute inset-0 hidden size-full dark:block", object)} />+ {mounted && <TurnClip preview={preview} leaving={leaving} object={object} />}+ </div>+ );+}++/** Mounted while `on`, and for the fade after it: the clip fades back to its still, then lets go of its decoder. */+function usePresence(on: boolean): { mounted: boolean; leaving: boolean } {+ const [mounted, setMounted] = useState(on);+ if (on && !mounted) setMounted(true);+ useEffect(() => {+ if (on || !mounted) return;+ const t = window.setTimeout(() => setMounted(false), 240);+ return () => window.clearTimeout(t);+ }, [on, mounted]);+ return { mounted, leaving: mounted && !on };+}++/** The turntable over the still, for the page's theme: shown once a frame is drawn, faded out when `leaving`. */+function TurnClip({ preview, leaving, object }: { preview: ReadyPreview3d; leaving: boolean; object: string }) {+ const ref = useRef<HTMLVideoElement>(null);+ const [drawn, setDrawn] = useState(false);+ useLayoutEffect(() => {+ const v = ref.current;+ if (!v) return;+ if (playing && playing !== v) playing.pause();+ playing = v;+ let live = true;+ const tone = document.documentElement.classList.contains("dark") ? "dark" : "light";+ const frame = () => live && setDrawn(true);+ const shown = () => ("requestVideoFrameCallback" in v ? v.requestVideoFrameCallback(frame) : frame());+ v.addEventListener("playing", shown, { once: true });+ // AV1 where the browser plays it (smaller), else H.264.+ const av1 = preview.webm?.[tone] && v.canPlayType('video/webm; codecs="av01.0.05M.08"') === "probably";+ v.src = av1 ? preview.webm![tone] : preview.clip[tone];+ void v.play().catch(() => {});+ return () => {+ live = false;+ if (playing === v) playing = null;+ releaseVideo(v);+ };+ }, [preview]);+ return (+ <video+ ref={ref}+ muted+ loop+ playsInline+ preload="auto"+ aria-hidden+ tabIndex={-1}+ data-on={drawn && !leaving ? "" : undefined}+ className={cn("absolute inset-0 size-full opacity-0 transition-opacity duration-200 ease-out data-[on]:opacity-100", object)}+ />+ );+}++/**+ * A 3D result with no preview of its own yet (an older result while its preview is made, or a file the server can't+ * draw): the photo it was made from, on the studio fill, with a small 3D mark; with no photo, a GLB is drawn in the+ * browser once the tile is in view (model-viewer, still, its whole model framed); only a file nothing can show keeps+ * the plain 3D card.+ */+export function ModelStandIn({ output, photo, fit, className }: { output: OutputFile; photo?: string; fit?: boolean; className?: string }) {+ if (photo) {+ return (+ <div className={cn("relative size-full overflow-hidden", STUDIO_FILL, className)}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={photo} alt="" loading="lazy" decoding="async" className={cn("absolute inset-0 size-full", fit ? "object-contain" : "object-cover")} />+ <span+ className="absolute top-2 left-2 inline-flex h-5 items-center gap-1 rounded-full bg-black/55 px-1.5 text-[10px] font-medium text-white backdrop-blur"+ aria-hidden+ >+ <Box className="size-3" /> 3D+ </span>+ </div>+ );+ }+ const glb = /\.glb(?:[?#]|$)/i.test(output.url) || output.contentType === "model/gltf-binary";+ if (glb) return <BrowserStill output={output} className={className} />;+ return <PlainCard className={className} />;+}++function PlainCard({ className }: { className?: string }) {+ return (+ <div className={cn("flex size-full flex-col items-center justify-center gap-2 bg-muted text-muted-foreground", className)}>+ <Box className="size-8" />+ <span className="text-[12px] font-medium">3D model</span>+ </div>+ );+}++/** A GLB drawn in the browser as a still, once its tile is in view (the fallback when no preview was made). */+function BrowserStill({ output, className }: { output: OutputFile; className?: string }) {+ const root = useRef<HTMLDivElement>(null);+ const [near, setNear] = useState(false);+ const [ready, setReady] = useState(false);+ const [failed, setFailed] = useState(false);+ useEffect(() => {+ const el = root.current;+ if (!el || near) return;+ const io = new IntersectionObserver(([e]) => e.isIntersecting && setNear(true), { rootMargin: "200px" });+ io.observe(el);+ return () => io.disconnect();+ }, [near]);+ useEffect(() => {+ if (!near) return;+ let live = true;+ loadModelViewer().then(+ () => live && setReady(true),+ () => live && setFailed(true),+ );+ return () => {+ live = false;+ };+ }, [near]);+ if (failed) return <PlainCard className={className} />;+ return (+ <div ref={root} className={cn("relative size-full overflow-hidden", STUDIO_FILL, className)}>+ {ready &&+ createElement("model-viewer", {+ src: viewerGlb(output),+ alt: "",+ loading: "lazy",+ reveal: "auto",+ "interaction-prompt": "none",+ "environment-image": "neutral",+ "tone-mapping": "neutral",+ "shadow-intensity": "0.8",+ "camera-orbit": "0deg 75deg 105%",+ style: {+ width: "100%",+ height: "100%",+ background: "transparent",+ pointerEvents: "none",+ "--poster-color": "transparent",+ "--progress-bar-height": "0",+ },+ })}+ </div>+ );+}diff --git a/src/components/studio/result-media.tsx b/src/components/studio/result-media.tsxindex 54605526..c50d1f39 100644--- a/src/components/studio/result-media.tsx+++ b/src/components/studio/result-media.tsx@@ -3,6 +3,7 @@import { AudioLines, Box, Download, FileText, Film, Layers, Rotate3d } from "lucide-react";import { createElement, useEffect, useState } from "react";import { loadModelViewer, useViewerSrc, viewerLook } from "@/components/model3d/model-viewer";+import { ModelStandIn, ModelTile } from "@/components/model3d/model-tile";import { hasWebgl2, SplatViewer, useReducedMotion } from "@/components/model3d/splat-viewer";import { useHydrated } from "@/lib/api";import { FALLBACK_TEXT, hazeCutoffFor, splatFallback, splatPose } from "@/lib/av/splat-view";@@ -12,6 +13,7 @@ import { firstFrameSrc, FRONT_YAW, splatFormatOf, turnOrbit, viewerGlb } from "@import type { Generation, OutputFile, VideoFormat } from "@/lib/catalog/types";import { extensionOf } from "@/lib/library";import { cuesOf, cueTime, editOnlyFormat, isLayered, layerInfo, modelPreview, textOf, videoPoster } from "@/lib/output-actions";+import { preview3dOf } from "@/lib/preview3d";import { cn } from "@/lib/utils";/** Any result as a tile picture: image, video (plays on hover), audio, text card, 3D preview. */@@ -56,21 +58,21 @@ export function MediaThumb({}if (output.kind === "text") return <TextPreview output={output} className={className} tag={tag} inset={inset} />;if (output.kind === "model3d") {+ // Its preview (a still on the theme's studio, turning on hover), else what the run brought (an orbit clip, a+ // still), else the photo it was made from; the 3D file loads only when the result is opened.+ const ready = preview3dOf(output);+ if (ready) return <ModelTile preview={ready} fit={fit} autoPlay={autoPlay} className={className} />;const { poster, video } = modelPreview(g ?? { outputs: [output] }, output);- if (video) return <MediaThumb output={{ url: video, kind: "video" }} autoPlay={autoPlay} fit={fit} className={className} />;- return (- <div className={cn("relative flex size-full flex-col items-center justify-center gap-2 bg-muted text-muted-foreground", className)}>- {poster ? (- // eslint-disable-next-line @next/next/no-img-element+ if (video) return <MediaThumb output={{ url: video, kind: "video", ...(poster && { meta: { poster } }) }} autoPlay={autoPlay} fit={fit} className={className} />;+ if (poster) {+ return (+ <div className={cn("relative size-full bg-muted", className)}>+ {/* eslint-disable-next-line @next/next/no-img-element */}<img src={poster} alt="" loading="lazy" decoding="async" className={cn("absolute inset-0 size-full", object)} />- ) : (- <>- <Box className="size-8" />- <span className="text-[12px] font-medium">3D model</span>- </>- )}- </div>- );+ </div>+ );+ }+ return <ModelStandIn output={output} photo={g?.request?.inputs?.images?.[0]} fit={fit} className={className} />;}// eslint-disable-next-line @next/next/no-img-elementreturn <img src={output.url} alt="" loading="lazy" decoding="async" className={cn("size-full", object, className)} />;diff --git a/src/lib/av/model3d.ts b/src/lib/av/model3d.tsindex a62611b3..af96017f 100644--- a/src/lib/av/model3d.ts+++ b/src/lib/av/model3d.ts@@ -3,6 +3,7 @@ import type { OwnSetup } from "@/lib/own-setup";import { PATH_FRAMES, keyAt } from "@/lib/camera-path";import { exactOrbitKeys, type ExactOrbit } from "@/lib/exact-orbit";import { idolCameraStills, isIdolClean } from "./idol-camera-still";+import { preview3dOf } from "@/lib/preview3d";export { idolCameraStills, isIdolCameraStill, isIdolClean, showableOutputs } from "./idol-camera-still";@@ -429,7 +430,9 @@ export function model3dView(g: Pick<Generation, "outputs" | "request">): Model3dconst format = splatFormatOf(mesh);const splat = mesh && format ? { url: mesh.url, format } : undefined;const clean = splat ? idolCleanLine(meta) : undefined;- const turntable = str(meta.turntable) ?? str(meta.video) ?? video?.url;+ // Its own preview first (src/lib/preview3d.ts): a turn and its still drawn from the model itself.+ const ready = preview3dOf(mesh);+ const turntable = ready?.clip.light ?? str(meta.turntable) ?? str(meta.video) ?? video?.url;const photo = g.request.inputs?.images?.[0];const images = g.outputs.filter((o) => o.kind === "image");// Idol 3D's clean graph: its own still (role "preview") is rendered from the camera Idol predicts, which can collapse@@ -450,8 +453,8 @@ export function model3dView(g: Pick<Generation, "outputs" | "request">): Model3dturntable,rendering: pending ? { queued: finish.turntable === "queued", progress: typeof finish.turntableProgress === "number" ? finish.turntableProgress : 0 } : undefined,material: str(finish.material),- poster: idolClean ? (orbitStill ?? photo) : (str(meta.preview) ?? str(meta.poster) ?? images[0]?.url),- ...(fromOrbit && !orbitStill && { stillClip: turntable }),+ poster: ready?.poster.light ?? (idolClean ? (orbitStill ?? photo) : (str(meta.preview) ?? str(meta.poster) ?? images[0]?.url)),+ ...(fromOrbit && !orbitStill && !ready && { stillClip: turntable }),photo,formats,rigged: meta.rigged === true || undefined,diff --git a/src/lib/finish-ticket.ts b/src/lib/finish-ticket.tsindex 5e5a2b43..eca1f39f 100644--- a/src/lib/finish-ticket.ts+++ b/src/lib/finish-ticket.ts@@ -5,6 +5,9 @@* - "model3d": an image-to-3D model's finish. The worker checks the GLB (a self-contained binary glTF only: no buffer or* picture that names another file), writes the web GLB, and renders a turntable clip and its poster.* - "path": a camera path drawn through a still and its depth picture (the guide of a camera move), as an MP4.+ * - "preview3d": the preview of any finished 3D result (a GLB mesh or a Gaussian splat): a turntable clip that loops and+ * a still from its first frame, each on a light and a dark studio backdrop, drawn on the CPU with no browser+ * (scripts/model3d/render-preview.mjs).** A finish ticket names its kind, its typed settings and its input files (slot, name, SHA-256). The worker runs it with* its own code (bin/lib/worker/finish.mjs) and sends back only the files its kind makes (FINISH_FILES). Both sides check@@ -16,9 +19,13 @@ import { INPUT_NAME } from "./relay";export const FINISH_VERSION = 1;-export const FINISH_KINDS = ["model3d", "path"] as const;+export const FINISH_KINDS = ["model3d", "path", "preview3d"] as const;export type FinishKind = (typeof FINISH_KINDS)[number];+/** The 3D files a preview is drawn from. */+export const PREVIEW_FORMATS = ["glb", "spz", "ply"] as const;+export type PreviewFormat = (typeof PREVIEW_FORMATS)[number];+/** The materials the GLB finish knows (scripts/model3d/finish-glb.mjs --material). */export const FINISH_MATERIALS = ["auto", "matte", "metal", "mixed"] as const;@@ -34,14 +41,14 @@ export interface FinishPathKey {export interface FinishTicket {v: typeof FINISH_VERSION;kind: FinishKind;- /** model3d: { material, turntable }; path: { keys, frames, fps }. */+ /** model3d: { material, turntable }; path: { keys, frames, fps }; preview3d: { format, yDown, frontYaw, cutoff }. */settings: Record<string, unknown>;- /** model3d: one "model" (the raw GLB); path: a "photo" and its "depth" picture. */+ /** model3d and preview3d: one "model" (the raw GLB, or the splat); path: a "photo" and its "depth" picture. */inputs: { slot: string; name: string; sha256: string }[];}/** The input slots each kind takes, in order. */-export const FINISH_SLOTS: Record<FinishKind, readonly string[]> = { model3d: ["model"], path: ["photo", "depth"] };+export const FINISH_SLOTS: Record<FinishKind, readonly string[]> = { model3d: ["model"], path: ["photo", "depth"], preview3d: ["model"] };/*** The files each kind may send back, by role: their kind on the server and the most each may weigh. The worker names@@ -54,8 +61,29 @@ export const FINISH_FILES: Record<FinishKind, Record<string, { kind: "model3d" |poster: { kind: "image", maxBytes: 16 * 2 ** 20 },},path: { path: { kind: "video", maxBytes: 512 * 2 ** 20 } },+ preview3d: {+ posterLight: { kind: "image", maxBytes: 4 * 2 ** 20 },+ posterDark: { kind: "image", maxBytes: 4 * 2 ** 20 },+ clipLight: { kind: "video", maxBytes: 32 * 2 ** 20 },+ clipDark: { kind: "video", maxBytes: 32 * 2 ** 20 },+ webmLight: { kind: "video", maxBytes: 32 * 2 ** 20 },+ webmDark: { kind: "video", maxBytes: 32 * 2 ** 20 },+ },};+/** A preview's files by role, as scripts/model3d/render-preview.mjs names them in its folder. */+export const PREVIEW_FILES: Record<string, { file: string; contentType: string }> = {+ posterLight: { file: "poster-light.webp", contentType: "image/webp" },+ posterDark: { file: "poster-dark.webp", contentType: "image/webp" },+ clipLight: { file: "turntable-light.mp4", contentType: "video/mp4" },+ clipDark: { file: "turntable-dark.mp4", contentType: "video/mp4" },+ webmLight: { file: "turntable-light.webm", contentType: "video/webm" },+ webmDark: { file: "turntable-dark.webm", contentType: "video/webm" },+};++/** The largest 3D file a preview is drawn from: a bigger one keeps its other stills (the photo it was made from). */+export const PREVIEW_MAX_BYTES = 200 * 2 ** 20;+/** A path's frames and frame rate: at most this many, and this fast. */export const PATH_LIMITS = { maxFrames: 241, maxFps: 60, maxKeys: 64 };@@ -86,6 +114,12 @@ export function finishProblem(t: unknown, o: { inputs?: { name: string; sha256:if (Object.keys(set).some((x) => x !== "material" && x !== "turntable")) return "a setting isn't one";if (!(FINISH_MATERIALS as readonly string[]).includes(String(set.material))) return "material isn't one";if (typeof set.turntable !== "boolean") return "turntable isn't a yes or no";+ } else if (kind === "preview3d") {+ if (Object.keys(set).some((x) => !["format", "yDown", "frontYaw", "cutoff"].includes(x))) return "a setting isn't one";+ if (!(PREVIEW_FORMATS as readonly string[]).includes(String(set.format))) return "format isn't one";+ if (typeof set.yDown !== "boolean") return "yDown isn't a yes or no";+ if (!Number.isInteger(set.frontYaw) || !finite(set.frontYaw, -360, 360)) return "frontYaw out of range";+ if (!finite(set.cutoff, 0, 0.5)) return "cutoff out of range";} else {if (Object.keys(set).some((x) => !["keys", "frames", "fps"].includes(x))) return "a setting isn't one";if (!Number.isInteger(set.frames) || !finite(set.frames, 2, PATH_LIMITS.maxFrames)) return "frames out of range";diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex e3094a3b..81befc7e 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -13,6 +13,7 @@ import { storedPath } from "./share";import { decodeMoss, LAYOUT_PARAM, readLayout, type LayoutDraft } from "./layout-prompt";import { REMOVE_DIALOGUE_FEATURE } from "./av/remove-dialogue";import { idolCameraStills, showableOutputs } from "./av/idol-camera-still";+import { preview3dOf } from "./preview3d";import { canEnhance, canRerender, ENHANCE_LABEL, REGEN_OFFERED, regenerateFamily, regenerateHref, rerenderLabel } from "./catalog/regenerate";import { CLEAN_FEATURE } from "./av/clean-voice";import { exportsCleanly } from "./av/keying";@@ -546,6 +547,9 @@ export function editOnlyFormat(g: Partial<Pick<Generation, "op" | "request">> |* its orbit, and its orbit stands in.*/export function modelPreview(g: Pick<Generation, "outputs">, o: OutputFile): { poster?: string; video?: string } {+ // Its own preview (src/lib/preview3d.ts) first: the still and the turntable on the light studio.+ const ready = preview3dOf(o);+ if (ready) return { poster: ready.poster.light, video: ready.clip.light };const m = (o.meta ?? {}) as Record<string, unknown>;const cameraStills = idolCameraStills(g);const str = (...keys: string[]) => keys.map((k) => m[k]).find((v): v is string => typeof v === "string" && v.length > 0 && !cameraStills.has(v));diff --git a/src/lib/preview3d.ts b/src/lib/preview3d.tsnew file mode 100644index 00000000..da61fbad--- /dev/null+++ b/src/lib/preview3d.ts@@ -0,0 +1,66 @@+import type { OutputFile } from "@/lib/catalog/types";+import type { PreviewFormat } from "@/lib/finish-ticket";++/**+ * A 3D result's preview (src/server/model3d-preview.ts), as its model output keeps it in meta.preview3d: a still and a+ * turntable clip (one turn that loops), each on a light and a dark studio backdrop, so tiles never load the 3D file.+ */+export interface Preview3d {+ state: "queued" | "drawing" | "done" | "failed";+ /** When it last changed. */+ at: number;+ tries?: number;+ /** queued / drawing: on a worker's CPU slot (its job's step) or on this server. */+ where?: "worker" | "here";+ step?: number;+ /** failed: a word for the server's own retries. */+ why?: string;+ poster?: { light: string; dark: string };+ clip?: { light: string; dark: string };+ /** AV1 copies of the clips, when the encoder had them. */+ webm?: { light: string; dark: string };+ seconds?: number;+ /** The files it kept (removed with the run). */+ assets?: string[];+}++export type ReadyPreview3d = Preview3d & {+ state: "done";+ poster: { light: string; dark: string };+ clip: { light: string; dark: string };+};++const str = (v: unknown): v is string => typeof v === "string" && v.length > 0;+const pair = (v: unknown): v is { light: string; dark: string } =>+ !!v && typeof v === "object" && str((v as { light?: unknown }).light) && str((v as { dark?: unknown }).dark);++/** A model output's finished preview, or null (none yet, or one that couldn't be made). */+export function preview3dOf(o: Pick<OutputFile, "kind" | "meta"> | undefined): ReadyPreview3d | null {+ const p = o?.kind === "model3d" ? (o.meta?.preview3d as Preview3d | undefined) : undefined;+ if (!p || p.state !== "done" || !pair(p.poster) || !pair(p.clip)) return null;+ return {+ ...p,+ state: "done",+ poster: p.poster,+ clip: p.clip,+ ...(pair(p.webm) ? { webm: p.webm } : { webm: undefined }),+ };+}++/** Whether a model output's preview is still being made (a tile shows its other stills meanwhile). */+export function preview3dComing(o: Pick<OutputFile, "kind" | "meta"> | undefined): boolean {+ const p = o?.kind === "model3d" ? (o.meta?.preview3d as Preview3d | undefined) : undefined;+ return p?.state === "queued" || p?.state === "drawing";+}++/** The 3D file a preview can be drawn from: a binary glTF, or a Gaussian splat as .spz or .ply; null for any other. */+export function previewFormatOf(o: Pick<OutputFile, "url" | "kind" | "contentType" | "meta">): PreviewFormat | null {+ if (o.kind !== "model3d") return null;+ const declared = typeof o.meta?.format === "string" ? o.meta.format.toLowerCase() : "";+ const ext = /\.([a-z0-9]{2,5})(?:[?#]|$)/i.exec(o.url.split("/").pop() ?? "")?.[1]?.toLowerCase() ?? "";+ const ct = (o.contentType ?? "").toLowerCase();+ if (declared === "spz" || ext === "spz" || ct.includes("spz")) return "spz";+ if (declared === "ply" || ext === "ply") return "ply";+ if (ct === "model/gltf-binary" || ext === "glb" || declared === "glb") return "glb";+ return null;+}diff --git a/src/lib/share.ts b/src/lib/share.tsindex 8ec509e9..0a79394d 100644--- a/src/lib/share.ts+++ b/src/lib/share.ts@@ -175,6 +175,9 @@ export function outputFiles(o: { url: string; meta?: Record<string, unknown> }):const v = o.meta?.[k];if (typeof v === "string") out.push(storedPath(v));}+ // A 3D result's preview: its stills and turntables (src/lib/preview3d.ts).+ const p = o.meta?.preview3d as { state?: unknown; poster?: Record<string, unknown>; clip?: Record<string, unknown>; webm?: Record<string, unknown> } | undefined;+ if (p?.state === "done") for (const set of [p.poster, p.clip, p.webm]) for (const v of Object.values(set ?? {})) if (typeof v === "string") out.push(storedPath(v));return out.filter((p): p is string => !!p);}@@ -265,6 +268,8 @@ export interface PublicMedia {width?: number;height?: number;poster?: string;+ /** A 3D model's turntable (one turn that loops) and its stills, on the light and the dark studio; poster is the light still. */+ turntable?: { light: string; dark: string; posterDark: string };/** A text output's words, inline. */text?: string;/** A file name for Download. */diff --git a/src/server/computer/finish.ts b/src/server/computer/finish.tsindex cccaaf4a..68b0e611 100644--- a/src/server/computer/finish.ts+++ b/src/server/computer/finish.ts@@ -13,7 +13,7 @@ import { getSetting } from "../settings";import { absolutePath, deleteAsset, getAsset, readRef, saveFile, type Asset } from "../storage";import { tenantAccount } from "../tenant";import { cpuSlotOf, poolWaitMs, RETRY_WINDOW_MS, runPlaceOf, ticketReady } from "./pool";-import { createTask, endTask, json, receivedFile, resultOf, stageInput, stagedInput, type FinishedPlan, type TaskRow } from "./tasks";+import { createTask, endTask, json, receivedFile, resultOf, stageInput, stagedInput, type FinishedPlan, type Principal, type TaskRow } from "./tasks";import type { WorkerRow } from "./workers";/**@@ -88,12 +88,15 @@ function runWaitMs(generationId: string): number | undefined {export function queueFinish(o: {kind: FinishKind;generationId: string;- account: string;+ /** The run's account; none: the owner's run. */+ account?: string;inputs: { slot: string; data: Buffer; contentType: string; name: string }[];settings: Record<string, unknown>;step?: number;+ /** Its class and place in the line, in place of the run's own (a preview made for an older result goes last). */+ place?: { class: "paid" | "free" | "owner"; rankAt: number };}): string {- const principal = `acct:${o.account}` as const;+ const principal: Principal = o.account ? `acct:${o.account}` : "owner";const queued = () => {const had = finishTask(o.generationId, o.kind, o.step ?? 0);return had && had.state !== "canceled" ? had.id : null;@@ -121,7 +124,7 @@ export function queueFinish(o: {if (again) return again;// The run's class and place in line (pool.ts runPlaceOf): a chain's camera path is queued for a step that has no// job of its own yet, and keeps the place of the steps of its run before it.- const run = runPlaceOf(o.generationId);+ const run = o.place ?? runPlaceOf(o.generationId);const now = Date.now();const wait = runWaitMs(o.generationId);const t = createTask({@@ -135,7 +138,7 @@ export function queueFinish(o: {pool: {pools: ["pool"],account: o.account,- class: run?.class ?? "free",+ class: run?.class ?? (o.account ? "free" : "owner"),rankAt: run?.rankAt ?? now,lane: "small",needs: { workflowId: `finish-${o.kind}`, files: [], packs: [], minVramBytes: 0 },diff --git a/src/server/generations.ts b/src/server/generations.tsindex 9ce00922..efded4b1 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -138,6 +138,7 @@ import { songFormat, songToolProblem } from "@/lib/lyrics";import { hostedUntested } from "@/lib/catalog/hosted-untested";import { appliesOwnStyle } from "@/lib/catalog/applied-style";import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";+import { stopPreviews, tickPreviews } from "./model3d-preview";import { finishTask, pathOnWorker, poolFinishes3d, startWorkerModelFinish, stopWorkerFinish } from "./computer/finish";import { PATH_FPS, PATH_FRAMES } from "@/lib/camera-path";import { cropPicture, isCropWindow } from "./crop-picture";@@ -1016,9 +1017,10 @@ export function assetInUse(assetId: string, exceptGeneration = ""): boolean {* src/server/library.ts (they cancel running jobs first); moving to the Trash is trashGenerations.*/export function deleteGeneration(id: string): void {- // A 3D job's finish or turntable render stops with it.+ // A 3D job's finish, turntable render or preview stops with it.stopModelFinish(id);stopWorkerFinish(id);+ stopPreviews(id);const assets = db().prepare("SELECT id FROM assets WHERE generation_id = ?").all(id) as { id: string }[];db().transaction(() => {db().prepare("DELETE FROM generations WHERE id = ?").run(id);@@ -4207,6 +4209,8 @@ async function tick(): Promise<void> {// service. Neither does anything while no service is set.if (moderationConfigured()) await sweepOutputChecks();void sweepBilling();+ // Finished 3D results without a preview yet (and the ones on their way): model3d-preview.ts, every few seconds.+ if (!draining()) tickPreviews();// The hourly run counts forget a run (and the client address it came from) two hours on, whether more runs come.try {prunePoolAdmissions();diff --git a/src/server/model3d-finish.ts b/src/server/model3d-finish.tsindex dfc5b3b8..ea80fb93 100644--- a/src/server/model3d-finish.ts+++ b/src/server/model3d-finish.ts@@ -430,3 +430,33 @@ async function renderTurntable(generationId: string, mesh: OutputFile, store: Ouawait removeDir(tmp);}}++// ---------------------------------------------------------------------------+// A 3D result's preview drawn on this server (model3d-preview.ts: only where no worker's CPU slot draws it).++/**+ * Draw a 3D file's preview here (scripts/model3d/render-preview.mjs: the CPU, no browser), one at a time with the+ * turntables, at below-normal priority, into a temp folder. Returns the folder (the caller removes it) and the script's+ * exit code: 0 drew it, 3 can't draw this file here (no ffmpeg, a compressed glTF).+ */+export async function renderPreviewHere(file: string, s: { format: string; yDown: boolean; frontYaw: number; cutoff: number }, signal: AbortSignal): Promise<{ dir: string; code: number | null; error: string }> {+ const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "fuobe-preview-"));+ const out = path.join(dir, "preview");+ try {+ const run = await oneAtATime(() =>+ runScript("render-preview.mjs", ["--in", file, "--out-dir", out, "--format", s.format, "--front-yaw", String(s.frontYaw), "--cutoff", String(s.cutoff), ...(s.yDown ? ["--y-down"] : [])], {+ timeoutMs: TURNTABLE_TIMEOUT_MS,+ signal,+ cwd: dir,+ lowPriority: true,+ }),+ );+ return { dir: out, code: run.code, error: tail(run.stderr) };+ } catch (e) {+ await removeDir(dir);+ throw e;+ }+}++/** Remove the temp folder a preview was drawn in (renderPreviewHere's `dir` is a folder inside it). */+export const removePreviewDir = (dir: string) => removeDir(path.dirname(dir));diff --git a/src/server/model3d-preview.ts b/src/server/model3d-preview.tsnew file mode 100644index 00000000..827ef65e--- /dev/null+++ b/src/server/model3d-preview.ts@@ -0,0 +1,408 @@+import "server-only";+import fs from "node:fs";+import path from "node:path";+import { FRONT_YAW } from "@/lib/av/model3d";+import { hazeCutoffFor, splatPose } from "@/lib/av/splat-view";+import type { GenerationRequest, OutputFile } from "@/lib/catalog/types";+import { PREVIEW_FILES, PREVIEW_MAX_BYTES, type PreviewFormat } from "@/lib/finish-ticket";+import { previewFormatOf, type Preview3d } from "@/lib/preview3d";+import { finishOutcome, finishTask, queueFinish, workersFinish } from "./computer/finish";+import { ownerRunClass } from "./computer/pool";+import { json } from "./computer/tasks";+import { db } from "./db";+import { removePreviewDir, renderPreviewHere } from "./model3d-finish";+import { getSetting } from "./settings";+import { absolutePath, deleteAsset, getAsset, saveFile, type Asset } from "./storage";++/**+ * Every finished 3D result gets a preview, made once: a turntable clip (one turn, about 5 s, looping with no seam) and a+ * still from its first frame, each on a light and a dark studio backdrop, so a tile shows a picture of the model and+ * turns it on hover without ever loading the 3D file. A GLB mesh (Pixal3D, TRELLIS, Hunyuan3D, Idol 3D's mesh, a+ * provider's model) and a Gaussian splat (.spz, .ply) alike. scripts/model3d/render-preview.mjs draws it on the CPU, with+ * no browser and no GPU.+ *+ * Where: on a worker's CPU slot when one draws previews (a "preview3d" finishing job, src/lib/finish-ticket.ts), in the+ * run's place in line (an older result's, after everyone's). Without one, this server draws it only where that is its+ * work: an install that runs ComfyUI itself, or a provider's result of the owner's. An account's result on an install+ * with workers waits for a worker.+ *+ * What it writes: meta.preview3d on the model output ({ state, poster, clip, webm, seconds }, src/lib/preview3d.ts).+ * A result whose model already has a turntable (the server's own, rendered in a browser) keeps it. Older results get+ * theirs the same way, newest first, a few at a time: tickPreviews looks every few seconds.+ */++/** How many previews are being made at once (the rest wait their turn, newest first). */+const IN_FLIGHT = 3;+/** How often tickPreviews looks. */+const LOOK_MS = 8_000;+/** A preview this server was drawing when it stopped (a restart) is drawn again after this. */+const STALE_HERE_MS = 15 * 60_000;+/** How many times one result's preview is tried, and the failures worth another try (a draw here that stopped or failed). */+const TRIES = 2;+const RETRY = ["stopped", "failed", "not kept", "not queued"];++type Row = {+ id: string;+ status: string;+ provider: string;+ model_id: string;+ op: string;+ request_json: string;+ outputs_json: string;+ completed_at: number | null;+};++declare global {+ var __fuobePreview3d: { last: number; here: Map<string, AbortController> } | undefined;+}+const state = () => (globalThis.__fuobePreview3d ??= { last: 0, here: new Map() });++const turntableOf = (o: OutputFile) => (o.meta?.finish as { turntable?: unknown } | undefined)?.turntable;++/**+ * The model outputs of a run that still need a preview: a GLB, .spz or .ply kept as one of its files, with no preview+ * and no turntable of its own (one still being rendered in a browser is waited for).+ */+export function previewTargets(outputs: OutputFile[]): number[] {+ const out: number[] = [];+ outputs.forEach((o, i) => {+ if (o.kind !== "model3d" || !o.assetId || o.meta?.preview3d) return;+ if (!previewFormatOf(o)) return;+ const tt = turntableOf(o);+ if (tt === "done" || tt === "queued" || tt === "rendering") return;+ out.push(i);+ });+ return out;+}++/** How a model is drawn: its format, which way is up and front, and the haze a splat leaves out. */+export function previewSettings(+ r: Pick<Row, "provider" | "model_id">,+ o: OutputFile,+): {+ format: PreviewFormat;+ yDown: boolean;+ frontYaw: number;+ cutoff: number;+} | null {+ const format = previewFormatOf(o);+ if (!format) return null;+ if (format === "glb")+ return {+ format,+ yDown: false,+ frontYaw: Math.round(FRONT_YAW[r.model_id] ?? 0),+ cutoff: 0,+ };+ const pose = splatPose({ provider: r.provider }, o);+ return {+ format,+ yDown: pose.yDown,+ frontYaw: Math.round(pose.frontYaw),+ cutoff: Math.min(0.5, hazeCutoffFor(r.model_id)),+ };+}++/** Store a preview's state on a run's model output (by its file), as one change of the run (its live update). */+function setPreview(id: string, assetId: string, p: Preview3d): boolean {+ return db()+ .transaction((): boolean => {+ const row = db().prepare("SELECT outputs_json FROM generations WHERE id = ?").get(id) as Pick<Row, "outputs_json"> | undefined;+ if (!row) return false;+ const outputs = json<OutputFile[]>(row.outputs_json, []);+ const i = outputs.findIndex((o) => o.kind === "model3d" && o.assetId === assetId);+ if (i < 0) return false;+ outputs[i] = {+ ...outputs[i],+ meta: { ...outputs[i].meta, preview3d: p },+ };+ db().prepare("UPDATE generations SET outputs_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(outputs), Date.now(), id);+ return true;+ })+ .immediate();+}++/** The preview's files from a folder (by role), kept as the run's derived files; the preview state that names them. */+function keepFiles(id: string, files: Partial<Record<keyof typeof PREVIEW_FILES, string>>, tries: number): Preview3d | null {+ const saved: Asset[] = [];+ const save = (role: keyof typeof PREVIEW_FILES) => {+ const file = files[role];+ if (!file || !fs.existsSync(file)) return null;+ const f = PREVIEW_FILES[role];+ const a = saveFile({+ data: fs.readFileSync(file),+ contentType: f.contentType,+ name: f.file,+ source: "derived",+ generationId: id,+ });+ saved.push(a);+ return a.url;+ };+ try {+ const poster = { light: save("posterLight"), dark: save("posterDark") };+ const clip = { light: save("clipLight"), dark: save("clipDark") };+ if (!poster.light || !poster.dark || !clip.light || !clip.dark) throw new Error("a still or a clip is missing");+ const webmLight = save("webmLight");+ const webmDark = save("webmDark");+ return {+ state: "done",+ at: Date.now(),+ tries,+ poster: { light: poster.light, dark: poster.dark },+ clip: { light: clip.light, dark: clip.dark },+ ...(webmLight && webmDark && { webm: { light: webmLight, dark: webmDark } }),+ seconds: 5,+ assets: saved.map((a) => a.id),+ };+ } catch (e) {+ for (const a of saved) deleteAsset(a.id);+ console.warn(`[fuobe] 3D preview for ${id}: ${(e as Error).message}`);+ return null;+ }+}++/** Whether this server draws a run's preview itself when no worker does (see the header). */+function drawsHere(r: Pick<Row, "provider">, account: string | undefined): boolean {+ if (getSetting("comfyWhere") !== "workers") return true;+ return !account && r.provider !== "comfyui";+}++const accountOf = (r: Pick<Row, "request_json">) => json<GenerationRequest | null>(r.request_json, null)?.account;++/** Start one output's preview: queued for a worker, drawn here, or (neither now) left for a later look. */+function start(r: Row, i: number, outputs: OutputFile[], tries: number): void {+ const o = outputs[i];+ const asset = getAsset(o.assetId!);+ const s = previewSettings(r, o);+ if (!asset || !s)+ return void setPreview(r.id, o.assetId!, {+ state: "failed",+ at: Date.now(),+ tries,+ why: "no file",+ });+ if (asset.size > PREVIEW_MAX_BYTES)+ return void setPreview(r.id, o.assetId!, {+ state: "failed",+ at: Date.now(),+ tries,+ why: "too big",+ });+ const account = accountOf(r);+ if (workersFinish("preview3d")) {+ // A run finished in the last hour keeps its place in line; an older result's preview goes after everyone's.+ const fresh = !!r.completed_at && Date.now() - r.completed_at < 60 * 60_000;+ const place = fresh ? undefined : { class: "owner" as const, rankAt: Date.now() };+ try {+ queueFinish({+ kind: "preview3d",+ generationId: r.id,+ ...(account && { account }),+ step: i,+ inputs: [+ {+ slot: "model",+ data: fs.readFileSync(absolutePath(asset.relPath)),+ contentType: o.contentType || "application/octet-stream",+ name: `model.${s.format}`,+ },+ ],+ settings: s,+ place:+ place ??+ (account+ ? undefined+ : {+ class: ownerRunClass(r.id),+ rankAt: r.completed_at ?? Date.now(),+ }),+ });+ setPreview(r.id, o.assetId!, {+ state: "queued",+ at: Date.now(),+ tries,+ where: "worker",+ step: i,+ });+ } catch (e) {+ console.warn(`[fuobe] 3D preview for ${r.id} wasn't queued: ${(e as Error).message}`);+ setPreview(r.id, o.assetId!, {+ state: "failed",+ at: Date.now(),+ tries,+ why: "not queued",+ });+ }+ return;+ }+ if (!drawsHere(r, account)) return;+ const ctl = new AbortController();+ state().here.set(`${r.id}:${o.assetId}`, ctl);+ setPreview(r.id, o.assetId!, {+ state: "drawing",+ at: Date.now(),+ tries,+ where: "here",+ });+ void renderPreviewHere(absolutePath(asset.relPath), s, ctl.signal)+ .then(async ({ dir, code, error }) => {+ try {+ const files = Object.fromEntries(Object.entries(PREVIEW_FILES).map(([role, f]) => [role, path.join(dir, f.file)]));+ const kept = code === 0 ? keepFiles(r.id, files, tries) : null;+ if (code !== 0) console.warn(`[fuobe] 3D preview for ${r.id}: ${code === 3 ? "not drawn here" : "failed"}${error ? ` (${error})` : ""}`);+ setPreview(+ r.id,+ o.assetId!,+ kept ?? {+ state: "failed",+ at: Date.now(),+ tries,+ why: code === 3 ? "can't draw" : "failed",+ },+ );+ } finally {+ await removePreviewDir(dir);+ }+ })+ .catch((e) => {+ if (!ctl.signal.aborted) {+ console.warn(`[fuobe] 3D preview for ${r.id}: ${(e as Error).message}`);+ setPreview(r.id, o.assetId!, {+ state: "failed",+ at: Date.now(),+ tries,+ why: "failed",+ });+ }+ })+ .finally(() => state().here.delete(`${r.id}:${o.assetId}`));+}++/** Look at a preview on its way: a worker's job that ended (its files kept, or failed), or a draw here that stopped. */+function follow(r: Row, o: OutputFile, p: Preview3d): void {+ if (p.where === "here") {+ if (state().here.has(`${r.id}:${o.assetId}`)) return;+ // Drawn by a process that stopped (a restart, a deploy's other instance takes a while): again, later.+ if (Date.now() - p.at > STALE_HERE_MS)+ setPreview(r.id, o.assetId!, {+ state: "failed",+ at: Date.now(),+ tries: p.tries ?? 1,+ why: "stopped",+ });+ return;+ }+ const t = finishTask(r.id, "preview3d", p.step ?? 0);+ if (!t)+ return void setPreview(r.id, o.assetId!, {+ state: "failed",+ at: Date.now(),+ tries: TRIES,+ why: "gone",+ });+ const out = finishOutcome(t);+ if (out.state === "waiting") return;+ // (A worker's job is tried again by the line itself; one that failed there stays as it is.)+ if (out.state === "failed")+ return void setPreview(r.id, o.assetId!, {+ state: "failed",+ at: Date.now(),+ tries: TRIES,+ why: "worker",+ });+ // Kept once, whichever app process looks first (a deploy's overlap): the job notes the preview it gave.+ const kept = db()+ .transaction((): Preview3d | null => {+ const extra = json<{ preview?: Preview3d }>(+ (db().prepare("SELECT extra_json FROM relay_tasks WHERE id = ?").get(t.id) as { extra_json: string | null } | undefined)?.extra_json ?? null,+ {},+ );+ if (extra.preview) return extra.preview;+ const files = Object.fromEntries(Object.entries(out.files).map(([role, f]) => [role, f.path]));+ const p2 = keepFiles(r.id, files, p.tries ?? 1);+ if (p2)+ db()+ .prepare("UPDATE relay_tasks SET extra_json = json_set(COALESCE(extra_json, '{}'), '$.preview', json(?)) WHERE id = ?")+ .run(JSON.stringify(p2), t.id);+ return p2;+ })+ .immediate();+ setPreview(+ r.id,+ o.assetId!,+ kept ?? {+ state: "failed",+ at: Date.now(),+ tries: p.tries ?? 1,+ why: "not kept",+ },+ );+}++/**+ * Every few seconds (the runner's tick): the previews on their way followed, failed ones tried again (up to TRIES),+ * and new ones started (newest results first) while fewer than IN_FLIGHT are on their way.+ */+export function tickPreviews(now = Date.now()): void {+ // FUOBE_PREVIEWS_3D=0 turns it off (the tests do, but for their own).+ if (process.env.FUOBE_PREVIEWS_3D === "0") return;+ const s = state();+ if (now - s.last < LOOK_MS) return;+ s.last = now;+ try {+ const going = db()+ .prepare(+ `SELECT id, status, provider, model_id, op, request_json, outputs_json, completed_at FROM generations+ WHERE status = 'succeeded' AND (outputs_json LIKE '%"preview3d":{"state":"queued"%' OR outputs_json LIKE '%"preview3d":{"state":"drawing"%')`,+ )+ .all() as Row[];+ let inFlight = 0;+ for (const r of going) {+ for (const o of json<OutputFile[]>(r.outputs_json, [])) {+ const p = o.meta?.preview3d as Preview3d | undefined;+ if (o.kind !== "model3d" || !p || (p.state !== "queued" && p.state !== "drawing")) continue;+ inFlight++;+ follow(r, o, p);+ }+ }+ if (inFlight >= IN_FLIGHT) return;+ // Results with a model and no preview yet (or one to try again), newest first; a run in the Trash waits.+ const rows = db()+ .prepare(+ `SELECT g.id, g.status, g.provider, g.model_id, g.op, g.request_json, g.outputs_json, g.completed_at FROM generations g+ LEFT JOIN generation_trash t ON t.generation_id = g.id+ WHERE g.status = 'succeeded' AND t.generation_id IS NULL AND g.outputs_json LIKE '%"kind":"model3d"%'+ AND (g.outputs_json NOT LIKE '%"preview3d"%' OR g.outputs_json LIKE '%"preview3d":{"state":"failed"%')+ ORDER BY COALESCE(g.completed_at, g.created_at) DESC LIMIT 40`,+ )+ .all() as Row[];+ for (const r of rows) {+ if (inFlight >= IN_FLIGHT) break;+ const outputs = json<OutputFile[]>(r.outputs_json, []);+ for (const [i, o] of outputs.entries()) {+ if (inFlight >= IN_FLIGHT) break;+ const p = o.meta?.preview3d as Preview3d | undefined;+ // A failed one is tried again once, a while after.+ if (p) {+ if (p.state !== "failed" || (p.tries ?? 1) >= TRIES || now - p.at < 10 * 60_000 || !RETRY.includes(p.why ?? "")) continue;+ const again = outputs.map((x, j) => (j === i ? { ...x, meta: { ...x.meta, preview3d: undefined } } : x));+ if (!previewTargets(again).includes(i)) continue;+ start(r, i, outputs, (p.tries ?? 1) + 1);+ inFlight++;+ continue;+ }+ if (!previewTargets(outputs).includes(i)) continue;+ start(r, i, outputs, 1);+ inFlight++;+ }+ }+ } catch (e) {+ console.warn(`[fuobe] 3D previews: ${(e as Error).message}`);+ }+}++/** Stop a preview this server is drawing (the run was deleted). */+export function stopPreviews(id: string): void {+ for (const [k, ctl] of state().here) if (k.startsWith(`${id}:`)) ctl.abort();+}diff --git a/src/server/shares.ts b/src/server/shares.tsindex 1cfaff0d..24cadd06 100644--- a/src/server/shares.ts+++ b/src/server/shares.ts@@ -11,6 +11,7 @@ import { OPERATION_LABELS, type Generation, type OutputFile } from "@/lib/cataloimport { HELPER_FEATURES, HELPER_SUFFIX, extensionOf, userTitle } from "@/lib/library";import { unwrapScene } from "@/lib/storyboard-board";import { shownOutputs } from "@/lib/output-actions";+import { preview3dOf } from "@/lib/preview3d";import {expiryFrom,fileName,@@ -113,6 +114,14 @@ function parseIds(json: string): string[] {}}+/** A 3D model's preview on a page: its light still as the poster, and its turntables (share-scoped). */+function turntableOf(token: string, o: OutputFile): Pick<PublicMedia, "poster" | "turntable"> | Record<string, never> {+ const p = preview3dOf(o);+ if (!p) return {};+ const [poster, posterDark, light, dark] = [p.poster.light, p.poster.dark, p.clip.light, p.clip.dark].map((u) => shareFileUrl(token, u));+ return poster && posterDark && light && dark ? { poster, turntable: { light, dark, posterDark } } : {};+}+/** The outputs a piece shows: a 3D result its turntable (a video output) with the model as a download, else what feeds show. */const shownIndices = (g: Generation) => (g.kind === "model3d" ? g.outputs.map((_, i) => i) : shownOutputs(g));@@ -174,6 +183,7 @@ export function buildPublicShare(row: ShareRow, token: string): { page: PublicSh...(o.width && { width: o.width }),...(o.height && { height: o.height }),...(o.kind === "video" && posterSrc && { poster: shareFileUrl(token, posterSrc)! }),+ ...(o.kind === "model3d" && turntableOf(token, o)),...(o.kind === "text" && typeof o.text === "string" && { text: o.text.slice(0, 20_000) }),download: fileName(title, index, extensionOf(o)),};diff --git a/tests/preview3d.test.ts b/tests/preview3d.test.tsnew file mode 100644index 00000000..2aeffb4d--- /dev/null+++ b/tests/preview3d.test.ts@@ -0,0 +1,205 @@+import { spawnSync } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import zlib from "node:zlib";+import { Document, NodeIO } from "@gltf-transform/core";+import { describe, expect, it, vi } from "vitest";+import { FINISH_FILES, finishProblem, PREVIEW_FILES } from "@/lib/finish-ticket";+import { modelPreview } from "@/lib/output-actions";+import { preview3dOf, previewFormatOf, type Preview3d } from "@/lib/preview3d";+import type { OutputFile } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";+import * as core from "../scripts/model3d/preview3d-core.mjs";+import { PREVIEW_FILES as WORKER_PREVIEW_FILES } from "../bin/lib/worker/finish.mjs";++vi.setConfig({ testTimeout: 120_000 });+const dir = tempDir("fuobe-preview3d-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PREVIEWS_3D = "1";+const { previewSettings, previewTargets, tickPreviews } = await import("@/server/model3d-preview");+const { saveFile } = await import("@/server/storage");+const { db } = await import("@/server/db");++const ffmpegOk = spawnSync(process.env.FFMPEG_PATH || "ffmpeg", ["-hide_banner", "-encoders"], { encoding: "utf8" }).stdout?.includes("libx264") ?? false;++/** A unit cube on the floor (y 0..1) with a red top and a blue body, as a binary glTF. */+async function cubeGlb(): Promise<Uint8Array> {+ const doc = new Document();+ const buf = doc.createBuffer();+ const p: number[] = [];+ const n: number[] = [];+ const idx: number[] = [];+ const faces: [number[], number[], number[]][] = [+ [[0, 1, 0], [1, 0, 0], [0, 0, 1]],+ [[0, -1, 0], [1, 0, 0], [0, 0, -1]],+ [[1, 0, 0], [0, 0, -1], [0, 1, 0]],+ [[-1, 0, 0], [0, 0, 1], [0, 1, 0]],+ [[0, 0, 1], [1, 0, 0], [0, 1, 0]],+ [[0, 0, -1], [-1, 0, 0], [0, 1, 0]],+ ];+ for (const [nn, u, v] of faces) {+ const base = p.length / 3;+ for (const [a, b] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {+ p.push(0.5 * (nn[0] + a * u[0] + b * v[0]), 0.5 + 0.5 * (nn[1] + a * u[1] + b * v[1]), 0.5 * (nn[2] + a * u[2] + b * v[2]));+ n.push(...nn);+ }+ idx.push(base, base + 1, base + 2, base, base + 2, base + 3);+ }+ const mat = doc.createMaterial("m").setBaseColorFactor([0.2, 0.3, 0.9, 1]).setMetallicFactor(0).setRoughnessFactor(0.6);+ const prim = doc+ .createPrimitive()+ .setAttribute("POSITION", doc.createAccessor().setType("VEC3").setArray(new Float32Array(p)).setBuffer(buf))+ .setAttribute("NORMAL", doc.createAccessor().setType("VEC3").setArray(new Float32Array(n)).setBuffer(buf))+ .setIndices(doc.createAccessor().setType("SCALAR").setArray(new Uint32Array(idx)).setBuffer(buf))+ .setMaterial(mat);+ doc.createScene().addChild(doc.createNode().setMesh(doc.createMesh().addPrimitive(prim)));+ return new NodeIO().writeBinary(doc);+}++/** A .spz (version 2) of a column of Gaussians, red at its top in the file's own frame. */+function columnSpz(yDown: boolean): Buffer {+ const count = 400;+ const head = Buffer.alloc(16);+ head.writeUInt32LE(0x5053474e, 0);+ head.writeUInt32LE(2, 4);+ head.writeUInt32LE(count, 8);+ head[12] = 0;+ head[13] = 12;+ const pos = Buffer.alloc(count * 9);+ const alpha = Buffer.alloc(count, 240);+ const color = Buffer.alloc(count * 3);+ const scale = Buffer.alloc(count * 3, Math.round((Math.log(0.04) + 10) * 16));+ const rot = Buffer.alloc(count * 3, 128);+ for (let i = 0; i < count; i++) {+ const h = i / (count - 1); // 0 at the foot, 1 at the head+ const y = (yDown ? -1 : 1) * h * 1.8;+ const put = (v: number, at: number) => {+ const q = Math.round(v * 4096) & 0xffffff;+ pos[at] = q & 255;+ pos[at + 1] = (q >> 8) & 255;+ pos[at + 2] = (q >> 16) & 255;+ };+ put(Math.cos(i) * 0.2, i * 9);+ put(y, i * 9 + 3);+ put(Math.sin(i) * 0.2, i * 9 + 6);+ // Red at the head, blue at the foot (colour bytes: 0.5 + dc * 0.15 scaled to a byte).+ const red = h > 0.8;+ color[i * 3] = red ? 255 : 60;+ color[i * 3 + 1] = 60;+ color[i * 3 + 2] = red ? 60 : 255;+ }+ return zlib.gzipSync(Buffer.concat([head, pos, alpha, color, scale, rot]));+}++describe("3D previews", () => {+ it("a preview3d ticket is checked like every finish ticket, and both sides name its files the same", () => {+ const ok = { v: 1, kind: "preview3d", settings: { format: "glb", yDown: false, frontYaw: 90, cutoff: 0 }, inputs: [{ slot: "model", name: "fuobe_abcdefgh1234.glb", sha256: "a".repeat(64) }] };+ expect(finishProblem(ok)).toBeNull();+ expect(finishProblem({ ...ok, settings: { ...ok.settings, format: "obj" } })).toMatch(/format/);+ expect(finishProblem({ ...ok, settings: { ...ok.settings, cutoff: 2 } })).toMatch(/cutoff/);+ expect(finishProblem({ ...ok, settings: { ...ok.settings, extra: 1 } })).toMatch(/setting/);+ expect(WORKER_PREVIEW_FILES).toEqual(PREVIEW_FILES);+ expect(Object.keys(FINISH_FILES.preview3d).sort()).toEqual(Object.keys(PREVIEW_FILES).sort());+ });++ it("knows which 3D files it draws, and reads a finished preview only", () => {+ const glb: OutputFile = { url: "/api/files/a.glb", kind: "model3d", contentType: "model/gltf-binary" };+ expect(previewFormatOf(glb)).toBe("glb");+ expect(previewFormatOf({ url: "/api/files/a.spz", kind: "model3d", contentType: "model/x-spz" })).toBe("spz");+ expect(previewFormatOf({ url: "/api/files/a.ply", kind: "model3d" })).toBe("ply");+ expect(previewFormatOf({ url: "/api/files/a.ksplat", kind: "model3d" })).toBeNull();+ expect(previewFormatOf({ url: "/api/files/a.png", kind: "image" })).toBeNull();+ const done: Preview3d = { state: "done", at: 1, poster: { light: "/p-l.webp", dark: "/p-d.webp" }, clip: { light: "/c-l.mp4", dark: "/c-d.mp4" } };+ expect(preview3dOf({ ...glb, meta: { preview3d: done } })?.clip.dark).toBe("/c-d.mp4");+ expect(preview3dOf({ ...glb, meta: { preview3d: { ...done, state: "queued" } } })).toBeNull();+ expect(preview3dOf({ ...glb, meta: { preview3d: { ...done, poster: { light: "/p-l.webp" } } } })).toBeNull();+ // Every tile that reads a model's still and turntable gets the preview's first.+ expect(modelPreview({ outputs: [{ ...glb, meta: { preview3d: done } }] }, { ...glb, meta: { preview3d: done } })).toEqual({ poster: "/p-l.webp", video: "/c-l.mp4" });+ });++ it("picks the model outputs that still need one, and draws each the way its viewer stands it", () => {+ const outs: OutputFile[] = [+ { url: "/a.glb", kind: "model3d", contentType: "model/gltf-binary", assetId: "a" },+ { url: "/b.glb", kind: "model3d", contentType: "model/gltf-binary", assetId: "b", meta: { finish: { turntable: "done" } } },+ { url: "/c.glb", kind: "model3d", contentType: "model/gltf-binary", assetId: "c", meta: { finish: { turntable: "rendering" } } },+ { url: "/d.spz", kind: "model3d", assetId: "d", meta: { preview3d: { state: "done", at: 1 } } },+ { url: "/e.spz", kind: "model3d", assetId: "e", meta: { finish: { turntable: "skipped: no browser" } } },+ { url: "/f.png", kind: "image", assetId: "f" },+ ];+ expect(previewTargets(outs)).toEqual([0, 4]);+ // ComfyUI's splats are y down and face +x (splatPose); Idol's haze is left out; a cloud .ply stands as it is.+ expect(previewSettings({ provider: "comfyui", model_id: "oss-idol" }, outs[4])).toMatchObject({ format: "spz", yDown: true, frontYaw: 90 });+ expect(previewSettings({ provider: "fal", model_id: "fal-x" }, { url: "/x.ply", kind: "model3d" })).toMatchObject({ format: "ply", yDown: false, frontYaw: 0, cutoff: 0 });+ expect(previewSettings({ provider: "comfyui", model_id: "oss-idol-mesh" }, outs[0])).toMatchObject({ format: "glb", frontYaw: 90 });+ });++ it("draws a mesh centred, on the floor, and the same at the end of its turn as at the start (a loop with no seam)", async () => {+ const glb = core.readGlb(await cubeGlb());+ const mesh = core.meshOf(glb, []);+ const light = core.studioLight({ width: 8, height: 4, data: new Float32Array(8 * 4 * 3).fill(1) });+ const cyl = core.meshCylinder(mesh);+ const view = { cyl, frame: core.frameCylinder(cyl) };+ const a = core.drawMesh(mesh, light, view, 0, { size: 96 });+ const b = core.drawMesh(mesh, light, view, 2 * Math.PI, { size: 96 });+ let covered = 0, sx = 0, sy = 0, diff = 0;+ for (let i = 0; i < 96 * 96; i++) {+ diff += Math.abs(a[i * 4] - b[i * 4]) + Math.abs(a[i * 4 + 3] - b[i * 4 + 3]);+ if (a[i * 4 + 3] === 255) {+ covered++;+ sx += i % 96;+ sy += Math.floor(i / 96);+ }+ }+ expect(covered).toBeGreaterThan(96 * 96 * 0.1);+ expect(Math.abs(sx / covered - 48)).toBeLessThan(6);+ expect(Math.abs(sy / covered - 48)).toBeLessThan(10);+ expect(diff / (96 * 96)).toBeLessThan(1);+ });++ it("stands a y-down splat upright, its head at the top of the frame", () => {+ for (const yDown of [true, false]) {+ const s = core.readSpz(columnSpz(yDown), zlib.gunzipSync);+ const sp = core.prepareSplat(s, { yDown });+ const view = { cyl: sp.cyl, frame: core.frameCylinder(sp.cyl) };+ const px = core.drawSplat(sp, view, 0, { size: 96, shadow: 0 });+ let redY = 0, redN = 0, blueY = 0, blueN = 0;+ for (let i = 0; i < 96 * 96; i++) {+ if (px[i * 4 + 3] < 128) continue;+ const y = Math.floor(i / 96);+ if (px[i * 4] > px[i * 4 + 2]) {+ redY += y;+ redN++;+ } else {+ blueY += y;+ blueN++;+ }+ }+ expect(redN).toBeGreaterThan(0);+ expect(redY / redN).toBeLessThan(blueY / blueN);+ }+ });++ it.skipIf(!ffmpegOk)("renders the clips and stills, and the server keeps them on the model output (drawn here without workers)", async () => {+ const data = Buffer.from(await cubeGlb());+ const asset = saveFile({ data, contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: "g-cube" });+ const outputs: OutputFile[] = [{ url: asset.url, kind: "model3d", contentType: "model/gltf-binary", assetId: asset.id }];+ const now = Date.now();+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at, completed_at) VALUES ('g-cube', 'image-to-3d', 'fal-trellis', 'cloud', 'fal', 'image-to-3d', 'model3d', 'succeeded', ?, ?, ?, ?, ?)",+ )+ .run(JSON.stringify({ feature: "image-to-3d", modelId: "fal-trellis", op: "image-to-3d" }), JSON.stringify(outputs), now, now, now);+ tickPreviews(now + 60_000);+ const read = () => (JSON.parse((db().prepare("SELECT outputs_json FROM generations WHERE id = 'g-cube'").get() as { outputs_json: string }).outputs_json) as OutputFile[])[0];+ expect((read().meta?.preview3d as Preview3d).state).toBe("drawing");+ const end = Date.now() + 100_000;+ while ((read().meta?.preview3d as Preview3d).state === "drawing" && Date.now() < end) await new Promise((r) => setTimeout(r, 200));+ const p = preview3dOf(read());+ expect(p).not.toBeNull();+ const file = (url: string) => path.join(dir, "files", ...url.replace(/^\/api\/files\//, "").split("/"));+ for (const u of [p!.poster.light, p!.poster.dark, p!.clip.light, p!.clip.dark]) expect(fs.existsSync(file(u)) || u.startsWith("/api/files/")).toBe(true);+ // Once made, never again.+ tickPreviews(Date.now() + 120_000);+ expect(preview3dOf(read())?.clip.light).toBe(p!.clip.light);+ });+});diff --git a/vitest.config.ts b/vitest.config.tsindex 65c52a07..6913ae56 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -20,6 +20,8 @@ export default defineConfig({// one set a key in Settings and point the provider at a stand-in (FUOBE_LLM_TEST_BASE).env: {LMSTUDIO_URL: "http://127.0.0.1:9",+ // No 3D previews drawn in the background of other tests (tests/preview3d.test.ts turns them on for its own).+ FUOBE_PREVIEWS_3D: "0",UNSLOTH_URL: "http://127.0.0.1:9",...Object.fromEntries([