Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Image to 3D: look around splats on result cards and in the full-screen viewer

Claudecd7af65631dc
diff --git a/package.json b/package.json
index 63c8692b..363a325d 100644
--- a/package.json
+++ b/package.json
@@ -37,6 +37,7 @@
"@gltf-transform/extensions": "4.5.1",
"@gltf-transform/functions": "4.5.1",
"@google/model-viewer": "4.3.1",
+ "@sparkjsdev/spark": "2.3.1",
"@tanstack/react-query": "^5.104.3",
"@xyflow/react": "^12.12.0",
"better-sqlite3": "^13.0.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 09ff6025..d6c13f16 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -26,6 +26,9 @@ importers:
'@google/model-viewer':
specifier: 4.3.1
version: 4.3.1([email protected])
+ '@sparkjsdev/spark':
+ specifier: 2.3.1
+ version: 2.3.1([email protected])
'@tanstack/react-query':
specifier: ^5.104.3
version: 5.104.3([email protected])
@@ -1478,6 +1481,11 @@ packages:
resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==}
engines: {node: '>=18'}
+ '@sparkjsdev/[email protected]':
+ resolution: {integrity: sha512-K+SyIbkO/dx1TLLudK8Jp3/noS13z/kdNPo6OK2waxQaGy81HBmKGnNBT/t/K9Ew3dsIXmWqsJXxGfmAu1T5Jg==}
+ peerDependencies:
+ three: '>=0.180.0'
+
'@stablelib/[email protected]':
resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}
@@ -6042,6 +6050,11 @@ snapshots:
'@sindresorhus/[email protected]': {}
+ dependencies:
+ fflate: 0.8.3
+ three: 0.183.2
+
'@stablelib/[email protected]': {}
diff --git a/public/samples/demo-splat.ply b/public/samples/demo-splat.ply
new file mode 100644
index 00000000..46799357
Binary files /dev/null and b/public/samples/demo-splat.ply differ
diff --git a/public/samples/demo-splat.spz b/public/samples/demo-splat.spz
new file mode 100644
index 00000000..3edd0168
Binary files /dev/null and b/public/samples/demo-splat.spz differ
diff --git a/scripts/gen-demo-splat.mjs b/scripts/gen-demo-splat.mjs
new file mode 100644
index 00000000..e65aef4b
--- /dev/null
+++ b/scripts/gen-demo-splat.mjs
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+/**
+ * Demo-mode Gaussian splats for Image to 3D → Splat: the same faceted crystal as the demo GLB, as a standard 3DGS
+ * .ply (public/samples/demo-splat.ply, what cloud TripoSplat returns) and a Niantic .spz v2 (demo-splat.spz, what
+ * the open TripoSplat and Idol 3D graphs write). Like an Idol splat, about a third of its Gaussians are faint haze
+ * (opacity under 0.05) around the object, so the viewer's "Hide faint haze" slider has something to hide.
+ * Deterministic (a seeded generator). Run: node scripts/gen-demo-splat.mjs
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import zlib from "node:zlib";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const out = path.join(root, "public", "samples");
+
+const SOLID = 2816;
+const HAZE = 1280;
+const N = SOLID + HAZE;
+
+// mulberry32: the same file on every run.
+let seed = 0x5d4bdb;
+const rand = () => {
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+};
+
+// The crystal's outline (gen-demo-3d.mjs): an octagonal bipyramid, tip at y 1.05, girdle at y 0.25 to -0.05
+// (radius 0.62), bottom tip at y -1.25. y is up.
+const radiusAt = (y) => (y > 0.25 ? 0.62 * (1.05 - y) / 0.8 : y < -0.05 ? 0.62 * (y + 1.25) / 1.2 : 0.62);
+const PALETTE = [
+ [0.365, 0.294, 0.859],
+ [0.51, 0.44, 0.95],
+ [0.27, 0.2, 0.7],
+ [0.62, 0.55, 0.98],
+];
+const SH_C0 = 0.28209479177387814;
+const logit = (p) => Math.log(p / (1 - p));
+
+/** Each Gaussian: position, colour (linear 0-1), opacity (0-1), scale (world units), rotation (w, x, y, z). */
+const splats = [];
+for (let i = 0; i < N; i++) {
+ const haze = i >= SOLID;
+ const y = -1.25 + rand() * 2.3;
+ const a = rand() * Math.PI * 2;
+ // Solid ones sit near the surface (facets: the octagon's sector picks the colour); haze floats a little outside.
+ const r = haze ? radiusAt(y) * (1.05 + rand() * 0.35) + 0.04 : radiusAt(y) * (0.82 + rand() * 0.18);
+ const sector = Math.floor(((a / (Math.PI * 2)) * 8 + (y > 0.1 ? 0.5 : 0)) % 8);
+ const base = PALETTE[(sector + (y > 0.1 ? 0 : 1)) % PALETTE.length];
+ const shade = 0.85 + 0.3 * ((y + 1.25) / 2.3);
+ const color = haze ? [0.72, 0.7, 0.8] : base.map((c) => Math.min(1, c * shade));
+ const s = haze ? 0.05 + rand() * 0.05 : 0.025 + rand() * 0.025;
+ // Turned about y (by up to 180°: w stays positive, so both files hold the very same quaternion).
+ const half = rand() * (Math.PI / 2);
+ splats.push({
+ p: [Math.cos(a) * r, y, Math.sin(a) * r],
+ color,
+ opacity: haze ? 0.01 + rand() * 0.035 : 0.75 + rand() * 0.24,
+ scale: [s, s * (0.6 + rand() * 0.4), s],
+ rot: [Math.cos(half), 0, Math.sin(half), 0],
+ });
+}
+
+// .ply: the 17 float32 values per Gaussian that Idol / TripoSplat write (x y z, zero normals, f_dc, logit opacity,
+// log scale, rotation w x y z).
+const PROPS = ["x", "y", "z", "nx", "ny", "nz", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1", "scale_2", "rot_0", "rot_1", "rot_2", "rot_3"];
+const header = `ply\nformat binary_little_endian 1.0\nelement vertex ${N}\n${PROPS.map((p) => `property float ${p}`).join("\n")}\nend_header\n`;
+const body = Buffer.alloc(N * PROPS.length * 4);
+splats.forEach((g, i) => {
+ const v = [...g.p, 0, 0, 0, ...g.color.map((c) => (c - 0.5) / SH_C0), logit(g.opacity), ...g.scale.map(Math.log), ...g.rot];
+ v.forEach((x, k) => body.writeFloatLE(x, (i * PROPS.length + k) * 4));
+});
+const ply = Buffer.concat([Buffer.from(header, "ascii"), body]);
+fs.writeFileSync(path.join(out, "demo-splat.ply"), ply);
+
+// .spz v2 (github.com/nianticlabs/spz): a 16-byte header, then positions (24-bit fixed point), alphas, colours,
+// scales and rotations, each as one block, all gzipped. Same axes as the .ply.
+const FRACTIONAL_BITS = 12;
+const u8 = (x) => Math.max(0, Math.min(255, Math.round(x)));
+const head = Buffer.alloc(16);
+head.writeUInt32LE(0x5053474e, 0); // "NGSP"
+head.writeUInt32LE(2, 4);
+head.writeUInt32LE(N, 8);
+head.writeUInt8(0, 12); // SH degree 0
+head.writeUInt8(FRACTIONAL_BITS, 13);
+head.writeUInt8(0, 14); // flags
+const positions = Buffer.alloc(N * 9);
+const alphas = Buffer.alloc(N);
+const colors = Buffer.alloc(N * 3);
+const scales = Buffer.alloc(N * 3);
+const rotations = Buffer.alloc(N * 3);
+splats.forEach((g, i) => {
+ g.p.forEach((x, k) => {
+ const fixed = Math.round(x * (1 << FRACTIONAL_BITS)) & 0xffffff;
+ positions.writeUIntLE(fixed, (i * 3 + k) * 3, 3);
+ });
+ alphas[i] = u8(g.opacity * 255);
+ // spz stores the DC coefficient scaled by 0.15 around 0.5.
+ g.color.forEach((c, k) => (colors[i * 3 + k] = u8((((c - 0.5) / SH_C0) * 0.15 + 0.5) * 255)));
+ g.scale.forEach((s, k) => (scales[i * 3 + k] = u8((Math.log(s) + 10) * 16)));
+ // x, y, z of the unit quaternion with w >= 0.
+ const [w, x, y, z] = g.rot;
+ const sign = w < 0 ? -1 : 1;
+ [x, y, z].forEach((q, k) => (rotations[i * 3 + k] = u8(q * sign * 127.5 + 127.5)));
+});
+const spz = zlib.gzipSync(Buffer.concat([head, positions, alphas, colors, scales, rotations]), { level: 9 });
+fs.writeFileSync(path.join(out, "demo-splat.spz"), spz);
+console.log(`wrote demo-splat.ply (${ply.length} bytes) and demo-splat.spz (${spz.length} bytes), ${N} Gaussians, ${HAZE} of them haze`);
diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsx
index b12a514b..87e0042e 100644
--- a/src/components/model3d/model-card.tsx
+++ b/src/components/model3d/model-card.tsx
@@ -2,7 +2,7 @@
import { Box, Camera, Clapperboard, Download, ImageIcon, Loader2, Paintbrush, Pause, PersonStanding, Play, Printer, Rotate3d, Sparkles, Video, Wand2 } from "lucide-react";
import Link from "next/link";
-import { createElement, useCallback, useEffect, useEffectEvent, useRef, useState, useSyncExternalStore } from "react";
+import { createElement, useCallback, useEffect, useEffectEvent, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { uploadFile, useEngine, useHydrated } from "@/lib/api";
@@ -21,6 +21,8 @@ import { PoweredByHi3d, RefineDialog } from "./refine-option";
import { HI3D_NOTICE, canRefine, isRefined } from "@/lib/av/hi3d";
import { PlaceholderChip } from "@/components/demo-mode";
import { recordableType, recordTurntable } from "./turntable";
+import { hasWebgl2, SplatViewer, useReducedMotion } from "./splat-viewer";
+import { FALLBACK_TEXT, hazeCutoffFor } from "@/lib/av/splat-view";
/** Downloads besides the main file, by the name the provider gave them. */
const FORMAT_LABEL: Record<string, string> = { rigged: "Rigged .glb", walking: "Walk .glb", running: "Run .glb", fbx: ".fbx", splat: "Splat", points: "Points .glb" };
@@ -40,13 +42,15 @@ function rigClips(g: Generation, view: Model3dView): { key: string; label: strin
/**
* A finished 3D model. The card plays its turntable (or shows its poster or photo); the orbitable viewer, and with it
* the GLB, loads only when "View in 3D" opens it: the web GLB when the server made one, else the original (a rig
- * plays its animation). A splat shows its orbit video or picture with the file to download. Then the turntable,
- * Animate the spin and Rig & animate.
+ * plays its animation). A splat shows its orbit video or picture, and "View in 3D" opens the splat viewer in its
+ * place (Spark, loaded only then; the orbit video stays where there's no WebGL2). Then the turntable, Animate the
+ * spin and Rig & animate.
*/
export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g: Generation; info: Record<string, Model3dInfo>; cloudAllowed: boolean; refineAllowed?: boolean }) {
const view = model3dView(g);
- // "preview": the turntable or the still (a splat with an orbit video: the video). "3d": the viewer (a splat: its picture).
- const [show, setShow] = useState<"preview" | "3d">("preview");
+ // "preview": the turntable or the still (a splat with an orbit video: the video). "3d": the viewer (a splat: its
+ // picture). "look": a splat in the splat viewer.
+ const [show, setShow] = useState<"preview" | "3d" | "look">("preview");
const [viewer, setViewer] = useState<HTMLElement | null>(null);
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
@@ -63,6 +67,12 @@ export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g:
const focusViewer = useRef(false);
const hydrated = useHydrated();
const canRecord = hydrated && !!recordableType();
+ // A splat opens in the splat viewer where the browser draws WebGL2 and the file isn't too big for it (it says so).
+ const [splatNote, setSplatNote] = useState<string | null>(null);
+ const canLook = !!view.splat && hydrated && hasWebgl2() && !splatNote;
+ const looking = show === "look" && canLook;
+ // Opened with "View in 3D" (which unmounts itself): the viewer takes the focus once it's drawn.
+ const [focusLook, setFocusLook] = useState(false);
const clips = rigClips(g, view);
const [clipKey, setClipKey] = useState("main");
const rigClip = clips.find((c) => c.key === clipKey);
@@ -172,7 +182,7 @@ export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g:
viewer.removeEventListener("error", onError);
};
}, [viewer, startRecording, onOriginal]);
- const switchTo = (v: "preview" | "3d") => {
+ const switchTo = (v: "preview" | "3d" | "look") => {
// A recording asked for before the model loaded is off once the 3D view is closed.
if (v === "preview") pendingRecord.current = pendingFilm.current = false;
setShow(v);
@@ -207,12 +217,15 @@ export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g:
// The radio buttons in the corner: the preview and the 3D view, a rig's clips, or a splat's video and picture.
// A rig's clip is picked by its key ("main", "walking", "running"); "3d" is the model itself.
const choices: { key: string; label: string; on: boolean }[] = view.splat
- ? clip
- ? [
- { key: "preview", label: "Turntable", on: show === "preview" },
- { key: "3d", label: "Preview", on: show === "3d" },
- ]
- : []
+ ? [
+ ...(clip
+ ? [
+ { key: "preview", label: "Turntable", on: show === "preview" },
+ { key: "3d", label: "Preview", on: show === "3d" },
+ ]
+ : [{ key: "preview", label: "Preview", on: show !== "look" }]),
+ ...(canLook ? [{ key: "look", label: "3D", on: looking }] : []),
+ ]
: view.glb
? [
{ key: "preview", label: clip ? "Turntable" : "Preview", on: show === "preview" },
@@ -222,7 +235,8 @@ export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g:
]
: [];
const pick = (key: string) => {
- if (key === "preview") return switchTo("preview");
+ setFocusLook(false);
+ if (key === "preview" || key === "look") return switchTo(key);
if (key !== "3d") setClipKey(key);
switchTo("3d");
};
@@ -249,17 +263,32 @@ export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g:
return (
<article className="overflow-hidden rounded-2xl border bg-background shadow-soft">
<div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]" style={open3d && backdrop ? { background: backdrop } : undefined}>
- {!open3d ? (
+ {looking && view.splat ? (
+ <SplatViewer
+ url={view.splat.url}
+ format={view.splat.format}
+ poster={view.poster}
+ name={name}
+ defaultCutoff={hazeCutoffFor(g.modelId)}
+ label={`the ${label} splat`}
+ autoFocus={focusLook}
+ onUnavailable={(note) => {
+ setSplatNote(note);
+ setShow("preview");
+ }}
+ />
+ ) : !open3d ? (
<>
{clip && show === "preview" ? <TurntableLoop src={clip} poster={still} label={`Turntable of the ${label} model`} /> : placeholder}
- {view.glb && (
+ {(view.glb || canLook) && (
<Button
size="sm"
variant="secondary"
className="absolute bottom-3 left-1/2 -translate-x-1/2 rounded-full shadow-soft"
onClick={() => {
- focusViewer.current = true;
- switchTo("3d");
+ if (view.splat) setFocusLook(true);
+ else focusViewer.current = true;
+ switchTo(view.splat ? "look" : "3d");
}}
>
<Rotate3d className="size-3.5" /> View in 3D
@@ -321,11 +350,7 @@ export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g:
{g.modelName}
{g.prompt && !view.rigged ? ` · ${g.prompt}` : ""}
</p>
- {view.splat && (
- <p className="text-[12px] text-muted-foreground">
- Fuobe doesn&apos;t draw splats yet: {clip ? "the turntable shows it turning" : "the picture is what the model saw"}. Open the .{view.splat.format} in a Gaussian-splat viewer (SuperSplat, for one) to look around it.
- </p>
- )}
+ {view.splat && hydrated && !canLook && <p className="text-[12px] text-muted-foreground">{splatNote ?? FALLBACK_TEXT["no-webgl2"]}</p>}
<div className="flex flex-wrap gap-1.5">
{view.splat ? (
<Button asChild variant="outline" size="sm" className="rounded-full">
@@ -441,21 +466,6 @@ export function ModelCard({ g, info, cloudAllowed, refineAllowed = false }: { g:
);
}
-const REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
-
-/** Whether the user prefers reduced motion (true until hydrated, so nothing moves before it's known). */
-function useReducedMotion(): boolean {
- return useSyncExternalStore(
- (cb) => {
- const mq = window.matchMedia(REDUCED_MOTION);
- mq.addEventListener("change", cb);
- return () => mq.removeEventListener("change", cb);
- },
- () => window.matchMedia(REDUCED_MOTION).matches,
- () => true,
- );
-}
-
/**
* A card's turntable loop: it loads and plays only while the card is on screen, not at all when the user
* prefers reduced motion (the poster shows instead), and has a pause / play button (WCAG 2.2.2).
diff --git a/src/components/model3d/splat-engine.ts b/src/components/model3d/splat-engine.ts
new file mode 100644
index 00000000..8f536e01
--- /dev/null
+++ b/src/components/model3d/splat-engine.ts
@@ -0,0 +1,209 @@
+"use client";
+
+import { dyno, SparkRenderer, SplatFileType, SplatMesh } from "@sparkjsdev/spark";
+import * as THREE from "three";
+import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
+
+/**
+ * The splat viewer's three.js side (idol-4): Spark (@sparkjsdev/spark 2.3.1, MIT, World Labs) draws the Gaussians
+ * inside a plain three.js scene with OrbitControls. Loaded only through a dynamic import from splat-viewer.tsx, so
+ * no page pays for it until a splat opens. It renders on demand (a drag, a slider, Spark's sort finishing), not in
+ * a loop, so an idle viewer costs nothing.
+ */
+
+const FILE_TYPES: Record<string, SplatFileType> = { ply: SplatFileType.PLY, spz: SplatFileType.SPZ, ksplat: SplatFileType.KSPLAT, splat: SplatFileType.SPLAT };
+
+export interface SplatLoadInfo {
+ splats: number;
+ bytes: number;
+}
+
+export class SplatEngine {
+ private renderer: THREE.WebGLRenderer;
+ private scene = new THREE.Scene();
+ private camera = new THREE.PerspectiveCamera(40, 1, 0.01, 1000);
+ private controls: OrbitControls;
+ private spark: SparkRenderer;
+ private mesh: SplatMesh | null = null;
+ private cutoff = dyno.dynoFloat(0);
+ private home = { position: new THREE.Vector3(0, 0, 3), target: new THREE.Vector3() };
+ private frame = 0;
+ private disposed = false;
+ /** The last frame's CPU time in milliseconds (renderer.render), for the numbers in docs/research/idol-9.md. */
+ lastFrameMs = 0;
+
+ constructor(private canvas: HTMLCanvasElement) {
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: "high-performance" });
+ this.spark = new SparkRenderer({ renderer: this.renderer, onDirty: () => this.requestRender() });
+ this.scene.add(this.spark);
+ this.controls = new OrbitControls(this.camera, canvas);
+ this.controls.enableDamping = true;
+ this.controls.dampingFactor = 0.12;
+ this.controls.zoomToCursor = false;
+ this.controls.addEventListener("change", () => this.requestRender());
+ }
+
+ /** Fetch the file (abortable, its size checked against maxBytes first), then build the splat. */
+ async load(url: string, format: string, { signal, maxBytes, onProgress }: { signal?: AbortSignal; maxBytes?: number; onProgress?: (p: number) => void } = {}): Promise<SplatLoadInfo> {
+ const res = await fetch(url, { signal });
+ if (!res.ok) throw new Error(`The splat didn't load (${res.status})`);
+ const length = Number(res.headers.get("content-length")) || 0;
+ if (maxBytes && length > maxBytes) throw new SplatTooBigError(length);
+ const bytes = await readAll(res, length, maxBytes, onProgress);
+ if (this.disposed || signal?.aborted) throw new DOMException("Aborted", "AbortError");
+ const mesh = new SplatMesh({ fileBytes: bytes, fileType: FILE_TYPES[format], fileName: `splat.${format}` });
+ await mesh.initialized;
+ if (this.disposed || signal?.aborted) {
+ mesh.dispose();
+ throw new DOMException("Aborted", "AbortError");
+ }
+ // The haze cut-off: a Gaussian fainter than the slider's value isn't drawn (its opacity goes to 0).
+ const cutoff = this.cutoff;
+ mesh.objectModifier = dyno.dynoBlock({ gsplat: dyno.Gsplat }, { gsplat: dyno.Gsplat }, ({ gsplat }) => {
+ if (!gsplat) throw new Error("no splat");
+ const { opacity } = dyno.splitGsplat(gsplat).outputs;
+ return { gsplat: dyno.combineGsplat({ gsplat, opacity: dyno.select(dyno.lessThan(opacity, cutoff), dyno.dynoConst("float", 0), opacity) }) };
+ });
+ mesh.updateGenerator();
+ this.mesh = mesh;
+ this.scene.add(mesh);
+ this.frameObject(mesh.getBoundingBox(true));
+ this.requestRender();
+ return { splats: mesh.packedSplats?.numSplats ?? 0, bytes: bytes.byteLength };
+ }
+
+ /** Point the camera at the splat from the front, a little above, far enough to see all of it. */
+ private frameObject(box: THREE.Box3) {
+ const center = box.isEmpty() ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
+ const size = box.isEmpty() ? 2 : Math.max(...box.getSize(new THREE.Vector3()).toArray(), 0.01);
+ const distance = (size * 0.62) / Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2));
+ this.home.target.copy(center);
+ this.home.position.copy(center).add(new THREE.Vector3(0, size * 0.18, distance));
+ this.camera.near = Math.max(distance / 200, 0.001);
+ this.camera.far = distance * 50;
+ this.camera.updateProjectionMatrix();
+ this.controls.minDistance = size * 0.25;
+ this.controls.maxDistance = distance * 6;
+ this.reset();
+ }
+
+ reset() {
+ this.camera.position.copy(this.home.position);
+ this.controls.target.copy(this.home.target);
+ this.controls.update();
+ this.requestRender();
+ }
+
+ /** Turn the splat over (a file saved y-down shows upside down). */
+ flip() {
+ if (!this.mesh) return;
+ this.mesh.rotateX(Math.PI);
+ this.mesh.updateMatrixWorld();
+ const box = this.mesh.getBoundingBox(true).applyMatrix4(this.mesh.matrixWorld);
+ this.frameObject(box);
+ }
+
+ /** Orbit by angles in radians (the arrow keys), around the target. */
+ orbit(azimuth: number, polar: number) {
+ const offset = this.camera.position.clone().sub(this.controls.target);
+ const s = new THREE.Spherical().setFromVector3(offset);
+ s.theta -= azimuth;
+ s.phi = THREE.MathUtils.clamp(s.phi - polar, 0.05, Math.PI - 0.05);
+ this.camera.position.copy(this.controls.target).add(new THREE.Vector3().setFromSpherical(s));
+ this.controls.update();
+ this.requestRender();
+ }
+
+ /** Move closer (factor < 1) or further (> 1), within the controls' limits (the + and - keys). */
+ zoom(factor: number) {
+ const offset = this.camera.position.clone().sub(this.controls.target);
+ const d = THREE.MathUtils.clamp(offset.length() * factor, this.controls.minDistance, this.controls.maxDistance);
+ this.camera.position.copy(this.controls.target).add(offset.setLength(d));
+ this.controls.update();
+ this.requestRender();
+ }
+
+ setCutoff(value: number) {
+ this.cutoff.value = value;
+ this.mesh?.updateVersion();
+ this.requestRender();
+ }
+
+ setBackground(color: string) {
+ this.scene.background = new THREE.Color(color);
+ this.requestRender();
+ }
+
+ resize(width: number, height: number, dpr: number) {
+ if (!width || !height) return;
+ this.renderer.setPixelRatio(dpr);
+ this.renderer.setSize(width, height, false);
+ this.camera.aspect = width / height;
+ this.camera.updateProjectionMatrix();
+ this.requestRender();
+ }
+
+ /** The current view as a PNG, at the canvas's own size (rendered and read in the same task). */
+ capture(): Promise<Blob> {
+ this.render();
+ return new Promise((resolve, reject) => this.canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't save the still"))), "image/png"));
+ }
+
+ private requestRender() {
+ if (this.frame || this.disposed) return;
+ this.frame = requestAnimationFrame(() => {
+ this.frame = 0;
+ this.render();
+ // Damping keeps the camera gliding after a drag: keep drawing until it settles.
+ if (this.controls.update()) this.requestRender();
+ });
+ }
+
+ private render() {
+ if (this.disposed) return;
+ const t = performance.now();
+ this.renderer.render(this.scene, this.camera);
+ this.lastFrameMs = performance.now() - t;
+ }
+
+ dispose() {
+ this.disposed = true;
+ if (this.frame) cancelAnimationFrame(this.frame);
+ this.controls.dispose();
+ this.mesh?.dispose();
+ this.spark.dispose();
+ this.renderer.dispose();
+ }
+}
+
+export class SplatTooBigError extends Error {
+ constructor(readonly bytes: number) {
+ super("This splat is too big to open on this device");
+ }
+}
+
+/** Read a response body, reporting progress and stopping once it passes maxBytes (a server that sent no length). */
+async function readAll(res: Response, length: number, maxBytes: number | undefined, onProgress?: (p: number) => void): Promise<Uint8Array> {
+ if (!res.body) return new Uint8Array(await res.arrayBuffer());
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let got = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ got += value.byteLength;
+ if (maxBytes && got > maxBytes) {
+ void reader.cancel();
+ throw new SplatTooBigError(got);
+ }
+ if (length) onProgress?.(Math.min(1, got / length));
+ }
+ const out = new Uint8Array(got);
+ let at = 0;
+ for (const c of chunks) {
+ out.set(c, at);
+ at += c.byteLength;
+ }
+ return out;
+}
diff --git a/src/components/model3d/splat-viewer.tsx b/src/components/model3d/splat-viewer.tsx
new file mode 100644
index 00000000..42c3f293
--- /dev/null
+++ b/src/components/model3d/splat-viewer.tsx
@@ -0,0 +1,318 @@
+"use client";
+
+import { Camera, FlipVertical2, Loader2, RotateCcw, SlidersHorizontal } from "lucide-react";
+import { useTheme } from "next-themes";
+import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Slider } from "@/components/ui/slider";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { uploadFile, useIsGuest } from "@/lib/api";
+import { backgroundColor, FALLBACK_TEXT, HAZE_MAX, HAZE_STEP, SPLAT_BACKGROUNDS, SPLAT_MAX_BYTES, stillFileName, type SplatBackground } from "@/lib/av/splat-view";
+import { toastError } from "@/lib/refusals";
+import { cn } from "@/lib/utils";
+import type { SplatEngine } from "./splat-engine";
+
+const REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
+
+/** Whether the user prefers reduced motion (true until hydrated, so nothing moves before it's known). */
+export function useReducedMotion(): boolean {
+ return useSyncExternalStore(
+ (cb) => {
+ const mq = window.matchMedia(REDUCED_MOTION);
+ mq.addEventListener("change", cb);
+ return () => mq.removeEventListener("change", cb);
+ },
+ () => window.matchMedia(REDUCED_MOTION).matches,
+ () => true,
+ );
+}
+
+let webgl2: boolean | undefined;
+/** Whether this browser draws WebGL2 (checked once; false before hydration). */
+export function hasWebgl2(): boolean {
+ if (typeof document === "undefined") return false;
+ if (webgl2 === undefined) {
+ try {
+ const gl = document.createElement("canvas").getContext("webgl2");
+ webgl2 = !!gl;
+ gl?.getExtension("WEBGL_lose_context")?.loseContext();
+ } catch {
+ webgl2 = false;
+ }
+ }
+ return webgl2;
+}
+
+const isCoarse = () => typeof window !== "undefined" && window.matchMedia("(pointer: coarse)").matches;
+
+type Status = "loading" | "ready" | "too-big" | "error";
+
+/**
+ * Look around a Gaussian splat (.spz / .ply / .ksplat): drag to turn it, pinch or scroll to zoom, the arrow keys and
+ * + / − from the keyboard, Reset view, a light / grey / dark background, "Hide faint haze" (an opacity cut-off) and
+ * "Save a still" to the Library. The renderer (Spark on three.js) loads only when this mounts; the poster shows
+ * until the splat is drawn, and a file the device can't take leaves the poster with a note.
+ */
+export function SplatViewer({
+ url,
+ format,
+ poster,
+ name,
+ defaultCutoff,
+ tone = "card",
+ label = "the splat",
+ autoFocus = false,
+ onUnavailable,
+}: {
+ url: string;
+ format: string;
+ poster?: string;
+ name: string;
+ defaultCutoff: number;
+ /** "card": compact controls on a result card; "panel": the full-screen viewer's dark stage. */
+ tone?: "card" | "panel";
+ label?: string;
+ autoFocus?: boolean;
+ /** The viewer can't open this file here (too big, no WebGL, it failed): the caller shows its fallback. */
+ onUnavailable?: (reason: string) => void;
+}) {
+ const [canvas, setCanvas] = useState<HTMLCanvasElement | null>(null);
+ const stageRef = useRef<HTMLDivElement>(null);
+ const engineRef = useRef<SplatEngine | null>(null);
+ const [status, setStatus] = useState<Status>("loading");
+ const [progress, setProgress] = useState(0);
+ const [cutoff, setCutoff] = useState(defaultCutoff);
+ const { resolvedTheme } = useTheme();
+ const [background, setBackground] = useState<SplatBackground>(() => (tone === "panel" ? "dark" : resolvedTheme === "dark" ? "dark" : "light"));
+ const [saving, setSaving] = useState(false);
+ const guest = useIsGuest();
+ const helpId = useId();
+ const onUnavailableRef = useRef(onUnavailable);
+ useEffect(() => void (onUnavailableRef.current = onUnavailable));
+ const cutoffRef = useRef(cutoff);
+ const backgroundRef = useRef(background);
+
+ // Load Spark and the file (again for another file).
+ useEffect(() => {
+ if (!canvas) return;
+ const ctl = new AbortController();
+ let eng: SplatEngine | null = null;
+ const coarse = isCoarse();
+ import("./splat-engine")
+ .then(async ({ SplatEngine, SplatTooBigError }) => {
+ if (ctl.signal.aborted) return;
+ eng = new SplatEngine(canvas);
+ engineRef.current = eng;
+ const el = stageRef.current;
+ if (el) eng.resize(el.clientWidth, el.clientHeight, Math.min(window.devicePixelRatio || 1, coarse ? 1.5 : 2));
+ eng.setBackground(backgroundColor(backgroundRef.current));
+ eng.setCutoff(cutoffRef.current);
+ try {
+ await eng.load(url, format, { signal: ctl.signal, maxBytes: coarse ? SPLAT_MAX_BYTES.coarse : SPLAT_MAX_BYTES.fine, onProgress: setProgress });
+ if (!ctl.signal.aborted) setStatus("ready");
+ } catch (e) {
+ if (ctl.signal.aborted) return;
+ if (e instanceof SplatTooBigError) {
+ setStatus("too-big");
+ onUnavailableRef.current?.(FALLBACK_TEXT["too-big"]);
+ } else throw e;
+ }
+ })
+ .catch(() => {
+ if (ctl.signal.aborted) return;
+ setStatus("error");
+ onUnavailableRef.current?.("The 3D view couldn't open here. Download the file to look around it in a splat viewer.");
+ });
+ return () => {
+ ctl.abort();
+ eng?.dispose();
+ engineRef.current = null;
+ };
+ }, [canvas, url, format]);
+
+ useEffect(() => {
+ const el = stageRef.current;
+ if (!el) return;
+ const coarse = isCoarse();
+ const ro = new ResizeObserver(() => engineRef.current?.resize(el.clientWidth, el.clientHeight, Math.min(window.devicePixelRatio || 1, coarse ? 1.5 : 2)));
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ useEffect(() => {
+ cutoffRef.current = cutoff;
+ engineRef.current?.setCutoff(cutoff);
+ }, [cutoff]);
+ useEffect(() => {
+ backgroundRef.current = background;
+ engineRef.current?.setBackground(backgroundColor(background));
+ }, [background]);
+ useEffect(() => {
+ if (autoFocus && status === "ready") stageRef.current?.focus({ preventScroll: true });
+ }, [autoFocus, status]);
+
+ const ready = status === "ready";
+ const onKey = (e: React.KeyboardEvent) => {
+ const eng = engineRef.current;
+ if (!eng || !ready || e.altKey || e.metaKey || e.ctrlKey) return;
+ const step = Math.PI / 12;
+ const act: Record<string, () => void> = {
+ ArrowLeft: () => eng.orbit(-step, 0),
+ ArrowRight: () => eng.orbit(step, 0),
+ ArrowUp: () => eng.orbit(0, step),
+ ArrowDown: () => eng.orbit(0, -step),
+ "+": () => eng.zoom(0.85),
+ "=": () => eng.zoom(0.85),
+ "-": () => eng.zoom(1 / 0.85),
+ "0": () => eng.reset(),
+ Home: () => eng.reset(),
+ };
+ const fn = act[e.key];
+ if (!fn) return;
+ e.preventDefault();
+ fn();
+ };
+
+ const saveStill = async () => {
+ const eng = engineRef.current;
+ if (!eng) return;
+ setSaving(true);
+ try {
+ const blob = await eng.capture();
+ await uploadFile(new File([blob], stillFileName(name), { type: "image/png" }));
+ toast.success("Still saved to your Library (Uploads)");
+ } catch (e) {
+ toastError(e, "Couldn't save the still");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const panel = tone === "panel";
+ const haze = (
+ <div className={cn("flex items-center gap-2", panel ? "w-56" : "w-full")}>
+ <label id={`${helpId}-haze`} className="shrink-0 text-[12px] font-medium">
+ Hide faint haze
+ </label>
+ <Slider
+ aria-labelledby={`${helpId}-haze`}
+ aria-valuetext={cutoff === 0 ? "Off: every Gaussian drawn" : `Under ${Math.round(cutoff * 100)}% opacity hidden`}
+ min={0}
+ max={HAZE_MAX}
+ step={HAZE_STEP}
+ value={[cutoff]}
+ onValueChange={([v]) => setCutoff(v)}
+ disabled={!ready}
+ className="min-w-20 flex-1"
+ />
+ <span className="w-8 shrink-0 text-right text-[11px] tabular-nums opacity-80">{cutoff === 0 ? "Off" : `${Math.round(cutoff * 100)}%`}</span>
+ </div>
+ );
+
+ return (
+ // Touches stay here: a drag that turns the splat isn't a swipe to the next result (the studio viewer's).
+ <div className="relative size-full overflow-hidden" style={{ background: backgroundColor(background) }} onTouchStart={(e) => e.stopPropagation()} onTouchEnd={(e) => e.stopPropagation()}>
+ <div
+ ref={stageRef}
+ tabIndex={0}
+ role="application"
+ aria-roledescription="3D viewer"
+ aria-label={`Look around ${label}`}
+ aria-describedby={helpId}
+ aria-busy={!ready}
+ onKeyDown={onKey}
+ className="absolute inset-0 touch-none outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
+ >
+ <canvas ref={setCanvas} className={cn("size-full transition-opacity", ready ? "opacity-100" : "opacity-0")} />
+ <p id={helpId} className="sr-only">
+ Drag to turn it, pinch or scroll to zoom. From the keyboard: the arrow keys turn it, plus and minus zoom, 0 resets the view.
+ </p>
+ </div>
+ {!ready && (
+ <div className="pointer-events-none absolute inset-0" role="status" aria-label={status === "loading" ? "Loading the 3D view" : undefined}>
+ {poster && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={poster} alt="" className="size-full object-contain p-4" />
+ )}
+ {status === "loading" && (
+ <span className={cn("absolute right-3 bottom-3 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-medium shadow-soft", panel ? "bg-white/15 text-white" : "bg-background/85")}>
+ <Loader2 className="size-3.5 animate-spin" aria-hidden /> {progress > 0 && progress < 1 ? `Loading ${Math.round(progress * 100)}%` : "Loading the 3D view"}
+ </span>
+ )}
+ </div>
+ )}
+ {ready && (
+ <div
+ role="toolbar"
+ aria-label="3D view"
+ className={cn(
+ "absolute inset-x-2 bottom-2 flex flex-wrap items-center justify-center gap-1 rounded-2xl px-1.5 py-1 shadow-soft backdrop-blur sm:inset-x-auto sm:left-1/2 sm:-translate-x-1/2",
+ panel ? "bg-black/55 text-white" : "bg-background/85 text-foreground",
+ )}
+ >
+ <IconButton text="Reset view" panel={panel} onClick={() => engineRef.current?.reset()}>
+ <RotateCcw className="size-3.5" />
+ </IconButton>
+ <IconButton text="Turn it over" panel={panel} onClick={() => engineRef.current?.flip()}>
+ <FlipVertical2 className="size-3.5" />
+ </IconButton>
+ <div role="radiogroup" aria-label="Background" className="flex items-center gap-1 px-1">
+ {SPLAT_BACKGROUNDS.map((b) => (
+ <button
+ key={b.id}
+ type="button"
+ role="radio"
+ aria-checked={background === b.id}
+ aria-label={`${b.label} background`}
+ title={`${b.label} background`}
+ onClick={() => setBackground(b.id)}
+ className={cn("size-5 rounded-full border border-black/20 transition dark:border-white/30", background === b.id && "ring-2 ring-primary ring-offset-1 ring-offset-transparent")}
+ style={{ background: b.color }}
+ />
+ ))}
+ </div>
+ {panel ? (
+ <div className="px-1">{haze}</div>
+ ) : (
+ <Popover>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <PopoverTrigger asChild>
+ <Button type="button" size="icon" variant="ghost" aria-label="Hide faint haze" className={cn("size-7 rounded-full", cutoff > 0 && "text-primary")}>
+ <SlidersHorizontal className="size-3.5" />
+ </Button>
+ </PopoverTrigger>
+ </TooltipTrigger>
+ <TooltipContent>Hide faint haze</TooltipContent>
+ </Tooltip>
+ <PopoverContent side="top" className="w-64 p-3">
+ {haze}
+ <p className="mt-2 text-[11px] text-muted-foreground">Hides the near-transparent Gaussians around the object. The download keeps them all.</p>
+ </PopoverContent>
+ </Popover>
+ )}
+ {!guest && (
+ <IconButton text={saving ? "Saving the still…" : "Save a still"} panel={panel} onClick={() => void saveStill()} disabled={saving}>
+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : <Camera className="size-3.5" />}
+ </IconButton>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function IconButton({ text, panel, onClick, disabled, children }: { text: string; panel: boolean; onClick: () => void; disabled?: boolean; children: React.ReactNode }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button type="button" size="icon" variant="ghost" aria-label={text} onClick={onClick} disabled={disabled} className={cn("size-7 rounded-full", panel && "text-white hover:bg-white/15 hover:text-white")}>
+ {children}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{text}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/src/components/studio/result-media.tsx b/src/components/studio/result-media.tsx
index 1e90b467..a01ef47b 100644
--- a/src/components/studio/result-media.tsx
+++ b/src/components/studio/result-media.tsx
@@ -1,8 +1,11 @@
"use client";
-import { AudioLines, Box, Download, FileText, Film, Layers } from "lucide-react";
+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 { hasWebgl2, SplatViewer, useReducedMotion } from "@/components/model3d/splat-viewer";
+import { useHydrated } from "@/lib/api";
+import { FALLBACK_TEXT, hazeCutoffFor, splatFallback } from "@/lib/av/splat-view";
import { FORMAT_INFO } from "@/lib/av/formats";
import { splatFormatOf, viewerGlb } from "@/lib/av/model3d";
import type { Generation, OutputFile, VideoFormat } from "@/lib/catalog/types";
@@ -194,8 +197,8 @@ export function LayersStack({ g, className, bare }: { g: Generation; className?:
/**
* A .glb in an orbitable viewer. @google/model-viewer (with three.js) loads only when one is opened. A Gaussian
- * splat (.ply / .spz / .ksplat), which it can't load, shows its orbit video or picture and the file to download.
- * A rigged character plays its animation instead of turning.
+ * splat (.ply / .spz / .ksplat) opens in the splat viewer (Spark, loaded only then), its orbit video or picture
+ * staying where it can't (see SplatPanel). A rigged character plays its animation instead of turning.
*/
export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }) {
const [ready, setReady] = useState(false);
@@ -217,7 +220,7 @@ export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }
};
}, [splat]);
const { poster, video } = modelPreview(g, output);
- if (splat) return <SplatPreview output={output} format={splat} poster={poster} video={video} />;
+ if (splat) return <SplatPanel output={output} format={splat} poster={poster} video={video} g={g} />;
if (failed) return <p className="text-[13px] text-white/80">Couldn&apos;t load the 3D viewer. Download the .glb to open it.</p>;
if (!ready) {
return (
@@ -243,24 +246,54 @@ export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }
});
}
-/** A splat in the full-screen viewer: its orbit video or picture, what Fuobe can't do yet, and the file. */
-function SplatPreview({ output, format, poster, video }: { output: OutputFile; format: string; poster?: string; video?: string }) {
+/**
+ * A splat in the full-screen viewer (the Library's 3D tab and "View in 3D" open it): the splat viewer, with the file
+ * to download. The orbit video (or the picture) stays instead where the browser has no WebGL2 or the file is too big
+ * for the device, and when the user prefers reduced motion until they choose "Look around in 3D".
+ */
+function SplatPanel({ output, format, poster, video, g }: { output: OutputFile; format: string; poster?: string; video?: string; g: Generation }) {
+ const hydrated = useHydrated();
+ const reducedMotion = useReducedMotion();
+ const [asked, setAsked] = useState(false);
+ const [note, setNote] = useState<string | null>(null);
+ const fallback = !hydrated ? "reduced-motion" : note ? "too-big" : splatFallback({ webgl2: hasWebgl2(), coarse: false, reducedMotion, asked });
+ const name = (g.modelName ?? "splat").replace(/[^\w .-]+/g, "");
+ const download = (
+ <a href={output.url} download={`${name}.${format}`} className="inline-flex h-8 items-center gap-1.5 rounded-full bg-white/15 px-3.5 text-[13px] font-medium text-white hover:bg-white/25">
+ <Download className="size-4" aria-hidden /> .{format}
+ </a>
+ );
+ if (!fallback) {
+ return (
+ <div className="flex size-full flex-col">
+ <div className="relative min-h-0 flex-1 overflow-hidden md:rounded-lg">
+ <SplatViewer url={output.url} format={format} poster={poster} name={name} defaultCutoff={hazeCutoffFor(g.modelId)} tone="panel" label={g.request.prompt || "the splat"} autoFocus onUnavailable={setNote} />
+ </div>
+ <div className="flex shrink-0 justify-center pt-2">{download}</div>
+ </div>
+ );
+ }
+ const text = note ?? (fallback === "reduced-motion" ? null : FALLBACK_TEXT[fallback]);
return (
<div className="flex size-full flex-col items-center justify-center gap-3 p-4 text-center text-white/80">
{video ? (
- <video src={video} controls autoPlay loop muted playsInline aria-label="Orbit video of the splat" className="max-h-[70%] max-w-full" />
+ // Reduced motion: the orbit video waits for play.
+ <video src={video} poster={poster} controls autoPlay={!reducedMotion} loop muted playsInline aria-label="Orbit video of the splat" className="max-h-[70%] max-w-full" />
) : poster ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={poster} alt="The subject the splat was made from" className="max-h-[70%] max-w-full object-contain" />
) : (
<Box className="size-10" aria-hidden />
)}
- <p className="max-w-md text-[13px]">
- Fuobe doesn&apos;t draw Gaussian splats yet. Download the .{format} and open it in a splat viewer (SuperSplat, for one) to look around it.
- </p>
- <a href={output.url} download className="inline-flex h-9 items-center gap-1.5 rounded-full bg-white/15 px-4 text-[13px] font-medium text-white hover:bg-white/25">
- <Download className="size-4" aria-hidden /> .{format}
- </a>
+ {text && <p className="max-w-md text-[13px]">{text}</p>}
+ <div className="flex flex-wrap justify-center gap-2">
+ {hydrated && fallback === "reduced-motion" && (
+ <button type="button" onClick={() => setAsked(true)} className="inline-flex h-8 items-center gap-1.5 rounded-full bg-white px-3.5 text-[13px] font-medium text-black hover:bg-white/90">
+ <Rotate3d className="size-4" aria-hidden /> Look around in 3D
+ </button>
+ )}
+ {download}
+ </div>
</div>
);
}
diff --git a/src/lib/av/splat-view.ts b/src/lib/av/splat-view.ts
new file mode 100644
index 00000000..7b1a85a6
--- /dev/null
+++ b/src/lib/av/splat-view.ts
@@ -0,0 +1,67 @@
+import type { OutputFile } from "@/lib/catalog/types";
+import { isIdol, splatFormatOf } from "./model3d";
+
+/**
+ * Looking around a Gaussian splat (idol-4). The page draws .spz / .ply / .ksplat / .splat with Spark (a three.js
+ * splat renderer, loaded only when a splat opens: src/components/model3d/splat-engine.ts); a GLB keeps
+ * @google/model-viewer. What decides between them, the haze cut-off a result starts with, and when the orbit
+ * video stays instead (no WebGL2, reduced motion, a file too big for the device). Pure, so tests can check it.
+ */
+
+/** Which viewer draws a 3D output: the splat viewer, @google/model-viewer for a GLB, or none. */
+export type Model3dViewer = "splat" | "glb";
+
+export function viewerFor(o: Pick<OutputFile, "url" | "meta" | "kind"> | undefined): Model3dViewer | undefined {
+ if (!o || o.kind !== "model3d") return undefined;
+ return splatFormatOf(o) ? "splat" : "glb";
+}
+
+/**
+ * The opacity a result's viewer hides Gaussians under, to start with. Idol 3D emits about half its Gaussians under
+ * 0.05 (ComfyUI-Idol's README; docs/research/idol-9.md §2.4), so its results start at 0.05. TripoSplat's haze isn't
+ * documented, so it starts at 0 (everything drawn) until the splat A/B (idol-3) says otherwise.
+ */
+export const IDOL_HAZE_CUTOFF = 0.05;
+export function hazeCutoffFor(modelId: string | null | undefined): number {
+ return isIdol(modelId) ? IDOL_HAZE_CUTOFF : 0;
+}
+
+/** The slider's range: 0 (draw every Gaussian) to 0.3 (only the solid ones), in steps of 0.01. */
+export const HAZE_MAX = 0.3;
+export const HAZE_STEP = 0.01;
+
+/** The backgrounds behind the splat. */
+export type SplatBackground = "light" | "dark" | "grey";
+export const SPLAT_BACKGROUNDS: { id: SplatBackground; label: string; color: string }[] = [
+ { id: "light", label: "Light", color: "#f4f4f5" },
+ { id: "grey", label: "Grey", color: "#808080" },
+ { id: "dark", label: "Dark", color: "#111113" },
+];
+export const backgroundColor = (id: SplatBackground) => SPLAT_BACKGROUNDS.find((b) => b.id === id)!.color;
+
+/**
+ * The biggest file the viewer opens: a 1,048,576-Gaussian .ply is about 71 MB (68 bytes each), an .spz about a
+ * tenth. A phone (coarse pointer) stops at 48 MB, about a 700,000-Gaussian .ply; a computer at 160 MB.
+ */
+export const SPLAT_MAX_BYTES = { coarse: 48 * 1024 * 1024, fine: 160 * 1024 * 1024 } as const;
+export const splatTooBig = (bytes: number | undefined, coarse: boolean) => bytes !== undefined && bytes > (coarse ? SPLAT_MAX_BYTES.coarse : SPLAT_MAX_BYTES.fine);
+
+/** Why the orbit video (or picture) stays instead of the viewer, or null when the viewer can open. */
+export type SplatFallback = "no-webgl2" | "too-big" | "reduced-motion";
+export function splatFallback(o: { webgl2: boolean; bytes?: number; coarse: boolean; reducedMotion: boolean; asked?: boolean }): SplatFallback | null {
+ if (!o.webgl2) return "no-webgl2";
+ if (splatTooBig(o.bytes, o.coarse)) return "too-big";
+ // Reduced motion: nothing opens by itself; "Look around" (asked) still opens it.
+ if (o.reducedMotion && !o.asked) return "reduced-motion";
+ return null;
+}
+
+/** What the page says for each fallback. */
+export const FALLBACK_TEXT: Record<SplatFallback, string> = {
+ "no-webgl2": "This browser can't draw 3D splats. Download the file to look around it in a splat viewer.",
+ "too-big": "This splat is too big to open on this device. Download it to look around it in a splat viewer.",
+ "reduced-motion": "",
+};
+
+/** The file name a still is saved under: the model's name, then "still". */
+export const stillFileName = (name: string) => `${name.replace(/[^\w .-]+/g, "").trim() || "splat"} still.png`;
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index 6ac145ad..cf983f87 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -314,15 +314,22 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,
{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb" } },
{ url: "sample:demo-turntable.mp4", kind: "video", contentType: "video/mp4", meta: { demo: true, turntable: true } },
];
- // Round 4. A splat and a rig come back as the demo mesh (a real splat is a .ply or .spz). A scene is the
- // mesh and its depth map on the open engine (MoGe), the depth map alone on the cloud (Marigold).
+ // Round 4. A rig comes back as the demo mesh. A scene is the mesh and its depth map on the open engine (MoGe),
+ // the depth map alone on the cloud (Marigold).
case "scene-3d": {
const depth = demoDepth(brief, ar, kind === "image");
if (kind === "image") return [depth];
return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", scene: true, role: "scene" } }, depth];
}
+ // A splat is a real one (scripts/gen-demo-splat.mjs), so the splat viewer opens in demo mode: an .spz with its
+ // orbit video on the open engine (as the TripoSplat and Idol 3D graphs write), a .ply on the cloud (fal's).
case "splat":
- return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", splat: true } }];
+ return meta.openSplat
+ ? [
+ { url: "sample:demo-splat.spz", kind: "model3d", contentType: "model/x-spz", meta: { demo: true, format: "spz", role: "splat" } },
+ { url: "sample:demo-turntable.mp4", kind: "video", contentType: "video/mp4", meta: { demo: true, turntable: true } },
+ ]
+ : [{ url: "sample:demo-splat.ply", kind: "model3d", contentType: "model/ply", meta: { demo: true, format: "ply" } }];
case "rig-3d":
return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", rigged: true } }];
// Hi3D's refine: the demo mesh, geometry only as the real one is.
@@ -451,6 +458,8 @@ export const mockProvider: ProviderAdapter = {
master: route.provider === "comfyui" && route.endpoint === "video-character-swap-h3-segment",
// H3 Person Removal: each window's preview and checkpoint, so "Redo from here" can be tried (H3 Relay's review).
h3Review: route.provider === "comfyui" && route.endpoint === H3_REMOVAL_WORKFLOW,
+ // A splat on the open engine is an .spz with an orbit video; fal's is a .ply.
+ openSplat: route.op === "splat" && route.provider === "comfyui",
// A stem split that also transcribes (ComfyUI's dub-prepare-separate-transcribe).
transcript: route.op === "separate-audio" && route.provider === "comfyui" && route.endpoint.includes("transcribe"),
// A dialogue / music / effects split (ComfyUI's separate-soundtrack-dbs): four stems.
diff --git a/tests/demo-ops.test.ts b/tests/demo-ops.test.ts
index 0322380a..10d3c6fa 100644
--- a/tests/demo-ops.test.ts
+++ b/tests/demo-ops.test.ts
@@ -209,13 +209,18 @@ describe("demo outputs for the round-4 operations", () => {
expect(await wavSeconds(done["audio-loop"].outputs[0].url)).toBeCloseTo(20, 1);
expect(await wavSeconds(done["audio-join"].outputs[0].url)).toBeCloseTo(9, 1);
- for (const k of ["scene-3d", "splat", "text-to-3d", "rig-3d"]) {
+ for (const k of ["scene-3d", "text-to-3d", "rig-3d"]) {
const m = done[k].outputs.find((o) => o.kind === "model3d");
expect(m, k).toMatchObject({ contentType: "model/gltf-binary" });
expect(m!.url, k).toMatch(/\.glb$/);
}
expect(done["rig-3d"].outputs[0].meta?.rigged).toBe(true);
- checkGlb(Buffer.from(await (await serve(done.splat.outputs[0].url)).arrayBuffer()));
+ checkGlb(Buffer.from(await (await serve(done["rig-3d"].outputs[0].url)).arrayBuffer()));
+ // A cloud splat is a real .ply (the splat viewer draws it in demo mode), like fal's TripoSplat.
+ expect(done.splat.outputs).toEqual([expect.objectContaining({ kind: "model3d", contentType: "model/ply", meta: expect.objectContaining({ format: "ply" }) })]);
+ expect(done.splat.outputs[0].url).toMatch(/\.ply$/);
+ const ply = Buffer.from(await (await serve(done.splat.outputs[0].url)).arrayBuffer());
+ expect(ply.subarray(0, 4).toString("ascii")).toBe("ply\n");
const frames = done["extract-frames"].outputs;
expect(frames.map((f) => [f.kind, f.meta?.index])).toEqual([0, 1, 2, 3].map((i) => ["image", i]));
diff --git a/tests/splat-view.test.ts b/tests/splat-view.test.ts
new file mode 100644
index 00000000..9ed13b49
--- /dev/null
+++ b/tests/splat-view.test.ts
@@ -0,0 +1,129 @@
+import fs from "node:fs";
+import path from "node:path";
+import zlib from "node:zlib";
+import { describe, expect, it } from "vitest";
+import { IDOL_MODELS, model3dView, splatFormatOf } from "@/lib/av/model3d";
+import { FALLBACK_TEXT, hazeCutoffFor, SPLAT_MAX_BYTES, splatFallback, splatTooBig, stillFileName, viewerFor } from "@/lib/av/splat-view";
+
+/**
+ * Looking around splats (idol-4): which viewer a 3D output opens in, the haze cut-off each model starts with, when
+ * the orbit video stays instead, the demo splats (parsed by Spark itself), and that only the splat viewer's
+ * dynamic import brings Spark in.
+ */
+
+const samples = path.join(process.cwd(), "public", "samples");
+
+describe("which viewer draws a 3D output", () => {
+ it("a splat file goes to the splat viewer, a GLB to model-viewer", () => {
+ expect(viewerFor({ url: "/api/files/g/a.spz", kind: "model3d" })).toBe("splat");
+ expect(viewerFor({ url: "https://fal.test/x/splat.ply?sig=1", kind: "model3d" })).toBe("splat");
+ expect(viewerFor({ url: "/api/files/g/a.bin", kind: "model3d", meta: { format: "ksplat" } })).toBe("splat");
+ expect(viewerFor({ url: "/api/files/g/a.glb", kind: "model3d" })).toBe("glb");
+ // The demo GLB marked as a splat (older demo results) stays a GLB.
+ expect(viewerFor({ url: "sample:demo-model.glb", kind: "model3d", meta: { format: "glb", splat: true } })).toBe("glb");
+ expect(viewerFor({ url: "/api/files/g/a.png", kind: "image" })).toBeUndefined();
+ expect(viewerFor(undefined)).toBeUndefined();
+ });
+
+ it("the demo splats read as splats on the card", () => {
+ expect(splatFormatOf({ url: "/api/files/outputs/x.spz", meta: { format: "spz" } })).toBe("spz");
+ const view = model3dView({
+ outputs: [
+ { url: "/api/files/g/demo.spz", kind: "model3d", meta: { demo: true, format: "spz", role: "splat" } },
+ { url: "/api/files/g/orbit.mp4", kind: "video", meta: { turntable: true } },
+ ],
+ request: { feature: "image-to-3d", modelId: "oss-triposplat", op: "splat" },
+ } as never);
+ expect(view).toMatchObject({ glb: undefined, splat: { url: "/api/files/g/demo.spz", format: "spz" }, turntable: "/api/files/g/orbit.mp4" });
+ });
+});
+
+describe("the haze cut-off a result starts with", () => {
+ it("Idol 3D hides Gaussians under 0.05 on both engines; TripoSplat and others draw them all", () => {
+ expect(hazeCutoffFor(IDOL_MODELS.open)).toBe(0.05);
+ expect(hazeCutoffFor(IDOL_MODELS.cloud)).toBe(0.05);
+ expect(hazeCutoffFor("oss-triposplat")).toBe(0);
+ expect(hazeCutoffFor("triposplat")).toBe(0);
+ expect(hazeCutoffFor(undefined)).toBe(0);
+ });
+});
+
+describe("when the orbit video stays instead of the viewer", () => {
+ it("no WebGL2, a file too big for the device, reduced motion until asked", () => {
+ expect(splatFallback({ webgl2: true, coarse: false, reducedMotion: false })).toBeNull();
+ expect(splatFallback({ webgl2: false, coarse: false, reducedMotion: false })).toBe("no-webgl2");
+ expect(splatFallback({ webgl2: true, coarse: true, reducedMotion: false, bytes: SPLAT_MAX_BYTES.coarse + 1 })).toBe("too-big");
+ expect(splatFallback({ webgl2: true, coarse: false, reducedMotion: false, bytes: SPLAT_MAX_BYTES.coarse + 1 })).toBeNull();
+ expect(splatFallback({ webgl2: true, coarse: false, reducedMotion: true })).toBe("reduced-motion");
+ expect(splatFallback({ webgl2: true, coarse: false, reducedMotion: true, asked: true })).toBeNull();
+ expect(FALLBACK_TEXT["no-webgl2"]).toMatch(/Download/);
+ });
+
+ it("a 262,144-Gaussian .ply opens on a phone; a 1,048,576-Gaussian one only on a computer", () => {
+ const ply = (n: number) => n * 68 + 1000;
+ expect(splatTooBig(ply(262_144), true)).toBe(false);
+ expect(splatTooBig(ply(1_048_576), true)).toBe(true);
+ expect(splatTooBig(ply(1_048_576), false)).toBe(false);
+ expect(splatTooBig(undefined, true)).toBe(false);
+ });
+
+ it("a still is saved under the model's name", () => {
+ expect(stillFileName("Idol 3D")).toBe("Idol 3D still.png");
+ expect(stillFileName("<>")).toBe("splat still.png");
+ });
+});
+
+describe("the demo splats", () => {
+ const ply = fs.readFileSync(path.join(samples, "demo-splat.ply"));
+ const spz = fs.readFileSync(path.join(samples, "demo-splat.spz"));
+
+ it("are a standard 3DGS .ply (17 floats per Gaussian, as Idol writes) and a gzipped .spz v2", () => {
+ const header = ply.subarray(0, ply.indexOf("end_header\n") + 11).toString("ascii");
+ expect(header).toMatch(/^ply\nformat binary_little_endian 1\.0\nelement vertex 4096\n/);
+ expect(header.match(/^property float /gm)).toHaveLength(17);
+ expect(ply.length).toBe(header.length + 4096 * 17 * 4);
+ const raw = zlib.gunzipSync(spz);
+ expect(raw.readUInt32LE(0)).toBe(0x5053474e);
+ expect(raw.readUInt32LE(4)).toBe(2);
+ expect(raw.readUInt32LE(8)).toBe(4096);
+ // Small enough for the repo: under 300 KB and 60 KB.
+ expect(ply.length).toBeLessThan(300_000);
+ expect(spz.length).toBeLessThan(60_000);
+ });
+
+ it("Spark reads both, and a 0.05 cut-off leaves the 2,816 solid Gaussians of 4,096", async () => {
+ const spark = await import("@sparkjsdev/spark");
+ expect(spark.getSplatFileType(new Uint8Array(ply))).toBe("ply");
+ expect(spark.getSplatFileType(new Uint8Array(spz))).toBe("spz");
+ for (const [bytes, fileType] of [
+ [ply, spark.SplatFileType.PLY],
+ [spz, spark.SplatFileType.SPZ],
+ ] as const) {
+ for (const [threshold, count] of [
+ [undefined, 4096],
+ [0.05, 2816],
+ ] as const) {
+ const { fileBytes } = await spark.transcodeSpz({ inputs: [{ fileBytes: new Uint8Array(bytes), fileType }], opacityThreshold: threshold });
+ expect(zlib.gunzipSync(Buffer.from(fileBytes)).readUInt32LE(8), `${fileType} ${threshold}`).toBe(count);
+ }
+ }
+ }, 30_000);
+});
+
+describe("Spark loads only with the splat viewer", () => {
+ const files = (dir: string): string[] =>
+ fs.readdirSync(dir, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? files(path.join(dir, d.name)) : /\.(ts|tsx)$/.test(d.name) ? [path.join(dir, d.name)] : []));
+ const src = files(path.join(process.cwd(), "src"));
+
+ it("only splat-engine.ts imports it, and only through a dynamic import", () => {
+ const importers = src.filter((f) => fs.readFileSync(f, "utf8").includes("@sparkjsdev/spark"));
+ expect(importers.map((f) => path.relative(process.cwd(), f))).toEqual(["src/components/model3d/splat-engine.ts"]);
+ const engineUsers = src.filter((f) => /["']\.\/splat-engine["']|model3d\/splat-engine["']/.test(fs.readFileSync(f, "utf8")));
+ for (const f of engineUsers) {
+ const text = fs.readFileSync(f, "utf8");
+ // Type imports vanish from the bundle; anything else must be import("./splat-engine").
+ expect(text.replace(/import type [^;]+;/g, "").replace(/import\("\.\/splat-engine"\)/g, ""), path.relative(process.cwd(), f)).not.toMatch(/splat-engine/);
+ }
+ expect(engineUsers.map((f) => path.relative(process.cwd(), f))).toEqual(["src/components/model3d/splat-viewer.tsx"]);
+ });
+});