Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Add forge studio lab, update deps and clean up scripts

nirholasf4d6c2ce83a0
diff --git a/package-lock.json b/package-lock.json
index e83e96a34..fe96e600d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -60,6 +60,7 @@
"@metaplex-foundation/mpl-core": "^1.10.0",
"@metaplex-foundation/umi": "^1.5.1",
"@metaplex-foundation/umi-bundle-defaults": "^1.5.1",
+ "@mkkellogg/gaussian-splats-3d": "^0.4.7",
"@modelcontextprotocol/sdk": "^1.29.0",
"@neondatabase/serverless": "^0.10.1",
"@neynar/nodejs-sdk": "^3.176.0",
@@ -13038,6 +13039,15 @@
"@solana/web3.js": "^1.72.0"
}
},
+ "node_modules/@mkkellogg/gaussian-splats-3d": {
+ "version": "0.4.7",
+ "resolved": "https://registry.npmjs.org/@mkkellogg/gaussian-splats-3d/-/gaussian-splats-3d-0.4.7.tgz",
+ "integrity": "sha512-0vy9/i9sJLFH/v3WJZ4axCsqjkToe8UsV3xY7bvK5EUC0akiRsWZODoCiSzpxhTLNyzSKTsyQKozIFeNA5RWRA==",
+ "license": "MIT",
+ "peerDependencies": {
+ "three": ">=0.160.0"
+ }
+ },
"node_modules/@modelcontextprotocol/ext-apps": {
"version": "1.7.4",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-1.7.4.tgz",
@@ -54719,6 +54729,9 @@
"bin": {
"tour-build-curriculum": "bin/tour-build-curriculum.mjs"
},
+ "devDependencies": {
+ "esbuild": "^0.27.7"
+ },
"engines": {
"node": ">=18"
},
diff --git a/package.json b/package.json
index b53471798..b82e82b6c 100644
--- a/package.json
+++ b/package.json
@@ -203,6 +203,7 @@
"@metaplex-foundation/mpl-core": "^1.10.0",
"@metaplex-foundation/umi": "^1.5.1",
"@metaplex-foundation/umi-bundle-defaults": "^1.5.1",
+ "@mkkellogg/gaussian-splats-3d": "^0.4.7",
"@modelcontextprotocol/sdk": "^1.29.0",
"@neondatabase/serverless": "^0.10.1",
"@neynar/nodejs-sdk": "^3.176.0",
diff --git a/pages/forge-studio.html b/pages/forge-studio.html
index 4a11fe7ca..749797c86 100644
--- a/pages/forge-studio.html
+++ b/pages/forge-studio.html
@@ -2923,6 +2923,164 @@
#studio-avatar .btn-primary { justify-content: center; }
#studio-avatar .hint { text-align: center; }
}
+
+ /* ── Lab pane (free client-side 3D generators) ─────────────────────── */
+ #studio-lab {
+ --panel: #0a0a0a;
+ --panel-elev: #111111;
+ --border: #1a1a1a;
+ --border-strong: #2a2a2a;
+ --text: #e8e8e8;
+ --muted: #888888;
+ --accent: #ffffff;
+ --accent-ink: #000000;
+ }
+ #studio-lab .lab {
+ display: grid;
+ grid-template-columns: minmax(220px, 280px) 1fr;
+ gap: var(--space-lg, 20px);
+ align-items: start;
+ max-width: 1180px;
+ margin: 8px auto 0;
+ }
+ #studio-lab .lab-tools { display: flex; flex-direction: column; gap: 8px; }
+ #studio-lab .lab-tool {
+ text-align: left;
+ border: 1px solid var(--border-strong);
+ background: var(--panel);
+ color: var(--text);
+ border-radius: 12px;
+ padding: 12px 14px;
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ transition: border-color 0.15s, background 0.15s, transform 0.12s;
+ }
+ #studio-lab .lab-tool:hover { border-color: #444; background: var(--panel-elev); }
+ #studio-lab .lab-tool:active { transform: translateY(1px); }
+ #studio-lab .lab-tool:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ #studio-lab .lab-tool[aria-pressed='true'] { border-color: var(--accent); background: var(--panel-elev); }
+ #studio-lab .lab-tool-name { font-weight: 600; font-size: 14.5px; }
+ #studio-lab .lab-tool-blurb { font-size: 12px; color: var(--muted); line-height: 1.4; }
+ #studio-lab .lab-stage { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
+ #studio-lab .lab-controls {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 14px;
+ border: 1px solid var(--border-strong);
+ border-radius: 14px;
+ background: var(--panel);
+ padding: 16px;
+ }
+ #studio-lab .lab-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
+ #studio-lab .lab-field[hidden] { display: none; }
+ #studio-lab .lab-field-label {
+ font-size: 12.5px;
+ color: var(--muted);
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ align-items: baseline;
+ }
+ #studio-lab .lab-field-out { font-size: 11.5px; color: #666; font-variant-numeric: tabular-nums; }
+ #studio-lab .lab-field input[type='range'] { width: 100%; accent-color: var(--accent); }
+ #studio-lab .lab-field input[type='color'] {
+ width: 100%;
+ height: 36px;
+ padding: 2px;
+ border: 1px solid var(--border-strong);
+ border-radius: 10px;
+ background: var(--panel-elev);
+ cursor: pointer;
+ }
+ #studio-lab .lab-field input[type='text'],
+ #studio-lab .lab-field select,
+ #studio-lab .lab-field textarea,
+ #studio-lab .lab-field input[type='file'] {
+ width: 100%;
+ border: 1px solid var(--border-strong);
+ background: var(--panel-elev);
+ color: var(--text);
+ border-radius: 10px;
+ padding: 9px 11px;
+ font: inherit;
+ font-size: 13px;
+ outline: none;
+ }
+ #studio-lab .lab-field textarea { resize: vertical; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; line-height: 1.5; }
+ #studio-lab .lab-field input:focus-visible,
+ #studio-lab .lab-field select:focus-visible,
+ #studio-lab .lab-field textarea:focus-visible { border-color: var(--accent); }
+ #studio-lab .lab-field-check { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text); cursor: pointer; }
+ #studio-lab .lab-field-check input { width: 16px; height: 16px; accent-color: var(--accent); }
+ #studio-lab .lab-preview {
+ position: relative;
+ width: 100%;
+ aspect-ratio: 16 / 10;
+ border: 1px solid var(--border-strong);
+ border-radius: 16px;
+ background: radial-gradient(circle at 50% 35%, #15151c, #060608 75%);
+ overflow: hidden;
+ }
+ #studio-lab .lab-preview model-viewer,
+ #studio-lab .lab-splat {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ }
+ #studio-lab .lab-splat { cursor: grab; }
+ #studio-lab .lab-splat[hidden] { display: none; }
+ #studio-lab model-viewer[hidden] { display: none; }
+ #studio-lab .lab-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
+ #studio-lab .btn-primary {
+ display: inline-flex;
+ align-items: center;
+ gap: 9px;
+ background: var(--accent);
+ color: var(--accent-ink);
+ border: 0;
+ border-radius: 12px;
+ padding: 12px 22px;
+ font-size: 15px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: opacity 0.15s, transform 0.12s;
+ }
+ #studio-lab .btn-primary:hover { opacity: 0.9; }
+ #studio-lab .btn-primary:active { transform: translateY(1px); }
+ #studio-lab .btn-primary:disabled { opacity: 0.45; cursor: progress; }
+ #studio-lab .btn-primary:focus-visible { outline: 2px solid #fff; outline-offset: 3px; }
+ #studio-lab .btn-ghost {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ background: var(--panel);
+ color: var(--text);
+ border: 1px solid var(--border-strong);
+ border-radius: 12px;
+ padding: 11px 18px;
+ font-size: 14px;
+ font-weight: 500;
+ cursor: pointer;
+ text-decoration: none;
+ transition: border-color 0.15s, background 0.15s, transform 0.12s, opacity 0.15s;
+ }
+ #studio-lab .btn-ghost:hover { border-color: #444; background: var(--panel-elev); }
+ #studio-lab .btn-ghost.is-disabled { opacity: 0.4; pointer-events: none; }
+ #studio-lab .btn-ghost.is-hidden { display: none; }
+ #studio-lab .lab-status { font-size: 13px; color: var(--muted); }
+ #studio-lab .lab-status[data-kind='ok'] { color: #6ee7a8; }
+ #studio-lab .lab-status[data-kind='err'] { color: #f3b4b4; }
+ #studio-lab .lab-foot { font-size: 12px; color: #666; margin: 0; max-width: 70ch; }
+ #studio-lab .lab-foot a { color: #aaa; text-decoration: underline; text-underline-offset: 2px; }
+ #studio-lab .lab-foot a:hover { color: var(--text); }
+ @media (max-width: 760px) {
+ #studio-lab .lab { grid-template-columns: 1fr; }
+ #studio-lab .lab-tools { flex-direction: row; flex-wrap: wrap; }
+ #studio-lab .lab-tool { flex: 1 1 140px; }
+ }
</style>
<link rel="canonical" href="https://three.ws/forge-studio">
@@ -2961,6 +3119,16 @@
>
<span class="dot" aria-hidden="true"></span>Avatar
</button>
+ <button
+ type="button"
+ role="tab"
+ id="studio-tab-lab"
+ data-studio-mode="lab"
+ aria-selected="false"
+ aria-controls="studio-lab"
+ >
+ <span class="dot" aria-hidden="true"></span>Lab
+ </button>
</div>
</header>
@@ -3759,6 +3927,48 @@
</div>
</section>
</section><!-- /#studio-avatar -->
+
+ <section id="studio-lab" class="studio-pane" role="tabpanel" aria-labelledby="studio-tab-lab" hidden>
+ <div class="lab">
+ <aside class="lab-tools" id="lab-tools" aria-label="3D tools"></aside>
+ <div class="lab-stage">
+ <div class="lab-controls" id="lab-controls"></div>
+ <div class="lab-preview">
+ <model-viewer
+ id="lab-viewer"
+ camera-controls
+ auto-rotate
+ rotation-per-second="18deg"
+ interaction-prompt="none"
+ shadow-intensity="0.6"
+ shadow-softness="0.8"
+ environment-image="neutral"
+ exposure="1.0"
+ loading="eager"
+ alt="Generated 3D model preview"
+ ></model-viewer>
+ <div id="lab-splat" class="lab-splat" hidden></div>
+ </div>
+ <div class="lab-actions">
+ <button class="btn-primary" id="lab-generate" type="button">Generate model</button>
+ <a class="btn-ghost is-disabled" id="lab-download" href="#" download>
+ Download GLB
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M12 3v12" /><polyline points="7 11 12 16 17 11" /><line x1="5" y1="20" x2="19" y2="20" />
+ </svg>
+ </a>
+ <span class="lab-status" id="lab-status" role="status" aria-live="polite"></span>
+ </div>
+ <p class="lab-foot">
+ Every Lab tool runs entirely in your browser — no API key, no upload, no cost.
+ Mesh tools export a real binary <strong>GLB</strong>; the Gaussian-splat viewer
+ renders the photoreal radiance-field format. Powered by
+ <a href="https://threejs.org" rel="noopener" target="_blank">three.js</a> and
+ <a href="https://github.com/mkkellogg/GaussianSplats3D" rel="noopener" target="_blank">GaussianSplats3D</a>.
+ </p>
+ </div>
+ </div>
+ </section><!-- /#studio-lab -->
</main>
<script src="/nav.js" defer></script>
@@ -3779,11 +3989,13 @@
// the Avatar pane (prompt → rigged avatar) lazy-inits its controller the
// first time it's shown so it never competes with Forge on load.
import { initCreatePrompt, focusPrompt } from '/src/forge-studio/create-prompt.js';
+ import { initLab } from '/src/forge-studio/lab/lab.js';
const tabs = Array.from(document.querySelectorAll('.studio-tabs [data-studio-mode]'));
const panes = {
object: document.getElementById('studio-object'),
avatar: document.getElementById('studio-avatar'),
+ lab: document.getElementById('studio-lab'),
};
function setMode(mode, { focus = false } = {}) {
@@ -3792,11 +4004,12 @@
const on = t.dataset.studioMode === mode;
t.setAttribute('aria-selected', on ? 'true' : 'false');
}
- panes.object.hidden = mode !== 'object';
- panes.avatar.hidden = mode !== 'avatar';
+ for (const [key, pane] of Object.entries(panes)) pane.hidden = key !== mode;
if (mode === 'avatar') {
initCreatePrompt();
if (focus) focusPrompt();
+ } else if (mode === 'lab') {
+ initLab();
}
const url = new URL(window.location.href);
if (mode === 'object') url.searchParams.delete('mode');
@@ -3808,9 +4021,9 @@
t.addEventListener('click', () => setMode(t.dataset.studioMode, { focus: true }));
}
- // Deep-link: /forge-studio?mode=avatar opens straight into the avatar pane.
+ // Deep-link: /forge-studio?mode=avatar|lab opens straight into that pane.
const initial = new URLSearchParams(window.location.search).get('mode');
- if (initial === 'avatar') setMode('avatar');
+ if (initial === 'avatar' || initial === 'lab') setMode(initial);
</script>
<div id="footer-container"></div>
<script src="/footer.js"></script>
diff --git a/scripts/club-diag.mjs b/scripts/club-diag.mjs
deleted file mode 100644
index e22952c89..000000000
--- a/scripts/club-diag.mjs
+++ /dev/null
@@ -1,99 +0,0 @@
-import { chromium } from 'playwright';
-
-const URL = process.env.CLUB_URL || 'http://localhost:3001/club';
-const SETTLE = Number(process.env.SETTLE || 12000);
-
-const browser = await chromium.launch({
- args: ['--no-sandbox', '--disable-dev-shm-usage', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--use-gl=angle', '--use-angle=swiftshader'],
-});
-const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
-await ctx.addInitScript(() => {
- const future = new Date(Date.now() + 12 * 3600 * 1000).toISOString();
- localStorage.setItem('club:pass:v1', JSON.stringify({ passId: 'dev', tier: 'regular', visits: 1, expiresAt: future, wallet: 'devwallet', issuedAt: new Date().toISOString() }));
-});
-const page = await ctx.newPage();
-const logs = [];
-page.on('console', (m) => logs.push(`[${m.type()}] ${m.text()}`));
-await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 45000 });
-await page.waitForTimeout(SETTLE);
-
-const diag = await page.evaluate(() => {
- const THREE = window.__THREE || null;
- const stations = window.__clubStations || [];
- function applyMat(m, x, y, z) {
- const e = m.elements;
- return {
- x: e[0] * x + e[4] * y + e[8] * z + e[12],
- y: e[1] * x + e[5] * y + e[9] * z + e[13],
- z: e[2] * x + e[6] * y + e[10] * z + e[14],
- };
- }
- function boxOf(obj) {
- try {
- obj.updateMatrixWorld(true);
- const min = { x: Infinity, y: Infinity, z: Infinity };
- const max = { x: -Infinity, y: -Infinity, z: -Infinity };
- let skinned = 0, meshes = 0;
- obj.traverse((n) => {
- if (n.isSkinnedMesh) skinned++;
- if (n.isMesh) meshes++;
- if (n.isMesh && n.geometry) {
- let bb;
- if (n.isSkinnedMesh && typeof n.computeBoundingBox === 'function') {
- n.skeleton?.update?.();
- n.computeBoundingBox();
- bb = n.boundingBox;
- } else {
- n.geometry.computeBoundingBox?.();
- bb = n.geometry.boundingBox;
- }
- if (!bb) return;
- for (const xi of [bb.min.x, bb.max.x]) for (const yi of [bb.min.y, bb.max.y]) for (const zi of [bb.min.z, bb.max.z]) {
- const w = applyMat(n.matrixWorld, xi, yi, zi);
- min.x = Math.min(min.x, w.x); min.y = Math.min(min.y, w.y); min.z = Math.min(min.z, w.z);
- max.x = Math.max(max.x, w.x); max.y = Math.max(max.y, w.y); max.z = Math.max(max.z, w.z);
- }
- }
- });
- const r = (v) => +v.toFixed(2);
- return {
- meshes, skinned,
- worldMin: { x: r(min.x), y: r(min.y), z: r(min.z) },
- worldMax: { x: r(max.x), y: r(max.y), z: r(max.z) },
- worldH: r(max.y - min.y), worldW: r(max.x - min.x),
- };
- } catch (e) { return { err: String(e) }; }
- }
- return stations.map((s) => {
- const rig = s.rig;
- const child = rig && rig.children && rig.children[0];
- const info = {
- idx: s.idx, id: s.id,
- walkPhase: s.walkPhase,
- rigPos: rig ? { x: +rig.position.x.toFixed(2), y: +rig.position.y.toFixed(2), z: +rig.position.z.toFixed(2) } : null,
- rigChildren: rig ? rig.children.length : -1,
- skinnedSet: !!s.skinned,
- child: child ? boxOf(child) : null,
- childScale: child ? { x: +child.scale.x.toFixed(3), y: +child.scale.y.toFixed(3), z: +child.scale.z.toFixed(3) } : null,
- childPosY: child ? +child.position.y.toFixed(3) : null,
- childVisible: child ? child.visible : null,
- hasAnim: !!s.anim,
- currentName: s.anim?.currentName ?? null,
- actions: s.anim ? [...s.anim.actions.keys()] : null,
- supportsCanonical: s.anim?.supportsCanonicalClips?.() ?? null,
- };
- // Force bind pose: stop the mixer, reset the skeleton to bind, re-measure.
- try {
- s.anim?.mixer?.stopAllAction();
- if (child) {
- child.traverse((n) => { if (n.isSkinnedMesh) { n.skeleton.pose(); n.skeleton.update(); } });
- info.bindBox = boxOf(child);
- }
- } catch (e) { info.bindErr = String(e); }
- return info;
- });
-});
-console.log(JSON.stringify(diag, null, 2));
-console.log('--- relevant logs ---');
-console.log(logs.filter((l) => /club|retarget|avatar|fallen|error|warn/i.test(l)).slice(0, 30).join('\n'));
-await browser.close();
diff --git a/scripts/club-shot.mjs b/scripts/club-shot.mjs
deleted file mode 100644
index 8205ebeb9..000000000
--- a/scripts/club-shot.mjs
+++ /dev/null
@@ -1,46 +0,0 @@
-import { chromium } from 'playwright';
-
-const URL = process.env.CLUB_URL || 'http://localhost:3001/club';
-const OUT = process.env.OUT || '/tmp/club.png';
-const SETTLE = Number(process.env.SETTLE || 9000);
-
-const browser = await chromium.launch({
- args: [
- '--no-sandbox',
- '--disable-dev-shm-usage',
- '--ignore-gpu-blocklist',
- '--enable-unsafe-swiftshader',
- '--use-gl=angle',
- '--use-angle=swiftshader',
- ],
-});
-const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 }, deviceScaleFactor: 1 });
-await ctx.addInitScript(() => {
- const future = new Date(Date.now() + 12 * 3600 * 1000).toISOString();
- localStorage.setItem('club:pass:v1', JSON.stringify({
- passId: 'dev', tier: 'regular', visits: 1,
- expiresAt: future, wallet: 'devwallet', issuedAt: new Date().toISOString(),
- }));
-});
-const page = await ctx.newPage();
-const errors = [];
-page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') errors.push(`[${m.type()}] ${m.text()}`); });
-page.on('pageerror', (e) => errors.push(`[pageerror] ${e.message}`));
-await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 45000 });
-await page.waitForTimeout(SETTLE);
-const state = await page.evaluate(() => (window.__clubStations || []).map((s) => ({
- idx: s.idx, id: s.id,
- curr: s.anim?.currentName ?? null,
- clips: s.anim ? [...(s.anim.clips?.keys?.() || [])] : null,
- actions: s.anim ? [...s.anim.actions.keys()] : null,
- fallen: s.anim?._fallen ? [...s.anim._fallen] : null,
- failed: s.anim?._failed ? [...s.anim._failed] : null,
- idleWeight: (() => { const a = s.anim?.actions?.get('idle'); return a ? +a.getEffectiveWeight().toFixed(2) : null; })(),
- mixerTime: s.anim?.mixer?.time ?? null,
-})));
-console.log('STATE', JSON.stringify(state));
-await page.screenshot({ path: OUT, timeout: 90000, animations: 'disabled' });
-console.log('saved', OUT);
-console.log('--- console errors/warnings ---');
-console.log(errors.slice(0, 40).join('\n'));
-await browser.close();
diff --git a/src/forge-studio/lab/generators.js b/src/forge-studio/lab/generators.js
new file mode 100644
index 000000000..ddece1e95
--- /dev/null
+++ b/src/forge-studio/lab/generators.js
@@ -0,0 +1,379 @@
+/**
+ * Studio Lab — free, client-side 3D generators.
+ *
+ * Every generator is pure three.js (npm `three` + its github `examples/jsm`
+ * addons) and returns a `THREE.Object3D`. The Lab controller (lab.js) exports
+ * whatever they return to a real binary GLB, so each one is a genuine
+ * text/parameters → downloadable 3D model pipeline — no API keys, no network.
+ *
+ * Adding a generator: export a `{ id, label, blurb, controls, build }` object
+ * and register it in GENERATORS at the bottom. `controls` is a declarative
+ * field list the Lab renders; `build(params)` returns an Object3D (or a promise).
+ */
+
+import * as THREE from 'three';
+import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
+import { FontLoader } from 'three/addons/loaders/FontLoader.js';
+import { SVGLoader } from 'three/addons/loaders/SVGLoader.js';
+import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
+import helvetikerBold from 'three/examples/fonts/helvetiker_bold.typeface.json';
+
+// ── Shared helpers ────────────────────────────────────────────────────────────
+
+const _fontCache = new Map();
+function getFont() {
+ if (!_fontCache.has('helvetiker')) {
+ _fontCache.set('helvetiker', new FontLoader().parse(helvetikerBold));
+ }
+ return _fontCache.get('helvetiker');
+}
+
+function standardMesh(geometry, color, opts = {}) {
+ geometry.computeVertexNormals();
+ const mat = new THREE.MeshStandardMaterial({
+ color: new THREE.Color(color),
+ metalness: opts.metalness ?? 0.1,
+ roughness: opts.roughness ?? 0.55,
+ flatShading: !!opts.flatShading,
+ vertexColors: !!opts.vertexColors,
+ side: opts.side ?? THREE.FrontSide,
+ });
+ return new THREE.Mesh(geometry, mat);
+}
+
+// Deterministic value noise (no deps) for terrain — seeded so the same seed
+// always rebuilds the same model.
+function makeNoise(seed) {
+ const perm = new Uint8Array(512);
+ let s = (seed * 1013904223 + 1664525) >>> 0;
+ const rnd = () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296);
+ const p = Array.from({ length: 256 }, (_, i) => i);
+ for (let i = 255; i > 0; i--) {
+ const j = Math.floor(rnd() * (i + 1));
+ [p[i], p[j]] = [p[j], p[i]];
+ }
+ for (let i = 0; i < 512; i++) perm[i] = p[i & 255];
+ const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
+ const lerp = (a, b, t) => a + t * (b - a);
+ const grad = (h, x, y) => ((h & 1) ? -x : x) + ((h & 2) ? -y : y);
+ return (x, y) => {
+ const X = Math.floor(x) & 255;
+ const Y = Math.floor(y) & 255;
+ const xf = x - Math.floor(x);
+ const yf = y - Math.floor(y);
+ const u = fade(xf);
+ const v = fade(yf);
+ const aa = perm[perm[X] + Y];
+ const ab = perm[perm[X] + Y + 1];
+ const ba = perm[perm[X + 1] + Y];
+ const bb = perm[perm[X + 1] + Y + 1];
+ const x1 = lerp(grad(aa, xf, yf), grad(ba, xf - 1, yf), u);
+ const x2 = lerp(grad(ab, xf, yf - 1), grad(bb, xf - 1, yf - 1), u);
+ return (lerp(x1, x2, v) + 1) / 2; // 0..1
+ };
+}
+
+// ── 1. Parametric solids (superformula + presets) ─────────────────────────────
+
+const PARAMETRIC_PRESETS = {
+ knot: { geo: () => new THREE.TorusKnotGeometry(1, 0.32, 220, 32, 2, 3) },
+ torus: { geo: () => new THREE.TorusGeometry(1, 0.4, 48, 120) },
+ spring: {
+ geo: () => {
+ const pts = [];
+ const turns = 5;
+ const steps = 600;
+ for (let i = 0; i <= steps; i++) {
+ const t = (i / steps) * Math.PI * 2 * turns;
+ pts.push(new THREE.Vector3(Math.cos(t) * 0.9, (i / steps) * 2.4 - 1.2, Math.sin(t) * 0.9));
+ }
+ return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 600, 0.16, 16, false);
+ },
+ },
+ capsule: { geo: () => new THREE.CapsuleGeometry(0.7, 1.2, 24, 48) },
+ icosa: { geo: () => new THREE.IcosahedronGeometry(1.2, 1) },
+};
+
+function superformulaGeometry(m, n1, n2, n3, segments) {
+ // 3D supershape: two superformula profiles (lat × lon) swept onto a sphere.
+ const sf = (angle) => {
+ const t1 = Math.pow(Math.abs(Math.cos((m * angle) / 4)), n2);
+ const t2 = Math.pow(Math.abs(Math.sin((m * angle) / 4)), n3);
+ const r = Math.pow(t1 + t2, -1 / n1);
+ return Number.isFinite(r) ? r : 0;
+ };
+ const lonSteps = segments;
+ const latSteps = Math.max(8, Math.floor(segments / 2));
+ const positions = [];
+ const grid = [];
+ for (let i = 0; i <= latSteps; i++) {
+ const lat = -Math.PI / 2 + (i / latSteps) * Math.PI;
+ const r2 = sf(lat);
+ const row = [];
+ for (let j = 0; j <= lonSteps; j++) {
+ const lon = -Math.PI + (j / lonSteps) * 2 * Math.PI;
+ const r1 = sf(lon);
+ const x = r1 * Math.cos(lon) * r2 * Math.cos(lat);
+ const y = r1 * Math.sin(lon) * r2 * Math.cos(lat);
+ const z = r2 * Math.sin(lat);
+ row.push(positions.length / 3);
+ positions.push(x, z, y);
+ }
+ grid.push(row);
+ }
+ const indices = [];
+ for (let i = 0; i < latSteps; i++) {
+ for (let j = 0; j < lonSteps; j++) {
+ const a = grid[i][j];
+ const b = grid[i][j + 1];
+ const c = grid[i + 1][j];
+ const d = grid[i + 1][j + 1];
+ indices.push(a, b, d, a, d, c);
+ }
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ geo.setIndex(indices);
+ geo.scale(1.4, 1.4, 1.4);
+ return geo;
+}
+
+const parametric = {
+ id: 'parametric',
+ label: 'Parametric',
+ blurb: 'Math-driven solids — supershapes, knots, springs. Pure geometry, infinitely tweakable.',
+ controls: [
+ {
+ key: 'preset',
+ label: 'Shape',
+ type: 'select',
+ default: 'supershape',
+ options: [
+ { value: 'supershape', label: 'Supershape' },
+ { value: 'knot', label: 'Torus knot' },
+ { value: 'torus', label: 'Torus' },
+ { value: 'spring', label: 'Spring' },
+ { value: 'capsule', label: 'Capsule' },
+ { value: 'icosa', label: 'Icosahedron' },
+ ],
+ },
+ { key: 'm', label: 'Symmetry (m)', type: 'range', min: 1, max: 20, step: 1, default: 7, when: { preset: 'supershape' } },
+ { key: 'n1', label: 'Roundness (n1)', type: 'range', min: 0.2, max: 4, step: 0.1, default: 0.4, when: { preset: 'supershape' } },
+ { key: 'detail', label: 'Detail', type: 'range', min: 24, max: 220, step: 4, default: 140, when: { preset: 'supershape' } },
+ { key: 'color', label: 'Color', type: 'color', default: '#b8c0ff' },
+ ],
+ build(p) {
+ let geo;
+ if (p.preset === 'supershape') {
+ geo = superformulaGeometry(Number(p.m), Number(p.n1), 1.7, 1.7, Number(p.detail));
+ } else {
+ geo = PARAMETRIC_PRESETS[p.preset].geo();
+ }
+ return standardMesh(geo, p.color || '#b8c0ff', { metalness: 0.25, roughness: 0.4 });
+ },
+};
+
+// ── 2. 3D Text ────────────────────────────────────────────────────────────────
+
+const text3d = {
+ id: 'text3d',
+ label: '3D Text',
+ blurb: 'Extruded, beveled 3D lettering from any string. Export and drop into a scene or logo.',
+ controls: [
+ { key: 'text', label: 'Text', type: 'text', default: 'three.ws', maxlength: 24, placeholder: 'Your text' },
+ { key: 'depth', label: 'Depth', type: 'range', min: 0.05, max: 1, step: 0.05, default: 0.3 },
+ { key: 'bevel', label: 'Bevel', type: 'range', min: 0, max: 0.1, step: 0.01, default: 0.03 },
+ { key: 'color', label: 'Color', type: 'color', default: '#ffd166' },
+ ],
+ build(p) {
+ const str = (p.text || 'three.ws').slice(0, 24) || 'three.ws';
+ const geo = new TextGeometry(str, {
+ font: getFont(),
+ size: 1,
+ depth: Number(p.depth),
+ curveSegments: 8,
+ bevelEnabled: Number(p.bevel) > 0,
+ bevelThickness: Number(p.bevel),
+ bevelSize: Number(p.bevel) * 0.7,
+ bevelSegments: 3,
+ });
+ geo.center();
+ return standardMesh(geo, p.color || '#ffd166', { metalness: 0.3, roughness: 0.35 });
+ },
+};
+
+// ── 3. SVG → 3D (extrude vector art) ──────────────────────────────────────────
+
+const DEFAULT_SVG = `<svg viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 21 12 17.77 5.82 21 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>`;
+
+const svg3d = {
+ id: 'svg3d',
+ label: 'SVG → 3D',
+ blurb: 'Turn any SVG path — an icon, a logo, a sketch — into a solid extruded 3D model.',
+ controls: [
+ { key: 'svg', label: 'SVG markup', type: 'textarea', default: DEFAULT_SVG, placeholder: 'Paste <svg>…</svg>' },
+ { key: 'depth', label: 'Depth', type: 'range', min: 0.5, max: 12, step: 0.5, default: 4 },
+ { key: 'color', label: 'Color', type: 'color', default: '#8be9fd' },
+ ],
+ build(p) {
+ const markup = (p.svg && p.svg.trim()) || DEFAULT_SVG;
+ const data = new SVGLoader().parse(markup);
+ const geometries = [];
+ for (const path of data.paths) {
+ const shapes = SVGLoader.createShapes(path);
+ for (const shape of shapes) {
+ const g = new THREE.ExtrudeGeometry(shape, {
+ depth: Number(p.depth),
+ bevelEnabled: true,
+ bevelThickness: Number(p.depth) * 0.08,
+ bevelSize: Number(p.depth) * 0.06,
+ bevelSegments: 2,
+ curveSegments: 12,
+ });
+ geometries.push(g);
+ }
+ }
+ if (!geometries.length) throw new Error('No drawable paths found in that SVG.');
+ const merged = BufferGeometryUtils.mergeGeometries(geometries, false);
+ // SVG Y grows downward; flip and center so it stands upright.
+ merged.scale(1, -1, 1);
+ merged.computeBoundingBox();
+ const c = merged.boundingBox.getCenter(new THREE.Vector3());
+ merged.translate(-c.x, -c.y, -c.z);
+ const s = 2.6 / Math.max(merged.boundingBox.max.x - merged.boundingBox.min.x, merged.boundingBox.max.y - merged.boundingBox.min.y, 0.001);
+ merged.scale(s, s, s);
+ return standardMesh(merged, p.color || '#8be9fd', { metalness: 0.15, roughness: 0.5, side: THREE.DoubleSide });
+ },
+};
+
+// ── 4. Lithophane (image → 3D relief) ─────────────────────────────────────────
+
+const lithophane = {
+ id: 'lithophane',
+ label: 'Lithophane',
+ blurb: 'Drop a photo — its brightness becomes 3D relief. The classic backlit-panel print, generated in your browser.',
+ controls: [
+ { key: 'image', label: 'Image', type: 'image', default: null },
+ { key: 'relief', label: 'Relief depth', type: 'range', min: 0.1, max: 2, step: 0.1, default: 0.8 },
+ { key: 'res', label: 'Resolution', type: 'range', min: 64, max: 256, step: 16, default: 160 },
+ { key: 'invert', label: 'Invert (light = deep)', type: 'checkbox', default: false },
+ ],
+ async build(p) {
+ const img = await loadImage(p.image || PLACEHOLDER_IMG);
+ const res = Number(p.res);
+ const aspect = img.width / img.height || 1;
+ const cols = aspect >= 1 ? res : Math.round(res * aspect);
+ const rows = aspect >= 1 ? Math.round(res / aspect) : res;
+ const canvas = document.createElement('canvas');
+ canvas.width = cols;
+ canvas.height = rows;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ ctx.drawImage(img, 0, 0, cols, rows);
+ const { data } = ctx.getImageData(0, 0, cols, rows);
+ const lum = new Float32Array(cols * rows);
+ for (let i = 0; i < cols * rows; i++) {
+ const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];
+ let l = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+ if (p.invert) l = 1 - l;
+ lum[i] = l;
+ }
+ const w = 3 * (cols / Math.max(cols, rows));
+ const h = 3 * (rows / Math.max(cols, rows));
+ const geo = new THREE.PlaneGeometry(w, h, cols - 1, rows - 1);
+ const pos = geo.attributes.position;
+ const relief = Number(p.relief);
+ for (let i = 0; i < pos.count; i++) {
+ // PlaneGeometry verts run left→right, top→bottom.
+ const col = i % cols;
+ const row = Math.floor(i / cols);
+ const l = lum[row * cols + col] ?? 0;
+ pos.setZ(i, (1 - l) * relief);
+ }
+ geo.computeVertexNormals();
+ return standardMesh(geo, '#f5f5f5', { metalness: 0, roughness: 0.85, side: THREE.DoubleSide });
+ },
+};
+
+// ── 5. Terrain (procedural noise heightfield) ─────────────────────────────────
+
+const terrain = {
+ id: 'terrain',
+ label: 'Terrain',
+ blurb: 'Procedural landscape from layered value noise, colored by elevation. New seed, new world.',
+ controls: [
+ { key: 'seed', label: 'Seed', type: 'range', min: 1, max: 999, step: 1, default: 42 },
+ { key: 'height', label: 'Height', type: 'range', min: 0.3, max: 3, step: 0.1, default: 1.4 },
+ { key: 'roughness', label: 'Roughness', type: 'range', min: 1, max: 8, step: 0.5, default: 4 },
+ { key: 'res', label: 'Resolution', type: 'range', min: 48, max: 220, step: 4, default: 140 },
+ ],
+ build(p) {
+ const seg = Number(p.res);
+ const size = 4;
+ const geo = new THREE.PlaneGeometry(size, size, seg, seg);
+ geo.rotateX(-Math.PI / 2);
+ const noise = makeNoise(Number(p.seed));
+ const pos = geo.attributes.position;
+ const colors = new Float32Array(pos.count * 3);
+ const H = Number(p.height);
+ const freq = Number(p.roughness) / size;
+ const low = new THREE.Color('#2c5364');
+ const mid = new THREE.Color('#4e944f');
+ const high = new THREE.Color('#e8e8e8');
+ let maxE = 0.0001;
+ const elev = new Float32Array(pos.count);
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i);
+ const z = pos.getZ(i);
+ let e = 0, amp = 1, f = freq;
+ for (let o = 0; o < 4; o++) {
+ e += noise(x * f + 100, z * f + 100) * amp;
+ amp *= 0.5;
+ f *= 2;
+ }
+ elev[i] = e;
+ if (e > maxE) maxE = e;
+ }
+ for (let i = 0; i < pos.count; i++) {
+ const n = elev[i] / maxE;
+ pos.setY(i, n * H - H * 0.3);
+ const c = n < 0.45 ? low.clone().lerp(mid, n / 0.45) : mid.clone().lerp(high, (n - 0.45) / 0.55);
+ colors[i * 3] = c.r;
+ colors[i * 3 + 1] = c.g;
+ colors[i * 3 + 2] = c.b;
+ }
+ geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
+ geo.computeVertexNormals();
+ return standardMesh(geo, '#ffffff', { vertexColors: true, roughness: 0.9, metalness: 0, flatShading: false });
+ },
+};
+
+// 1×1 transparent-ish gray PNG used when Lithophane has no upload yet (so the
+// feature always produces a real model on first click — a soft radial gradient).
+const PLACEHOLDER_IMG = (() => {
+ const c = document.createElement('canvas');
+ c.width = c.height = 256;
+ const g = c.getContext('2d');
+ const grad = g.createRadialGradient(128, 110, 20, 128, 128, 150);
+ grad.addColorStop(0, '#ffffff');
+ grad.addColorStop(0.5, '#9aa');
+ grad.addColorStop(1, '#111');
+ g.fillStyle = grad;
+ g.fillRect(0, 0, 256, 256);
+ g.fillStyle = '#000';
+ g.font = 'bold 64px sans-serif';
+ g.textAlign = 'center';
+ g.fillText('3D', 128, 150);
+ return c.toDataURL('image/png');
+})();
+
+function loadImage(src) {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.crossOrigin = 'anonymous';
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error('Could not read that image.'));
+ img.src = src;
+ });
+}
+
+export const GENERATORS = [parametric, text3d, svg3d, lithophane, terrain];
diff --git a/src/forge-studio/lab/lab.js b/src/forge-studio/lab/lab.js
new file mode 100644
index 000000000..ecbb433e6
--- /dev/null
+++ b/src/forge-studio/lab/lab.js
@@ -0,0 +1,350 @@
+/**
+ * Studio Lab controller — the "every type of 3D" tab.
+ *
+ * Hosts a set of free, client-side 3D tools:
+ * - Five mesh generators (parametric, 3D text, SVG→3D, lithophane, terrain)
+ * from npm `three` + its github examples/jsm addons. Each builds a real
+ * THREE.Object3D, which we export to a binary GLB (GLTFExporter) and preview
+ * in <model-viewer> with a working Download GLB button.
+ * - A Gaussian-splat / radiance-field viewer from the npm package
+ * `@mkkellogg/gaussian-splats-3d` — a 3D representation the platform didn't
+ * have. Loads a .splat/.ply (or a generated sample) into its own renderer.
+ *
+ * Nothing here calls a paid API or the network; every model is computed in the
+ * browser, so it is fully self-contained and testable.
+ */
+
+import * as THREE from 'three';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import { GENERATORS } from './generators.js';
+
+let _inited = false;
+let _activeId = null;
+let _lastGlbUrl = null;
+let _splat = null; // lazy { viewer, dispose }
+
+const SPLAT_TOOL = {
+ id: 'splat',
+ label: 'Gaussian Splats',
+ blurb: 'View a Gaussian-splat / radiance-field capture (.splat or .ply) — the photoreal 3D format. Drop a file, or render the built-in sample.',
+ kind: 'splat',
+ controls: [
+ { key: 'file', label: 'Splat file (.splat / .ply / .ksplat)', type: 'splatfile', default: null },
+ ],
+};
+
+const TOOLS = [...GENERATORS.map((g) => ({ ...g, kind: 'mesh' })), SPLAT_TOOL];
+
+// ── DOM helpers ───────────────────────────────────────────────────────────────
+
+const root = () => document.getElementById('studio-lab');
+const $ = (sel) => root()?.querySelector(sel);
+
+function el(tag, attrs = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (v != null) node.setAttribute(k, v);
+ }
+ for (const c of [].concat(children)) if (c) node.appendChild(c);
+ return node;
+}
+
+function status(msg, kind = '') {
+ const s = $('#lab-status');
+ if (!s) return;
+ s.textContent = msg || '';
+ s.dataset.kind = kind;
+}
+
+// ── Tool picker + controls ────────────────────────────────────────────────────
+
+function renderToolPicker() {
+ const host = $('#lab-tools');
+ host.innerHTML = '';
+ for (const tool of TOOLS) {
+ const btn = el('button', {
+ type: 'button',
+ class: 'lab-tool',
+ 'data-tool': tool.id,
+ 'aria-pressed': tool.id === _activeId ? 'true' : 'false',
+ });
+ btn.appendChild(el('span', { class: 'lab-tool-name', text: tool.label }));
+ btn.appendChild(el('span', { class: 'lab-tool-blurb', text: tool.blurb }));
+ btn.addEventListener('click', () => selectTool(tool.id));
+ host.appendChild(btn);
+ }
+}
+
+function controlVisible(field, values) {
+ if (!field.when) return true;
+ return Object.entries(field.when).every(([k, v]) => values[k] === v);
+}
+
+function currentValues() {
+ const tool = TOOLS.find((t) => t.id === _activeId);
+ const values = {};
+ for (const f of tool.controls) {
+ const node = $(`#lab-field-${f.key}`);
+ if (!node) {
+ values[f.key] = f.default;
+ continue;
+ }
+ if (f.type === 'checkbox') values[f.key] = node.checked;
+ else if (f.type === 'image' || f.type === 'splatfile') values[f.key] = node._fileData ?? f.default;
+ else values[f.key] = node.value;
+ }
+ return values;
+}
+
+function renderControls() {
+ const tool = TOOLS.find((t) => t.id === _activeId);
+ const host = $('#lab-controls');
+ host.innerHTML = '';
+ const values = {};
+ for (const f of tool.controls) values[f.key] = f.default;
+
+ for (const f of tool.controls) {
+ const wrap = el('div', { class: 'lab-field', id: `lab-field-wrap-${f.key}` });
+ const labelRow = el('label', { class: 'lab-field-label', for: `lab-field-${f.key}`, text: f.label });
+ let input;
+
+ if (f.type === 'range') {
+ input = el('input', { type: 'range', id: `lab-field-${f.key}`, min: f.min, max: f.max, step: f.step, value: f.default });
+ const out = el('output', { class: 'lab-field-out', text: String(f.default) });
+ input.addEventListener('input', () => { out.textContent = input.value; });
+ wrap.appendChild(labelRow);
+ labelRow.appendChild(out);
+ wrap.appendChild(input);
+ } else if (f.type === 'select') {
+ input = el('select', { id: `lab-field-${f.key}` });
+ for (const o of f.options) {
+ const opt = el('option', { value: o.value, text: o.label });
+ if (o.value === f.default) opt.selected = true;
+ input.appendChild(opt);
+ }
+ input.addEventListener('change', () => syncConditional());
+ wrap.appendChild(labelRow);
+ wrap.appendChild(input);
+ } else if (f.type === 'color') {
+ input = el('input', { type: 'color', id: `lab-field-${f.key}`, value: f.default });
+ wrap.appendChild(labelRow);
+ wrap.appendChild(input);
+ } else if (f.type === 'checkbox') {
+ input = el('input', { type: 'checkbox', id: `lab-field-${f.key}` });
+ input.checked = !!f.default;
+ const inline = el('label', { class: 'lab-field-check' });
+ inline.appendChild(input);
+ inline.appendChild(el('span', { text: f.label }));
+ wrap.appendChild(inline);
+ } else if (f.type === 'text') {
+ input = el('input', { type: 'text', id: `lab-field-${f.key}`, value: f.default, maxlength: f.maxlength, placeholder: f.placeholder });
+ wrap.appendChild(labelRow);
+ wrap.appendChild(input);
+ } else if (f.type === 'textarea') {
+ input = el('textarea', { id: `lab-field-${f.key}`, rows: '4', placeholder: f.placeholder });
+ input.value = f.default || '';
+ wrap.appendChild(labelRow);
+ wrap.appendChild(input);
+ } else if (f.type === 'image' || f.type === 'splatfile') {
+ const accept = f.type === 'image' ? 'image/*' : '.splat,.ply,.ksplat';
+ input = el('input', { type: 'file', id: `lab-field-${f.key}`, accept });
+ const hint = el('span', { class: 'lab-field-out', text: f.type === 'image' ? 'optional — uses a sample if empty' : 'optional — renders a sample if empty' });
+ input.addEventListener('change', async () => {
+ const file = input.files?.[0];
+ if (!file) { input._fileData = null; return; }
+ if (f.type === 'image') {
+ input._fileData = await fileToDataURL(file);
+ } else {
+ input._fileData = { buffer: await file.arrayBuffer(), name: file.name };
+ }
+ hint.textContent = file.name;
+ });
+ wrap.appendChild(labelRow);
+ labelRow.appendChild(hint);
+ wrap.appendChild(input);
+ }
+
+ host.appendChild(wrap);
+ }
+ syncConditional();
+}
+
+function syncConditional() {
+ const tool = TOOLS.find((t) => t.id === _activeId);
+ const values = currentValues();
+ for (const f of tool.controls) {
+ const wrap = $(`#lab-field-wrap-${f.key}`);
+ if (wrap) wrap.hidden = !controlVisible(f, values);
+ }
+}
+
+function selectTool(id) {
+ _activeId = id;
+ for (const b of root().querySelectorAll('.lab-tool')) {
+ b.setAttribute('aria-pressed', b.dataset.tool === id ? 'true' : 'false');
+ }
+ const tool = TOOLS.find((t) => t.id === id);
+ renderControls();
+ const isSplat = tool.kind === 'splat';
+ $('#lab-viewer').hidden = isSplat;
+ $('#lab-splat').hidden = !isSplat;
+ $('#lab-download').classList.toggle('is-hidden', isSplat);
+ $('#lab-generate').textContent = isSplat ? 'Render splats' : 'Generate model';
+ status('');
+ if (!isSplat) teardownSplat();
+}
+
+// ── Generate (mesh → GLB) ─────────────────────────────────────────────────────
+
+async function exportGlb(object3d) {
+ const exporter = new GLTFExporter();
+ const result = await exporter.parseAsync(object3d, { binary: true, onlyVisible: true });
+ return new Blob([result], { type: 'model/gltf-binary' });
+}
+
+async function generate() {
+ const tool = TOOLS.find((t) => t.id === _activeId);
+ const btn = $('#lab-generate');
+ btn.disabled = true;
+ try {
+ if (tool.kind === 'splat') {
+ await renderSplats();
+ return;
+ }
+ status('Building geometry…');
+ const params = currentValues();
+ const object = await tool.build(params);
+ object.name = tool.label;
+ status('Exporting GLB…');
+ const blob = await exportGlb(object);
+ if (_lastGlbUrl) URL.revokeObjectURL(_lastGlbUrl);
+ _lastGlbUrl = URL.createObjectURL(blob);
+ const viewer = $('#lab-viewer');
+ viewer.setAttribute('src', _lastGlbUrl);
+ const dl = $('#lab-download');
+ dl.href = _lastGlbUrl;
+ dl.setAttribute('download', `${tool.id}-${Date.now()}.glb`);
+ dl.classList.remove('is-disabled');
+ // Free the geometry/material we just exported.
+ object.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });
+ status(`${tool.label} ready · ${(blob.size / 1024).toFixed(0)} KB GLB`, 'ok');
+ } catch (err) {
+ status(err.message || 'Generation failed.', 'err');
+ // eslint-disable-next-line no-console
+ console.error('[studio-lab]', err);
+ } finally {
+ btn.disabled = false;
+ }
+}
+
+// ── Gaussian splats ───────────────────────────────────────────────────────────
+
+// Build a sample .splat cloud (antimatter15 format: 32 bytes/splat —
+// center f32×3, scale f32×3, color u8×4, rotation u8×4). A rainbow sphere shell.
+function sampleSplatBuffer(count = 4000) {
+ const buf = new ArrayBuffer(count * 32);
+ const f = new DataView(buf);
+ const col = new THREE.Color();
+ for (let i = 0; i < count; i++) {
+ const base = i * 32;
+ // Fibonacci sphere for even coverage.
+ const t = i / count;
+ const phi = Math.acos(1 - 2 * t);
+ const theta = Math.PI * (1 + Math.sqrt(5)) * i;
+ const r = 1;
+ const x = r * Math.sin(phi) * Math.cos(theta);
+ const y = r * Math.cos(phi);
+ const z = r * Math.sin(phi) * Math.sin(theta);
+ f.setFloat32(base, x, true);
+ f.setFloat32(base + 4, y, true);
+ f.setFloat32(base + 8, z, true);
+ // scale (log-free world units for .splat)
+ f.setFloat32(base + 12, 0.03, true);
+ f.setFloat32(base + 16, 0.03, true);
+ f.setFloat32(base + 20, 0.03, true);
+ col.setHSL((y + 1) / 2, 0.7, 0.55);
+ f.setUint8(base + 24, Math.round(col.r * 255));
+ f.setUint8(base + 25, Math.round(col.g * 255));
+ f.setUint8(base + 26, Math.round(col.b * 255));
+ f.setUint8(base + 27, 255);
+ // identity rotation: (w,x,y,z) bytes
+ f.setUint8(base + 28, 255);
+ f.setUint8(base + 29, 128);
+ f.setUint8(base + 30, 128);
+ f.setUint8(base + 31, 128);
+ }
+ return buf;
+}
+
+async function renderSplats() {
+ status('Loading splat engine…');
+ const GS = await import('@mkkellogg/gaussian-splats-3d');
+ teardownSplat();
+ const host = $('#lab-splat');
+ host.innerHTML = '';
+
+ const fileField = $('#lab-field-file');
+ const uploaded = fileField?._fileData || null;
+ let url, format;
+ if (uploaded) {
+ url = URL.createObjectURL(new Blob([uploaded.buffer]));
+ format =
+ uploaded.name.endsWith('.ply') ? GS.SceneFormat.Ply :
+ uploaded.name.endsWith('.ksplat') ? GS.SceneFormat.KSplat :
+ GS.SceneFormat.Splat;
+ } else {
+ url = URL.createObjectURL(new Blob([sampleSplatBuffer()]));
+ format = GS.SceneFormat.Splat;
+ }
+
+ const viewer = new GS.Viewer({
+ rootElement: host,
+ sharedMemoryForWorkers: false,
+ dynamicScene: false,
+ useBuiltInControls: true,
+ gpuAcceleratedSort: false,
+ cameraUp: [0, 1, 0],
+ initialCameraPosition: [0, 0, 4],
+ initialCameraLookAt: [0, 0, 0],
+ });
+ _splat = { viewer, url };
+ status('Rendering splats…');
+ await viewer.addSplatScene(url, { format, showLoadingUI: false, progressiveLoad: false });
+ viewer.start();
+ const total = viewer.getSplatCount ? viewer.getSplatCount() : null;
+ status(uploaded ? `Loaded ${uploaded.name}${total ? ` · ${total.toLocaleString()} splats` : ''}` : `Sample radiance field · ${total ? total.toLocaleString() : '4,000'} splats`, 'ok');
+}
+
+function teardownSplat() {
+ if (!_splat) return;
+ try {
+ _splat.viewer.stop?.();
+ _splat.viewer.dispose?.();
+ } catch { /* viewer may already be torn down */ }
+ if (_splat.url) URL.revokeObjectURL(_splat.url);
+ _splat = null;
+ const host = document.getElementById('lab-splat');
+ if (host) host.innerHTML = '';
+}
+
+// ── Misc ──────────────────────────────────────────────────────────────────────
+
+function fileToDataURL(file) {
+ return new Promise((resolve, reject) => {
+ const r = new FileReader();
+ r.onload = () => resolve(r.result);
+ r.onerror = () => reject(new Error('Could not read that file.'));
+ r.readAsDataURL(file);
+ });
+}
+
+export function initLab() {
+ if (_inited) return;
+ if (!root()) return;
+ _inited = true;
+ renderToolPicker();
+ $('#lab-generate').addEventListener('click', generate);
+ selectTool(TOOLS[0].id);
+}