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.

feat: forge tiers, animation system, pose studio, magic-brush, segment/stylize UI

nirholasb60469b0caac
diff --git a/.env.example b/.env.example
index 76b0667e7..b8ff30e20 100644
--- a/.env.example
+++ b/.env.example
@@ -734,8 +734,17 @@ GCP_RECONSTRUCTION_URL=
GCP_REMBG_URL=
# workers/remesh → mesh processing (GLB → clean GLB)
GCP_REMESH_URL=
-# workers/texture → text-guided texturing (GLB + prompt → textured GLB)
+# workers/texture → text-guided texturing (GLB + prompt → textured GLB).
+# Also serves the Magic Brush /retexture_region endpoint (local region
+# inpainting) — no separate URL needed.
GCP_TEXTURE_URL=
+# workers/segment → part segmentation (GLB → segmented GLB + parts manifest)
+GCP_SEGMENT_URL=
+
+# Magic Brush region inpainting model (workers/texture /retexture_region). SDXL
+# inpaint checkpoint loaded lazily on first region edit. Override only to pin a
+# different inpaint model.
+SDXL_INPAINT_MODEL=diffusers/stable-diffusion-xl-1.0-inpainting-0.1
# ── IPFS pinning (additional) ───────────────────────────────────────────────
# nft.storage token used by /api/erc8004/* when PINATA_JWT and
diff --git a/.gitignore b/.gitignore
index 008a4b265..e637c45b0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -182,3 +182,7 @@ docs/ibm.md
# Vanity keypair files — contain private keys, never commit
.keys/
+
+# Python bytecode (workers/)
+__pycache__/
+*.pyc
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.js
index 0a34073cd..40482ef5c 100644
--- a/api/_lib/forge-store.js
+++ b/api/_lib/forge-store.js
@@ -71,6 +71,8 @@ export async function createCreation({
viewsUsed,
multiview,
backend,
+ tier,
+ path,
}) {
if (!forgeStoreEnabled()) return null;
const id = randomUUID();
@@ -79,13 +81,13 @@ export async function createCreation({
insert into forge_creations
(id, client_key, ip_hash, prompt, aspect, preview_image_url,
replicate_job_id, text_to_image_model, views_requested, views_used,
- multiview, backend, status, outcome)
+ multiview, backend, tier, path, status, outcome)
values
(${id}, ${clientKey}, ${ipHash ?? null}, ${prompt}, ${aspect ?? null},
${previewImageUrl ?? null}, ${replicateJobId ?? null},
${textToImageModel ?? null}, ${viewsRequested ?? null}, ${viewsUsed ?? null},
${typeof multiview === 'boolean' ? multiview : null}, ${backend ?? null},
- 'generating', 'generated')
+ ${tier ?? null}, ${path ?? null}, 'generating', 'generated')
`;
return id;
} catch (err) {
@@ -101,7 +103,7 @@ export async function findByJob({ replicateJobId, clientKey }) {
try {
const rows = await sql`
select id, status, glb_url, glb_key, prompt, preview_image_url,
- views_requested, views_used, multiview, backend
+ views_requested, views_used, multiview, backend, tier, path
from forge_creations
where replicate_job_id = ${replicateJobId} and client_key = ${clientKey}
limit 1
@@ -241,7 +243,7 @@ export async function listCreations({ clientKey, limit = 24 }) {
try {
const rows = await sql`
select id, prompt, aspect, glb_url, preview_image_url, outcome, downloaded,
- views_used, multiview, backend, created_at
+ views_used, multiview, backend, tier, path, created_at
from forge_creations
where client_key = ${clientKey} and status = 'done' and glb_url is not null
order by created_at desc
@@ -258,6 +260,8 @@ export async function listCreations({ clientKey, limit = 24 }) {
views_used: r.views_used ?? null,
multiview: r.multiview ?? null,
backend: r.backend ?? null,
+ tier: r.tier ?? null,
+ path: r.path ?? null,
created_at: r.created_at,
}));
} catch (err) {
diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.js
new file mode 100644
index 000000000..41c3f821d
--- /dev/null
+++ b/api/_lib/forge-tiers.js
@@ -0,0 +1,239 @@
+// Forge quality tiers + generation-backend registry — the single source of
+// truth shared by the /api/forge endpoint, the public catalog the UI renders,
+// and the per-provider param builders.
+//
+// Two orthogonal axes describe a generation request:
+//
+// path — how geometry is produced:
+// • "image" → image-intermediate. Text is painted into a
+// reference image (FLUX/Imagen) then reconstructed to a mesh
+// (TRELLIS / Hunyuan3D). This is the existing fast default.
+// • "geometry" → geometry-first. A native 3D model emits mesh
+// geometry directly from the prompt (or a single photo) with no
+// synthesized intermediate view, so detail isn't capped by what
+// one image implies. Meshy / Tripo text-to-3D.
+//
+// tier — how much geometric budget to spend: draft / standard / high. Maps
+// to a target polygon count where the backend supports it, plus
+// texture richness. Higher tiers cost more credits and take longer.
+//
+// A backend declares which paths it serves, whether it needs a user-supplied
+// (BYOK) key, and its per-(path,tier) cost/latency estimates so the UI can
+// communicate the trade-off before the user commits.
+
+export const PATHS = Object.freeze(['image', 'geometry']);
+export const DEFAULT_PATH = 'image';
+export const TIER_IDS = Object.freeze(['draft', 'standard', 'high']);
+export const DEFAULT_TIER = 'standard';
+
+// Polygon budget + texture richness per tier. `polycount` is the target the
+// poly-aware backends (Meshy, Tripo) decimate toward — 100–300k is Meshy's
+// accepted range; we stay inside it. `pbr`/`hd` only apply where the backend
+// produces textures (the geometry path's optional refine, or image-to-3D).
+export const TIERS = Object.freeze({
+ draft: Object.freeze({
+ id: 'draft',
+ label: 'Draft',
+ blurb: 'Fast, low-poly. Good for blockout and iteration.',
+ polycount: 12_000,
+ pbr: false,
+ hd: false,
+ etaMultiplier: 0.6,
+ }),
+ standard: Object.freeze({
+ id: 'standard',
+ label: 'Standard',
+ blurb: 'Balanced detail. The default for most assets.',
+ polycount: 30_000,
+ pbr: false,
+ hd: false,
+ etaMultiplier: 1,
+ }),
+ high: Object.freeze({
+ id: 'high',
+ label: 'High',
+ blurb: 'Maximum geometric detail + PBR textures. Slower, pricier.',
+ polycount: 200_000,
+ pbr: true,
+ hd: true,
+ etaMultiplier: 2.2,
+ }),
+});
+
+export function resolveTier(id) {
+ return TIERS[id] || TIERS[DEFAULT_TIER];
+}
+
+// Generation backends. `provider` selects the api/_providers/* client that
+// talks to it. `byok` names the provider-key the caller must supply (false for
+// platform-keyed backends). `requiresEnv` lists env vars that must be present
+// for a platform backend to be live. `baseEta` is wall-clock seconds at the
+// standard tier; the tier's etaMultiplier scales it. `credits` is the estimated
+// vendor credit spend per (path → tier) — null when the backend bills by GPU
+// time rather than credits (TRELLIS/Hunyuan via our own infra).
+export const BACKENDS = Object.freeze({
+ trellis: Object.freeze({
+ id: 'trellis',
+ label: 'TRELLIS',
+ vendor: 'Microsoft · Replicate',
+ paths: Object.freeze(['image']),
+ byok: false,
+ provider: 'replicate',
+ requiresEnv: Object.freeze(['REPLICATE_API_TOKEN']),
+ polyControl: false,
+ baseEta: 60,
+ credits: null,
+ blurb: 'Image-intermediate reconstruction. The fast default; no poly target.',
+ }),
+ meshy: Object.freeze({
+ id: 'meshy',
+ label: 'Meshy 6',
+ vendor: 'Meshy AI',
+ paths: Object.freeze(['geometry', 'image']),
+ byok: 'meshy',
+ provider: 'meshy',
+ requiresEnv: Object.freeze([]),
+ polyControl: true,
+ baseEta: 75,
+ // Meshy bills 20 credits for a text-to-3D preview (geometry), 30 for
+ // image-to-3D, +10 when PBR/HD texturing is enabled (high tier).
+ credits: Object.freeze({
+ geometry: Object.freeze({ draft: 20, standard: 20, high: 30 }),
+ image: Object.freeze({ draft: 30, standard: 30, high: 40 }),
+ }),
+ blurb: 'Native text→geometry (preview) + image→3D. Quad topology, t-pose ready.',
+ }),
+ tripo: Object.freeze({
+ id: 'tripo',
+ label: 'Tripo v3.1',
+ vendor: 'Tripo AI',
+ paths: Object.freeze(['geometry', 'image']),
+ byok: 'tripo',
+ provider: 'tripo',
+ requiresEnv: Object.freeze([]),
+ polyControl: true,
+ baseEta: 70,
+ // Tripo bills credits per task type; texture/quad add-ons cost extra.
+ credits: Object.freeze({
+ geometry: Object.freeze({ draft: 20, standard: 20, high: 30 }),
+ image: Object.freeze({ draft: 30, standard: 30, high: 40 }),
+ }),
+ blurb: 'Cleanest quad topology. Native text→model + image→model.',
+ }),
+ hunyuan3d: Object.freeze({
+ id: 'hunyuan3d',
+ label: 'Hunyuan3D',
+ vendor: 'Tencent · self-host',
+ paths: Object.freeze(['image']),
+ byok: false,
+ provider: 'gcp',
+ requiresEnv: Object.freeze(['GCP_RECONSTRUCTION_URL', 'GCP_RECONSTRUCTION_KEY']),
+ polyControl: true,
+ baseEta: 120,
+ credits: null,
+ blurb: 'Self-hosted high-poly reconstruction. Image-conditioned geometry.',
+ }),
+});
+
+// Backend chosen when the caller doesn't name one, per path. Image path keeps
+// the existing TRELLIS fast default; geometry path defaults to Meshy.
+export const DEFAULT_BACKEND_FOR_PATH = Object.freeze({
+ image: 'trellis',
+ geometry: 'meshy',
+});
+
+export function resolveBackendId({ path, backend }) {
+ const p = PATHS.includes(path) ? path : DEFAULT_PATH;
+ if (backend && BACKENDS[backend] && BACKENDS[backend].paths.includes(p)) {
+ return backend;
+ }
+ return DEFAULT_BACKEND_FOR_PATH[p];
+}
+
+function readEnv(name) {
+ if (typeof process !== 'undefined' && process.env && process.env[name]) return process.env[name];
+ return null;
+}
+
+// A platform backend is "live" only when its required env is present. BYOK
+// backends are always selectable — liveness depends on the caller's key, which
+// is resolved per-request, not here.
+export function backendIsConfigured(backendId) {
+ const b = BACKENDS[backendId];
+ if (!b) return false;
+ if (b.byok) return true;
+ return b.requiresEnv.every((name) => Boolean(readEnv(name)));
+}
+
+// Estimated wall-clock seconds for a (backend, path, tier) combination —
+// used to populate the client progress estimate and the catalog.
+export function estimateEtaSeconds({ backendId, tier }) {
+ const b = BACKENDS[backendId];
+ if (!b) return 90;
+ const t = resolveTier(tier?.id || tier);
+ return Math.round(b.baseEta * t.etaMultiplier);
+}
+
+// Estimated vendor credits for a (backend, path, tier) — null when the backend
+// doesn't bill in credits.
+export function estimateCredits({ backendId, path, tier }) {
+ const b = BACKENDS[backendId];
+ if (!b || !b.credits) return null;
+ const p = PATHS.includes(path) ? path : DEFAULT_PATH;
+ const byPath = b.credits[p];
+ if (!byPath) return null;
+ const tierId = (tier?.id || tier || DEFAULT_TIER);
+ return byPath[tierId] ?? byPath[DEFAULT_TIER] ?? null;
+}
+
+// Build the public catalog the /forge UI renders: every tier, and every backend
+// with its supported paths, BYOK requirement, live/configured flag, and the
+// time+cost estimate matrix. No secrets — safe to serve unauthenticated.
+export function buildCatalog() {
+ return {
+ paths: PATHS,
+ default_path: DEFAULT_PATH,
+ default_tier: DEFAULT_TIER,
+ default_backend: DEFAULT_BACKEND_FOR_PATH,
+ tiers: TIER_IDS.map((id) => {
+ const t = TIERS[id];
+ return {
+ id: t.id,
+ label: t.label,
+ blurb: t.blurb,
+ polycount: t.polycount,
+ pbr: t.pbr,
+ hd: t.hd,
+ };
+ }),
+ backends: Object.values(BACKENDS).map((b) => ({
+ id: b.id,
+ label: b.label,
+ vendor: b.vendor,
+ paths: b.paths,
+ byok: b.byok || null,
+ poly_control: b.polyControl,
+ configured: backendIsConfigured(b.id),
+ blurb: b.blurb,
+ estimates: b.paths.reduce((acc, p) => {
+ acc[p] = TIER_IDS.map((tierId) => ({
+ tier: tierId,
+ eta_seconds: estimateEtaSeconds({ backendId: b.id, tier: tierId }),
+ credits: estimateCredits({ backendId: b.id, path: p, tier: tierId }),
+ }));
+ return acc;
+ }, {}),
+ })),
+ };
+}
+
+// Translate a resolved (path, tier) into the mesh-budget params the poly-aware
+// providers (Meshy/Tripo) accept. Backends without poly control ignore these.
+export function meshBudgetFor({ tier }) {
+ const t = resolveTier(tier?.id || tier);
+ return {
+ targetPolycount: t.polycount,
+ pbr: t.pbr,
+ hd: t.hd,
+ };
+}
diff --git a/api/_lib/migrations/20260607000000_forge_tier_path.sql b/api/_lib/migrations/20260607000000_forge_tier_path.sql
new file mode 100644
index 000000000..10e2a47ec
--- /dev/null
+++ b/api/_lib/migrations/20260607000000_forge_tier_path.sql
@@ -0,0 +1,17 @@
+-- Forge quality tiers + generation path — record how each mesh was generated.
+--
+-- /forge gained two new request axes (see api/_lib/forge-tiers.js):
+--
+-- path — "image" (image-intermediate: text→image→mesh, the fast default)
+-- "geometry" (geometry-first: native text→mesh / image→mesh with no
+-- synthesized intermediate view)
+-- tier — "draft" | "standard" | "high" — the target polygon budget + texture
+-- richness. The high tier produces a visibly denser mesh.
+--
+-- The `backend` column already exists (added by the multiview migration); these
+-- two columns complete the provenance so every job result can report
+-- tier + backend + path, and the data flywheel can segment training pairs by
+-- generation route and quality.
+
+alter table forge_creations add column if not exists tier text;
+alter table forge_creations add column if not exists path text;
diff --git a/api/_lib/provider-keys.js b/api/_lib/provider-keys.js
index ab7c03526..05c064505 100644
--- a/api/_lib/provider-keys.js
+++ b/api/_lib/provider-keys.js
@@ -54,6 +54,7 @@ export const BYOK_PROVIDERS = {
anthropic: { label: 'Anthropic', prefix: 'sk-ant-', hint: 'console.anthropic.com/settings/keys' },
openai: { label: 'OpenAI', prefix: 'sk-', hint: 'platform.openai.com/api-keys' },
meshy: { label: 'Meshy AI', prefix: 'msy_', hint: 'www.meshy.ai/settings/api' },
+ tripo: { label: 'Tripo AI', prefix: 'tsk_', hint: 'platform.tripo3d.ai/api-keys' },
};
// Load and decrypt all stored provider keys for a user.
diff --git a/api/_lib/pump-pricing.js b/api/_lib/pump-pricing.js
index 406d004d8..e58754b74 100644
--- a/api/_lib/pump-pricing.js
+++ b/api/_lib/pump-pricing.js
@@ -17,11 +17,21 @@ import { sql } from './db.js';
export const TOOL_PRICING = Object.freeze({
// Heavy compute or external calls — priced.
- optimize_model: { amount_usdc: 0.05, description: 'Per call' },
- inspect_model: { amount_usdc: 0.01, description: 'Per call' },
- validate_model: { amount_usdc: 0.01, description: 'Per call' },
- render_avatar: { amount_usdc: 0.005, description: 'Per call' },
- // Discovery / lookups — free
+ optimize_model: { amount_usdc: 0.05, description: 'Per call' },
+ segment_model: { amount_usdc: 0.04, description: 'Per call — split a mesh into named parts' },
+ inspect_model: { amount_usdc: 0.01, description: 'Per call' },
+ validate_model: { amount_usdc: 0.01, description: 'Per call' },
+ render_avatar: { amount_usdc: 0.005, description: 'Per call' },
+ apply_animation: {
+ amount_usdc: 0.02,
+ description: 'Per call — retarget + bake an animated GLB',
+ },
+ // 3D Studio generation tools — GPU-bound, priced per call. A full surface
+ // retexture regenerates every viewpoint (minutes of GPU); the magic-brush
+ // region edit only inpaints one masked patch, so it is priced well below it.
+ retexture_model: { amount_usdc: 0.1, description: 'Per full retexture' },
+ retexture_region: { amount_usdc: 0.03, description: 'Per region edit (magic brush)' },
+ // Discovery / lookups (incl. list_animations) — free
});
export function priceFor(toolName) {
diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.js
index ce42990a6..3769fa09c 100644
--- a/api/_lib/render-clip.js
+++ b/api/_lib/render-clip.js
@@ -70,6 +70,9 @@ function viewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expr
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
window.__renderDone = false;
window.__renderError = null;
@@ -164,7 +167,19 @@ const orbit = ${orbitJson};
const poseMap = ${poseJson};
const expression = ${expressionJson};
-new GLTFLoader().load(${JSON.stringify(glbUrl)}, (gltf) => {
+// Pipeline GLBs ship Draco geometry, Meshopt buffers, and KTX2 textures;
+// a bare GLTFLoader throws "No DRACOLoader instance provided". Register
+// every standard compression decoder from the pinned three.js release.
+const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';
+const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');
+const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);
+
+const loader = new GLTFLoader();
+loader.setDRACOLoader(dracoLoader);
+loader.setKTX2Loader(ktx2Loader);
+loader.setMeshoptDecoder(MeshoptDecoder);
+
+loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
try {
const root = gltf.scene;
scene.add(root);
diff --git a/api/_lib/render-glb.js b/api/_lib/render-glb.js
index ec9c543a1..933e07e0b 100644
--- a/api/_lib/render-glb.js
+++ b/api/_lib/render-glb.js
@@ -72,6 +72,9 @@ function viewerHtml({ glbUrl, width, height, background }) {
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
window.__renderDone = false;
window.__renderError = null;
@@ -96,7 +99,22 @@ const key = new THREE.DirectionalLight(0xffffff, 1.4); key.position.set(2, 3, 4)
const fill = new THREE.DirectionalLight(0xbfd6ff, 0.6); fill.position.set(-3, 1, 2); scene.add(fill);
const rim = new THREE.DirectionalLight(0xc7a8ff, 0.5); rim.position.set(0, 2, -4); scene.add(rim);
-new GLTFLoader().load(${JSON.stringify(glbUrl)}, (gltf) => {
+// Avatars from the forge/remesh/texture pipeline ship Draco-compressed
+// geometry, Meshopt-packed buffers, and KTX2 (Basis) textures. A bare
+// GLTFLoader throws "No DRACOLoader instance provided" on the first such
+// model — register every standard compression decoder so the renderer
+// handles optimized GLBs instead of falling back to the SVG card. Decoder
+// assets load from the same pinned three.js release as the loaders.
+const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';
+const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');
+const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);
+
+const loader = new GLTFLoader();
+loader.setDRACOLoader(dracoLoader);
+loader.setKTX2Loader(ktx2Loader);
+loader.setMeshoptDecoder(MeshoptDecoder);
+
+loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
try {
const root = gltf.scene;
scene.add(root);
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.js
index 4427ea6c7..ac673b1bc 100644
--- a/api/_mcp/catalog.js
+++ b/api/_mcp/catalog.js
@@ -6,8 +6,16 @@ import { toolDefs as modelDefs } from './tools/models.js';
import { toolDefs as solanaDefs } from './tools/solana.js';
import { toolDefs as pumpfunDefs } from './tools/pumpfun.js';
import { toolDefs as agentDefs } from './tools/agents.js';
+import { toolDefs as animationDefs } from './tools/animations.js';
-const allDefs = [...avatarDefs, ...modelDefs, ...solanaDefs, ...pumpfunDefs, ...agentDefs];
+const allDefs = [
+ ...avatarDefs,
+ ...modelDefs,
+ ...animationDefs,
+ ...solanaDefs,
+ ...pumpfunDefs,
+ ...agentDefs,
+];
// Schema objects for tools/list — strip internal fields (scope, handler).
export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.js
index ede8e16b9..669b66094 100644
--- a/api/_mcp/dispatch.js
+++ b/api/_mcp/dispatch.js
@@ -20,7 +20,7 @@ export function rpcError(code, message, data) {
return e;
}
-export async function dispatch(msg, auth, _req) {
+export async function dispatch(msg, auth, req) {
const started = Date.now();
const id = msg.id;
const isNotification = id === undefined;
@@ -64,7 +64,8 @@ export async function dispatch(msg, auth, _req) {
};
}),
});
- if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started));
+ if (method === 'tools/call')
+ return ok(id, await onToolCall(msg.params, auth, started, req));
if (method === 'resources/list') return ok(id, { resources: [] });
if (method === 'resources/templates/list') return ok(id, { resourceTemplates: [] });
if (method === 'prompts/list') return ok(id, { prompts: [] });
@@ -111,7 +112,7 @@ async function onInitialize(_params, _auth) {
};
}
-async function onToolCall(params, auth, started) {
+async function onToolCall(params, auth, started, req) {
const { name, arguments: args = {} } = params || {};
const tool = TOOLS[name];
if (!tool) throw rpcError(-32602, `unknown tool: ${name}`);
@@ -159,8 +160,7 @@ async function onToolCall(params, auth, started) {
amount_usdc: price.amount_usdc,
recipient_mint: billingMint,
prep_endpoint: '/api/pump/accept-payment-prep',
- hint:
- 'POST a confirmed acceptPayment whose end_time > now() and tool_name matches this tool, then retry.',
+ hint: 'POST a confirmed acceptPayment whose end_time > now() and tool_name matches this tool, then retry.',
});
}
auth.subscription = sub;
@@ -178,7 +178,7 @@ async function onToolCall(params, auth, started) {
}
try {
- const result = await tool.handler(args, auth);
+ const result = await tool.handler(args, auth, req);
recordEvent({
userId: auth.userId,
apiKeyId: auth.apiKeyId,
diff --git a/api/_mcp/tools/animations.js b/api/_mcp/tools/animations.js
new file mode 100644
index 000000000..2f158a41e
--- /dev/null
+++ b/api/_mcp/tools/animations.js
@@ -0,0 +1,365 @@
+// MCP tools for the animation preset library.
+//
+// • list_animations (free) — the curated catalogue of retargetable clips.
+// • apply_animation (paid) — retarget a preset onto a caller-supplied rigged
+// GLB and return an animated GLB (or the
+// retargeted clip JSON), plus a retarget report.
+//
+// apply_animation runs three.js headless, exactly like scripts/build-animations.mjs:
+// parse the rig with GLTFLoader, rewrite the canonical clip's track names onto
+// the rig's actual bones, bake with GLTFExporter. The DOM shims below cover the
+// handful of browser globals three's loader/exporter touch; they're scoped to
+// this serverless function (no DOM exists here) and applied before any three
+// addon is dynamically imported inside the handler.
+
+import { limits } from '../../_lib/rate-limit.js';
+import { fetchModel, FetchModelError } from '../../_lib/fetch-model.js';
+import {
+ canonicalNodeMapFromObject,
+ retargetClip,
+ scaleClipSpeed,
+ parseClipJSON,
+ MIN_COVERAGE,
+} from '../../../src/animation-retarget.js';
+import { categoryOf } from '../../../src/animation-presets.js';
+
+// Largest base64-encoded GLB we'll inline in a JSON-RPC response before falling
+// back to the (small) clip JSON. Keeps responses sane for very heavy avatars.
+const MAX_INLINE_GLB_BYTES = 8 * 1024 * 1024;
+
+function rpcError(code, message, data) {
+ const e = new Error(message);
+ e.code = code;
+ e.data = data;
+ return e;
+}
+
+// ── Origin + catalogue helpers ────────────────────────────────────────────
+function resolveOrigin(req) {
+ const env =
+ process.env.APP_ORIGIN || process.env.PUBLIC_ORIGIN || process.env.PUBLIC_APP_ORIGIN;
+ if (env) return env.replace(/\/$/, '');
+ const host = req?.headers?.host;
+ if (host) return `${/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https'}://${host}`;
+ if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;
+ throw new Error('cannot resolve site origin to load the animation catalogue');
+}
+
+async function loadManifest(origin) {
+ const res = await fetch(`${origin}/animations/manifest.json`, { cache: 'no-store' });
+ if (!res.ok) throw new Error(`manifest fetch failed (HTTP ${res.status})`);
+ const manifest = await res.json();
+ if (!Array.isArray(manifest) || !manifest.length)
+ throw new Error('animation manifest is empty');
+ return manifest;
+}
+
+async function loadClipJSON(origin, def) {
+ // def.url is a site-relative path like /animations/clips/idle.json
+ const res = await fetch(`${origin}${def.url}`, { cache: 'no-store' });
+ if (!res.ok) throw new Error(`clip fetch failed (HTTP ${res.status})`);
+ return res.json();
+}
+
+async function safeFetchModel(url) {
+ try {
+ return await fetchModel(url);
+ } catch (e) {
+ if (e instanceof FetchModelError) throw new Error(`fetch failed: ${e.message} (${e.code})`);
+ throw e;
+ }
+}
+
+// ── Headless three setup (shims + loaders) ──────────────────────────────────
+let _shimmed = false;
+function installDomShims() {
+ if (_shimmed) return;
+ if (typeof globalThis.self === 'undefined') globalThis.self = globalThis;
+ if (typeof globalThis.window === 'undefined') globalThis.window = globalThis;
+ if (typeof globalThis.document === 'undefined') {
+ globalThis.document = { createElementNS: () => ({}) };
+ }
+ if (typeof globalThis.FileReader === 'undefined') {
+ // GLTFExporter reads Blob-wrapped binary/texture chunks via FileReader.
+ globalThis.FileReader = class extends EventTarget {
+ readAsDataURL(blob) {
+ blob.arrayBuffer().then((buf) => {
+ const b64 = Buffer.from(buf).toString('base64');
+ this.result = `data:${blob.type || 'application/octet-stream'};base64,${b64}`;
+ this.onload?.({ target: this });
+ this.dispatchEvent(new Event('load'));
+ });
+ }
+ readAsArrayBuffer(blob) {
+ blob.arrayBuffer().then((buf) => {
+ this.result = buf;
+ this.onload?.({ target: this });
+ this.dispatchEvent(new Event('load'));
+ });
+ }
+ };
+ }
+ _shimmed = true;
+}
+
+async function parseGLB(bytes) {
+ const { GLTFLoader } = await import('three/examples/jsm/loaders/GLTFLoader.js');
+ const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
+ const loader = new GLTFLoader();
+ return new Promise((resolve, reject) => loader.parse(ab, '', resolve, reject));
+}
+
+// Bake an animated GLB, bounded by a timeout. GLTFExporter reads texture pixels
+// through a canvas; headless Node has none, so a textured rig can stall the
+// exporter indefinitely. We race it against a timeout and let the caller fall
+// back to the (always-reliable) retargeted clip JSON rather than hang the
+// function. The first-class, guaranteed GLB path is the browser /pose gallery.
+const GLB_EXPORT_TIMEOUT_MS = 15_000;
+async function exportGLB(scene, clip) {
+ const { GLTFExporter } = await import('three/examples/jsm/exporters/GLTFExporter.js');
+ const exporter = new GLTFExporter();
+ const bake = exporter.parseAsync(scene, {
+ binary: true,
+ animations: [clip],
+ embedImages: true,
+ });
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('headless GLB bake timed out (textured rig)')),
+ GLB_EXPORT_TIMEOUT_MS,
+ );
+ });
+ try {
+ return await Promise.race([bake, timeout]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// Hip-translation scale: target rig's rest hip height ÷ the clip's authored hip
+// height, so root motion lands on the new rig instead of the authoring rig.
+async function computeHipScale(scene, clip) {
+ const { Vector3 } = await import('three');
+ let hipsNode = null;
+ scene.traverse((n) => {
+ if (
+ !hipsNode &&
+ n.name &&
+ /(^|[:_])hips$/i.test(n.name.replace(/^mixamorig\d*[:_]?/i, ''))
+ ) {
+ hipsNode = n;
+ }
+ });
+ if (!hipsNode) return 1;
+ scene.updateMatrixWorld(true);
+ const targetY = hipsNode.getWorldPosition(new Vector3()).y;
+ const track = clip.tracks.find((t) =>
+ /hips\.position$/i.test(t.name.replace(/^mixamorig\d*[:_]?/i, '')),
+ );
+ const sourceY = track && track.values.length >= 2 ? track.values[1] : 0;
+ if (targetY > 0.05 && sourceY > 0.05) return Math.min(5, Math.max(0.2, targetY / sourceY));
+ return 1;
+}
+
+// ── Tool defs ───────────────────────────────────────────────────────────────
+export const toolDefs = [
+ {
+ name: 'list_animations',
+ title: 'List animation presets',
+ description:
+ 'List the curated, retargetable animation presets in the three.ws library — name, label, category, and whether the clip loops. Use this to discover valid `animation` values for apply_animation.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ category: {
+ type: 'string',
+ description:
+ 'Optional category filter (e.g. "dance", "locomotion", "gesture").',
+ },
+ },
+ additionalProperties: false,
+ },
+ async handler(args, auth, req) {
+ const origin = resolveOrigin(req);
+ const manifest = await loadManifest(origin);
+ let defs = manifest.map((d) => ({
+ name: d.name,
+ label: d.label || d.name,
+ category: categoryOf(d.name),
+ loop: d.loop !== false,
+ }));
+ if (args.category) {
+ const c = String(args.category).toLowerCase();
+ defs = defs.filter((d) => d.category === c);
+ }
+ const lines = defs
+ .map(
+ (d) =>
+ ` ${d.name.padEnd(22)} ${d.loop ? 'loop' : 'once'} [${d.category}] ${d.label}`,
+ )
+ .join('\n');
+ return {
+ content: [{ type: 'text', text: `${defs.length} animation presets:\n${lines}` }],
+ structuredContent: { count: defs.length, animations: defs },
+ };
+ },
+ },
+ {
+ name: 'apply_animation',
+ title: 'Apply an animation preset to a rigged model',
+ description:
+ 'Retarget a curated animation preset onto a caller-supplied rigged humanoid GLB. Returns the retargeted three.js AnimationClip JSON (keyed to the rig\'s actual bone names, hip translation rescaled to its proportions) plus a retarget report — load it alongside the model and play. Set format="glb" to also bake an animated GLB server-side (best-effort: textured rigs may exceed the headless bake budget and fall back to clip JSON — the /pose gallery is the guaranteed GLB export). SSRF-hardened: only public https model URLs are fetched.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ model_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a rigged humanoid .glb to animate.',
+ },
+ animation: {
+ type: 'string',
+ description: 'Preset name from list_animations (e.g. "idle", "walk", "dance").',
+ },
+ format: {
+ type: 'string',
+ enum: ['glb', 'clip'],
+ default: 'clip',
+ description:
+ 'clip = retargeted AnimationClip JSON (reliable); glb = also attempt a baked animated GLB (base64, best-effort).',
+ },
+ speed: {
+ type: 'number',
+ minimum: 0.25,
+ maximum: 2.5,
+ default: 1,
+ description:
+ 'Playback-speed multiplier baked into the result (1.8 turns a walk into a run).',
+ },
+ },
+ required: ['model_url', 'animation'],
+ additionalProperties: false,
+ },
+ async handler(args, auth, req) {
+ const rl = await limits.mcpOptimize?.(auth.userId || auth.rateKey);
+ if (rl && !rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+
+ const origin = resolveOrigin(req);
+ const manifest = await loadManifest(origin);
+ const def = manifest.find((d) => d.name === args.animation);
+ if (!def) {
+ throw rpcError(-32602, `unknown animation "${args.animation}"`, {
+ hint: 'call list_animations for valid names',
+ });
+ }
+
+ installDomShims();
+ const clipJSON = await loadClipJSON(origin, def);
+ const baseClip = parseClipJSON(clipJSON, def.name);
+
+ const { bytes, url, filename } = await safeFetchModel(args.model_url);
+ let gltf;
+ try {
+ gltf = await parseGLB(bytes);
+ } catch (e) {
+ throw new Error(`could not parse the rigged GLB: ${e.message || e}`);
+ }
+ const scene = gltf.scene || gltf.scenes?.[0];
+ if (!scene) throw new Error('the model has no scene to animate');
+
+ const map = canonicalNodeMapFromObject(scene);
+ if (map.size === 0) {
+ throw new Error(
+ 'no recognizable humanoid skeleton found in the model — apply_animation needs a rigged GLB',
+ );
+ }
+ const hipScale = await computeHipScale(scene, baseClip);
+ const result = retargetClip(baseClip, map, { hipScale });
+
+ const report = {
+ animation: def.name,
+ label: def.label || def.name,
+ source_model: url,
+ filename,
+ bones_matched: result.matched,
+ bones_total: result.total,
+ coverage: Number(result.coverage.toFixed(3)),
+ bones_unmapped: [...new Set(result.dropped)],
+ hip_scale: Number(result.hipScale.toFixed(3)),
+ speed: args.speed || 1,
+ loop: def.loop !== false,
+ };
+
+ if (!result.clip) {
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Could not retarget "${def.name}" onto this rig: only ${result.matched}/${result.total} tracks mapped (need ${Math.round(MIN_COVERAGE * 100)}%). The skeleton is too different from the canonical humanoid rig.`,
+ },
+ ],
+ structuredContent: { ok: false, ...report },
+ };
+ }
+
+ const finalClip = scaleClipSpeed(result.clip, args.speed || 1);
+ finalClip.name = def.name;
+
+ const { AnimationClip } = await import('three');
+ const clipResult = (note) => ({
+ content: [
+ {
+ type: 'text',
+ text: `Retargeted "${def.label || def.name}" → ${report.bones_matched}/${report.bones_total} bones (${Math.round(report.coverage * 100)}%), hip scale ${report.hip_scale}×.${note ? ' ' + note : ''} Returning AnimationClip JSON — load it alongside the model and play.`,
+ },
+ ],
+ structuredContent: {
+ ok: true,
+ ...report,
+ format: note ? 'clip-fallback' : 'clip',
+ clip: AnimationClip.toJSON(finalClip),
+ },
+ });
+
+ if (args.format !== 'glb') return clipResult();
+
+ // Best-effort GLB bake. A textured rig can exceed the headless bake
+ // budget (no canvas to read texture pixels) — fall back to clip JSON
+ // rather than fail or hang.
+ let glbBytes;
+ try {
+ glbBytes = Buffer.from(await exportGLB(scene, finalClip));
+ } catch (e) {
+ return clipResult(
+ `Server-side GLB bake unavailable (${e.message || e}); use the /pose gallery to export a GLB in-browser.`,
+ );
+ }
+ if (glbBytes.length > MAX_INLINE_GLB_BYTES) {
+ return clipResult(
+ `Animated GLB is ${(glbBytes.length / 1024 / 1024).toFixed(1)} MB — too large to inline.`,
+ );
+ }
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Applied "${def.label || def.name}" to ${filename}: ${report.bones_matched}/${report.bones_total} bones (${Math.round(report.coverage * 100)}%), hip scale ${report.hip_scale}×, ${(glbBytes.length / 1024).toFixed(0)} KB animated GLB.`,
+ },
+ ],
+ structuredContent: {
+ ok: true,
+ ...report,
+ format: 'glb',
+ glb_bytes: glbBytes.length,
+ glb_base64: glbBytes.toString('base64'),
+ mime_type: 'model/gltf-binary',
+ },
+ };
+ },
+ },
+];
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index 38a810235..dbe6791bc 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -4,7 +4,9 @@
// generation_status polls that job. preview_3d renders any GLB inline.
// remove_background strips image backgrounds (rembg/BRIA RMBG-2.0).
// remesh_model converts, simplifies, and repairs meshes.
+// stylize_model applies one-click geometric filters (voxel/brick/voronoi/lowpoly).
// retexture_model paints a new texture onto a mesh from a text prompt.
+// retexture_region (magic brush) repaints only a masked UV region, preserving the rest.
import { limits } from '../../_lib/rate-limit.js';
import { assertSafePublicUrl } from '../../_lib/ssrf-guard.js';
@@ -278,6 +280,37 @@ export const toolDefs = [
if (result.status === 'done' && result.resultGlbUrl) {
const glbUrl = result.resultGlbUrl;
+ // A segmentation job carries a parts manifest — surface the named,
+ // addressable parts (and where to inspect them) alongside the GLB.
+ if (Array.isArray(result.parts) && result.parts.length) {
+ const partLines = result.parts
+ .map((p) => ` • ${p.id} — ${p.name} (${p.face_count} faces, ${p.color})`)
+ .join('\n');
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Segmented into ${result.partCount || result.parts.length} parts.\n` +
+ `Segmented GLB (each part is a named node): ${glbUrl}\n` +
+ (result.manifestUrl ? `Parts manifest: ${result.manifestUrl}\n` : '') +
+ `Parts:\n${partLines}\n` +
+ 'Display the attached text/html resource as an inline 3D artifact.',
+ },
+ viewerArtifact({ glbUrl, name: 'Segmented 3D model' }),
+ ],
+ structuredContent: {
+ job_id: args.job_id,
+ status: 'done',
+ glb_url: glbUrl,
+ manifest_url: result.manifestUrl || null,
+ part_count: result.partCount || result.parts.length,
+ parts: result.parts,
+ source_faces: result.sourceFaces ?? null,
+ method: result.segmentMethod || null,
+ },
+ };
+ }
return {
content: [
{
@@ -417,7 +450,7 @@ export const toolDefs = [
name: 'remesh_model',
title: 'Remesh, simplify, repair, or convert a 3D model',
description:
- 'Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format. Returns a clean GLB (or the requested format) job_id to poll with generation_status.',
+ 'Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format (including FBX with skeleton for Unity/Unreal — a convert of a rigged GLB keeps its bones, skin weights, and blendshapes). Returns a clean GLB (or the requested format) job_id to poll with generation_status.',
inputSchema: {
type: 'object',
properties: {
@@ -441,8 +474,9 @@ export const toolDefs = [
},
output_format: {
type: 'string',
- enum: ['glb', 'obj', 'stl', 'ply', 'usdz', '3mf'],
+ enum: ['glb', 'obj', 'stl', 'ply', 'usdz', '3mf', 'fbx'],
default: 'glb',
+ description: 'Target format. fbx + operation=convert preserves a rigged GLB\'s skeleton, skin weights, and blendshapes (for Unity/Unreal); other operations produce a static fbx.',
},
},
required: ['mesh_url'],
@@ -563,6 +597,95 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'segment_model',
+ title: 'Split a 3D model into named, separable parts',
+ description:
+ 'Segment a GLB/OBJ/STL/PLY mesh into meaningful parts with clean boundaries — head/torso/limbs on a character, body/wheels on a vehicle. Splits at physically disconnected shells and at concave creases (the minima rule), then names each part by region and tints it a distinct colour. Returns a GLB whose nodes ARE the parts (so each can be hidden, recoloured, replaced, or exported on its own) plus a parts manifest. Poll with generation_status; the result lists every part with its id, name, face count, and colour. Pass only_part to export a single part on its own.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mesh_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of the source mesh (GLB/OBJ/FBX/STL/PLY).',
+ },
+ method: {
+ type: 'string',
+ enum: ['auto', 'connected', 'crease'],
+ default: 'auto',
+ description:
+ 'auto = disconnected shells + concave-crease splitting inside each shell (best); connected = split only at disconnected shells; crease = minima-rule crease splitting over the whole mesh.',
+ },
+ max_parts: {
+ type: 'integer',
+ minimum: 2,
+ maximum: 64,
+ default: 24,
+ description: 'Upper bound on parts. Smaller fragments are merged into neighbours until the count fits.',
+ },
+ min_part_faces: {
+ type: 'integer',
+ minimum: 4,
+ maximum: 100000,
+ default: 64,
+ description: 'Parts smaller than this many faces are merged into their largest neighbour.',
+ },
+ crease_angle: {
+ type: 'number',
+ minimum: 5,
+ maximum: 170,
+ default: 40,
+ description: 'Dihedral angle (degrees) above which a concave edge is treated as a part boundary. Lower = more parts.',
+ },
+ only_part: {
+ type: 'string',
+ maxLength: 64,
+ description: 'Optional: export just this part by id ("part_03") or name ("upper-left"). Run once without it to discover part ids.',
+ },
+ },
+ required: ['mesh_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!(await isPublicHttpsUrl(args.mesh_url))) {
+ return {
+ content: [{ type: 'text', text: 'Error: mesh_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ const provider = regenProvider('segment');
+ const job = await provider.submit({
+ mode: 'segment',
+ sourceUrl: args.mesh_url,
+ params: {
+ method: args.method || 'auto',
+ max_parts: args.max_parts || 24,
+ min_part_faces: args.min_part_faces || 64,
+ crease_angle: args.crease_angle ?? 40,
+ only_part: args.only_part,
+ },
+ });
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Segmentation started (${args.method || 'auto'}).\nJob ID: ${job.extJobId}\n` +
+ 'Poll with generation_status — when done it lists every named part. Typically completes in 10–60 seconds.',
+ },
+ ],
+ structuredContent: {
+ job_id: job.extJobId,
+ status: 'queued',
+ source_mesh_url: args.mesh_url,
+ method: args.method || 'auto',
+ eta_seconds: job.eta,
+ },
+ };
+ },
+ },
{
name: 'retexture_model',
title: 'Paint a new texture onto a 3D model from a text prompt',
@@ -640,4 +763,126 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'retexture_region',
+ title: 'Repaint one masked region of a model\'s texture (magic brush)',
+ description:
+ 'Surgically repaint ONLY a region of an existing texture from a prompt and/or colour, ' +
+ 'leaving the rest of the surface untouched and feathering the seam so the edit is invisible. ' +
+ 'Real SDXL inpainting in UV space — fix a seam, recolour one panel, add a logo to a chest plate. ' +
+ 'Supply mask_url: a UV-space mask PNG in the model\'s own UV layout where WHITE marks the area to ' +
+ 'repaint and black is preserved. Safe to run repeatedly — chain passes by feeding the previous ' +
+ 'result GLB back in as mesh_url. Returns a job_id to poll with generation_status.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mesh_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of the textured GLB to edit.',
+ },
+ mask_url: {
+ type: 'string',
+ format: 'uri',
+ description:
+ 'Public https URL of the UV-space mask PNG (white = repaint, black = keep), ' +
+ 'in the same UV layout as the mesh.',
+ },
+ prompt: {
+ type: 'string',
+ maxLength: 500,
+ description: 'What to paint into the masked region, e.g. "weathered copper plate".',
+ },
+ color: {
+ type: 'string',
+ pattern: '^#?[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$',
+ description: 'Optional target colour as a hex value, e.g. "#1e90ff".',
+ },
+ negative_prompt: {
+ type: 'string',
+ maxLength: 300,
+ default: 'blurry, low quality, distorted, watermark, seam',
+ },
+ texture_size: {
+ type: 'integer',
+ enum: [512, 1024, 2048],
+ default: 1024,
+ },
+ strength: {
+ type: 'number',
+ minimum: 0.2,
+ maximum: 1,
+ default: 0.85,
+ description: 'How aggressively to regenerate the region (higher = more change).',
+ },
+ feather: {
+ type: 'integer',
+ minimum: 1,
+ maximum: 128,
+ default: 24,
+ description: 'Seam feather radius in atlas pixels — larger blends softer.',
+ },
+ },
+ required: ['mesh_url', 'mask_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!(await isPublicHttpsUrl(args.mesh_url))) {
+ return {
+ content: [{ type: 'text', text: 'Error: mesh_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ if (!(await isPublicHttpsUrl(args.mask_url))) {
+ return {
+ content: [{ type: 'text', text: 'Error: mask_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ if (!args.prompt && !args.color) {
+ return {
+ content: [
+ { type: 'text', text: 'Error: provide a prompt and/or a color for the region.' },
+ ],
+ isError: true,
+ };
+ }
+ const provider = regenProvider('retex_region');
+ const job = await provider.submit({
+ mode: 'retex_region',
+ sourceUrl: args.mesh_url,
+ params: {
+ prompt: args.prompt || '',
+ negative_prompt: args.negative_prompt,
+ mask: args.mask_url,
+ color: args.color || null,
+ texture_size: args.texture_size || 1024,
+ strength: args.strength ?? 0.85,
+ feather: args.feather ?? 24,
+ },
+ });
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Region retexture started${args.prompt ? ` for "${args.prompt}"` : ''}.\n` +
+ `Job ID: ${job.extJobId}\n` +
+ 'Poll with generation_status. Typically completes in 30–90 seconds. ' +
+ 'To stack edits, feed the resulting GLB back in as mesh_url.',
+ },
+ ],
+ structuredContent: {
+ job_id: job.extJobId,
+ status: 'queued',
+ source_mesh_url: args.mesh_url,
+ mask_url: args.mask_url,
+ prompt: args.prompt || null,
+ color: args.color || null,
+ eta_seconds: job.eta,
+ },
+ };
+ },
+ },
];
diff --git a/api/_providers/gcp.js b/api/_providers/gcp.js
index 590b85089..19fba5421 100644
--- a/api/_providers/gcp.js
+++ b/api/_providers/gcp.js
@@ -59,6 +59,8 @@ function serviceUrlForMode(mode) {
case 'stylize':
return readEnv('GCP_STYLIZE_URL');
case 'retex':
+ case 'retex_region':
+ // Region (magic-brush) edits run on the same texture worker.
return readEnv('GCP_TEXTURE_URL');
case 'rembg':
return readEnv('GCP_REMBG_URL');
@@ -129,6 +131,28 @@ function buildWorkerRequest(request) {
};
}
+ if (mode === 'retex_region') {
+ // Magic brush: repaint only the masked UV region of the existing texture.
+ // The mask arrives as inline base64 (browser canvas) or a public URL.
+ return {
+ path: '/retexture_region',
+ resultKey: 'result_url',
+ body: {
+ mesh: sourceUrl,
+ prompt: params?.prompt || '',
+ negative_prompt:
+ params?.negative_prompt || 'blurry, low quality, distorted, watermark, seam',
+ mask_b64: params?.mask_b64 || null,
+ mask: params?.mask || null,
+ color: params?.color || null,
+ texture_size: params?.texture_size || 1024,
+ strength: params?.strength ?? 0.85,
+ feather: params?.feather ?? 24,
+ seed: params?.seed ?? 0,
+ },
+ };
+ }
+
if (mode === 'rembg') {
return {
path: '/remove',
@@ -176,6 +200,7 @@ const MODE_ETA = {
remesh: 30,
stylize: 25,
retex: 180,
+ retex_region: 60,
rembg: 5,
segment: 45,
rerig: 45,
diff --git a/api/_providers/meshy.js b/api/_providers/meshy.js
new file mode 100644
index 000000000..57eb20e5c
--- /dev/null
+++ b/api/_providers/meshy.js
@@ -0,0 +1,178 @@
+// Meshy provider — the geometry-first + high-poly backend.
+//
+// Two real Meshy endpoints back the two forge paths:
+//
+// geometry path → POST /openapi/v2/text-to-3d (mode: "preview")
+// Native text→geometry: emits an untextured mesh directly from the
+// prompt with no synthesized intermediate image. `target_polycount`
+// (from the quality tier) is honored via server-side remesh, so the
+// high tier yields a visibly denser mesh than draft.
+//
+// image path → POST /openapi/v1/image-to-3d
+// Single-image reconstruction with native geometry + PBR texturing.
+//
+// Both are asynchronous: submit returns a task id, which we poll on the
+// matching GET endpoint until SUCCEEDED, then read model_urls.glb.
+//
+// BYOK only: the caller passes the user's Meshy API key (msy_…). No platform
+// key — when absent, the forge endpoint never reaches this module.
+
+const MESHY_BASE = 'https://api.meshy.ai';
+
+// Meshy accepts 100–300,000 for target_polycount. Clamp the tier budget into
+// that window so a high-tier request never 422s on an out-of-range count.
+const POLY_MIN = 100;
+const POLY_MAX = 300_000;
+
+function clampPoly(n) {
+ const v = Math.round(Number(n) || 0);
+ return Math.max(POLY_MIN, Math.min(POLY_MAX, v));
+}
+
+function mapStatus(meshyStatus) {
+ switch (meshyStatus) {
+ case 'PENDING':
+ return 'queued';
+ case 'IN_PROGRESS':
+ return 'running';
+ case 'SUCCEEDED':
+ return 'done';
+ case 'FAILED':
+ case 'CANCELED':
+ return 'failed';
+ default:
+ return 'queued';
+ }
+}
+
+// The two Meshy task families live on different API versions; poll routes here.
+const ENDPOINT = Object.freeze({
+ 'text-to-3d': '/openapi/v2/text-to-3d',
+ 'image-to-3d': '/openapi/v1/image-to-3d',
+});
+
+export function createMeshyProvider(apiKey) {
+ if (!apiKey) {
+ throw Object.assign(new Error('Meshy API key is required'), { code: 'missing_key' });
+ }
+ const headers = {
+ authorization: `Bearer ${apiKey}`,
+ 'content-type': 'application/json',
+ };
+
+ async function postTask(path, body) {
+ let res;
+ try {
+ res = await fetch(`${MESHY_BASE}${path}`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ });
+ } catch (err) {
+ throw Object.assign(new Error(`meshy unreachable: ${err?.message}`), {
+ code: 'provider_unreachable',
+ status: 502,
+ });
+ }
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 401 || res.status === 403) {
+ throw Object.assign(new Error('Meshy rejected the API key.'), {
+ code: 'invalid_key',
+ status: 401,
+ providerStatus: res.status,
+ });
+ }
+ if (res.status === 402) {
+ throw Object.assign(new Error('Meshy account is out of credits.'), {
+ code: 'insufficient_credits',
+ status: 402,
+ providerStatus: 402,
+ });
+ }
+ if (res.status === 429) {
+ throw Object.assign(new Error('Meshy is rate limiting this key.'), {
+ code: 'rate_limited',
+ status: 429,
+ providerStatus: 429,
+ });
+ }
+ if (!res.ok) {
+ throw Object.assign(
+ new Error(data?.message || data?.error || `meshy returned ${res.status}`),
+ { code: 'provider_error', status: 502, providerStatus: res.status },
+ );
+ }
+ // v2 returns { result: "<id>" }; some endpoints return { id }.
+ const id = data.result || data.id;
+ if (!id) {
+ throw Object.assign(new Error('meshy accepted the task but returned no id'), {
+ code: 'provider_error',
+ status: 502,
+ });
+ }
+ return String(id);
+ }
+
+ return {
+ // Native geometry-first: text → untextured mesh, no intermediate image.
+ async textToGeometry({ prompt, tier }) {
+ const taskId = await postTask(ENDPOINT['text-to-3d'], {
+ mode: 'preview',
+ prompt: String(prompt).slice(0, 600),
+ ai_model: 'meshy-6',
+ topology: 'triangle',
+ target_polycount: clampPoly(tier.polycount),
+ should_remesh: true,
+ target_formats: ['glb'],
+ });
+ return { kind: 'text-to-3d', taskId };
+ },
+
+ // Single image → native geometry + textures, poly target from the tier.
+ async imageTo3d({ imageUrl, prompt, tier }) {
+ const body = {
+ image_url: imageUrl,
+ ai_model: 'meshy-6',
+ topology: 'triangle',
+ target_polycount: clampPoly(tier.polycount),
+ should_remesh: true,
+ should_texture: true,
+ enable_pbr: Boolean(tier.pbr),
+ hd_texture: Boolean(tier.hd),
+ target_formats: ['glb'],
+ };
+ if (prompt) body.texture_prompt = String(prompt).slice(0, 600);
+ const taskId = await postTask(ENDPOINT['image-to-3d'], body);
+ return { kind: 'image-to-3d', taskId };
+ },
+
+ // Poll a task on the endpoint matching its kind.
+ async status({ kind, taskId }) {
+ const base = ENDPOINT[kind];
+ if (!base) return { status: 'failed', error: `unknown meshy task kind "${kind}"` };
+ let res;
+ try {
+ res = await fetch(`${MESHY_BASE}${base}/${encodeURIComponent(taskId)}`, { headers });
+ } catch (err) {
+ return { status: 'running', error: `meshy poll failed: ${err?.message}` };
+ }
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 404) return { status: 'failed', error: 'meshy task not found' };
+ if (!res.ok) return { status: 'running', error: `meshy returned ${res.status}` };
+
+ const status = mapStatus(data.status);
+ const result = { status, progress: Number(data.progress) || 0 };
+ if (typeof data.consumed_credits === 'number') result.credits = data.consumed_credits;
+
+ if (status === 'done') {
+ const glb = data?.model_urls?.glb;
+ if (glb) result.resultGlbUrl = glb;
+ else result.error = 'meshy finished but produced no GLB';
+ }
+ if (status === 'failed') {
+ result.error = data?.task_error?.message || data?.task_error || 'meshy task failed';
+ }
+ return result;
+ },
+ };
+}
diff --git a/api/_providers/replicate.js b/api/_providers/replicate.js
index 41bfc489a..2a291f54a 100644
--- a/api/_providers/replicate.js
+++ b/api/_providers/replicate.js
@@ -45,6 +45,7 @@ const MODE_TO_ENV = Object.freeze({
restyle: 'REPLICATE_RESTYLE_MODEL',
remesh: 'REPLICATE_REMESH_MODEL',
retex: 'REPLICATE_RETEX_MODEL',
+ retex_region: 'REPLICATE_RETEX_REGION_MODEL',
rerig: 'REPLICATE_RERIG_MODEL',
});
diff --git a/api/_providers/tripo.js b/api/_providers/tripo.js
new file mode 100644
index 000000000..2a2e07532
--- /dev/null
+++ b/api/_providers/tripo.js
@@ -0,0 +1,179 @@
+// Tripo provider — alternative native geometry-first backend.
+//
+// geometry path → POST /v2/openapi/task { type: "text_to_model" }
+// Native text→model: clean (often quad) geometry directly from the
+// prompt. `face_limit` carries the tier's poly budget.
+//
+// image path → POST /v2/openapi/task { type: "image_to_model" }
+// Single-image reconstruction with PBR textures.
+//
+// Tripo wraps every response in { code, data } and polls a single task
+// endpoint regardless of type, so this client is simpler than Meshy's.
+//
+// BYOK only: the caller passes the user's Tripo key (tsk_…). The model version
+// defaults to v3.1 and is overridable via TRIPO_MODEL_VERSION.
+
+const TRIPO_BASE = 'https://api.tripo3d.ai/v2/openapi';
+const DEFAULT_MODEL_VERSION = 'v3.1-20260211';
+
+// Tripo's face_limit is unbounded upward in practice, but keep the same sane
+// floor/ceiling as the rest of the pipeline so a tier can't request an
+// unworkable mesh.
+const FACE_MIN = 100;
+const FACE_MAX = 300_000;
+
+function clampFaces(n) {
+ const v = Math.round(Number(n) || 0);
+ return Math.max(FACE_MIN, Math.min(FACE_MAX, v));
+}
+
+function modelVersion() {
+ if (typeof process !== 'undefined' && process.env?.TRIPO_MODEL_VERSION) {
+ return process.env.TRIPO_MODEL_VERSION;
+ }
+ return DEFAULT_MODEL_VERSION;
+}
+
+function mapStatus(s) {
+ switch (String(s || '').toLowerCase()) {
+ case 'queued':
+ return 'queued';
+ case 'running':
+ return 'running';
+ case 'success':
+ return 'done';
+ case 'failed':
+ case 'cancelled':
+ case 'banned':
+ case 'expired':
+ case 'unknown':
+ return 'failed';
+ default:
+ return 'queued';
+ }
+}
+
+// .jpg / .jpeg / .png — Tripo's image_to_model `file` needs an explicit type.
+function imageTypeFor(url) {
+ const m = /\.(jpe?g|png|webp)(\?|$)/i.exec(url || '');
+ const ext = m ? m[1].toLowerCase() : 'jpg';
+ return ext === 'jpeg' ? 'jpg' : ext;
+}
+
+export function createTripoProvider(apiKey) {
+ if (!apiKey) {
+ throw Object.assign(new Error('Tripo API key is required'), { code: 'missing_key' });
+ }
+ const headers = {
+ authorization: `Bearer ${apiKey}`,
+ 'content-type': 'application/json',
+ };
+
+ async function createTask(body) {
+ let res;
+ try {
+ res = await fetch(`${TRIPO_BASE}/task`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ });
+ } catch (err) {
+ throw Object.assign(new Error(`tripo unreachable: ${err?.message}`), {
+ code: 'provider_unreachable',
+ status: 502,
+ });
+ }
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 401 || res.status === 403) {
+ throw Object.assign(new Error('Tripo rejected the API key.'), {
+ code: 'invalid_key',
+ status: 401,
+ providerStatus: res.status,
+ });
+ }
+ if (res.status === 402 || data?.code === 2000) {
+ throw Object.assign(new Error('Tripo account is out of credits.'), {
+ code: 'insufficient_credits',
+ status: 402,
+ });
+ }
+ if (res.status === 429) {
+ throw Object.assign(new Error('Tripo is rate limiting this key.'), {
+ code: 'rate_limited',
+ status: 429,
+ providerStatus: 429,
+ });
+ }
+ // Tripo signals success with code 0; anything else is an error envelope.
+ if (!res.ok || data?.code !== 0) {
+ throw Object.assign(
+ new Error(data?.message || `tripo returned ${res.status} (code ${data?.code})`),
+ { code: 'provider_error', status: 502, providerStatus: res.status },
+ );
+ }
+ const taskId = data?.data?.task_id;
+ if (!taskId) {
+ throw Object.assign(new Error('tripo accepted the task but returned no task_id'), {
+ code: 'provider_error',
+ status: 502,
+ });
+ }
+ return String(taskId);
+ }
+
+ return {
+ async textToGeometry({ prompt, tier }) {
+ const taskId = await createTask({
+ type: 'text_to_model',
+ prompt: String(prompt).slice(0, 1024),
+ model_version: modelVersion(),
+ face_limit: clampFaces(tier.polycount),
+ texture: false,
+ pbr: false,
+ });
+ return { kind: 'task', taskId };
+ },
+
+ async imageTo3d({ imageUrl, tier }) {
+ const taskId = await createTask({
+ type: 'image_to_model',
+ file: { type: imageTypeFor(imageUrl), url: imageUrl },
+ model_version: modelVersion(),
+ face_limit: clampFaces(tier.polycount),
+ texture: true,
+ pbr: Boolean(tier.pbr),
+ });
+ return { kind: 'task', taskId };
+ },
+
+ // One status endpoint for every task type.
+ async status({ taskId }) {
+ let res;
+ try {
+ res = await fetch(`${TRIPO_BASE}/task/${encodeURIComponent(taskId)}`, { headers });
+ } catch (err) {
+ return { status: 'running', error: `tripo poll failed: ${err?.message}` };
+ }
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 404) return { status: 'failed', error: 'tripo task not found' };
+ if (!res.ok || data?.code !== 0) {
+ return { status: 'running', error: `tripo returned ${res.status}` };
+ }
+
+ const d = data.data || {};
+ const status = mapStatus(d.status);
+ const result = { status, progress: Number(d.progress) || 0 };
+
+ if (status === 'done') {
+ const out = d.output || d.result || {};
+ const glb = out.pbr_model || out.model || out.base_model;
+ if (glb) result.resultGlbUrl = glb;
+ else result.error = 'tripo finished but produced no model url';
+ }
+ if (status === 'failed') {
+ result.error = `tripo task ${d.status || 'failed'}`;
+ }
+ return result;
+ },
+ };
+}
diff --git a/api/avatar/render.js b/api/avatar/render.js
index f637bf1d5..016c45006 100644
--- a/api/avatar/render.js
+++ b/api/avatar/render.js
@@ -285,6 +285,9 @@ function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit,
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
window.__renderDone = false;
window.__renderError = null;
@@ -393,7 +396,19 @@ const poseMap = ${poseJson};
const expression = ${expressionJson};
const preset = ${presetJson};
-new GLTFLoader().load(${JSON.stringify(glbUrl)}, (gltf) => {
+// Pipeline GLBs ship Draco geometry, Meshopt buffers, and KTX2 textures;
+// a bare GLTFLoader throws "No DRACOLoader instance provided". Register
+// every standard compression decoder from the pinned three.js release.
+const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';
+const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');
+const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);
+
+const loader = new GLTFLoader();
+loader.setDRACOLoader(dracoLoader);
+loader.setKTX2Loader(ktx2Loader);
+loader.setMeshoptDecoder(MeshoptDecoder);
+
+loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
try {
const root = gltf.scene;
scene.add(root);
diff --git a/api/forge-remesh.js b/api/forge-remesh.js
index 20c669990..0bff2742e 100644
--- a/api/forge-remesh.js
+++ b/api/forge-remesh.js
@@ -7,7 +7,7 @@
* operation?: "full"|"simplify"|"repair"|"convert", // triangle mode only
* target_faces?: number,
* texture_size?: 512|1024|2048,
- * output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf"
+ * output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf"|"fbx"
* } → 202 { job_id, status }
*
* GET /api/forge-remesh?job=<id>
@@ -22,7 +22,7 @@ import { createRegenProvider } from './_providers/gcp.js';
const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;
const VALID_OPERATIONS = new Set(['full', 'simplify', 'repair', 'convert']);
-const VALID_FORMATS = new Set(['glb', 'obj', 'stl', 'ply', 'usdz', '3mf']);
+const VALID_FORMATS = new Set(['glb', 'obj', 'stl', 'ply', 'usdz', '3mf', 'fbx']);
const VALID_MODES = new Set(['triangle', 'quad', 'lowpoly']);
const VALID_TEXTURE_SIZES = new Set([512, 1024, 2048]);
diff --git a/api/forge.js b/api/forge.js
index 7594e2872..731c04340 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -22,6 +22,25 @@ import { cors, json, method, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { textToImage } from './_mcp3d/text-to-image.js';
import { createRegenProvider } from './_providers/replicate.js';
+import { createRegenProvider as createGcpProvider } from './_providers/gcp.js';
+import { createMeshyProvider } from './_providers/meshy.js';
+import { createTripoProvider } from './_providers/tripo.js';
+import {
+ PATHS,
+ DEFAULT_PATH,
+ TIER_IDS,
+ DEFAULT_TIER,
+ BACKENDS,
+ resolveTier,
+ resolveBackendId,
+ backendIsConfigured,
+ estimateEtaSeconds,
+ estimateCredits,
+ buildCatalog,
+} from './_lib/forge-tiers.js';
+import { getSessionUser } from './_lib/auth.js';
+import { sql } from './_lib/db.js';
+import { loadUserProviderKeys } from './_lib/provider-keys.js';
import {
hashClient,
hashIp,
@@ -55,6 +74,76 @@ function clientKeyFrom(req) {
return hashClient(Array.isArray(raw) ? raw[0] : raw);
}
+// Resolve the requested generation path + quality tier from the body, falling
+// back to the existing fast defaults (image-intermediate, standard tier).
+function parsePath(body) {
+ const p = typeof body?.path === 'string' ? body.path.trim() : '';
+ return PATHS.includes(p) ? p : DEFAULT_PATH;
+}
+function parseTier(body) {
+ const t = typeof body?.tier === 'string' ? body.tier.trim() : '';
+ return TIER_IDS.includes(t) ? t : DEFAULT_TIER;
+}
+
+// BYOK key resolution for the geometry providers (Meshy / Tripo). No platform
+// key exists for these, so the key must come from the caller. Two real sources,
+// in priority order:
+// 1. An inline key on the request — header `x-forge-provider-key` (preferred,
+// kept out of URLs/logs) or `provider_key` in the POST body. Used
+// transiently and never persisted.
+// 2. The signed-in user's stored, encrypted key (the dashboard BYOK store),
+// when the request carries a session cookie.
+// Returns the plaintext key or null when none is available.
+async function resolveProviderKey(req, body, providerName) {
+ const header = req.headers['x-forge-provider-key'];
+ const inline =
+ (typeof header === 'string' && header) ||
+ (Array.isArray(header) && header[0]) ||
+ (typeof body?.provider_key === 'string' ? body.provider_key : '');
+ if (inline && inline.trim()) return inline.trim();
+
+ try {
+ const session = await getSessionUser(req);
+ if (session?.id) {
+ const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${session.id}`;
+ const keys = await loadUserProviderKeys(row?.provider_keys);
+ if (keys[providerName]) return keys[providerName];
+ }
+ } catch {
+ // No DB / no session — fall through to "no key".
+ }
+ return null;
+}
+
+// Jobs from the geometry providers are polled on a different upstream than the
+// default Replicate path, so we hand the browser an opaque token that records
+// which provider + task-kind to poll. The legacy Replicate path keeps returning
+// its bare prediction id (it matches JOB_ID_RE), so old links never break.
+function encodeJobToken({ provider, kind, taskId }) {
+ return `f1.${Buffer.from(JSON.stringify({ p: provider, k: kind, t: taskId }), 'utf8').toString('base64url')}`;
+}
+function decodeJobToken(token) {
+ if (typeof token !== 'string' || !token.startsWith('f1.')) return null;
+ try {
+ const obj = JSON.parse(Buffer.from(token.slice(3), 'base64url').toString('utf8'));
+ if (!obj?.p || !obj?.t) return null;
+ return { provider: obj.p, kind: obj.k || null, taskId: String(obj.t) };
+ } catch {
+ return null;
+ }
+}
+
+// "needs a BYOK key" — a designed, branchable state (mirrors rig_unconfigured)
+// rather than a generic error, so the page can prompt for the key inline.
+function needsKey(res, providerName) {
+ const meta = BACKENDS[providerName];
+ return json(res, 501, {
+ error: 'needs_key',
+ provider: providerName,
+ message: `The geometry path uses ${meta?.label || providerName}, which needs your own API key. Add a ${meta?.byok || providerName} key to use it.`,
+ });
+}
+
// Normalize the caller's reference image input into an ordered, de-duplicated
// list of view URLs. Accepts the multi-view `image_urls: string[]` form and the
// legacy single `image_url: string` (backward compatible — a single string
@@ -140,14 +229,94 @@ async function startJob(req, res) {
}
const aspect = VALID_ASPECT.has(body?.aspect_ratio) ? body.aspect_ratio : '1:1';
- let provider;
- try {
- provider = createRegenProvider();
- } catch {
- return unconfigured(res);
- }
+ // Two request axes beyond input mode: which generation path (image-
+ // intermediate vs geometry-first) and which quality tier (poly budget).
+ const path = parsePath(body);
+ const tier = resolveTier(parseTier(body));
+ const backendId = resolveBackendId({ path, backend: body?.backend });
try {
+ // ── Geometry-first path (Meshy / Tripo, BYOK) ───────────────────────────
+ // A native 3D model emits mesh geometry directly — from the prompt
+ // (text→geometry) or a single photo (image→3D) — with no synthesized
+ // intermediate view, so detail isn't capped by one image. These backends
+ // have no platform key; the caller supplies their own.
+ if (path === 'geometry') {
+ const providerName = BACKENDS[backendId].byok; // 'meshy' | 'tripo'
+ const key = await resolveProviderKey(req, body, providerName);
+ if (!key) return needsKey(res, backendId);
+
+ let gp;
+ try {
+ gp = backendId === 'tripo' ? createTripoProvider(key) : createMeshyProvider(key);
+ } catch {
+ return needsKey(res, backendId);
+ }
+
+ let submitted;
+ let previewImageUrl = null;
+ if (isImageMode) {
+ // The native image→3D endpoints reconstruct from a single primary
+ // view; multi-view fusion stays on the image/TRELLIS path.
+ previewImageUrl = imageUrls[0];
+ submitted = await gp.imageTo3d({ imageUrl: previewImageUrl, prompt: prompt || undefined, tier });
+ } else {
+ submitted = await gp.textToGeometry({ prompt, tier });
+ }
+
+ const token = encodeJobToken({ provider: providerName, kind: submitted.kind, taskId: submitted.taskId });
+
+ // Store the upstream task id as the job handle so findByJob/materialize
+ // resolve it on poll, exactly like the Replicate path.
+ const creationId = await createCreation({
+ clientKey: clientKeyFrom(req),
+ ipHash: hashIp(ip),
+ prompt: prompt || (isImageMode ? 'image-to-3d' : ''),
+ aspect: isImageMode ? null : aspect,
+ previewImageUrl,
+ replicateJobId: submitted.taskId,
+ textToImageModel: null,
+ viewsRequested: isImageMode ? imageUrls.length : 0,
+ viewsUsed: isImageMode ? 1 : null,
+ multiview: false,
+ backend: backendId,
+ tier: tier.id,
+ path,
+ });
+
+ return json(res, 200, {
+ job_id: token,
+ creation_id: creationId,
+ status: 'queued',
+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
+ path,
+ tier: tier.id,
+ backend: backendId,
+ prompt: prompt || null,
+ preview_image_url: previewImageUrl,
+ reference_image_urls: isImageMode ? [imageUrls[0]] : [],
+ eta_seconds: estimateEtaSeconds({ backendId, tier }),
+ estimated_credits: estimateCredits({ backendId, path, tier }),
+ });
+ }
+
+ // ── Image-intermediate path (TRELLIS default, or Hunyuan3D self-host) ────
+ let provider;
+ try {
+ provider = backendId === 'hunyuan3d' ? createGcpProvider() : createRegenProvider();
+ } catch {
+ // A selected-but-unconfigured self-host backend gets a branchable 501;
+ // the default TRELLIS path keeps its existing "not configured" 503.
+ if (backendId === 'hunyuan3d') {
+ return json(res, 501, {
+ error: 'backend_unconfigured',
+ backend: 'hunyuan3d',
+ message: 'Hunyuan3D self-host is not configured on this deployment.',
+ });
+ }
+ return unconfigured(res);
+ }
+
// Resolve the reference views: supplied directly (image→3D) or a single
// view synthesized from the prompt (text→3D). `referenceImageUrl` is the
// primary view — the durable preview + the synthesis target.
@@ -165,10 +334,20 @@ async function startJob(req, res) {
views = [referenceImageUrl];
}
+ // Only poly-aware backends (Hunyuan3D self-host) accept a target budget;
+ // TRELLIS validates its input schema and would 422 on an unknown field, so
+ // the tier rides along as the recorded provenance only.
+ const reconstructParams = { images: views, prompt: prompt || undefined };
+ if (BACKENDS[backendId].polyControl) {
+ reconstructParams.target_polycount = tier.polycount;
+ reconstructParams.tier = tier.id;
+ reconstructParams.path = path;
+ }
+
const job = await provider.submit({
mode: 'reconstruct',
sourceUrl: referenceImageUrl,
- params: { images: views, prompt: prompt || undefined },
+ params: reconstructParams,
});
// How the job was actually conditioned. The provider reports back which
@@ -178,7 +357,15 @@ async function startJob(req, res) {
const viewsRequested = views.length;
const viewsUsed = typeof job.viewsUsed === 'number' ? job.viewsUsed : viewsRequested;
const multiview = Boolean(job.multiview);
- const backend = job.backend || 'replicate';
+
+ // TRELLIS returns a bare Replicate prediction id (kept as the job handle
+ // for backward compatibility); the GCP/Hunyuan3D provider returns its own
+ // opaque envelope, which we wrap in a forge token so polling routes back to
+ // the GCP provider. Either way the upstream id is what the store keys on.
+ const jobHandle =
+ backendId === 'hunyuan3d'
+ ? encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId })
+ : job.extJobId;
// Record the generation the moment it starts so the prompt + reference
// image survive even if the mesh step later fails. Fail-soft: a missing
@@ -194,29 +381,45 @@ async function startJob(req, res) {
viewsRequested,
viewsUsed,
multiview,
- backend,
+ backend: backendId,
+ tier: tier.id,
+ path,
});
return json(res, 200, {
- job_id: job.extJobId,
+ job_id: jobHandle,
creation_id: creationId,
status: 'queued',
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
+ path,
+ tier: tier.id,
+ backend: backendId,
prompt: prompt || null,
preview_image_url: referenceImageUrl,
reference_image_urls: views,
views_requested: viewsRequested,
views_used: viewsUsed,
multiview,
- backend,
text_to_image_model: textToImageModel,
- eta_seconds: typeof job.eta === 'number' ? job.eta : null,
+ eta_seconds: estimateEtaSeconds({ backendId, tier }),
+ estimated_credits: estimateCredits({ backendId, path, tier }),
});
} catch (err) {
if (err?.code === 'unconfigured') return unconfigured(res);
- // Upstream (Replicate) throttling is a transient 429, not a server fault —
- // return it as such with a retry hint so the page can show a "busy, try
- // again shortly" state instead of a hard error.
+ if (err?.code === 'invalid_key') {
+ return json(res, 401, {
+ error: 'invalid_key',
+ message: err.message || 'The provider rejected this API key.',
+ });
+ }
+ if (err?.code === 'insufficient_credits') {
+ return json(res, 402, {
+ error: 'insufficient_credits',
+ message: err.message || 'The provider account is out of credits.',
+ });
+ }
+ // Upstream throttling is a transient 429, not a server fault — return it as
+ // such with a retry hint so the page can show a "busy, try again" state.
if (err?.code === 'rate_limited' || err?.providerStatus === 429) {
return json(res, 429, {
error: 'rate_limited',
@@ -310,7 +513,11 @@ async function startRigJob(req, res) {
}
async function pollJob(req, res, jobId) {
- if (!JOB_ID_RE.test(jobId)) {
+ // A job handle is either a bare Replicate prediction id (legacy / image-
+ // TRELLIS path) or a forge token encoding the geometry/GCP provider + the
+ // upstream task id. Decode to learn which provider to poll.
+ const token = decodeJobToken(jobId);
+ if (!token && !JOB_ID_RE.test(jobId)) {
return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
}
@@ -322,41 +529,79 @@ async function pollJob(req, res, jobId) {
});
}
- let provider;
- try {
- provider = createRegenProvider();
- } catch {
- return unconfigured(res);
- }
-
+ const provider = token?.provider || 'replicate';
+ const upstreamId = token?.taskId || jobId;
const clientKey = clientKeyFrom(req);
- // How this job was conditioned (view count + backend), recorded at submit
- // time. Surfaced on every poll so a caller that only polls still learns
- // whether multi-view was honored. Fail-soft: absent when the store is off.
- const meta = await findByJob({ replicateJobId: jobId, clientKey });
+ // How this job was conditioned (path + tier + backend + view count), recorded
+ // at submit time. Surfaced on every poll so a caller that only polls still
+ // learns the provenance. Fail-soft: absent when the store is off.
+ const meta = await findByJob({ replicateJobId: upstreamId, clientKey });
const metaFields = meta
? {
views_requested: meta.views_requested ?? null,
views_used: meta.views_used ?? null,
multiview: meta.multiview ?? null,
backend: meta.backend ?? null,
+ tier: meta.tier ?? null,
+ path: meta.path ?? null,
}
: {};
- const result = await provider.status(jobId);
+ // Poll the provider that owns this job. BYOK providers re-resolve the key per
+ // poll (the client resends it, or it loads from the session store).
+ let result;
+ try {
+ if (provider === 'meshy' || provider === 'tripo') {
+ const key = await resolveProviderKey(req, null, provider);
+ if (!key) {
+ return json(res, 200, {
+ job_id: jobId,
+ status: 'failed',
+ error: 'Your API key is required to check this job. Re-enter it and retry.',
+ ...metaFields,
+ });
+ }
+ const gp = provider === 'tripo' ? createTripoProvider(key) : createMeshyProvider(key);
+ result = await gp.status({ kind: token.kind, taskId: upstreamId });
+ } else if (provider === 'gcp') {
+ let gcp;
+ try {
+ gcp = createGcpProvider();
+ } catch {
+ return json(res, 501, {
+ error: 'backend_unconfigured',
+ message: 'Hunyuan3D self-host is not configured on this deployment.',
+ });
+ }
+ result = await gcp.status(upstreamId);
+ } else {
+ let rep;
+ try {
+ rep = createRegenProvider();
+ } catch {
+ return unconfigured(res);
+ }
+ result = await rep.status(jobId);
+ }
+ } catch {
+ // A transient poll error shouldn't fail the job — report running so the
+ // client's loop retries.
+ return json(res, 200, { job_id: jobId, status: 'running', ...metaFields });
+ }
+
if (result.status === 'done' && result.resultGlbUrl) {
- // Copy the mesh + reference image into our own storage so the model is
- // permanent (Replicate delivery URLs expire in ~1h) and serve the durable
- // CDN url. Falls back to the provider url where the store is unavailable.
+ // Copy the mesh into our own storage so the model is permanent (provider
+ // delivery URLs expire) and serve the durable CDN url. Falls back to the
+ // provider url where the store is unavailable.
const durable = await materializeCreation({
- replicateJobId: jobId,
+ replicateJobId: upstreamId,
clientKey,
glbUrl: result.resultGlbUrl,
});
return json(res, 200, {
job_id: jobId,
- creation_id: durable?.id ?? null,
+ creation_id: durable?.id ?? meta?.id ?? null,
status: 'done',
glb_url: durable?.glbUrl ?? result.resultGlbUrl,
durable: Boolean(durable),
@@ -364,7 +609,7 @@ async function pollJob(req, res, jobId) {
});
}
if (result.status === 'failed') {
- await markFailed({ replicateJobId: jobId, clientKey, error: result.error });
+ await markFailed({ replicateJobId: upstreamId, clientKey, error: result.error });
return json(res, 200, {
job_id: jobId,
status: 'failed',
@@ -390,6 +635,13 @@ export default wrap(async (req, res) => {
return startJob(req, res);
}
+ // ?catalog — the tier + backend + cost/time matrix the composer renders.
+ // Public, no secrets; lets the UI communicate the time/cost trade-off and
+ // which backends are live before the user commits.
+ if (url.searchParams.has('catalog')) {
+ return json(res, 200, buildCatalog());
+ }
+
const jobId = (url.searchParams.get('job') || '').trim();
if (!jobId) {
return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll a job.' });
diff --git a/api/studio/retexture-region.js b/api/studio/retexture-region.js
new file mode 100644
index 000000000..bf9f81d70
--- /dev/null
+++ b/api/studio/retexture-region.js
@@ -0,0 +1,178 @@
+// Magic Brush — local region retexture.
+//
+// POST /api/studio/retexture-region submit a masked region edit → { job }
+// GET /api/studio/retexture-region?job=<token> poll → { status, result_url? }
+//
+// Repaints ONLY the masked UV region of an existing texture from a prompt and/or
+// colour, preserving the rest of the surface and feathering the seam. The heavy
+// SDXL inpainting runs on the GCP texture worker (workers/texture/main.py,
+// /retexture_region); this endpoint is the thin, auth'd, SSRF-guarded gateway.
+//
+// Stateless jobs: the worker task handle (mode + taskId + worker baseUrl) is
+// packed into the opaque `job` token the provider returns. We hand that straight
+// back to the client and, on status, re-validate that its baseUrl is the worker
+// we actually configured before polling — so a forged token can never steer the
+// server's fetch at an attacker-chosen host (no SSRF, no DB row needed).
+
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { limits } from '../_lib/rate-limit.js';
+import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';
+import { createRegenProvider } from '../_providers/gcp.js';
+import { parse } from '../_lib/validate.js';
+import { z } from 'zod';
+
+const MODE = 'retex_region';
+
+// Mask is a small 1-channel PNG; base64 of a 1024² mask is well under 1 MB even
+// when busy. Cap generously and let readJson enforce the transport ceiling.
+const MAX_MASK_B64 = 10 * 1024 * 1024;
+
+const submitSchema = z
+ .object({
+ mesh_url: z.string().trim().url().max(2048),
+ prompt: z.string().trim().max(500).optional().default(''),
+ negative_prompt: z.string().trim().max(300).optional(),
+ mask_b64: z.string().min(1).max(MAX_MASK_B64),
+ color: z
+ .string()
+ .trim()
+ .regex(/^#?[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/, 'color must be a hex value')
+ .optional(),
+ texture_size: z
+ .union([z.literal(512), z.literal(1024), z.literal(2048)])
+ .optional()
+ .default(1024),
+ strength: z.number().min(0.2).max(1).optional().default(0.85),
+ feather: z.number().int().min(1).max(128).optional().default(24),
+ seed: z.number().int().min(0).max(2 ** 31).optional().default(0),
+ })
+ .refine((b) => b.prompt.length >= 3 || !!b.color, {
+ message: 'provide a prompt (3+ chars) and/or a color',
+ });
+
+async function resolveUser(req, scope) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer && hasScope(bearer.scope, scope)) return bearer.userId;
+ return null;
+}
+
+function getProviderOr501(res) {
+ try {
+ return createRegenProvider();
+ } catch (err) {
+ error(
+ res,
+ 501,
+ 'region_retex_unconfigured',
+ 'Region retexture requires the GCP texture worker. Set GCP_RECONSTRUCTION_KEY and GCP_TEXTURE_URL.',
+ { reason: err.message },
+ );
+ return null;
+ }
+}
+
+// Re-validate that an opaque job token points at THE worker we configured, not
+// an attacker-supplied URL. Returns true when safe to poll.
+function tokenTargetsOurWorker(token) {
+ try {
+ const job = JSON.parse(Buffer.from(String(token), 'base64url').toString('utf8'));
+ if (job?.mode !== MODE || !job?.baseUrl) return false;
+ const configured = (process.env.GCP_TEXTURE_URL || '').replace(/\/$/, '');
+ if (!configured) return false;
+ return String(job.baseUrl).replace(/\/$/, '') === configured;
+ } catch {
+ return false;
+ }
+}
+
+async function handleSubmit(req, res) {
+ const userId = await resolveUser(req, 'avatars:write');
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+
+ const rl = await limits.upload(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests — try again shortly');
+
+ const body = parse(submitSchema, await readJson(req, 12 * 1024 * 1024));
+
+ // The worker fetches the mesh server-side; validate it resolves to a public
+ // host before we hand it off (the worker re-checks, but fail fast + clearly).
+ try {
+ await assertSafePublicUrl(body.mesh_url, { allowHttp: false });
+ } catch {
+ return error(res, 400, 'invalid_mesh_url', 'mesh_url must be a public https URL');
+ }
+
+ const provider = getProviderOr501(res);
+ if (!provider) return;
+
+ let submission;
+ try {
+ submission = await provider.submit({
+ mode: MODE,
+ sourceUrl: body.mesh_url,
+ params: {
+ prompt: body.prompt,
+ negative_prompt: body.negative_prompt,
+ mask_b64: body.mask_b64,
+ color: body.color || null,
+ texture_size: body.texture_size,
+ strength: body.strength,
+ feather: body.feather,
+ seed: body.seed,
+ },
+ });
+ } catch (err) {
+ return error(
+ res,
+ err.status || 502,
+ err.code || 'provider_error',
+ err.message || 'texture worker rejected the job',
+ );
+ }
+
+ return json(res, 202, {
+ ok: true,
+ job: submission.extJobId,
+ status: 'queued',
+ eta: submission.eta ?? null,
+ });
+}
+
+async function handleStatus(req, res) {
+ const userId = await resolveUser(req, 'avatars:read');
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+
+ const url = new URL(req.url, 'http://x');
+ const token = url.searchParams.get('job');
+ if (!token) return error(res, 400, 'invalid_request', 'job token required');
+ if (!tokenTargetsOurWorker(token)) {
+ return error(res, 400, 'invalid_job', 'job token is malformed or not recognized');
+ }
+
+ const provider = getProviderOr501(res);
+ if (!provider) return;
+
+ let update;
+ try {
+ update = await provider.status(token);
+ } catch (err) {
+ return error(res, 502, 'provider_error', err.message || 'status poll failed');
+ }
+
+ return json(res, 200, {
+ ok: true,
+ status: update.status,
+ result_url: update.resultGlbUrl ?? null,
+ error: update.error ?? null,
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (req.method === 'POST') return handleSubmit(req, res);
+ return handleStatus(req, res);
+});
diff --git a/api/user/provider-keys.js b/api/user/provider-keys.js
index 9e43427c8..edbef6ee7 100644
--- a/api/user/provider-keys.js
+++ b/api/user/provider-keys.js
@@ -1,6 +1,6 @@
// GET /api/user/provider-keys — returns which keys are set (never returns values)
// PATCH /api/user/provider-keys — set or clear individual provider keys
-// body: { anthropic?: string | null, openai?: string | null, meshy?: string | null }
+// body: { anthropic?: string | null, openai?: string | null, meshy?: string | null, tripo?: string | null }
// null = delete that key; string = store encrypted
import { sql } from '../_lib/db.js';
@@ -14,6 +14,7 @@ const patchSchema = z.object({
anthropic: z.string().min(1).max(512).nullable().optional(),
openai: z.string().min(1).max(512).nullable().optional(),
meshy: z.string().min(1).max(512).nullable().optional(),
+ tripo: z.string().min(1).max(512).nullable().optional(),
});
export default wrap(async (req, res) => {
diff --git a/pages/forge.html b/pages/forge.html
index 3ca2143d9..5295402c4 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -608,6 +608,295 @@
color: var(--danger);
}
+ /* Optimize / retopology panel --------------------------------- */
+ .optimize {
+ border-top: 1px solid var(--stroke);
+ }
+ .optimize-toggle {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ background: transparent;
+ border: none;
+ color: var(--ink);
+ font-family: var(--font-display);
+ font-weight: 600;
+ font-size: var(--text-sm);
+ padding: var(--space-sm) var(--space-md);
+ cursor: pointer;
+ }
+ .optimize-toggle:hover {
+ background: var(--surface-2);
+ }
+ .optimize-toggle:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+ }
+ .optimize-toggle .chev {
+ transition: transform 0.18s ease;
+ color: var(--ink-dim);
+ }
+ .optimize[data-open='true'] .optimize-toggle .chev {
+ transform: rotate(180deg);
+ }
+ .optimize-body {
+ display: none;
+ flex-direction: column;
+ gap: var(--space-md);
+ padding: 0 var(--space-md) var(--space-md);
+ }
+ .optimize[data-open='true'] .optimize-body {
+ display: flex;
+ }
+ .opt-field {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+ }
+ .opt-field > span {
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ }
+ .seg {
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: 2px;
+ }
+ .seg button {
+ flex: 1 1 auto;
+ background: transparent;
+ border: none;
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ padding: 0.4rem 0.7rem;
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+ }
+ .seg button:hover {
+ color: var(--ink);
+ }
+ .seg button[aria-pressed='true'] {
+ background: var(--surface-3);
+ color: var(--ink);
+ }
+ .seg button:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .opt-mode-hint {
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ line-height: 1.4;
+ min-height: 1.4em;
+ }
+ .opt-row {
+ display: flex;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+ }
+ .opt-row .opt-field {
+ flex: 1 1 140px;
+ }
+ .opt-select {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ color: var(--ink);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ padding: 0.45rem 0.6rem;
+ }
+ .opt-select:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+ }
+ .opt-actions {
+ display: flex;
+ align-items: center;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+ }
+ .opt-status {
+ font-size: var(--text-xs);
+ font-family: var(--font-mono);
+ color: var(--ink-dim);
+ }
+ .opt-status[data-kind='error'] {
+ color: var(--danger);
+ }
+ .opt-status[data-kind='done'] {
+ color: var(--success);
+ }
+ .opt-stats {
+ display: flex;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .opt-stats strong {
+ color: var(--ink);
+ font-weight: 600;
+ }
+
+ /* Stylize — one-click geometric filters ----------------------- */
+ .stylize {
+ border-top: 1px solid var(--stroke);
+ padding: var(--space-md);
+ }
+ .stylize-head h3 {
+ font-family: var(--font-display);
+ font-size: var(--text-base);
+ margin: 0 0 0.15rem;
+ }
+ .stylize-sub {
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ margin: 0 0 var(--space-md);
+ max-width: 60ch;
+ }
+ .stylize-gallery {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
+ gap: var(--space-sm);
+ }
+ .stylize-card {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.35rem;
+ text-align: left;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: var(--space-sm);
+ cursor: pointer;
+ color: var(--ink);
+ font: inherit;
+ transition: border-color 0.15s, transform 0.12s, box-shadow 0.15s, background 0.15s;
+ }
+ .stylize-card:hover {
+ border-color: var(--stroke-strong);
+ transform: translateY(-2px);
+ box-shadow: 0 16px 36px -26px rgba(0, 0, 0, 0.9);
+ }
+ .stylize-card:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .stylize-card:active {
+ transform: translateY(0);
+ }
+ .stylize-card[aria-pressed='true'] {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .stylize-card[disabled] {
+ opacity: 0.5;
+ cursor: not-allowed;
+ transform: none;
+ box-shadow: none;
+ }
+ .stylize-thumb {
+ width: 100%;
+ aspect-ratio: 16 / 10;
+ display: grid;
+ place-items: center;
+ border-radius: var(--radius-sm);
+ background: radial-gradient(120% 120% at 50% 0%, #161616 0%, #0c0c0c 75%);
+ color: var(--ink-dim);
+ transition: color 0.15s, transform 0.2s ease;
+ }
+ .stylize-thumb svg {
+ width: 58%;
+ height: 58%;
+ }
+ .stylize-card:hover .stylize-thumb,
+ .stylize-card[aria-pressed='true'] .stylize-thumb {
+ color: var(--accent);
+ }
+ .stylize-card:hover .stylize-thumb svg {
+ transform: scale(1.08) rotate(-4deg);
+ }
+ .stylize-name {
+ font-family: var(--font-display);
+ font-weight: 600;
+ font-size: var(--text-sm);
+ }
+ .stylize-blurb {
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+ }
+ .stylize-controls {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-md);
+ margin-top: var(--space-md);
+ flex-wrap: wrap;
+ }
+ .stylize-slider {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-sm);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .stylize-slider input[type='range'] {
+ accent-color: var(--accent);
+ width: 160px;
+ cursor: pointer;
+ }
+ .stylize-slider input[type='range']:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 3px;
+ }
+ .stylize-slider output {
+ color: var(--ink);
+ min-width: 2.5ch;
+ text-align: right;
+ }
+ .stylize-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+ flex-wrap: wrap;
+ }
+ .stylize-status {
+ margin-top: var(--space-sm);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ min-height: 1.2em;
+ }
+ .stylize-status[data-kind='busy'] {
+ color: var(--accent);
+ }
+ .stylize-status[data-kind='error'] {
+ color: var(--danger);
+ }
+ .stylize-status[data-kind='done'] {
+ color: var(--success);
+ }
+ .stylize[data-busy='true'] .stylize-thumb svg {
+ animation: spin 1.1s linear infinite;
+ }
+
/* Your creations gallery -------------------------------------- */
.creations {
margin-top: var(--space-2xl);
@@ -746,23 +1035,66 @@
<main class="forge-main">
<header class="forge-head">
- <span class="forge-eyebrow">Text → 3D · live</span>
- <h1>Forge a 3D model from words</h1>
+ <span class="forge-eyebrow">Text · Image · Multi-view → 3D · live</span>
+ <h1>Forge a 3D model from words or photos</h1>
<p>
- Describe one object clearly. Forge paints a reference image, then reconstructs a
- textured mesh you can orbit, view in AR, and download as GLB.
+ Describe an object, or upload up to four photos of it from different angles. Forge
+ reconstructs a textured mesh you can orbit, view in AR, and download as GLB — and
+ more views mean a sharper model with no guessed-at back.
</p>
</header>
+ <div class="mode-switch-wrap">
+ <div class="mode-switch" role="tablist" aria-label="Generation mode" id="mode-switch">
+ <button type="button" role="tab" data-mode="text" aria-selected="true">
+ Describe it
+ </button>
+ <button type="button" role="tab" data-mode="image" aria-selected="false">
+ From photos
+ </button>
+ </div>
+ </div>
+
<form class="composer" id="composer" autocomplete="off">
- <label for="prompt" class="is-hidden">Describe the object to generate</label>
- <textarea
- id="prompt"
- name="prompt"
- maxlength="1000"
- placeholder="a worn leather armchair, studio lighting, plain background"
- aria-describedby="prompt-hint"
- ></textarea>
+ <!-- Text → 3D -->
+ <div id="text-pane">
+ <label for="prompt" class="is-hidden">Describe the object to generate</label>
+ <textarea
+ id="prompt"
+ name="prompt"
+ maxlength="1000"
+ placeholder="a worn leather armchair, studio lighting, plain background"
+ aria-describedby="prompt-hint"
+ ></textarea>
+ </div>
+
+ <!-- Image / multi-view → 3D -->
+ <div id="image-pane" class="image-pane is-hidden">
+ <div
+ class="views-grid"
+ id="views-grid"
+ aria-label="Reference views — add up to four photos of the same object"
+ ></div>
+ <input
+ type="file"
+ id="view-file-input"
+ accept="image/png,image/jpeg,image/webp"
+ multiple
+ hidden
+ />
+ <label for="image-prompt" class="is-hidden">Optional guidance for reconstruction</label>
+ <textarea
+ id="image-prompt"
+ class="image-prompt"
+ maxlength="1000"
+ placeholder="Optional guidance — e.g. “matte plastic, neutral pose, no background”"
+ ></textarea>
+ <p class="views-hint">
+ Add 1–4 views of the <strong>same</strong> object (front · back · left · right).
+ Drag to drop, click to browse, drag a thumbnail to reorder. PNG/JPG/WebP, up to 8&nbsp;MB each.
+ </p>
+ </div>
+
<div class="composer-row">
<div
class="aspect"
@@ -795,8 +1127,9 @@
<span class="glyph" aria-hidden="true">◳</span>
<h3>Nothing forged yet</h3>
<p>
- Type a description above or tap an example. Generation runs a fast image pass,
- then a mesh reconstruction — usually 30–90 seconds.
+ Type a description and tap an example, or switch to <strong>From photos</strong> and
+ drop in up to four views of one object. Generation reconstructs a textured mesh —
+ usually 30–90 seconds.
</p>
</div>
@@ -842,6 +1175,7 @@
></model-viewer>
<div class="result-bar">
<span class="label" id="result-label"></span>
+ <span class="views-badge is-hidden" id="result-views" title="Reference views fused"></span>
<div class="actions">
<div
class="verdict"
@@ -870,10 +1204,130 @@
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
Share
</button>
+ <a class="btn btn-ghost" id="forge-segment-btn" title="Split this model into selectable parts">Split into parts</a>
<a class="btn btn-ghost" id="download" download>Download GLB</a>
<button class="btn" type="button" id="again">Make another</button>
</div>
</div>
+
+ <!-- Optimize topology: triangle / quad / low-poly remesh -->
+ <div class="optimize" id="optimize" data-open="false">
+ <button
+ class="optimize-toggle"
+ type="button"
+ id="optimize-toggle"
+ aria-expanded="false"
+ aria-controls="optimize-body"
+ >
+ <span>Optimize topology — quad remesh &amp; game-ready low-poly</span>
+ <svg
+ class="chev"
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <polyline points="6 9 12 15 18 9" />
+ </svg>
+ </button>
+ <div class="optimize-body" id="optimize-body">
+ <div class="opt-field">
+ <span>Mode</span>
+ <div class="seg" id="opt-mode" role="group" aria-label="Remesh mode">
+ <button type="button" data-mode="triangle" aria-pressed="false">
+ Triangle
+ </button>
+ <button type="button" data-mode="quad" aria-pressed="true">
+ Quad retopo
+ </button>
+ <button type="button" data-mode="lowpoly" aria-pressed="false">
+ Low-poly
+ </button>
+ </div>
+ <p class="opt-mode-hint" id="opt-mode-hint"></p>
+ </div>
+
+ <div class="opt-row">
+ <label class="opt-field">
+ <span id="opt-target-label">Target faces</span>
+ <select class="opt-select" id="opt-target"></select>
+ </label>
+ <label class="opt-field">
+ <span>Format</span>
+ <select class="opt-select" id="opt-format">
+ <option value="glb">GLB (textured)</option>
+ <option value="obj">OBJ (true quads)</option>
+ <option value="fbx">FBX</option>
+ <option value="stl">STL</option>
+ <option value="ply">PLY</option>
+ <option value="usdz">USDZ</option>
+ <option value="3mf">3MF</option>
+ </select>
+ </label>
+ <label class="opt-field" id="opt-texsize-field">
+ <span>Texture</span>
+ <select class="opt-select" id="opt-texsize">
+ <option value="512">512px</option>
+ <option value="1024" selected>1024px</option>
+ <option value="2048">2048px</option>
+ </select>
+ </label>
+ </div>
+
+ <div class="opt-actions">
+ <button class="btn" type="button" id="opt-run">
+ <span id="opt-run-label">Optimize</span>
+ </button>
+ <span class="opt-status" id="opt-status" role="status" aria-live="polite"></span>
+ </div>
+
+ <div class="opt-stats is-hidden" id="opt-stats"></div>
+ </div>
+ </div>
+
+ <!-- Stylize — one-click geometric filters on the current model -->
+ <div class="stylize" id="stylize-panel" data-busy="false" hidden>
+ <div class="stylize-head">
+ <h3>Stylize</h3>
+ <p class="stylize-sub">
+ One-click geometric filters. Restyle this model as voxels, bricks, an open
+ lattice, or low-poly — source color is carried over where the style allows.
+ </p>
+ </div>
+ <div
+ class="stylize-gallery"
+ id="stylize-gallery"
+ role="group"
+ aria-label="Stylization filters"
+ ></div>
+ <div class="stylize-controls is-hidden" id="stylize-controls">
+ <div class="stylize-slider">
+ <label id="stylize-res-label" for="stylize-res">Resolution</label>
+ <input type="range" id="stylize-res" min="8" max="96" value="32" />
+ <output id="stylize-res-val" for="stylize-res">32</output>
+ </div>
+ <div class="stylize-actions">
+ <button class="btn btn-ghost" type="button" id="stylize-apply">Re-apply</button>
+ <a class="btn btn-ghost" id="stylize-download" download hidden
+ >Download stylized GLB</a
+ >
+ <button class="btn btn-ghost" type="button" id="stylize-revert" hidden>
+ Revert to original
+ </button>
+ </div>
+ </div>
+ <div
+ class="stylize-status"
+ id="stylize-status"
+ role="status"
+ aria-live="polite"
+ ></div>
+ </div>
</div>
<!-- Error -->
@@ -908,14 +1362,17 @@
</section>
<p class="hint-foot">
- Powered by flux-schnell + Microsoft TRELLIS on Replicate. Best results come from one
- clearly described subject. The same pipeline is available to agents over MCP at
- <a href="/docs">/api/mcp-3d</a>.
+ Powered by flux-schnell + Microsoft TRELLIS on Replicate, with multi-view conditioning
+ when you supply more than one photo. Best results: one clearly described subject, or
+ clean evenly-lit views from distinct angles. The same pipeline is available to agents
+ over MCP at <a href="/docs">/api/mcp-3d</a>.
</p>
</main>
<script src="/nav.js" defer></script>
<script type="module" src="/src/forge.js"></script>
+ <script type="module" src="/src/forge-stylize.js"></script>
+ <script type="module" src="/src/forge-optimize.js"></script>
<div id="footer-container"></div>
<script src="/footer.js"></script>
</body>
diff --git a/pages/pose.html b/pages/pose.html
index 6d2b7ddcc..51e2e97d4 100644
--- a/pages/pose.html
+++ b/pages/pose.html
@@ -45,14 +45,19 @@
--danger: #f87171;
--ok: #ffffff;
}
- html, body {
+ html,
+ body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: var(--bg);
color: var(--text);
- font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ font-family:
+ 'Inter',
+ system-ui,
+ -apple-system,
+ sans-serif;
-webkit-font-smoothing: antialiased;
overflow: hidden;
}
@@ -64,9 +69,9 @@
grid-template-columns: 280px 1fr 320px;
grid-template-rows: 52px 1fr auto;
grid-template-areas:
- "top top top"
- "left stage right"
- "timeline timeline timeline";
+ 'top top top'
+ 'left stage right'
+ 'timeline timeline timeline';
gap: 0;
}
@@ -98,7 +103,9 @@
font-weight: 500;
font-size: 13px;
}
- #pose-top .brand a:hover { color: var(--text); }
+ #pose-top .brand a:hover {
+ color: var(--text);
+ }
#pose-top .sep {
width: 1px;
height: 22px;
@@ -124,14 +131,20 @@
padding: 5px 11px;
border-radius: 999px;
cursor: pointer;
- transition: background 0.12s ease, color 0.12s ease;
+ transition:
+ background 0.12s ease,
+ color 0.12s ease;
+ }
+ .mode-btn:hover {
+ color: var(--text);
}
- .mode-btn:hover { color: var(--text); }
- .mode-btn[aria-pressed="true"] {
+ .mode-btn[aria-pressed='true'] {
background: rgba(255, 255, 255, 0.18);
color: #e8e8e8;
}
- .spacer { flex: 1; }
+ .spacer {
+ flex: 1;
+ }
.pose-btn {
appearance: none;
border: 1px solid var(--border);
@@ -146,7 +159,9 @@
display: inline-flex;
align-items: center;
gap: 6px;
- transition: background 0.12s ease, border-color 0.12s ease;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease;
}
.pose-btn:hover {
background: rgba(255, 255, 255, 0.08);
@@ -157,7 +172,9 @@
border-color: rgba(255, 255, 255, 0.45);
color: #e8e8e8;
}
- .pose-btn-primary:hover { background: rgba(255, 255, 255, 0.32); }
+ .pose-btn-primary:hover {
+ background: rgba(255, 255, 255, 0.32);
+ }
.pose-btn-ghost {
background: transparent;
border-style: dashed;
@@ -184,19 +201,19 @@
color: var(--text);
}
#pose-top .pose-btn-primary {
- background: rgba(255, 255, 255, 0.20);
- border-color: rgba(255, 255, 255, 0.40);
+ background: rgba(255, 255, 255, 0.2);
+ border-color: rgba(255, 255, 255, 0.4);
color: #e8e8e8;
}
#pose-top .pose-btn-primary:hover {
- background: rgba(255, 255, 255, 0.30);
+ background: rgba(255, 255, 255, 0.3);
color: #ffffff;
}
.file-label {
cursor: pointer;
}
- .file-label input[type="file"] {
+ .file-label input[type='file'] {
display: none;
}
@@ -248,7 +265,9 @@
margin-top: 12px;
margin-bottom: 6px;
}
- .pose-joint-group:first-child { margin-top: 0; }
+ .pose-joint-group:first-child {
+ margin-top: 0;
+ }
.pose-joint-btn {
appearance: none;
border: 1px solid var(--border);
@@ -260,7 +279,10 @@
border-radius: 8px;
cursor: pointer;
text-align: left;
- transition: background 0.1s ease, color 0.1s ease, border-color 0.1s ease;
+ transition:
+ background 0.1s ease,
+ color 0.1s ease,
+ border-color 0.1s ease;
}
.pose-joint-btn:hover {
background: rgba(255, 255, 255, 0.06);
@@ -279,15 +301,19 @@
font: inherit;
font-size: 12.5px;
margin-bottom: 10px;
- transition: border-color 0.12s ease, background 0.12s ease;
+ transition:
+ border-color 0.12s ease,
+ background 0.12s ease;
+ }
+ .pose-search::placeholder {
+ color: var(--text-3);
}
- .pose-search::placeholder { color: var(--text-3); }
.pose-search:focus {
outline: none;
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.07);
}
- .pose-joint-btn[aria-pressed="true"] {
+ .pose-joint-btn[aria-pressed='true'] {
background: rgba(255, 255, 255, 0.18);
border-color: rgba(255, 255, 255, 0.4);
color: #e8e8e8;
@@ -341,19 +367,19 @@
font-variant-numeric: tabular-nums;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
- .pose-slider-row input[type="range"] {
+ .pose-slider-row input[type='range'] {
grid-column: 1 / -1;
width: 100%;
margin: 0;
appearance: none;
background: transparent;
}
- .pose-slider-row input[type="range"]::-webkit-slider-runnable-track {
+ .pose-slider-row input[type='range']::-webkit-slider-runnable-track {
height: 4px;
background: rgba(255, 255, 255, 0.08);
border-radius: 999px;
}
- .pose-slider-row input[type="range"]::-webkit-slider-thumb {
+ .pose-slider-row input[type='range']::-webkit-slider-thumb {
appearance: none;
width: 14px;
height: 14px;
@@ -363,12 +389,12 @@
cursor: pointer;
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.18);
}
- .pose-slider-row input[type="range"]::-moz-range-track {
+ .pose-slider-row input[type='range']::-moz-range-track {
height: 4px;
background: rgba(255, 255, 255, 0.08);
border-radius: 999px;
}
- .pose-slider-row input[type="range"]::-moz-range-thumb {
+ .pose-slider-row input[type='range']::-moz-range-thumb {
width: 14px;
height: 14px;
background: var(--accent);
@@ -387,8 +413,8 @@
color: var(--text-2);
}
.pose-form-row select,
- .pose-form-row input[type="color"],
- .pose-form-row input[type="range"] {
+ .pose-form-row input[type='color'],
+ .pose-form-row input[type='range'] {
background: rgba(255, 255, 255, 0.04);
color: var(--text);
border: 1px solid var(--border);
@@ -397,13 +423,13 @@
font: inherit;
font-size: 12px;
}
- .pose-form-row input[type="color"] {
+ .pose-form-row input[type='color'] {
padding: 0;
width: 32px;
height: 22px;
cursor: pointer;
}
- .pose-form-row input[type="checkbox"] {
+ .pose-form-row input[type='checkbox'] {
accent-color: var(--accent);
}
@@ -421,7 +447,9 @@
cursor: grab;
touch-action: none;
}
- #pose-canvas:active { cursor: grabbing; }
+ #pose-canvas:active {
+ cursor: grabbing;
+ }
#pose-status {
position: absolute;
left: 50%;
@@ -438,7 +466,10 @@
-webkit-backdrop-filter: blur(8px);
transition: opacity 0.2s ease;
}
- #pose-status[data-kind="error"] { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
+ #pose-status[data-kind='error'] {
+ color: var(--danger);
+ border-color: rgba(248, 113, 113, 0.4);
+ }
/* ── Right panel: presets + props ──────────────────── */
#pose-right {
@@ -456,7 +487,9 @@
margin-top: 14px;
margin-bottom: 8px;
}
- .pose-preset-group:first-child { margin-top: 0; }
+ .pose-preset-group:first-child {
+ margin-top: 0;
+ }
.pose-preset-grid {
display: grid;
grid-template-columns: 1fr 1fr;
@@ -473,10 +506,12 @@
border-radius: 8px;
cursor: pointer;
text-align: left;
- transition: background 0.12s ease, border-color 0.12s ease;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease;
}
.pose-preset-btn:hover {
- background: rgba(255, 255, 255, 0.10);
+ background: rgba(255, 255, 255, 0.1);
border-color: rgba(255, 255, 255, 0.35);
}
.pose-prop-btn {
@@ -491,8 +526,11 @@
cursor: pointer;
transition: background 0.12s ease;
}
- .pose-prop-btn:hover { background: rgba(255, 255, 255, 0.06); color: var(--text); }
- .pose-prop-btn[aria-pressed="true"] {
+ .pose-prop-btn:hover {
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--text);
+ }
+ .pose-prop-btn[aria-pressed='true'] {
background: rgba(255, 255, 255, 0.18);
border-color: rgba(255, 255, 255, 0.45);
color: #e8e8e8;
@@ -503,6 +541,383 @@
gap: 6px;
}
+ /* ── Animation preset library ───────────────────────── */
+ .pose-section-sub {
+ font-size: 11.5px;
+ color: var(--text-3);
+ line-height: 1.45;
+ margin: -2px 0 10px;
+ }
+ .al-search {
+ width: 100%;
+ box-sizing: border-box;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border);
+ color: var(--text);
+ font: inherit;
+ font-size: 12px;
+ padding: 7px 10px;
+ border-radius: 8px;
+ margin-bottom: 9px;
+ }
+ .al-search::placeholder {
+ color: var(--text-3);
+ }
+ .al-search:focus {
+ outline: none;
+ border-color: var(--border-strong);
+ }
+ .al-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ margin-bottom: 11px;
+ }
+ .al-chip {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.02);
+ color: var(--text-2);
+ font: inherit;
+ font-size: 11px;
+ padding: 4px 9px;
+ border-radius: 999px;
+ cursor: pointer;
+ white-space: nowrap;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease,
+ color 0.12s ease;
+ }
+ .al-chip:hover {
+ background: rgba(255, 255, 255, 0.07);
+ color: var(--text);
+ }
+ .al-chip:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .al-chip[aria-selected='true'] {
+ background: rgba(255, 255, 255, 0.16);
+ border-color: rgba(255, 255, 255, 0.42);
+ color: #f4f4f5;
+ }
+ .al-section-label {
+ font-size: 10.5px;
+ font-weight: 600;
+ color: var(--text-3);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ margin: 14px 0 7px;
+ }
+ .al-section-label:first-child {
+ margin-top: 0;
+ }
+ .al-cards {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 7px;
+ }
+ .al-card {
+ position: relative;
+ appearance: none;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 4px;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.025);
+ color: var(--text);
+ font: inherit;
+ padding: 10px 10px 9px;
+ border-radius: 10px;
+ cursor: pointer;
+ text-align: left;
+ overflow: hidden;
+ transition:
+ background 0.13s ease,
+ border-color 0.13s ease,
+ transform 0.13s ease,
+ box-shadow 0.13s ease;
+ }
+ .al-card:hover {
+ background: rgba(255, 255, 255, 0.07);
+ border-color: rgba(255, 255, 255, 0.34);
+ transform: translateY(-1px);
+ }
+ .al-card:active {
+ transform: translateY(0);
+ }
+ .al-card:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .al-card.is-active {
+ background: rgba(34, 211, 238, 0.12);
+ border-color: rgba(34, 211, 238, 0.55);
+ box-shadow: 0 0 0 1px rgba(34, 211, 238, 0.25) inset;
+ }
+ .al-card-icon {
+ font-size: 19px;
+ line-height: 1;
+ }
+ .al-card-label {
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1.25;
+ }
+ .al-card-badge {
+ font-size: 9px;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ color: var(--text-3);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 1px 5px;
+ }
+ .al-card.is-active .al-card-badge {
+ color: #67e8f9;
+ border-color: rgba(34, 211, 238, 0.5);
+ }
+ /* Animated "now playing" equalizer — only visible on the active card. */
+ .al-card-eq {
+ position: absolute;
+ top: 9px;
+ right: 9px;
+ display: none;
+ align-items: flex-end;
+ gap: 2px;
+ height: 12px;
+ }
+ .al-card.is-active .al-card-eq {
+ display: inline-flex;
+ }
+ .al-card-eq i {
+ width: 2.5px;
+ background: #22d3ee;
+ border-radius: 1px;
+ animation: al-eq 0.9s ease-in-out infinite;
+ }
+ .al-card-eq i:nth-child(1) {
+ height: 5px;
+ animation-delay: 0s;
+ }
+ .al-card-eq i:nth-child(2) {
+ height: 11px;
+ animation-delay: 0.18s;
+ }
+ .al-card-eq i:nth-child(3) {
+ height: 7px;
+ animation-delay: 0.36s;
+ }
+ @keyframes al-eq {
+ 0%,
+ 100% {
+ transform: scaleY(0.4);
+ }
+ 50% {
+ transform: scaleY(1);
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .al-card-eq i {
+ animation: none;
+ }
+ .al-card:hover {
+ transform: none;
+ }
+ }
+ .al-no-match {
+ font-size: 12px;
+ color: var(--text-3);
+ padding: 10px 2px;
+ }
+ /* Empty / loading / error states */
+ .al-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ padding: 18px 8px;
+ gap: 4px;
+ }
+ .al-empty-icon {
+ font-size: 30px;
+ }
+ .al-empty-title {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text);
+ }
+ .al-empty-body {
+ font-size: 11.5px;
+ color: var(--text-3);
+ line-height: 1.5;
+ max-width: 260px;
+ margin: 0 0 6px;
+ }
+ .al-cta {
+ appearance: none;
+ border: 1px solid rgba(255, 255, 255, 0.42);
+ background: rgba(255, 255, 255, 0.16);
+ color: #f4f4f5;
+ font: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ padding: 7px 14px;
+ border-radius: 999px;
+ cursor: pointer;
+ transition: background 0.12s ease;
+ }
+ .al-cta:hover {
+ background: rgba(255, 255, 255, 0.26);
+ }
+ .al-cta:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .al-skeleton-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 7px;
+ width: 100%;
+ }
+ .al-skeleton {
+ height: 58px;
+ border-radius: 10px;
+ background: linear-gradient(
+ 100deg,
+ rgba(255, 255, 255, 0.03) 30%,
+ rgba(255, 255, 255, 0.08) 50%,
+ rgba(255, 255, 255, 0.03) 70%
+ );
+ background-size: 200% 100%;
+ animation: al-shimmer 1.3s linear infinite;
+ }
+ @keyframes al-shimmer {
+ from {
+ background-position: 200% 0;
+ }
+ to {
+ background-position: -200% 0;
+ }
+ }
+ /* Now-playing transport */
+ .al-transport {
+ margin-top: 12px;
+ padding: 11px;
+ border: 1px solid rgba(34, 211, 238, 0.4);
+ border-radius: 10px;
+ background: rgba(34, 211, 238, 0.06);
+ display: flex;
+ flex-direction: column;
+ gap: 9px;
+ }
+ .al-now {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12.5px;
+ font-weight: 600;
+ color: var(--text);
+ }
+ .al-now-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: #22d3ee;
+ box-shadow: 0 0 0 0 rgba(34, 211, 238, 0.5);
+ animation: al-pulse 1.6s ease-out infinite;
+ }
+ @keyframes al-pulse {
+ 0% {
+ box-shadow: 0 0 0 0 rgba(34, 211, 238, 0.5);
+ }
+ 70% {
+ box-shadow: 0 0 0 7px rgba(34, 211, 238, 0);
+ }
+ 100% {
+ box-shadow: 0 0 0 0 rgba(34, 211, 238, 0);
+ }
+ }
+ .al-speed-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 11.5px;
+ color: var(--text-3);
+ }
+ .al-speed {
+ flex: 1 1 auto;
+ accent-color: var(--accent);
+ }
+ .al-speed-val {
+ font-family: ui-monospace, monospace;
+ font-size: 11px;
+ color: var(--text-2);
+ min-width: 38px;
+ text-align: right;
+ }
+ .al-transport-actions {
+ display: flex;
+ gap: 7px;
+ }
+ .al-tbtn {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text);
+ font: inherit;
+ font-size: 12px;
+ padding: 7px 12px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: background 0.12s ease;
+ }
+ .al-tbtn:hover {
+ background: rgba(255, 255, 255, 0.09);
+ }
+ .al-tbtn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .al-export {
+ appearance: none;
+ flex: 1 1 auto;
+ border: 1px solid rgba(255, 255, 255, 0.45);
+ background: rgba(255, 255, 255, 0.2);
+ color: #f4f4f5;
+ font: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ padding: 7px 12px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease,
+ color 0.12s ease;
+ }
+ .al-export:hover {
+ background: rgba(255, 255, 255, 0.3);
+ }
+ .al-export:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .al-export.is-busy {
+ opacity: 0.6;
+ pointer-events: none;
+ }
+ .al-export.is-ok {
+ border-color: rgba(120, 255, 170, 0.5);
+ color: #b6ffce;
+ }
+ .al-export.is-err {
+ border-color: rgba(248, 113, 113, 0.6);
+ color: var(--danger);
+ }
+
/* ── Timeline ───────────────────────────────────────── */
#pose-timeline {
grid-area: timeline;
@@ -537,18 +952,35 @@
justify-content: center;
border-radius: 8px;
cursor: pointer;
- transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease,
+ color 0.12s ease;
+ }
+ .tl-btn:hover {
+ background: rgba(255, 255, 255, 0.09);
+ border-color: var(--border-strong);
}
- .tl-btn:hover { background: rgba(255, 255, 255, 0.09); border-color: var(--border-strong); }
- .tl-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
- .tl-btn[aria-pressed="true"] {
+ .tl-btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .tl-btn[aria-pressed='true'] {
background: rgba(255, 255, 255, 0.2);
border-color: rgba(255, 255, 255, 0.45);
color: #e8e8e8;
}
- .tl-btn:disabled { opacity: 0.4; cursor: not-allowed; }
- #tl-play { width: 36px; background: rgba(255, 255, 255, 0.12); }
- #tl-play:hover { background: rgba(255, 255, 255, 0.2); }
+ .tl-btn:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ #tl-play {
+ width: 36px;
+ background: rgba(255, 255, 255, 0.12);
+ }
+ #tl-play:hover {
+ background: rgba(255, 255, 255, 0.2);
+ }
.tl-time {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12.5px;
@@ -557,7 +989,10 @@
min-width: 104px;
text-align: center;
}
- .tl-time b { color: var(--text); font-weight: 600; }
+ .tl-time b {
+ color: var(--text);
+ font-weight: 600;
+ }
.tl-field {
display: inline-flex;
align-items: center;
@@ -565,7 +1000,7 @@
font-size: 11.5px;
color: var(--text-3);
}
- .tl-field input[type="number"],
+ .tl-field input[type='number'],
.tl-field select {
background: rgba(255, 255, 255, 0.04);
color: var(--text);
@@ -575,11 +1010,26 @@
font: inherit;
font-size: 12px;
}
- .tl-field input[type="number"] { width: 56px; }
- .tl-field input:focus, .tl-field select:focus { outline: none; border-color: var(--border-strong); }
- .tl-field input[type="checkbox"] { accent-color: var(--accent); }
- .tl-sep { width: 1px; height: 22px; background: var(--border); margin: 0 2px; }
- .tl-spacer { flex: 1 1 auto; }
+ .tl-field input[type='number'] {
+ width: 56px;
+ }
+ .tl-field input:focus,
+ .tl-field select:focus {
+ outline: none;
+ border-color: var(--border-strong);
+ }
+ .tl-field input[type='checkbox'] {
+ accent-color: var(--accent);
+ }
+ .tl-sep {
+ width: 1px;
+ height: 22px;
+ background: var(--border);
+ margin: 0 2px;
+ }
+ .tl-spacer {
+ flex: 1 1 auto;
+ }
.tl-add {
appearance: none;
border: 1px solid rgba(255, 255, 255, 0.45);
@@ -596,8 +1046,13 @@
gap: 6px;
transition: background 0.12s ease;
}
- .tl-add:hover { background: rgba(255, 255, 255, 0.32); }
- .tl-add:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .tl-add:hover {
+ background: rgba(255, 255, 255, 0.32);
+ }
+ .tl-add:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
/* Track + ruler */
.tl-track-wrap {
@@ -605,8 +1060,7 @@
height: 52px;
border: 1px solid var(--border);
border-radius: 10px;
- background:
- linear-gradient(rgba(255, 255, 255, 0.015), rgba(255, 255, 255, 0.015));
+ background: linear-gradient(rgba(255, 255, 255, 0.015), rgba(255, 255, 255, 0.015));
overflow: hidden;
cursor: pointer;
}
@@ -672,16 +1126,27 @@
border-radius: 3px;
transform: translateY(-50%) rotate(45deg);
cursor: grab;
- transition: background 0.1s ease, box-shadow 0.1s ease, transform 0.1s ease;
+ transition:
+ background 0.1s ease,
+ box-shadow 0.1s ease,
+ transform 0.1s ease;
z-index: 3;
}
- .tl-key:hover { background: #fff; box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.14); }
- .tl-key[aria-selected="true"] {
+ .tl-key:hover {
+ background: #fff;
+ box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.14);
+ }
+ .tl-key[aria-selected='true'] {
background: #22d3ee;
box-shadow: 0 0 0 4px rgba(34, 211, 238, 0.25);
}
- .tl-key:active { cursor: grabbing; }
- .tl-key:focus-visible { outline: 2px solid #22d3ee; outline-offset: 3px; }
+ .tl-key:active {
+ cursor: grabbing;
+ }
+ .tl-key:focus-visible {
+ outline: 2px solid #22d3ee;
+ outline-offset: 3px;
+ }
.tl-playhead {
position: absolute;
top: 0;
@@ -693,7 +1158,7 @@
z-index: 4;
}
.tl-playhead::before {
- content: "";
+ content: '';
position: absolute;
top: 0;
left: -5px;
@@ -703,10 +1168,22 @@
}
/* Export feedback */
- .tl-export:disabled { opacity: 0.4; cursor: not-allowed; }
- .tl-export.is-busy { opacity: 0.6; pointer-events: none; }
- .tl-export.is-ok { border-color: rgba(120, 255, 170, 0.5); color: #b6ffce; }
- .tl-export.is-err { border-color: rgba(248, 113, 113, 0.6); color: var(--danger); }
+ .tl-export:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ .tl-export.is-busy {
+ opacity: 0.6;
+ pointer-events: none;
+ }
+ .tl-export.is-ok {
+ border-color: rgba(120, 255, 170, 0.5);
+ color: #b6ffce;
+ }
+ .tl-export.is-err {
+ border-color: rgba(248, 113, 113, 0.6);
+ color: var(--danger);
+ }
/* ── Library: overlays, dialogs, drawer, cards ───────────── */
.pl-overlay {
@@ -722,7 +1199,14 @@
padding: 20px;
animation: pl-fade 0.14s ease;
}
- @keyframes pl-fade { from { opacity: 0; } to { opacity: 1; } }
+ @keyframes pl-fade {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
.pl-dialog {
width: min(440px, 100%);
max-height: 88vh;
@@ -736,10 +1220,28 @@
gap: 12px;
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);
}
- .pl-dialog-title { margin: 0; font-size: 17px; font-weight: 600; color: var(--text); }
- .pl-dialog-sub { margin: 0; font-size: 13px; line-height: 1.5; color: var(--text-2); }
- .pl-field { display: flex; flex-direction: column; gap: 5px; font-size: 12px; color: var(--text-2); }
- .pl-field > span { font-weight: 500; }
+ .pl-dialog-title {
+ margin: 0;
+ font-size: 17px;
+ font-weight: 600;
+ color: var(--text);
+ }
+ .pl-dialog-sub {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--text-2);
+ }
+ .pl-field {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ font-size: 12px;
+ color: var(--text-2);
+ }
+ .pl-field > span {
+ font-weight: 500;
+ }
.pl-input {
width: 100%;
box-sizing: border-box;
@@ -751,9 +1253,20 @@
font: inherit;
font-size: 13px;
}
- .pl-input:focus { outline: none; border-color: var(--border-strong); background: rgba(255, 255, 255, 0.07); }
- .pl-textarea { resize: vertical; min-height: 38px; }
- .pl-link-note { margin: 0; font-size: 11.5px; color: var(--text-3); }
+ .pl-input:focus {
+ outline: none;
+ border-color: var(--border-strong);
+ background: rgba(255, 255, 255, 0.07);
+ }
+ .pl-textarea {
+ resize: vertical;
+ min-height: 38px;
+ }
+ .pl-link-note {
+ margin: 0;
+ font-size: 11.5px;
+ color: var(--text-3);
+ }
.pl-dialog-err {
font-size: 12px;
color: var(--danger);
@@ -762,12 +1275,26 @@
border-radius: 8px;
padding: 7px 10px;
}
- .pl-dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }
- .pl-danger { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
- .pl-danger:hover { background: rgba(248, 113, 113, 0.12); }
+ .pl-dialog-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 4px;
+ }
+ .pl-danger {
+ color: var(--danger);
+ border-color: rgba(248, 113, 113, 0.4);
+ }
+ .pl-danger:hover {
+ background: rgba(248, 113, 113, 0.12);
+ }
/* Drawer */
- .pl-drawer-overlay { justify-content: flex-end; align-items: stretch; padding: 0; }
+ .pl-drawer-overlay {
+ justify-content: flex-end;
+ align-items: stretch;
+ padding: 0;
+ }
.pl-drawer {
width: min(720px, 100%);
background: var(--panel-solid);
@@ -776,9 +1303,14 @@
flex-direction: column;
transform: translateX(24px);
opacity: 0;
- transition: transform 0.2s ease, opacity 0.2s ease;
+ transition:
+ transform 0.2s ease,
+ opacity 0.2s ease;
+ }
+ .pl-drawer.pl-open {
+ transform: translateX(0);
+ opacity: 1;
}
- .pl-drawer.pl-open { transform: translateX(0); opacity: 1; }
.pl-drawer-head {
display: flex;
align-items: center;
@@ -786,19 +1318,50 @@
padding: 14px 18px;
border-bottom: 1px solid var(--border);
}
- .pl-tabs { display: flex; gap: 4px; padding: 3px; background: rgba(255, 255, 255, 0.04); border: 1px solid var(--border); border-radius: 999px; }
+ .pl-tabs {
+ display: flex;
+ gap: 4px;
+ padding: 3px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ }
.pl-tab {
- appearance: none; border: none; background: transparent; color: var(--text-2);
- font: inherit; font-size: 12.5px; padding: 6px 14px; border-radius: 999px; cursor: pointer;
- transition: background 0.12s ease, color 0.12s ease;
+ appearance: none;
+ border: none;
+ background: transparent;
+ color: var(--text-2);
+ font: inherit;
+ font-size: 12.5px;
+ padding: 6px 14px;
+ border-radius: 999px;
+ cursor: pointer;
+ transition:
+ background 0.12s ease,
+ color 0.12s ease;
+ }
+ .pl-tab:hover {
+ color: var(--text);
+ }
+ .pl-tab[aria-selected='true'] {
+ background: rgba(255, 255, 255, 0.18);
+ color: #e8e8e8;
}
- .pl-tab:hover { color: var(--text); }
- .pl-tab[aria-selected="true"] { background: rgba(255, 255, 255, 0.18); color: #e8e8e8; }
.pl-close {
- appearance: none; border: 1px solid var(--border); background: rgba(255, 255, 255, 0.04);
- color: var(--text-2); width: 30px; height: 30px; border-radius: 8px; cursor: pointer; font-size: 13px;
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text-2);
+ width: 30px;
+ height: 30px;
+ border-radius: 8px;
+ cursor: pointer;
+ font-size: 13px;
+ }
+ .pl-close:hover {
+ color: var(--text);
+ border-color: var(--border-strong);
}
- .pl-close:hover { color: var(--text); border-color: var(--border-strong); }
.pl-grid {
flex: 1;
overflow-y: auto;
@@ -815,28 +1378,130 @@
background: rgba(255, 255, 255, 0.02);
display: flex;
flex-direction: column;
- transition: border-color 0.12s ease, transform 0.12s ease;
- }
- .pl-card:hover { border-color: var(--border-strong); transform: translateY(-2px); }
- .pl-card-thumb { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; background: #0b0b0b; display: block; }
- .pl-card-thumb-empty { display: flex; align-items: center; justify-content: center; font-size: 28px; color: var(--text-3); }
- .pl-card-badges { display: flex; gap: 5px; flex-wrap: wrap; padding: 8px 10px 0; }
- .pl-badge { font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.05em; padding: 2px 7px; border-radius: 999px; border: 1px solid var(--border); color: var(--text-3); }
- .pl-badge-public { color: #b6ffce; border-color: rgba(120, 255, 170, 0.4); }
- .pl-badge-unlisted { color: #ffe6a3; border-color: rgba(255, 210, 100, 0.4); }
- .pl-badge-price { color: #a3d8ff; border-color: rgba(120, 180, 255, 0.4); }
- .pl-card-name { padding: 6px 10px 0; font-size: 13.5px; font-weight: 600; color: var(--text); }
- .pl-card-meta { padding: 2px 10px 0; font-size: 11px; color: var(--text-3); }
- .pl-card-tags { display: flex; flex-wrap: wrap; gap: 4px; padding: 6px 10px 0; }
- .pl-tag { font-size: 10px; color: var(--text-2); background: rgba(255, 255, 255, 0.05); border-radius: 4px; padding: 1px 6px; }
- .pl-card-actions { display: flex; flex-wrap: wrap; gap: 5px; padding: 10px; margin-top: auto; }
- .pl-card-actions .pose-btn { font-size: 11.5px; padding: 5px 9px; }
- .pl-skeleton { min-height: 240px; background: linear-gradient(110deg, rgba(255,255,255,0.03) 30%, rgba(255,255,255,0.07) 50%, rgba(255,255,255,0.03) 70%); background-size: 200% 100%; animation: pl-shimmer 1.3s ease infinite; }
- @keyframes pl-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
- .pl-empty { grid-column: 1 / -1; text-align: center; padding: 48px 20px; color: var(--text-2); }
- .pl-empty-icon { font-size: 38px; margin-bottom: 8px; }
- .pl-empty h3 { margin: 0 0 6px; font-size: 16px; color: var(--text); }
- .pl-empty p { margin: 0 auto 14px; font-size: 13px; max-width: 320px; line-height: 1.5; }
+ transition:
+ border-color 0.12s ease,
+ transform 0.12s ease;
+ }
+ .pl-card:hover {
+ border-color: var(--border-strong);
+ transform: translateY(-2px);
+ }
+ .pl-card-thumb {
+ width: 100%;
+ aspect-ratio: 1 / 1;
+ object-fit: cover;
+ background: #0b0b0b;
+ display: block;
+ }
+ .pl-card-thumb-empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 28px;
+ color: var(--text-3);
+ }
+ .pl-card-badges {
+ display: flex;
+ gap: 5px;
+ flex-wrap: wrap;
+ padding: 8px 10px 0;
+ }
+ .pl-badge {
+ font-size: 9.5px;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ padding: 2px 7px;
+ border-radius: 999px;
+ border: 1px solid var(--border);
+ color: var(--text-3);
+ }
+ .pl-badge-public {
+ color: #b6ffce;
+ border-color: rgba(120, 255, 170, 0.4);
+ }
+ .pl-badge-unlisted {
+ color: #ffe6a3;
+ border-color: rgba(255, 210, 100, 0.4);
+ }
+ .pl-badge-price {
+ color: #a3d8ff;
+ border-color: rgba(120, 180, 255, 0.4);
+ }
+ .pl-card-name {
+ padding: 6px 10px 0;
+ font-size: 13.5px;
+ font-weight: 600;
+ color: var(--text);
+ }
+ .pl-card-meta {
+ padding: 2px 10px 0;
+ font-size: 11px;
+ color: var(--text-3);
+ }
+ .pl-card-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 6px 10px 0;
+ }
+ .pl-tag {
+ font-size: 10px;
+ color: var(--text-2);
+ background: rgba(255, 255, 255, 0.05);
+ border-radius: 4px;
+ padding: 1px 6px;
+ }
+ .pl-card-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ padding: 10px;
+ margin-top: auto;
+ }
+ .pl-card-actions .pose-btn {
+ font-size: 11.5px;
+ padding: 5px 9px;
+ }
+ .pl-skeleton {
+ min-height: 240px;
+ background: linear-gradient(
+ 110deg,
+ rgba(255, 255, 255, 0.03) 30%,
+ rgba(255, 255, 255, 0.07) 50%,
+ rgba(255, 255, 255, 0.03) 70%
+ );
+ background-size: 200% 100%;
+ animation: pl-shimmer 1.3s ease infinite;
+ }
+ @keyframes pl-shimmer {
+ from {
+ background-position: 200% 0;
+ }
+ to {
+ background-position: -200% 0;
+ }
+ }
+ .pl-empty {
+ grid-column: 1 / -1;
+ text-align: center;
+ padding: 48px 20px;
+ color: var(--text-2);
+ }
+ .pl-empty-icon {
+ font-size: 38px;
+ margin-bottom: 8px;
+ }
+ .pl-empty h3 {
+ margin: 0 0 6px;
+ font-size: 16px;
+ color: var(--text);
+ }
+ .pl-empty p {
+ margin: 0 auto 14px;
+ font-size: 13px;
+ max-width: 320px;
+ line-height: 1.5;
+ }
/* ── Responsive ─────────────────────────────────────── */
@media (max-width: 1100px) {
@@ -849,18 +1514,23 @@
grid-template-columns: 1fr;
grid-template-rows: 52px 1fr auto auto;
grid-template-areas:
- "top"
- "stage"
- "timeline"
- "left";
+ 'top'
+ 'stage'
+ 'timeline'
+ 'left';
+ }
+ #pose-right {
+ display: none;
}
- #pose-right { display: none; }
#pose-left {
border-right: none;
border-top: 1px solid var(--border);
max-height: 36vh;
}
- .tl-field-fps, .tl-field-name { display: none; }
+ .tl-field-fps,
+ .tl-field-name {
+ display: none;
+ }
}
</style>
</head>
@@ -876,29 +1546,94 @@
<span class="sep"></span>
<div class="mode-group" role="group" aria-label="Posing mode">
- <button type="button" class="mode-btn" data-posemode="fk" aria-pressed="true" title="FK — select a bone and rotate it with the gizmo or sliders (F)">FK</button>
- <button type="button" class="mode-btn" data-posemode="ik" aria-pressed="false" title="IK — drag a hand or foot and the limb solves (I)">IK</button>
+ <button
+ type="button"
+ class="mode-btn"
+ data-posemode="fk"
+ aria-pressed="true"
+ title="FK — select a bone and rotate it with the gizmo or sliders (F)"
+ >
+ FK
+ </button>
+ <button
+ type="button"
+ class="mode-btn"
+ data-posemode="ik"
+ aria-pressed="false"
+ title="IK — drag a hand or foot and the limb solves (I)"
+ >
+ IK
+ </button>
</div>
<span class="sep"></span>
- <button type="button" id="pose-load-avatar" class="pose-btn" title="Load a rigged avatar to animate">Load avatar</button>
- <button type="button" id="pose-use-mannequin" class="pose-btn" title="Return to the built-in mannequin">Mannequin</button>
+ <button
+ type="button"
+ id="pose-load-avatar"
+ class="pose-btn"
+ title="Load a rigged avatar to animate"
+ >
+ Load avatar
+ </button>
+ <button
+ type="button"
+ id="pose-use-mannequin"
+ class="pose-btn"
+ title="Return to the built-in mannequin"
+ >
+ Mannequin
+ </button>
<span class="spacer"></span>
- <button type="button" id="pose-library" class="pose-btn" title="Your saved animations">My animations</button>
- <button type="button" id="pose-save" class="pose-btn pose-btn-primary" title="Save this animation to your account (Ctrl/Cmd+S)">Save</button>
+ <button
+ type="button"
+ id="pose-library"
+ class="pose-btn"
+ title="Your saved animations"
+ >
+ My animations
+ </button>
+ <button
+ type="button"
+ id="pose-save"
+ class="pose-btn pose-btn-primary"
+ title="Save this animation to your account (Ctrl/Cmd+S)"
+ >
+ Save
+ </button>
<span class="sep"></span>
- <button type="button" id="pose-reset" class="pose-btn" title="Reset the pose to rest">Reset pose</button>
+ <button
+ type="button"
+ id="pose-reset"
+ class="pose-btn"
+ title="Reset the pose to rest"
+ >
+ Reset pose
+ </button>
<label class="pose-btn file-label" title="Load a pose from JSON">
Import
<input type="file" id="pose-import-json" accept="application/json,.json" />
</label>
- <button type="button" id="pose-export-json" class="pose-btn" title="Save pose as JSON">Export JSON</button>
- <button type="button" id="pose-screenshot" class="pose-btn" title="Download a PNG of the current view">PNG screenshot</button>
+ <button
+ type="button"
+ id="pose-export-json"
+ class="pose-btn"
+ title="Save pose as JSON"
+ >
+ Export JSON
+ </button>
+ <button
+ type="button"
+ id="pose-screenshot"
+ class="pose-btn"
+ title="Download a PNG of the current view"
+ >
+ PNG screenshot
+ </button>
</header>
<!-- LEFT PANEL -->
@@ -921,7 +1656,8 @@
/>
<div id="pose-joint-picker"></div>
<p class="pose-shortcuts">
- <kbd>F</kbd> FK · <kbd>I</kbd> IK · <kbd>R</kbd> reset bone · <kbd>Esc</kbd> deselect
+ <kbd>F</kbd> FK · <kbd>I</kbd> IK · <kbd>R</kbd> reset bone ·
+ <kbd>Esc</kbd> deselect
</p>
</section>
@@ -961,15 +1697,36 @@
<h3>Key light</h3>
<div class="pose-form-row">
<label for="pose-light-azimuth">Direction</label>
- <input id="pose-light-azimuth" type="range" min="-180" max="180" step="1" value="52" />
+ <input
+ id="pose-light-azimuth"
+ type="range"
+ min="-180"
+ max="180"
+ step="1"
+ value="52"
+ />
</div>
<div class="pose-form-row">
<label for="pose-light-elevation">Height</label>
- <input id="pose-light-elevation" type="range" min="-10" max="89" step="1" value="55" />
+ <input
+ id="pose-light-elevation"
+ type="range"
+ min="-10"
+ max="89"
+ step="1"
+ value="55"
+ />
</div>
<div class="pose-form-row">
<label for="pose-light-intensity">Intensity</label>
- <input id="pose-light-intensity" type="range" min="0" max="3" step="0.05" value="1.4" />
+ <input
+ id="pose-light-intensity"
+ type="range"
+ min="0"
+ max="3"
+ step="0.05"
+ value="1.4"
+ />
</div>
</section>
</aside>
@@ -982,6 +1739,14 @@
<!-- RIGHT PANEL -->
<aside id="pose-right">
+ <section class="pose-section pose-section-anim">
+ <h2>Animation presets</h2>
+ <p class="pose-section-sub">
+ Load a rigged avatar, click a motion to preview it live, then export an
+ animated GLB.
+ </p>
+ <div id="pose-anim-library"></div>
+ </section>
<section class="pose-section">
<h2>Pose presets</h2>
<div id="pose-presets-host"></div>
@@ -995,19 +1760,71 @@
<!-- TIMELINE -->
<section id="pose-timeline" aria-label="Animation timeline">
<div class="tl-transport">
- <button type="button" id="tl-start" class="tl-btn" title="Jump to start (Home)" aria-label="Jump to start">⏮</button>
- <button type="button" id="tl-play" class="tl-btn" title="Play / pause (Space)" aria-label="Play or pause" aria-pressed="false">▶</button>
- <button type="button" id="tl-stop" class="tl-btn" title="Stop and rewind" aria-label="Stop">⏹</button>
- <button type="button" id="tl-end" class="tl-btn" title="Jump to end (End)" aria-label="Jump to end">⏭</button>
- <button type="button" id="tl-loop" class="tl-btn" title="Loop playback" aria-label="Loop playback" aria-pressed="true">↻</button>
+ <button
+ type="button"
+ id="tl-start"
+ class="tl-btn"
+ title="Jump to start (Home)"
+ aria-label="Jump to start"
+ >
+ ⏮
+ </button>
+ <button
+ type="button"
+ id="tl-play"
+ class="tl-btn"
+ title="Play / pause (Space)"
+ aria-label="Play or pause"
+ aria-pressed="false"
+ >
+ ▶
+ </button>
+ <button
+ type="button"
+ id="tl-stop"
+ class="tl-btn"
+ title="Stop and rewind"
+ aria-label="Stop"
+ >
+ ⏹
+ </button>
+ <button
+ type="button"
+ id="tl-end"
+ class="tl-btn"
+ title="Jump to end (End)"
+ aria-label="Jump to end"
+ >
+ ⏭
+ </button>
+ <button
+ type="button"
+ id="tl-loop"
+ class="tl-btn"
+ title="Loop playback"
+ aria-label="Loop playback"
+ aria-pressed="true"
+ >
+ ↻
+ </button>
<span class="tl-time" id="tl-time"><b>0.00</b> / 4.00s</span>
<span class="tl-sep"></span>
- <button type="button" id="tl-add-key" class="tl-add" title="Capture the current pose as a keyframe (K)">+ Add keyframe</button>
+ <button
+ type="button"
+ id="tl-add-key"
+ class="tl-add"
+ title="Capture the current pose as a keyframe (K)"
+ >
+ + Add keyframe
+ </button>
- <span class="tl-field" title="Easing for the selected keyframe (governs the segment after it)">
+ <span
+ class="tl-field"
+ title="Easing for the selected keyframe (governs the segment after it)"
+ >
<label for="tl-easing">Easing</label>
<select id="tl-easing" aria-label="Selected keyframe easing" disabled>
<option value="linear">Linear</option>
@@ -1016,43 +1833,103 @@
<option value="ease-in-out" selected>Ease in-out</option>
</select>
</span>
- <button type="button" id="tl-del-key" class="tl-btn" title="Delete selected keyframe (Del)" aria-label="Delete selected keyframe" disabled>🗑</button>
+ <button
+ type="button"
+ id="tl-del-key"
+ class="tl-btn"
+ title="Delete selected keyframe (Del)"
+ aria-label="Delete selected keyframe"
+ disabled
+ >
+ 🗑
+ </button>
<span class="tl-spacer"></span>
- <span class="tl-field tl-field-name" title="Animation name (used as the clip + file name)">
+ <span
+ class="tl-field tl-field-name"
+ title="Animation name (used as the clip + file name)"
+ >
<label for="tl-name">Name</label>
- <input type="text" id="tl-name" value="animation" size="10" aria-label="Animation name" autocomplete="off" />
+ <input
+ type="text"
+ id="tl-name"
+ value="animation"
+ size="10"
+ aria-label="Animation name"
+ autocomplete="off"
+ />
</span>
<span class="tl-field" title="Total animation length in seconds">
<label for="tl-duration">Duration</label>
- <input type="number" id="tl-duration" min="0.25" max="120" step="0.25" value="4" aria-label="Duration in seconds" />s
+ <input
+ type="number"
+ id="tl-duration"
+ min="0.25"
+ max="120"
+ step="0.25"
+ value="4"
+ aria-label="Duration in seconds"
+ />s
</span>
- <span class="tl-field tl-field-fps" title="Frames per second baked into the exported clip">
+ <span
+ class="tl-field tl-field-fps"
+ title="Frames per second baked into the exported clip"
+ >
<label for="tl-fps">FPS</label>
- <input type="number" id="tl-fps" min="1" max="120" step="1" value="30" aria-label="Frames per second" />
+ <input
+ type="number"
+ id="tl-fps"
+ min="1"
+ max="120"
+ step="1"
+ value="30"
+ aria-label="Frames per second"
+ />
</span>
<span class="tl-sep"></span>
- <button type="button" id="tl-export-json" class="pose-btn tl-export" title="Download a three.ws clip JSON">Export JSON</button>
- <button type="button" id="tl-export-glb" class="pose-btn pose-btn-primary tl-export" title="Download a GLB with the animation embedded">Export GLB</button>
+ <button
+ type="button"
+ id="tl-export-json"
+ class="pose-btn tl-export"
+ title="Download a three.ws clip JSON"
+ >
+ Export JSON
+ </button>
+ <button
+ type="button"
+ id="tl-export-glb"
+ class="pose-btn pose-btn-primary tl-export"
+ title="Download a GLB with the animation embedded"
+ >
+ Export GLB
+ </button>
</div>
- <div class="tl-track-wrap" id="tl-track" role="slider" tabindex="0"
+ <div
+ class="tl-track-wrap"
+ id="tl-track"
+ role="slider"
+ tabindex="0"
aria-label="Playhead — click or drag to scrub, arrow keys to step"
- aria-valuemin="0" aria-valuemax="4" aria-valuenow="0">
+ aria-valuemin="0"
+ aria-valuemax="4"
+ aria-valuenow="0"
+ >
<div class="tl-ruler" id="tl-ruler"></div>
<div class="tl-empty" id="tl-empty">
- Pose the figure, then press <kbd>K</kbd> or <b style="color:var(--text-2)">+ Add keyframe</b> to start your animation.
+ Pose the figure, then press <kbd>K</kbd> or
+ <b style="color: var(--text-2)">+ Add keyframe</b> to start your animation.
</div>
<div class="tl-lane" id="tl-lane"></div>
- <div class="tl-playhead" id="tl-playhead" style="left:0"></div>
+ <div class="tl-playhead" id="tl-playhead" style="left: 0"></div>
</div>
</section>
</div>
<script type="module" src="/src/pose-studio.js"></script>
<script src="/brand.js" defer></script>
-</body>
+ </body>
</html>
diff --git a/pages/scan.html b/pages/scan.html
index 69568019b..3e9e6d40a 100644
--- a/pages/scan.html
+++ b/pages/scan.html
@@ -520,6 +520,11 @@
Download
<span class="ext">.GLB</span>
</button>
+ <button class="export-btn" id="dl-fbx" type="button" data-format="fbx">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>
+ Engines
+ <span class="ext">.FBX</span>
+ </button>
<button class="export-btn" id="dl-usdz" type="button" data-format="usdz">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2 2 7l10 5 10-5-10-5z"/><path d="m2 17 10 5 10-5"/><path d="m2 12 10 5 10-5"/></svg>
iOS AR
@@ -824,14 +829,24 @@
const labelNodes = [...btn.childNodes];
btn.disabled = true;
try {
- const { downloadAvatar } = await import('/src/avatar-export.js');
await persistName();
- const { size } = await downloadAvatar(_modelUrl, {
- format,
- filename: _avatarName || '3d-scan',
- meta: { name: _avatarName },
- });
- toast(`Downloaded ${format.toUpperCase()} · ${(size / 1024 / 1024).toFixed(1)} MB`);
+ if (format === 'fbx') {
+ // FBX is built server-side (Blender) from the scanned GLB.
+ const { fbxFromUrl, downloadUrl } = await import('/src/remesh-convert.js');
+ const fbxUrl = await fbxFromUrl(_modelUrl, {
+ onStatus: (msg) => toast(msg),
+ });
+ downloadUrl(fbxUrl, `${_avatarName || '3d-scan'}.fbx`);
+ toast('Downloaded FBX');
+ } else {
+ const { downloadAvatar } = await import('/src/avatar-export.js');
+ const { size } = await downloadAvatar(_modelUrl, {
+ format,
+ filename: _avatarName || '3d-scan',
+ meta: { name: _avatarName },
+ });
+ toast(`Downloaded ${format.toUpperCase()} · ${(size / 1024 / 1024).toFixed(1)} MB`);
+ }
} catch (err) {
console.error('[scan] export failed', err);
toast(`Couldn't export ${format.toUpperCase()}. Try GLB.`);
diff --git a/pages/segment.html b/pages/segment.html
new file mode 100644
index 000000000..d3bb808c3
--- /dev/null
+++ b/pages/segment.html
@@ -0,0 +1,561 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Parts Studio · Segment a 3D model · three.ws</title>
+ <meta
+ name="description"
+ content="Split any 3D model into meaningful, separable parts — head, torso, limbs; body, wheels, glass. Click a part to isolate it, toggle visibility, and export it on its own as GLB."
+ />
+ <meta property="og:title" content="Parts Studio — Segment a 3D model · three.ws" />
+ <meta
+ property="og:description"
+ content="Turn a single mesh into addressable, named parts you can hide, recolour, replace, and export individually."
+ />
+ <meta property="og:type" content="website" />
+ <link rel="stylesheet" href="/style.css" />
+ <style>
+ .seg-main {
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: var(--space-xl) var(--space-md) var(--space-2xl);
+ }
+ .seg-head {
+ text-align: center;
+ margin-bottom: var(--space-lg);
+ }
+ .seg-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.45rem;
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 0.3rem 0.7rem;
+ }
+ .seg-eyebrow::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--success);
+ box-shadow: 0 0 8px var(--success);
+ }
+ .seg-head h1 {
+ font-family: var(--font-display);
+ font-size: clamp(2rem, 5vw, var(--text-2xl));
+ line-height: var(--leading-tight);
+ margin: var(--space-md) 0 var(--space-xs);
+ }
+ .seg-head p {
+ color: var(--ink-dim);
+ max-width: 52ch;
+ margin: 0 auto;
+ line-height: var(--leading-normal);
+ }
+
+ /* Composer ----------------------------------------------------- */
+ .composer {
+ background: var(--surface-glass);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ padding: var(--space-md);
+ box-shadow: 0 24px 60px -30px rgba(0, 0, 0, 0.8);
+ display: grid;
+ grid-template-columns: 1fr auto auto auto;
+ gap: var(--space-sm);
+ align-items: end;
+ }
+ @media (max-width: 760px) {
+ .composer {
+ grid-template-columns: 1fr 1fr;
+ }
+ .composer .field-url {
+ grid-column: 1 / -1;
+ }
+ .composer .btn {
+ grid-column: 1 / -1;
+ justify-content: center;
+ }
+ }
+ .field {
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+ min-width: 0;
+ }
+ .field label {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ }
+ .field input,
+ .field select {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ color: var(--ink);
+ font-family: var(--font-body);
+ font-size: var(--text-base);
+ padding: 0.6rem 0.7rem;
+ outline: none;
+ transition: border-color 0.15s, box-shadow 0.15s;
+ }
+ .field input:focus,
+ .field select:focus {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px var(--accent-soft);
+ }
+ .field input[type='number'] {
+ width: 6.5rem;
+ }
+ .btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-family: var(--font-display);
+ font-weight: 600;
+ font-size: var(--text-base);
+ color: #0b0b0b;
+ background: var(--accent);
+ border: 1px solid var(--accent);
+ border-radius: var(--radius-md);
+ padding: 0.62rem 1.2rem;
+ cursor: pointer;
+ transition: transform 0.12s ease, opacity 0.15s, box-shadow 0.15s;
+ }
+ .btn:hover {
+ box-shadow: 0 0 0 4px var(--accent-soft);
+ }
+ .btn:active {
+ transform: translateY(1px);
+ }
+ .btn[disabled] {
+ opacity: 0.45;
+ cursor: not-allowed;
+ }
+ .btn-ghost {
+ background: transparent;
+ color: var(--ink);
+ border: 1px solid var(--stroke-strong);
+ }
+ .btn-ghost:hover {
+ background: var(--surface-2);
+ box-shadow: none;
+ }
+ .btn:focus-visible,
+ .icon-btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+
+ /* Stage / states ---------------------------------------------- */
+ .stage {
+ margin-top: var(--space-lg);
+ min-height: 360px;
+ }
+ .panel {
+ background: var(--surface-glass);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ overflow: hidden;
+ }
+ .is-hidden {
+ display: none !important;
+ }
+
+ /* Loading */
+ .loading {
+ display: grid;
+ place-items: center;
+ padding: var(--space-2xl);
+ text-align: center;
+ }
+ .loading .spinner {
+ width: 38px;
+ height: 38px;
+ border-radius: 50%;
+ border: 3px solid var(--stroke-strong);
+ border-top-color: var(--accent);
+ animation: spin 0.8s linear infinite;
+ margin-bottom: var(--space-md);
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .loading h3 {
+ font-family: var(--font-display);
+ margin: 0 0 var(--space-xs);
+ }
+ .loading p {
+ color: var(--ink-dim);
+ margin: 0;
+ }
+ .loading .meta {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ margin-top: var(--space-sm);
+ }
+
+ /* Result layout: viewport + parts panel */
+ .result {
+ display: grid;
+ grid-template-columns: 1fr 320px;
+ min-height: min(70vh, 640px);
+ }
+ @media (max-width: 880px) {
+ .result {
+ grid-template-columns: 1fr;
+ }
+ }
+ .viewport-wrap {
+ position: relative;
+ background: radial-gradient(120% 120% at 50% 0%, #161616 0%, #0b0b0b 70%);
+ min-height: 360px;
+ }
+ .viewport {
+ position: absolute;
+ inset: 0;
+ }
+ .viewport-bar {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ background: linear-gradient(to top, rgba(0, 0, 0, 0.6), transparent);
+ flex-wrap: wrap;
+ }
+ .viewport-bar .label {
+ font-size: var(--text-sm);
+ color: var(--ink);
+ font-family: var(--font-mono);
+ }
+ .viewport-bar .actions {
+ display: inline-flex;
+ gap: var(--space-xs);
+ }
+ .tip {
+ position: absolute;
+ top: var(--space-sm);
+ left: var(--space-md);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ background: rgba(0, 0, 0, 0.4);
+ padding: 0.25rem 0.55rem;
+ border-radius: 999px;
+ pointer-events: none;
+ }
+
+ /* Parts panel */
+ .parts {
+ border-left: 1px solid var(--stroke);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ background: var(--surface-1);
+ }
+ @media (max-width: 880px) {
+ .parts {
+ border-left: none;
+ border-top: 1px solid var(--stroke);
+ }
+ }
+ .parts-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--space-sm) var(--space-md);
+ border-bottom: 1px solid var(--stroke);
+ }
+ .parts-head h2 {
+ font-family: var(--font-display);
+ font-size: var(--text-base);
+ margin: 0;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ }
+ .parts-head .count {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ background: var(--surface-3);
+ border-radius: 999px;
+ padding: 0.1rem 0.5rem;
+ }
+ .parts-list {
+ overflow-y: auto;
+ max-height: min(60vh, 560px);
+ padding: var(--space-xs);
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .part-row {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ border-radius: var(--radius-md);
+ padding: 0.15rem 0.25rem;
+ transition: background 0.12s;
+ }
+ .part-row:hover {
+ background: var(--surface-2);
+ }
+ .part-row.is-selected {
+ background: var(--accent-soft);
+ box-shadow: inset 0 0 0 1px var(--accent);
+ }
+ .part-row.is-hidden-part .part-text {
+ opacity: 0.4;
+ }
+ .part-main {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ background: transparent;
+ border: none;
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+ text-align: left;
+ padding: 0.4rem 0.4rem;
+ border-radius: var(--radius-sm);
+ }
+ .swatch {
+ width: 14px;
+ height: 14px;
+ border-radius: 4px;
+ flex: none;
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);
+ }
+ .part-text {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ line-height: 1.25;
+ }
+ .part-name {
+ font-size: var(--text-sm);
+ color: var(--ink);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .part-sub {
+ font-family: var(--font-mono);
+ font-size: 0.66rem;
+ color: var(--ink-dim);
+ }
+ .part-actions {
+ display: inline-flex;
+ gap: 1px;
+ flex: none;
+ }
+ .icon-btn {
+ background: transparent;
+ border: none;
+ color: var(--ink-dim);
+ font-size: 0.85rem;
+ width: 26px;
+ height: 26px;
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition: background 0.12s, color 0.12s;
+ }
+ .icon-btn:hover {
+ background: var(--surface-3);
+ color: var(--ink);
+ }
+
+ /* Notices (empty/error/unconfigured) */
+ .notice {
+ padding: var(--space-2xl) var(--space-lg);
+ text-align: center;
+ color: var(--ink-dim);
+ }
+ .notice h3 {
+ color: var(--ink);
+ font-family: var(--font-display);
+ margin: 0 0 var(--space-xs);
+ }
+ .notice.error h3 {
+ color: var(--danger);
+ }
+ .notice p {
+ max-width: 52ch;
+ margin: 0 auto;
+ line-height: var(--leading-normal);
+ }
+ .notice .glyph {
+ font-size: 2.4rem;
+ opacity: 0.5;
+ display: block;
+ margin-bottom: var(--space-sm);
+ }
+ .notice .actions {
+ margin-top: var(--space-md);
+ display: inline-flex;
+ gap: var(--space-xs);
+ }
+ .notice code {
+ font-family: var(--font-mono);
+ font-size: 0.85em;
+ background: var(--surface-2);
+ padding: 0.1rem 0.35rem;
+ border-radius: var(--radius-sm);
+ }
+ .hint-foot {
+ text-align: center;
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ margin-top: var(--space-lg);
+ line-height: var(--leading-normal);
+ }
+ .hint-foot a {
+ color: var(--ink);
+ }
+ </style>
+ </head>
+ <body>
+ <div id="nav-container"></div>
+
+ <main class="seg-main">
+ <header class="seg-head">
+ <span class="seg-eyebrow">Parts · segmentation</span>
+ <h1>Split a model into parts</h1>
+ <p>
+ Paste a GLB/OBJ/STL/PLY URL. Parts Studio separates it at disconnected shells and
+ concave creases into named, recolourable parts — then click any part to isolate it,
+ toggle its visibility, or export it on its own.
+ </p>
+ </header>
+
+ <form class="composer" id="composer" autocomplete="off">
+ <div class="field field-url">
+ <label for="mesh-url">Mesh URL (https)</label>
+ <input
+ id="mesh-url"
+ name="mesh-url"
+ type="url"
+ inputmode="url"
+ placeholder="https://…/model.glb"
+ required
+ />
+ </div>
+ <div class="field">
+ <label for="method">Method</label>
+ <select id="method" name="method">
+ <option value="auto" selected>Auto (shells + creases)</option>
+ <option value="connected">Connected shells</option>
+ <option value="crease">Concave creases</option>
+ </select>
+ </div>
+ <div class="field">
+ <label for="max-parts">Max parts</label>
+ <input id="max-parts" name="max-parts" type="number" min="2" max="64" value="24" />
+ </div>
+ <button class="btn" id="segment-btn" type="submit">
+ <span id="segment-label">Segment</span>
+ </button>
+ </form>
+
+ <section class="stage" id="stage" aria-live="polite">
+ <!-- Empty -->
+ <div class="panel notice" id="state-empty">
+ <span class="glyph" aria-hidden="true">⬢</span>
+ <h3>Nothing segmented yet</h3>
+ <p>
+ Paste a public mesh URL above and press Segment. Generated a model in
+ <a href="/forge">Forge</a>? Open it here with the “Split into parts” button on the
+ result, or paste its GLB link.
+ </p>
+ </div>
+
+ <!-- Loading -->
+ <div class="panel loading is-hidden" id="state-loading">
+ <div class="spinner" aria-hidden="true"></div>
+ <h3>Segmenting your model</h3>
+ <p id="loading-note">Fetching and analysing the mesh…</p>
+ <div class="meta" id="loading-meta">Elapsed 0s</div>
+ <div style="margin-top: var(--space-md)">
+ <button class="btn btn-ghost" type="button" id="cancel">Cancel</button>
+ </div>
+ </div>
+
+ <!-- Result -->
+ <div class="panel result is-hidden" id="state-result">
+ <div class="viewport-wrap">
+ <div class="viewport" id="viewport"></div>
+ <span class="tip" aria-hidden="true">Drag to orbit · click a part to select</span>
+ <div class="viewport-bar">
+ <span class="label" id="selection-label">click a part to inspect</span>
+ <div class="actions">
+ <button class="btn btn-ghost" type="button" id="reset-view">Reset view</button>
+ <button class="btn btn-ghost" type="button" id="show-all">Show all</button>
+ <a class="btn btn-ghost" id="download-glb" download>Download GLB</a>
+ </div>
+ </div>
+ </div>
+ <aside class="parts" aria-label="Parts">
+ <div class="parts-head">
+ <h2>Parts <span class="count" id="parts-count">0</span></h2>
+ </div>
+ <div class="parts-list" id="parts-list" role="list"></div>
+ </aside>
+ </div>
+
+ <!-- Error -->
+ <div class="panel notice error is-hidden" id="state-error">
+ <span class="glyph" aria-hidden="true">⚠</span>
+ <h3>Segmentation failed</h3>
+ <p id="error-message">Something went wrong. Try a simpler mesh or fewer parts.</p>
+ <div class="actions">
+ <button class="btn" type="button" id="retry">Try again</button>
+ </div>
+ </div>
+
+ <!-- Unconfigured -->
+ <div class="panel notice is-hidden" id="state-unconfigured">
+ <span class="glyph" aria-hidden="true">◌</span>
+ <h3>Segmenter not configured</h3>
+ <p>
+ Part segmentation needs the segment worker deployed. Once
+ <code>GCP_SEGMENT_URL</code> and <code>GCP_RECONSTRUCTION_KEY</code> are set, this
+ page runs the full pipeline with no further changes.
+ </p>
+ </div>
+ </section>
+
+ <p class="hint-foot">
+ Geometry-based segmentation — disconnected shells plus the minima rule (cut at concave
+ creases). Each part becomes a named node in the output GLB. The same tool is available to
+ agents over MCP as <code>segment_model</code> and over REST at
+ <a href="/docs">/api/forge-segment</a>.
+ </p>
+ </main>
+
+ <script src="/nav.js" defer></script>
+ <script type="module" src="/src/segment.js"></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/animations/LICENSES.md b/public/animations/LICENSES.md
index 399ae5214..3f70b0d4d 100644
--- a/public/animations/LICENSES.md
+++ b/public/animations/LICENSES.md
@@ -3,7 +3,13 @@
This file records the upstream source and license for every clip in
`/public/animations/clips/`. Each entry uses the canonical-skeleton JSON
emitted by [`scripts/build-animations.mjs`](../../scripts/build-animations.mjs)
-from a source FBX.
+from a source FBX or GLB.
+
+This is the same library exposed one-click in the `/pose` **Animation presets**
+gallery (preview + animated-GLB export) and through the `apply_animation` MCP
+tool. Every clip here is retargetable onto an arbitrary rigged humanoid via
+[`src/animation-retarget.js`](../../src/animation-retarget.js); nothing in the
+gallery is a placeholder or empty clip.
## Mixamo (commercial use OK)
@@ -13,42 +19,45 @@ commercial use of exported animations as part of a product (Mixamo Terms of
Use §2 — characters and animations may be used in personal, commercial, or
non-profit projects).
-| Clip name in manifest | Mixamo source | Notes |
-|---|---|---|
-| `idle` | Idle | trim |
-| `walk` | Walking | trim |
-| `dance` | Hip Hop Dancing | loop |
-| `rumba` | Rumba Dancing | loop |
-| `silly` | Silly Dancing | loop |
-| `thriller` | Thriller Part 2 | loop |
-| `capoeira` | Capoeira | loop |
-| `kiss` | Blow A Kiss | — |
-| `pray` | Praying | — |
-| `wave` | Waving | — |
-| `taunt` | Taunt | — |
-| `angry` | Angry Gesture | — |
-| `celebrate` | Cheering | — |
-| `reaction` | Surprised | — |
-| `defeated` | Defeated | — |
-| `dying` | Dying | — |
-| `falling` | Falling | — |
-| `falltolanding` | Falling To Landing | — |
-| `jump` | Jumping | — |
-| `jumpdown` | Jump Down | — |
-| `jumpdown2` | Jump Down (Light) | — |
-| `jumpdown3` | Jump Down (Heavy) | — |
-| `header` | Soccer Header | — |
-| `goalkeeper` | Goalkeeper Save | — |
-| `dodge` | Dodging | — |
-| `stepback` | Step Back | — |
-| `shoved` | Pushed To Floor | — |
-| `coverstand` | Cover Stand | — |
-| `removing` | Standup Cover | — |
-| `standup` | Standing Up | — |
-| `sitclap` | Sitting Clap | — |
-| `sitidle` | Sitting Idle | — |
-| `sitlaugh` | Sitting Laughing | — |
-| `downdog` | Down Dog | — |
+| Clip name in manifest | Mixamo source | Notes |
+| --------------------- | ------------------ | ----- |
+| `idle` | Idle | trim |
+| `walk` | Walking | trim |
+| `dance` | Hip Hop Dancing | loop |
+| `rumba` | Rumba Dancing | loop |
+| `silly` | Silly Dancing | loop |
+| `thriller` | Thriller Part 2 | loop |
+| `capoeira` | Capoeira | loop |
+| `kiss` | Blow A Kiss | — |
+| `pray` | Praying | — |
+| `wave` | Waving | — |
+| `taunt` | Taunt | — |
+| `angry` | Angry Gesture | — |
+| `celebrate` | Cheering | — |
+| `reaction` | Surprised | — |
+| `defeated` | Defeated | — |
+| `dying` | Dying | — |
+| `falling` | Falling | — |
+| `falltolanding` | Falling To Landing | — |
+| `jump` | Jumping | — |
+| `jumpdown` | Jump Down | — |
+| `jumpdown2` | Jump Down (Light) | — |
+| `jumpdown3` | Jump Down (Heavy) | — |
+| `header` | Soccer Header | — |
+| `goalkeeper` | Goalkeeper Save | — |
+| `dodge` | Dodging | — |
+| `stepback` | Step Back | — |
+| `shoved` | Pushed To Floor | — |
+| `coverstand` | Cover Stand | — |
+| `removing` | Standup Cover | — |
+| `standup` | Standing Up | — |
+| `sitclap` | Sitting Clap | — |
+| `sitidle` | Sitting Idle | — |
+| `sitlaugh` | Sitting Laughing | — |
+| `downdog` | Down Dog | — |
+| `av-listening-music` | Listening To Music | — |
+| `av-leaning-wall` | Leaning On A Wall | — |
+| `av-rap-dance` | Rap Dancing | — |
To add a new Mixamo clip:
@@ -62,6 +71,55 @@ To add a new Mixamo clip:
with a `name`, `url`, `label`, `icon`, and `loop` flag.
5. Add a row to the table above with the Mixamo source name.
+## Avaturn animation library (GLB packs)
+
+The `av-*` clips (plus `facepalm`) below are retargeted from GLB animation packs
+produced through the project's Avaturn avatar pipeline — the `Standard_*`,
+`Idle_*`, and named-action GLBs that ship with Avaturn-exported avatars. They
+are used under the Avaturn platform terms accepted at avatar export and are
+retargeted to the canonical three.ws rig by
+[`scripts/build-animations.mjs`](../../scripts/build-animations.mjs).
+
+> **License note:** these clips are cleared for use _within three.ws products_
+> as part of the Avaturn export pipeline. Before redistributing any single clip
+> as a standalone asset, confirm its upstream terms — packs whose individual
+> provenance is unverified should be treated as internal-only until checked.
+
+| Clip name in manifest | Source GLB | Label |
+| ----------------------- | ------------------------------------- | ------------------ |
+| `facepalm` | Facepalm.glb | Facepalm |
+| `av-idle-breath` | Idle_Breath.glb | Idle Breath |
+| `av-waiting` | Standard_Waiting.glb | Waiting |
+| `av-superhero-jump` | Suoerhero_Jump.glb | Superhero Jump |
+| `av-walk-crouching` | Standard_Walk_Crouching.glb | Walk Crouching |
+| `av-arm-flex` | Arm_Flex.glb | Arm Flex |
+| `av-boxer-dance` | Boxers_dance.glb | Boxer Dance |
+| `av-brag-claps` | Brag_n_Claps.glb | Brag & Clap |
+| `av-flexing-arm` | Flexing_Arm.glb | Flex Arm |
+| `av-vtubing` | Standard_Vtubing_Movement.glb | VTubing |
+| `av-stand-crouch-stand` | Standard_Stand_To_Crouch_To_Stand.glb | Stand-Crouch-Stand |
+| `av-smoking` | Standard_Smoking.glb | Smoking |
+| `av-gymnastics-aerial` | Gymnastics_Aerial.glb | Gymnastics |
+| `av-idle-anim` | idle_anim.glb | Idle (Avaturn) |
+| `av-back-flip` | back_flip.glb | Back Flip |
+| `av-idle-male` | idle_male_jan25.glb | Male Idle |
+| `av-idle-female` | idle_female_jan25.glb | Female Idle |
+| `av-chest-bump` | Gorilla_chest_bump.glb | Chest Bump |
+| `av-walk-feminine` | Standard_Walk_Cycle_Feminine.glb | Feminine Walk |
+| `av-push-block` | Standard_Push_Block_Variation.glb | Push Block |
+| `av-dance-shuffle` | dance_shuffle.glb | Shuffle Dance |
+| `av-headbang` | Dance_Head_Banging_V03.glb | Head Banging |
+| `av-call-me` | Call_Me.glb | Call Me |
+| `av-chilling` | Just_chilling.glb | Chilling |
+| `av-pose1` | pose1.glb | Pose |
+| `av-muay-thai` | Arm_Combo_Muay_Thai.glb | Muay Thai Combo |
+| `av-banging-tunes` | Banging_Tunes_left.glb | Banging Tunes |
+| `av-celebrating` | Celebrating.glb | Celebrating |
+| `av-spy` | Cheap_Spy.glb | Spy |
+| `av-cheering` | Cheering.glb | Cheering |
+| `av-joy` | Expressing_joy.glb | Joy |
+| `av-conductor` | Energic_conductor.glb | Conductor |
+
## Custom mocap
> _No custom-mocap clips have shipped yet._
diff --git a/src/animation-library.js b/src/animation-library.js
index 13484ccd9..97b9ae127 100644
--- a/src/animation-library.js
+++ b/src/animation-library.js
@@ -35,10 +35,11 @@ const el = (tag, attrs = {}, children = []) => {
if (k === 'class') node.className = v;
else if (k === 'text') node.textContent = v;
else if (k === 'html') node.innerHTML = v;
- else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
+ else if (k.startsWith('on') && typeof v === 'function')
+ node.addEventListener(k.slice(2), v);
else if (v !== false && v != null) node.setAttribute(k, v);
}
- for (const child of (Array.isArray(children) ? children : [children])) {
+ for (const child of Array.isArray(children) ? children : [children]) {
if (child == null) continue;
node.appendChild(typeof child === 'string' ? document.createTextNode(child) : child);
}
@@ -91,10 +92,13 @@ export class AnimationLibrary {
const res = await fetch(MANIFEST_URL, { cache: 'no-cache' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const manifest = await res.json();
- if (!Array.isArray(manifest) || manifest.length === 0) throw new Error('empty manifest');
+ if (!Array.isArray(manifest) || manifest.length === 0)
+ throw new Error('empty manifest');
this._curated = curate(manifest);
- this._defs = [this._curated.featured, this._curated.groups.flatMap((g) => g.items)]
- .flat();
+ this._defs = [
+ this._curated.featured,
+ this._curated.groups.flatMap((g) => g.items),
+ ].flat();
this._buildCategoryChips();
this._evaluateRig();
} catch (err) {
@@ -146,15 +150,22 @@ export class AnimationLibrary {
_renderShell() {
this.host.innerHTML = '';
const search = el('input', {
- type: 'search', class: 'al-search', placeholder: 'Search animations…',
- 'aria-label': 'Search animations', autocomplete: 'off',
+ type: 'search',
+ class: 'al-search',
+ placeholder: 'Search animations…',
+ 'aria-label': 'Search animations',
+ autocomplete: 'off',
});
search.addEventListener('input', () => {
this._query = search.value.trim().toLowerCase();
if (this._state === 'ready') this._renderGallery();
});
- const chips = el('div', { class: 'al-chips', role: 'tablist', 'aria-label': 'Animation categories' });
+ const chips = el('div', {
+ class: 'al-chips',
+ role: 'tablist',
+ 'aria-label': 'Animation categories',
+ });
const grid = el('div', { class: 'al-grid' });
const empty = el('div', { class: 'al-empty' });
const transport = this._renderTransport();
@@ -187,21 +198,40 @@ export class AnimationLibrary {
if (action) empty.appendChild(action);
};
if (state === 'loading') {
- empty.appendChild(el('div', { class: 'al-skeleton-grid' },
- Array.from({ length: 6 }, () => el('div', { class: 'al-skeleton' }))));
+ empty.appendChild(
+ el(
+ 'div',
+ { class: 'al-skeleton-grid' },
+ Array.from({ length: 6 }, () => el('div', { class: 'al-skeleton' })),
+ ),
+ );
} else if (state === 'error-load') {
const retry = el('button', { class: 'al-cta', type: 'button' }, ['Retry']);
retry.addEventListener('click', () => this.mount());
- make('⚠️', 'Couldn’t load the animation library',
- 'The clip manifest failed to load. Check your connection and try again.', retry);
+ make(
+ '⚠️',
+ 'Couldn’t load the animation library',
+ 'The clip manifest failed to load. Check your connection and try again.',
+ retry,
+ );
} else if (state === 'no-rig') {
const cta = el('button', { class: 'al-cta', type: 'button' }, ['Load a rigged avatar']);
- cta.addEventListener('click', () => document.querySelector('#pose-load-avatar')?.click());
- make('🦴', 'Load a rigged avatar to animate',
- 'Animation presets apply to a rigged model. Load one of your avatars (or a public avatar) and the full gallery unlocks here.', cta);
+ cta.addEventListener('click', () =>
+ document.querySelector('#pose-load-avatar')?.click(),
+ );
+ make(
+ '🦴',
+ 'Load a rigged avatar to animate',
+ 'Animation presets apply to a rigged model. Load one of your avatars (or a public avatar) and the full gallery unlocks here.',
+ cta,
+ );
} else if (state === 'incompatible') {
- make('🚫', 'This rig can’t be retargeted',
- `The loaded model exposes only ${this._rigBoneCount()} recognizable humanoid bones — too few to drive the preset library. Try a standard humanoid avatar.`, null);
+ make(
+ '🚫',
+ 'This rig can’t be retargeted',
+ `The loaded model exposes only ${this._rigBoneCount()} recognizable humanoid bones — too few to drive the preset library. Try a standard humanoid avatar.`,
+ null,
+ );
}
}
@@ -210,14 +240,22 @@ export class AnimationLibrary {
const { chips } = this._refs;
chips.innerHTML = '';
const mk = (key, label) => {
- const b = el('button', {
- class: 'al-chip', type: 'button', role: 'tab',
- 'data-cat': key, 'aria-selected': String(this._filterCat === key),
- }, [label]);
+ const b = el(
+ 'button',
+ {
+ class: 'al-chip',
+ type: 'button',
+ role: 'tab',
+ 'data-cat': key,
+ 'aria-selected': String(this._filterCat === key),
+ },
+ [label],
+ );
b.addEventListener('click', () => {
this._filterCat = key;
- chips.querySelectorAll('.al-chip').forEach((c) =>
- c.setAttribute('aria-selected', String(c.dataset.cat === key)));
+ chips
+ .querySelectorAll('.al-chip')
+ .forEach((c) => c.setAttribute('aria-selected', String(c.dataset.cat === key)));
this._renderGallery();
});
return b;
@@ -251,33 +289,43 @@ export class AnimationLibrary {
for (const group of this._curated.groups) {
const items = group.items.filter((d) => this._matches(d));
if (!items.length) continue;
- grid.appendChild(el('div', { class: 'al-section-label' }, [`${group.icon} ${group.label}`]));
+ grid.appendChild(
+ el('div', { class: 'al-section-label' }, [`${group.icon} ${group.label}`]),
+ );
const row = el('div', { class: 'al-cards' });
for (const def of items) row.appendChild(this._card(def));
grid.appendChild(row);
}
if (!grid.querySelector('.al-card')) {
- grid.appendChild(el('p', { class: 'al-no-match' },
- [`No animations match “${this._query}”.`]));
+ grid.appendChild(
+ el('p', { class: 'al-no-match' }, [`No animations match “${this._query}”.`]),
+ );
}
}
_card(def) {
const isActive = def.name === this._activeName;
- const card = el('button', {
- class: `al-card${isActive ? ' is-active' : ''}`,
- type: 'button',
- 'data-name': def.name,
- 'aria-pressed': String(isActive),
- title: `${def.label || def.name}${def.loop === false ? '' : ' · loops'}`,
- }, [
- el('span', { class: 'al-card-icon' }, [def.icon || '🎬']),
- el('span', { class: 'al-card-label' }, [def.label || def.name]),
- el('span', { class: 'al-card-badge' }, [def.loop === false ? 'once' : 'loop']),
- el('span', { class: 'al-card-eq', 'aria-hidden': 'true' },
- [el('i'), el('i'), el('i')]),
- ]);
+ const card = el(
+ 'button',
+ {
+ class: `al-card${isActive ? ' is-active' : ''}`,
+ type: 'button',
+ 'data-name': def.name,
+ 'aria-pressed': String(isActive),
+ title: `${def.label || def.name}${def.loop === false ? '' : ' · loops'}`,
+ },
+ [
+ el('span', { class: 'al-card-icon' }, [def.icon || '🎬']),
+ el('span', { class: 'al-card-label' }, [def.label || def.name]),
+ el('span', { class: 'al-card-badge' }, [def.loop === false ? 'once' : 'loop']),
+ el('span', { class: 'al-card-eq', 'aria-hidden': 'true' }, [
+ el('i'),
+ el('i'),
+ el('i'),
+ ]),
+ ],
+ );
card.addEventListener('click', () => this.preview(def));
return card;
}
@@ -325,7 +373,13 @@ export class AnimationLibrary {
return;
}
- const { clip: retargeted, matched, total, coverage, dropped } = retargetClipToRig(clip, rig);
+ const {
+ clip: retargeted,
+ matched,
+ total,
+ coverage,
+ dropped,
+ } = retargetClipToRig(clip, rig);
if (!retargeted) {
this.setStatus(
`“${def.label || def.name}” can’t retarget to this rig — only ${matched}/${total} tracks mapped (need ${Math.round(MIN_COVERAGE * 100)}%).`,
@@ -372,7 +426,11 @@ export class AnimationLibrary {
this._markActiveCard?.();
if (this._refs.transport) this._refs.transport.root.style.display = 'none';
// Hand the figure back to the host in a clean rest pose.
- try { this.getRig()?.resetPose?.(); } catch { /* rig may be gone */ }
+ try {
+ this.getRig()?.resetPose?.();
+ } catch {
+ /* rig may be gone */
+ }
this.onPreviewStop();
if (!silent) this.setStatus('Preview stopped.');
}
@@ -388,30 +446,46 @@ export class AnimationLibrary {
const label = el('span', { class: 'al-now-label' });
const speedVal = el('span', { class: 'al-speed-val' }, ['1.0×']);
const speed = el('input', {
- type: 'range', min: '0.25', max: '2.5', step: '0.05', value: '1',
- class: 'al-speed', 'aria-label': 'Playback speed',
+ type: 'range',
+ min: '0.25',
+ max: '2.5',
+ step: '0.05',
+ value: '1',
+ class: 'al-speed',
+ 'aria-label': 'Playback speed',
});
speed.addEventListener('input', () => {
this._setSpeed(parseFloat(speed.value));
});
- const stop = el('button', { class: 'al-tbtn', type: 'button', title: 'Stop preview' }, ['⏹ Stop']);
+ const stop = el('button', { class: 'al-tbtn', type: 'button', title: 'Stop preview' }, [
+ '⏹ Stop',
+ ]);
stop.addEventListener('click', () => this.stopPreview());
- const exportBtn = el('button', {
- class: 'al-export', type: 'button',
- title: 'Download a GLB with this animation baked in',
- }, ['Export animated GLB']);
+ const exportBtn = el(
+ 'button',
+ {
+ class: 'al-export',
+ type: 'button',
+ title: 'Download a GLB with this animation baked in',
+ },
+ ['Export animated GLB'],
+ );
exportBtn.addEventListener('click', () => this._exportGLB(exportBtn));
const root = el('div', { class: 'al-transport', style: 'display:none' }, [
el('div', { class: 'al-now' }, [el('span', { class: 'al-now-dot' }), label]),
- el('div', { class: 'al-speed-row' }, [
- el('label', {}, ['Speed']), speed, speedVal,
- ]),
+ el('div', { class: 'al-speed-row' }, [el('label', {}, ['Speed']), speed, speedVal]),
el('div', { class: 'al-transport-actions' }, [stop, exportBtn]),
]);
- this._refs = { ...this._refs, transportLabel: label, transportSpeedVal: speedVal, transportSpeed: speed, exportBtn };
+ this._refs = {
+ ...this._refs,
+ transportLabel: label,
+ transportSpeedVal: speedVal,
+ transportSpeed: speed,
+ exportBtn,
+ };
return { root };
}
@@ -432,7 +506,10 @@ export class AnimationLibrary {
btn.classList.remove('is-busy', 'is-ok', 'is-err');
if (cls) btn.classList.add(cls);
btn.textContent = txt;
- setTimeout(() => { btn.classList.remove('is-ok', 'is-err'); btn.textContent = original; }, 2400);
+ setTimeout(() => {
+ btn.classList.remove('is-ok', 'is-err');
+ btn.textContent = original;
+ }, 2400);
};
btn.classList.add('is-busy');
btn.textContent = 'Baking…';
@@ -445,7 +522,10 @@ export class AnimationLibrary {
// Park the figure on the clip's first frame so the exported rest pose
// is the animation's start, not wherever the live preview paused.
- if (this._action) { this._action.time = 0; this._mixer.update(0); }
+ if (this._action) {
+ this._action.time = 0;
+ this._mixer.update(0);
+ }
const exporter = new GLTFExporter();
const buffer = await exporter.parseAsync(rig.root, {
@@ -453,10 +533,14 @@ export class AnimationLibrary {
animations: [exportClip],
embedImages: true,
});
- const safeRig = (rig.root?.name || 'avatar').replace(/[^a-z0-9._-]+/gi, '-').slice(0, 40) || 'avatar';
+ const safeRig =
+ (rig.root?.name || 'avatar').replace(/[^a-z0-9._-]+/gi, '-').slice(0, 40) ||
+ 'avatar';
this._download(buffer, `${safeRig}-${this._activeDef.name}.glb`);
done('Saved ✓', 'is-ok');
- this.setStatus(`Exported animated GLB: ${this._activeDef.label || this._activeDef.name}.`);
+ this.setStatus(
+ `Exported animated GLB: ${this._activeDef.label || this._activeDef.name}.`,
+ );
} catch (err) {
log.warn('[AnimationLibrary] export failed:', err);
done('Failed', 'is-err');
@@ -465,7 +549,8 @@ export class AnimationLibrary {
}
_download(buffer, filename) {
- const blob = buffer instanceof Blob ? buffer : new Blob([buffer], { type: 'model/gltf-binary' });
+ const blob =
+ buffer instanceof Blob ? buffer : new Blob([buffer], { type: 'model/gltf-binary' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
@@ -479,7 +564,11 @@ export class AnimationLibrary {
_disposeMixer() {
if (this._mixer) {
this._mixer.stopAllAction();
- try { this._mixer.uncacheRoot(this._mixerRoot); } catch { /* root already gone */ }
+ try {
+ this._mixer.uncacheRoot(this._mixerRoot);
+ } catch {
+ /* root already gone */
+ }
}
this._mixer = null;
this._mixerRoot = null;
diff --git a/src/animation-presets.js b/src/animation-presets.js
index e642564b7..38054c223 100644
--- a/src/animation-presets.js
+++ b/src/animation-presets.js
@@ -24,35 +24,82 @@ export const CATEGORIES = [
// Clip name → category key. Names mirror manifest.json / animations.config.json.
export const CLIP_CATEGORIES = Object.freeze({
// Idle & stand
- idle: 'idle', 'av-idle-breath': 'idle', 'av-waiting': 'idle', 'av-idle-anim': 'idle',
- 'av-idle-male': 'idle', 'av-idle-female': 'idle', 'av-chilling': 'idle', 'av-pose1': 'idle',
- 'av-leaning-wall': 'idle', 'av-smoking': 'idle', 'av-listening-music': 'idle', standup: 'idle',
+ idle: 'idle',
+ 'av-idle-breath': 'idle',
+ 'av-waiting': 'idle',
+ 'av-idle-anim': 'idle',
+ 'av-idle-male': 'idle',
+ 'av-idle-female': 'idle',
+ 'av-chilling': 'idle',
+ 'av-pose1': 'idle',
+ 'av-leaning-wall': 'idle',
+ 'av-smoking': 'idle',
+ 'av-listening-music': 'idle',
+ standup: 'idle',
coverstand: 'idle',
// Locomotion
- walk: 'locomotion', 'av-walk-feminine': 'locomotion', 'av-walk-crouching': 'locomotion',
- stepback: 'locomotion', dodge: 'locomotion',
+ walk: 'locomotion',
+ 'av-walk-feminine': 'locomotion',
+ 'av-walk-crouching': 'locomotion',
+ stepback: 'locomotion',
+ dodge: 'locomotion',
// Dance
- dance: 'dance', rumba: 'dance', silly: 'dance', thriller: 'dance', capoeira: 'dance',
- 'av-dance-shuffle': 'dance', 'av-headbang': 'dance', 'av-boxer-dance': 'dance',
- 'av-rap-dance': 'dance', 'av-banging-tunes': 'dance', 'av-conductor': 'dance',
+ dance: 'dance',
+ rumba: 'dance',
+ silly: 'dance',
+ thriller: 'dance',
+ capoeira: 'dance',
+ 'av-dance-shuffle': 'dance',
+ 'av-headbang': 'dance',
+ 'av-boxer-dance': 'dance',
+ 'av-rap-dance': 'dance',
+ 'av-banging-tunes': 'dance',
+ 'av-conductor': 'dance',
// Gestures & expression
- wave: 'gesture', 'av-call-me': 'gesture', 'av-brag-claps': 'gesture', pray: 'gesture',
- kiss: 'gesture', taunt: 'gesture', 'av-vtubing': 'gesture', 'av-spy': 'gesture',
- 'av-joy': 'gesture', facepalm: 'gesture', angry: 'gesture', lookdown: 'gesture',
+ wave: 'gesture',
+ 'av-call-me': 'gesture',
+ 'av-brag-claps': 'gesture',
+ pray: 'gesture',
+ kiss: 'gesture',
+ taunt: 'gesture',
+ 'av-vtubing': 'gesture',
+ 'av-spy': 'gesture',
+ 'av-joy': 'gesture',
+ facepalm: 'gesture',
+ angry: 'gesture',
+ lookdown: 'gesture',
covereyes: 'gesture',
// Celebrations
- celebrate: 'gesture', 'av-celebrating': 'gesture', 'av-cheering': 'gesture',
+ celebrate: 'gesture',
+ 'av-celebrating': 'gesture',
+ 'av-cheering': 'gesture',
// Action & combat
- jump: 'action', 'av-superhero-jump': 'action', 'av-back-flip': 'action',
- 'av-gymnastics-aerial': 'action', 'av-muay-thai': 'action', 'av-chest-bump': 'action',
- 'av-arm-flex': 'action', 'av-flexing-arm': 'action', 'av-push-block': 'action',
- 'av-stand-crouch-stand': 'action', removing: 'action',
+ jump: 'action',
+ 'av-superhero-jump': 'action',
+ 'av-back-flip': 'action',
+ 'av-gymnastics-aerial': 'action',
+ 'av-muay-thai': 'action',
+ 'av-chest-bump': 'action',
+ 'av-arm-flex': 'action',
+ 'av-flexing-arm': 'action',
+ 'av-push-block': 'action',
+ 'av-stand-crouch-stand': 'action',
+ removing: 'action',
// Sports
- header: 'sport', goalkeeper: 'sport',
+ header: 'sport',
+ goalkeeper: 'sport',
// Reactions & falls
- reaction: 'reaction', shoved: 'reaction', defeated: 'reaction', dying: 'reaction',
- falling: 'reaction', falltolanding: 'reaction', jumpdown: 'reaction', jumpdown2: 'reaction',
- jumpdown3: 'reaction', sitclap: 'reaction', sitlaugh: 'reaction',
+ reaction: 'reaction',
+ shoved: 'reaction',
+ defeated: 'reaction',
+ dying: 'reaction',
+ falling: 'reaction',
+ falltolanding: 'reaction',
+ jumpdown: 'reaction',
+ jumpdown2: 'reaction',
+ jumpdown3: 'reaction',
+ sitclap: 'reaction',
+ sitlaugh: 'reaction',
// Fitness & yoga
downdog: 'fitness',
});
diff --git a/src/animation-retarget.js b/src/animation-retarget.js
index 5bfdf73b9..b90e03541 100644
--- a/src/animation-retarget.js
+++ b/src/animation-retarget.js
@@ -97,7 +97,8 @@ export function hipRestHeight(rig) {
// was authored around. The retarget scales other-height rigs by target/source.
function clipHipBaselineY(clip) {
const track = clip.tracks.find(
- (t) => t.name.endsWith('.position') && canonicalizeBoneName(t.name.split('.')[0]) === 'Hips',
+ (t) =>
+ t.name.endsWith('.position') && canonicalizeBoneName(t.name.split('.')[0]) === 'Hips',
);
if (!track || track.values.length < 3) return 0;
return track.values[1]; // [x, y, z, …] — Y of the first keyframe
diff --git a/src/avatar-page.js b/src/avatar-page.js
index ec03ca7ce..351896b31 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -9,6 +9,7 @@
import { openTalkMode } from './voice/talk-mode.js';
import { downloadAvatar } from './avatar-export.js';
+import { fbxFromUrl } from './remesh-convert.js';
import { log } from './shared/log.js';
import { emptyStateHTML } from './shared/state-kit.js';
@@ -380,6 +381,10 @@ function openDownloadMenu(ev) {
<strong>GLB</strong>
<span>Universal — game engines, Blender, browsers</span>
</button>
+ <button type="button" role="menuitem" data-format="fbx">
+ <strong>FBX</strong>
+ <span>Unity &amp; Unreal — keeps the skeleton</span>
+ </button>
<button type="button" role="menuitem" data-format="vrm">
<strong>VRM</strong>
<span>VRChat, Resonite, Hubs, VTube Studio</span>
@@ -412,6 +417,15 @@ function openDownloadMenu(ev) {
triggerLink(usdzUrl, `${fileBase}.usdz`);
statusEl.textContent = 'Download started.';
statusEl.dataset.tone = 'ok';
+ } else if (format === 'fbx') {
+ // FBX is built server-side from the GLB so the skeleton survives.
+ if (!glbUrl) throw new Error('No source GLB to convert.');
+ const fbxUrl = await fbxFromUrl(glbUrl, {
+ onStatus: (msg) => { statusEl.textContent = msg; },
+ });
+ triggerLink(fbxUrl, `${fileBase}.fbx`);
+ statusEl.textContent = 'Download started.';
+ statusEl.dataset.tone = 'ok';
} else {
// Build client-side from the GLB.
if (!glbUrl) throw new Error('No source GLB to convert.');
diff --git a/src/create-review-features.js b/src/create-review-features.js
index 9eb263af0..fe7833516 100644
--- a/src/create-review-features.js
+++ b/src/create-review-features.js
@@ -13,6 +13,7 @@
import { openTalkMode } from './voice/talk-mode.js';
import { downloadAvatar } from './avatar-export.js';
+import { fbxFromBlob, downloadUrl } from './remesh-convert.js';
import { log } from './shared/log.js';
// ── Feature-preview modal ────────────────────────────────────────────────────
@@ -629,6 +630,13 @@ const DOWNLOAD_FORMATS = [
ext: '.glb',
size: 'original',
},
+ {
+ id: 'fbx',
+ label: 'FBX',
+ blurb: 'Game-engine interchange. Imports into Unity and Unreal with the bone hierarchy, skin weights, and blendshapes intact.',
+ ext: '.fbx',
+ size: 'similar to GLB',
+ },
{
id: 'vrm',
label: 'VRM',
@@ -668,7 +676,7 @@ export function openDownloadModal(ctx) {
`,
).join('')}
</ul>
- <p class="fm-note">All conversion runs in your browser — no upload, no server.</p>
+ <p class="fm-note">GLB, VRM, and USDZ convert in your browser. FBX renders on our servers (keeps the skeleton for Unity/Unreal) — a few seconds.</p>
`;
openFeatureModal({
@@ -688,6 +696,17 @@ export function openDownloadModal(ctx) {
statusEl.textContent = 'Preparing…';
statusEl.dataset.tone = 'busy';
try {
+ if (format === 'fbx') {
+ // FBX is built server-side from the GLB so the skeleton survives.
+ const fbxUrl = await fbxFromBlob(ctx.blob, {
+ filename: safeName,
+ onStatus: (msg) => { statusEl.textContent = msg; },
+ });
+ downloadUrl(fbxUrl, `${safeName}.fbx`);
+ statusEl.textContent = 'FBX ready — download started.';
+ statusEl.dataset.tone = 'ok';
+ return;
+ }
const result = await downloadAvatar(ctx.blob, {
format,
filename: safeName,
diff --git a/src/editor/index.js b/src/editor/index.js
index 9938c0f5c..8604646d8 100644
--- a/src/editor/index.js
+++ b/src/editor/index.js
@@ -11,6 +11,7 @@ import { EditorSession } from './session.js';
import { MaterialEditor } from './material-editor.js';
import { SceneExplorer } from './scene-explorer.js';
import { TextureInspector } from './texture-inspector.js';
+import { MagicBrush } from './magic-brush.js';
import { exportEditedGLB, downloadGLB } from './glb-export.js';
import { log } from '../shared/log.js';
@@ -21,6 +22,7 @@ export class Editor {
this.materialEditor = new MaterialEditor(viewer, this.session);
this.textureInspector = new TextureInspector(viewer, this.session);
this.sceneExplorer = new SceneExplorer(viewer, this.session);
+ this.magicBrush = new MagicBrush(viewer, this.session, this);
this.exportFolder = null;
this._exportCtrl = null;
this._publishCtrl = null;
@@ -35,6 +37,7 @@ export class Editor {
this._attached = true;
this.sceneExplorer.attach();
this._addExportFolder();
+ this.magicBrush.attach();
this.session.onChange(() => {
this._updateExportLabel();
this._updateExportEnabled();
@@ -47,6 +50,7 @@ export class Editor {
this.materialEditor.rebuild();
this.textureInspector.rebuild();
this.sceneExplorer.rebuild();
+ this.magicBrush.rebuild();
this._updateExportLabel();
}
@@ -228,6 +232,7 @@ export class Editor {
this.materialEditor.dispose();
this.textureInspector.dispose();
this.sceneExplorer.detach();
+ this.magicBrush.dispose();
if (this.exportFolder && this.viewer.gui) {
try {
this.viewer.gui.removeFolder(this.exportFolder);
diff --git a/src/editor/magic-brush.js b/src/editor/magic-brush.js
new file mode 100644
index 000000000..44ba6675e
--- /dev/null
+++ b/src/editor/magic-brush.js
@@ -0,0 +1,792 @@
+/**
+ * MagicBrush — local region retexturing.
+ *
+ * Paint a mask directly on the model surface, type a prompt (and/or pick a
+ * colour), and only that region of the texture is repainted by SDXL inpainting —
+ * the rest of the surface is preserved pixel-for-pixel and the seam is feathered
+ * invisible. Passes compose: each Apply operates on the latest texture.
+ *
+ * Wiring (see editor/index.js):
+ * this.magicBrush = new MagicBrush(viewer, session, this);
+ * this.magicBrush.attach(); // adds the GUI toggle + key [B]
+ * this.magicBrush.rebuild(); // on every onContentChanged
+ *
+ * Surface selection → UV mask:
+ * We raycast the pointer onto the target mesh and stamp the hit's interpolated
+ * UV into an offscreen mask canvas. The mask is in the model's own UV layout
+ * (glTF convention: row 0 = top = v 0, flipY=false), so the worker can
+ * composite it straight onto the baseColour atlas with no remapping.
+ */
+import { Raycaster, Vector2, CanvasTexture, SRGBColorSpace } from 'three';
+import { log } from '../shared/log.js';
+
+const TEX = 1024; // mask + preview working resolution (UV space)
+const POLL_MS = 2500;
+const HIGHLIGHT = '#ff2da6';
+
+let _styleInjected = false;
+function injectStyles() {
+ if (_styleInjected || typeof document === 'undefined') return;
+ _styleInjected = true;
+ const css = `
+.mb-panel{position:absolute;right:16px;bottom:16px;z-index:30;width:300px;
+ font:13px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;color:#e8e8ec;
+ background:rgba(18,18,22,.92);backdrop-filter:blur(12px);border:1px solid rgba(255,255,255,.1);
+ border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.5);overflow:hidden;
+ opacity:0;transform:translateY(8px);transition:opacity .18s ease,transform .18s ease}
+.mb-panel.mb-open{opacity:1;transform:translateY(0)}
+.mb-head{display:flex;align-items:center;gap:8px;padding:12px 14px;border-bottom:1px solid rgba(255,255,255,.08)}
+.mb-head h3{margin:0;font-size:13px;font-weight:650;letter-spacing:.2px;flex:1}
+.mb-dot{width:8px;height:8px;border-radius:50%;background:${HIGHLIGHT};box-shadow:0 0 8px ${HIGHLIGHT}}
+.mb-x{all:unset;cursor:pointer;color:#9a9aa5;font-size:16px;line-height:1;padding:2px 4px;border-radius:6px}
+.mb-x:hover{color:#fff;background:rgba(255,255,255,.08)}
+.mb-x:focus-visible{outline:2px solid ${HIGHLIGHT};outline-offset:1px}
+.mb-body{padding:14px;display:flex;flex-direction:column;gap:12px}
+.mb-row{display:flex;flex-direction:column;gap:6px}
+.mb-row label{font-size:11px;font-weight:600;color:#a8a8b4;text-transform:uppercase;letter-spacing:.4px}
+.mb-hint{font-size:12px;color:#9a9aa5;margin:0}
+.mb-slide{display:flex;align-items:center;gap:10px}
+.mb-slide input[type=range]{flex:1;accent-color:${HIGHLIGHT}}
+.mb-slide .mb-val{min-width:34px;text-align:right;font-variant-numeric:tabular-nums;color:#cfcfd6}
+.mb-seg{display:flex;gap:6px}
+.mb-seg button{flex:1;all:unset;text-align:center;cursor:pointer;padding:7px 0;border-radius:8px;
+ background:rgba(255,255,255,.06);border:1px solid transparent;font-size:12px;font-weight:600;transition:background .12s}
+.mb-seg button:hover{background:rgba(255,255,255,.12)}
+.mb-seg button[aria-pressed=true]{background:${HIGHLIGHT};color:#fff;border-color:${HIGHLIGHT}}
+.mb-seg button:focus-visible{outline:2px solid ${HIGHLIGHT};outline-offset:1px}
+.mb-ta{width:100%;box-sizing:border-box;resize:vertical;min-height:54px;padding:8px 10px;border-radius:9px;
+ background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);color:#fff;font:inherit}
+.mb-ta:focus{outline:none;border-color:${HIGHLIGHT};box-shadow:0 0 0 3px rgba(255,45,166,.2)}
+.mb-color{display:flex;align-items:center;gap:9px}
+.mb-color input[type=color]{width:34px;height:30px;padding:0;border:1px solid rgba(255,255,255,.15);border-radius:8px;background:none;cursor:pointer}
+.mb-color .mb-swap{all:unset;cursor:pointer;font-size:11px;color:#9a9aa5;text-decoration:underline}
+.mb-color .mb-swap:hover{color:#fff}
+.mb-actions{display:flex;gap:8px}
+.mb-btn{all:unset;flex:1;text-align:center;cursor:pointer;padding:10px 0;border-radius:10px;font-weight:650;font-size:13px;transition:filter .12s,background .12s}
+.mb-btn:focus-visible{outline:2px solid #fff;outline-offset:1px}
+.mb-btn.mb-primary{background:linear-gradient(135deg,${HIGHLIGHT},#7a2dff);color:#fff}
+.mb-btn.mb-primary:hover{filter:brightness(1.08)}
+.mb-btn.mb-primary[disabled]{opacity:.45;cursor:not-allowed;filter:none}
+.mb-btn.mb-ghost{flex:0 0 auto;padding:10px 14px;background:rgba(255,255,255,.07)}
+.mb-btn.mb-ghost:hover{background:rgba(255,255,255,.13)}
+.mb-status{display:flex;align-items:center;gap:9px;font-size:12px;padding:9px 11px;border-radius:9px;min-height:18px}
+.mb-status.is-info{background:rgba(122,45,255,.16);color:#cbb8ff}
+.mb-status.is-busy{background:rgba(255,255,255,.06);color:#cfcfd6}
+.mb-status.is-ok{background:rgba(46,204,113,.16);color:#7be0a6}
+.mb-status.is-err{background:rgba(231,76,60,.16);color:#ff9b8f}
+.mb-spin{width:14px;height:14px;border-radius:50%;border:2px solid rgba(255,255,255,.25);border-top-color:#fff;animation:mb-spin .8s linear infinite;flex:0 0 auto}
+@keyframes mb-spin{to{transform:rotate(360deg)}}
+.mb-empty{padding:18px 16px;text-align:center;color:#a8a8b4}
+.mb-empty strong{display:block;color:#e8e8ec;margin-bottom:6px;font-size:13px}
+`;
+ const el = document.createElement('style');
+ el.id = 'mb-styles';
+ el.textContent = css;
+ document.head.appendChild(el);
+}
+
+export class MagicBrush {
+ constructor(viewer, session, editor) {
+ this.viewer = viewer;
+ this.session = session;
+ this.editor = editor;
+
+ this.enabled = false;
+ this.tool = 'paint'; // 'paint' | 'erase'
+ this.brush = 64; // mask px radius
+ this.prompt = '';
+ this.color = null; // hex string or null
+ this.quality = 1024; // texture_size
+ this.strength = 0.85;
+
+ this.busy = false;
+ this.painted = false;
+ this.status = null; // { kind, text }
+ this.jobToken = null;
+ this._pollTimer = null;
+
+ // Target mesh + its material/map we paint against.
+ this.targetMesh = null;
+ this.targetMaterial = null;
+ this._origMap = undefined;
+
+ // Offscreen canvases.
+ this.maskCanvas = null; // white discs on transparent (uploaded over black)
+ this.tintCanvas = null; // mask recoloured to HIGHLIGHT for on-model preview
+ this.baseCanvas = null; // current base atlas, drawn behind the tint
+ this.previewCanvas = null; // base + tint → CanvasTexture on the model
+ this.previewTexture = null;
+
+ this.raycaster = new Raycaster();
+ this.raycaster.firstHitOnly = true;
+ this._ndc = new Vector2();
+ this._lastUV = null;
+ this._painting = false;
+ this._recomposeQueued = false;
+
+ this.panel = null;
+ this._guiCtrl = null;
+
+ this._onPointerDown = this._onPointerDown.bind(this);
+ this._onPointerMove = this._onPointerMove.bind(this);
+ this._onPointerUp = this._onPointerUp.bind(this);
+ this._onKey = this._onKey.bind(this);
+ }
+
+ // ── lifecycle ──────────────────────────────────────────────────────────────
+
+ attach() {
+ injectStyles();
+ if (this.viewer?.gui) {
+ const folder = this.viewer.gui.__folders?.Editor || this.viewer.gui;
+ this._guiCtrl = folder
+ .add({ brush: () => this.toggle() }, 'brush')
+ .name('🖌 magic brush [B]');
+ }
+ window.addEventListener('keydown', this._onKey);
+ }
+
+ rebuild() {
+ // New content loaded — drop any in-flight state and re-acquire the target.
+ this._stopPolling();
+ this._teardownPreview();
+ this.painted = false;
+ this._lastUV = null;
+ this.jobToken = null;
+ this.busy = false;
+ this.status = null;
+ this._acquireTarget();
+ this._initCanvases();
+ if (this.enabled) {
+ this._installPreview();
+ this.render();
+ }
+ }
+
+ toggle() {
+ this.enabled ? this.disable() : this.enable();
+ }
+
+ enable() {
+ if (this.enabled) return;
+ this.enabled = true;
+ injectStyles();
+ this._acquireTarget();
+ this._initCanvases();
+ this._installPreview();
+ const canvas = this.viewer?.renderer?.domElement;
+ if (canvas) {
+ // Capture phase so we intercept the pointer BEFORE OrbitControls'
+ // own listener and can stop it from starting an orbit mid-stroke.
+ canvas.addEventListener('pointerdown', this._onPointerDown, true);
+ this._prevTouchAction = canvas.style.touchAction;
+ canvas.style.touchAction = 'none';
+ if (this.targetMesh) canvas.style.cursor = 'crosshair';
+ }
+ this._mountPanel();
+ this.render();
+ }
+
+ disable() {
+ if (!this.enabled) return;
+ this.enabled = false;
+ this._stopPolling();
+ this._endStroke();
+ const canvas = this.viewer?.renderer?.domElement;
+ if (canvas) {
+ canvas.removeEventListener('pointerdown', this._onPointerDown, true);
+ canvas.style.cursor = '';
+ if (this._prevTouchAction !== undefined) canvas.style.touchAction = this._prevTouchAction;
+ }
+ this._teardownPreview();
+ this._unmountPanel();
+ }
+
+ dispose() {
+ this.disable();
+ window.removeEventListener('keydown', this._onKey);
+ }
+
+ _onKey(e) {
+ if (e.key !== 'b' && e.key !== 'B') return;
+ const t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ this.toggle();
+ }
+
+ // ── target + canvases ────────────────────────────────────────────────────────
+
+ _acquireTarget() {
+ this.targetMesh = null;
+ this.targetMaterial = null;
+ const content = this.viewer?.content;
+ if (!content) return;
+ const candidates = [];
+ content.traverse((n) => {
+ if (n.isMesh && n.geometry?.attributes?.uv) candidates.push(n);
+ });
+ if (!candidates.length) return;
+ const matOf = (m) => (Array.isArray(m.material) ? m.material[0] : m.material);
+ const hasMap = (m) => (matOf(m)?.map ? 1 : 0);
+ const vcount = (m) => m.geometry.attributes.position?.count || 0;
+ candidates.sort((a, b) => hasMap(b) - hasMap(a) || vcount(b) - vcount(a));
+ this.targetMesh = candidates[0];
+ this.targetMaterial = matOf(this.targetMesh);
+ }
+
+ _initCanvases() {
+ if (!this.maskCanvas) {
+ this.maskCanvas = document.createElement('canvas');
+ this.tintCanvas = document.createElement('canvas');
+ this.baseCanvas = document.createElement('canvas');
+ this.previewCanvas = document.createElement('canvas');
+ for (const c of [this.maskCanvas, this.tintCanvas, this.baseCanvas, this.previewCanvas]) {
+ c.width = c.height = TEX;
+ }
+ }
+ // Clear mask + redraw the base from the current target texture.
+ this.maskCanvas.getContext('2d').clearRect(0, 0, TEX, TEX);
+ this.tintCanvas.getContext('2d').clearRect(0, 0, TEX, TEX);
+ this.painted = false;
+ this._drawBase();
+ }
+
+ _drawBase() {
+ const ctx = this.baseCanvas.getContext('2d');
+ ctx.clearRect(0, 0, TEX, TEX);
+ const img = this._origMapImage();
+ if (img) {
+ try {
+ ctx.drawImage(img, 0, 0, TEX, TEX);
+ return;
+ } catch (e) {
+ log.warn('[magic-brush] base texture not drawable:', e?.message);
+ }
+ }
+ // No usable source texture — neutral base so the highlight still reads.
+ ctx.fillStyle = '#7a7a7a';
+ ctx.fillRect(0, 0, TEX, TEX);
+ }
+
+ _origMapImage() {
+ const map = this.targetMaterial?.map;
+ if (!map || !map.image) return null;
+ const im = map.image;
+ // Accept anything drawImage can consume.
+ if (im instanceof HTMLImageElement || im instanceof HTMLCanvasElement) return im;
+ if (typeof ImageBitmap !== 'undefined' && im instanceof ImageBitmap) return im;
+ if (im.data && im.width && im.height) return null; // raw/compressed — not drawable
+ return im.width && im.height ? im : null;
+ }
+
+ _installPreview() {
+ if (!this.targetMaterial) return;
+ if (this.previewTexture) return; // already installed
+ this._origMap = this.targetMaterial.map ?? null;
+ this.previewTexture = new CanvasTexture(this.previewCanvas);
+ this.previewTexture.flipY = this._origMap ? this._origMap.flipY : false;
+ this.previewTexture.colorSpace = this._origMap?.colorSpace || SRGBColorSpace;
+ if (this._origMap) {
+ this.previewTexture.wrapS = this._origMap.wrapS;
+ this.previewTexture.wrapT = this._origMap.wrapT;
+ this.previewTexture.channel = this._origMap.channel ?? 0;
+ }
+ this.targetMaterial.map = this.previewTexture;
+ this.targetMaterial.needsUpdate = true;
+ this._recompose();
+ }
+
+ _teardownPreview() {
+ if (this.previewTexture && this.targetMaterial) {
+ this.targetMaterial.map = this._origMap ?? null;
+ this.targetMaterial.needsUpdate = true;
+ this.viewer?.invalidate?.();
+ }
+ if (this.previewTexture) {
+ this.previewTexture.dispose();
+ this.previewTexture = null;
+ }
+ this._origMap = undefined;
+ }
+
+ // ── painting ─────────────────────────────────────────────────────────────────
+
+ _hitUV(e) {
+ const canvas = this.viewer?.renderer?.domElement;
+ if (!canvas || !this.targetMesh) return null;
+ const rect = canvas.getBoundingClientRect();
+ this._ndc.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
+ this._ndc.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
+ this.raycaster.setFromCamera(this._ndc, this.viewer.activeCamera);
+ const hits = this.raycaster.intersectObject(this.targetMesh, true);
+ for (const h of hits) {
+ if (h.uv) return { x: h.uv.x, y: h.uv.y };
+ }
+ return null;
+ }
+
+ _onPointerDown(e) {
+ if (!this.enabled || this.busy) return;
+ const uv = this._hitUV(e);
+ if (!uv) return; // missed the mesh → let OrbitControls handle the drag
+ // Hit the mesh: claim the gesture for painting and keep OrbitControls
+ // (whose listener is on the same element, bubble phase) from seeing it.
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation();
+ this._painting = true;
+ if (this.viewer?.controls) this.viewer.controls.enabled = false;
+ try {
+ e.target.setPointerCapture?.(e.pointerId);
+ } catch {
+ /* not capturable — fine */
+ }
+ window.addEventListener('pointermove', this._onPointerMove);
+ window.addEventListener('pointerup', this._onPointerUp);
+ this._lastUV = null;
+ this._stampUV(uv);
+ }
+
+ _onPointerMove(e) {
+ if (!this._painting) return;
+ const uv = this._hitUV(e);
+ if (!uv) return;
+ this._stampUV(uv);
+ }
+
+ _onPointerUp() {
+ this._endStroke();
+ }
+
+ _endStroke() {
+ if (!this._painting) {
+ if (this.viewer?.controls) this.viewer.controls.enabled = true;
+ return;
+ }
+ this._painting = false;
+ this._lastUV = null;
+ window.removeEventListener('pointermove', this._onPointerMove);
+ window.removeEventListener('pointerup', this._onPointerUp);
+ if (this.viewer?.controls) this.viewer.controls.enabled = true;
+ this._syncApplyEnabled();
+ }
+
+ _stampUV(uv) {
+ const x = uv.x * TEX;
+ const y = uv.y * TEX; // glTF: v 0 = top row, no flip
+ if (this._lastUV) {
+ const dx = uv.x - this._lastUV.x;
+ const dy = uv.y - this._lastUV.y;
+ const dist = Math.hypot(dx, dy);
+ // Interpolate within an island; skip the gap when a stroke jumps a UV seam.
+ if (dist < 0.15) {
+ const steps = Math.ceil((dist * TEX) / (this.brush * 0.5)) || 1;
+ for (let i = 1; i <= steps; i++) {
+ const t = i / steps;
+ this._stampPx((this._lastUV.x + dx * t) * TEX, (this._lastUV.y + dy * t) * TEX);
+ }
+ } else {
+ this._stampPx(x, y);
+ }
+ } else {
+ this._stampPx(x, y);
+ }
+ this._lastUV = uv;
+ this.painted = this.tool === 'paint' ? true : this.painted;
+ this._queueRecompose();
+ }
+
+ _stampPx(x, y) {
+ const ctx = this.maskCanvas.getContext('2d');
+ ctx.save();
+ if (this.tool === 'erase') {
+ ctx.globalCompositeOperation = 'destination-out';
+ ctx.fillStyle = 'rgba(0,0,0,1)';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.fillStyle = '#ffffff';
+ }
+ ctx.beginPath();
+ ctx.arc(x, y, this.brush, 0, Math.PI * 2);
+ ctx.fill();
+ // Texture wraps at the UV border — stamp the horizontal/vertical wrap so a
+ // brush over a seam paints both sides.
+ for (const ox of [-TEX, TEX]) {
+ if (x + this.brush > TEX || x - this.brush < 0) {
+ ctx.beginPath();
+ ctx.arc(x + ox, y, this.brush, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ }
+ ctx.restore();
+ }
+
+ _queueRecompose() {
+ if (this._recomposeQueued) return;
+ this._recomposeQueued = true;
+ requestAnimationFrame(() => {
+ this._recomposeQueued = false;
+ this._recompose();
+ });
+ }
+
+ _recompose() {
+ // Rebuild the tinted mask, then base + tint → preview texture.
+ const tctx = this.tintCanvas.getContext('2d');
+ tctx.clearRect(0, 0, TEX, TEX);
+ tctx.drawImage(this.maskCanvas, 0, 0);
+ tctx.globalCompositeOperation = 'source-in';
+ tctx.fillStyle = HIGHLIGHT;
+ tctx.fillRect(0, 0, TEX, TEX);
+ tctx.globalCompositeOperation = 'source-over';
+
+ const pctx = this.previewCanvas.getContext('2d');
+ pctx.clearRect(0, 0, TEX, TEX);
+ pctx.drawImage(this.baseCanvas, 0, 0);
+ pctx.globalAlpha = 0.55;
+ pctx.drawImage(this.tintCanvas, 0, 0);
+ pctx.globalAlpha = 1;
+
+ if (this.previewTexture) this.previewTexture.needsUpdate = true;
+ this.viewer?.invalidate?.();
+ }
+
+ _clearMask() {
+ this.maskCanvas.getContext('2d').clearRect(0, 0, TEX, TEX);
+ this.painted = false;
+ this._recompose();
+ this._syncApplyEnabled();
+ }
+
+ // ── apply / poll ──────────────────────────────────────────────────────────────
+
+ _currentMeshUrl() {
+ const u = this.session?.sourceURL;
+ if (typeof u !== 'string') return null;
+ if (!/^https:\/\//i.test(u)) return null; // blob:/file: can't be fetched server-side
+ return u;
+ }
+
+ _exportMaskB64() {
+ // Composite white-on-black (worker thresholds white = repaint).
+ const out = document.createElement('canvas');
+ out.width = out.height = TEX;
+ const ctx = out.getContext('2d');
+ ctx.fillStyle = '#000000';
+ ctx.fillRect(0, 0, TEX, TEX);
+ ctx.drawImage(this.maskCanvas, 0, 0);
+ const data = out.toDataURL('image/png');
+ return data.split(',')[1];
+ }
+
+ async _apply() {
+ if (this.busy) return;
+ if (!this.targetMesh) {
+ this._setStatus('err', 'Load a textured model first.');
+ return;
+ }
+ if (!this.painted) {
+ this._setStatus('err', 'Paint a region on the model first.');
+ return;
+ }
+ if (this.prompt.trim().length < 3 && !this.color) {
+ this._setStatus('err', 'Describe the change, or pick a colour.');
+ return;
+ }
+ const meshUrl = this._currentMeshUrl();
+ if (!meshUrl) {
+ this._setStatus(
+ 'err',
+ 'Magic Brush needs a model loaded from a URL. Open a saved model or paste a GLB link.',
+ );
+ return;
+ }
+
+ this.busy = true;
+ this._setStatus('busy', 'Submitting region edit…');
+
+ let token;
+ try {
+ const resp = await fetch('/api/studio/retexture-region', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ mesh_url: meshUrl,
+ prompt: this.prompt.trim(),
+ color: this.color || undefined,
+ mask_b64: this._exportMaskB64(),
+ texture_size: this.quality,
+ strength: this.strength,
+ }),
+ });
+ const body = await resp.json().catch(() => ({}));
+ if (!resp.ok) {
+ if (resp.status === 401) throw new Error('Sign in to use Magic Brush.');
+ if (resp.status === 501) {
+ throw new Error('Region retexture is not configured on this deployment yet.');
+ }
+ throw new Error(body.error_description || `Request failed (${resp.status})`);
+ }
+ token = body.job;
+ this.jobToken = token;
+ } catch (err) {
+ this.busy = false;
+ this._setStatus('err', err.message);
+ return;
+ }
+
+ this._setStatus('busy', 'Painting the region… this usually takes ~1 minute.');
+ this._poll(token);
+ }
+
+ _poll(token) {
+ this._stopPolling();
+ this._pollTimer = setInterval(async () => {
+ try {
+ const resp = await fetch(
+ `/api/studio/retexture-region?job=${encodeURIComponent(token)}`,
+ { credentials: 'include' },
+ );
+ const body = await resp.json().catch(() => ({}));
+ if (!resp.ok) throw new Error(body.error_description || `Status failed (${resp.status})`);
+
+ if (body.status === 'done' && body.result_url) {
+ this._stopPolling();
+ await this._loadResult(body.result_url);
+ } else if (body.status === 'failed') {
+ this._stopPolling();
+ this.busy = false;
+ this._setStatus('err', body.error || 'Region edit failed.');
+ }
+ // queued / running → keep waiting.
+ } catch (err) {
+ this._stopPolling();
+ this.busy = false;
+ this._setStatus('err', err.message);
+ }
+ }, POLL_MS);
+ }
+
+ _stopPolling() {
+ if (this._pollTimer) {
+ clearInterval(this._pollTimer);
+ this._pollTimer = null;
+ }
+ }
+
+ async _loadResult(url) {
+ this._setStatus('busy', 'Loading the updated model…');
+ // Restore the real material before swapping content so we don't leave the
+ // preview texture dangling, then reload + re-point the editor.
+ this._teardownPreview();
+ try {
+ await this.viewer.load(url, '', new Map());
+ const name = url.split('/').pop().split('?')[0] || 'model';
+ // Re-points session.sourceURL to the result so the NEXT pass chains on
+ // it, and rebuilds every editor panel (including this brush).
+ this.editor.onContentChanged({ url, name });
+ this.busy = false;
+ this._setStatus('ok', 'Region updated. Paint again to keep editing.');
+ } catch (err) {
+ this.busy = false;
+ this._setStatus('err', `Loaded edit but failed to display it: ${err.message}`);
+ }
+ }
+
+ // ── panel UI ──────────────────────────────────────────────────────────────────
+
+ _setStatus(kind, text) {
+ this.status = { kind, text };
+ this.render();
+ }
+
+ _syncApplyEnabled() {
+ const btn = this.panel?.querySelector('.mb-apply');
+ if (!btn) return;
+ const ready =
+ !!this.targetMesh &&
+ this.painted &&
+ (this.prompt.trim().length >= 3 || !!this.color) &&
+ !this.busy;
+ btn.disabled = !ready;
+ }
+
+ _mountPanel() {
+ if (this.panel) return;
+ const host = this.viewer?.el || document.body;
+ if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
+ this.panel = document.createElement('div');
+ this.panel.className = 'mb-panel';
+ host.appendChild(this.panel);
+ this.render();
+ requestAnimationFrame(() => this.panel?.classList.add('mb-open'));
+ }
+
+ _unmountPanel() {
+ if (!this.panel) return;
+ const p = this.panel;
+ this.panel = null;
+ p.classList.remove('mb-open');
+ setTimeout(() => p.remove(), 200);
+ }
+
+ render() {
+ if (!this.panel) return;
+ const open = this.panel.classList.contains('mb-open');
+ this.panel.innerHTML = '';
+ this.panel.className = `mb-panel${open ? ' mb-open' : ''}`;
+
+ const head = document.createElement('div');
+ head.className = 'mb-head';
+ head.innerHTML = `<span class="mb-dot"></span><h3>Magic Brush</h3>`;
+ const x = document.createElement('button');
+ x.className = 'mb-x';
+ x.setAttribute('aria-label', 'Close magic brush');
+ x.textContent = '✕';
+ x.addEventListener('click', () => this.disable());
+ head.appendChild(x);
+ this.panel.appendChild(head);
+
+ // Empty state: no paintable mesh.
+ if (!this.targetMesh) {
+ const empty = document.createElement('div');
+ empty.className = 'mb-empty';
+ empty.innerHTML = `<strong>No paintable surface</strong>
+ Load a model with a UV-mapped texture, then reopen Magic Brush to repaint part of it.`;
+ this.panel.appendChild(empty);
+ return;
+ }
+
+ const body = document.createElement('div');
+ body.className = 'mb-body';
+ this.panel.appendChild(body);
+
+ const hint = document.createElement('p');
+ hint.className = 'mb-hint';
+ hint.textContent =
+ 'Paint over the area to change, describe it, then Apply. Only that region is repainted.';
+ body.appendChild(hint);
+
+ // Tool segment: paint / erase.
+ const toolRow = document.createElement('div');
+ toolRow.className = 'mb-row';
+ toolRow.innerHTML = `<label>Tool</label>`;
+ const seg = document.createElement('div');
+ seg.className = 'mb-seg';
+ for (const t of ['paint', 'erase']) {
+ const b = document.createElement('button');
+ b.textContent = t === 'paint' ? '🖌 Paint' : '🩹 Erase';
+ b.setAttribute('aria-pressed', String(this.tool === t));
+ b.addEventListener('click', () => {
+ this.tool = t;
+ this.render();
+ });
+ seg.appendChild(b);
+ }
+ toolRow.appendChild(seg);
+ body.appendChild(toolRow);
+
+ // Brush size.
+ const sizeRow = document.createElement('div');
+ sizeRow.className = 'mb-row';
+ sizeRow.innerHTML = `<label>Brush size</label>`;
+ const slide = document.createElement('div');
+ slide.className = 'mb-slide';
+ const range = document.createElement('input');
+ range.type = 'range';
+ range.min = '8';
+ range.max = '220';
+ range.step = '2';
+ range.value = String(this.brush);
+ const val = document.createElement('span');
+ val.className = 'mb-val';
+ val.textContent = String(this.brush);
+ range.addEventListener('input', () => {
+ this.brush = Number(range.value);
+ val.textContent = range.value;
+ });
+ slide.append(range, val);
+ sizeRow.appendChild(slide);
+ body.appendChild(sizeRow);
+
+ // Prompt.
+ const promptRow = document.createElement('div');
+ promptRow.className = 'mb-row';
+ promptRow.innerHTML = `<label>Describe the change</label>`;
+ const ta = document.createElement('textarea');
+ ta.className = 'mb-ta';
+ ta.placeholder = 'e.g. weathered copper plate with green patina';
+ ta.value = this.prompt;
+ ta.addEventListener('input', () => {
+ this.prompt = ta.value;
+ this._syncApplyEnabled();
+ });
+ promptRow.appendChild(ta);
+ body.appendChild(promptRow);
+
+ // Colour (optional).
+ const colorRow = document.createElement('div');
+ colorRow.className = 'mb-row';
+ colorRow.innerHTML = `<label>Target colour (optional)</label>`;
+ const cwrap = document.createElement('div');
+ cwrap.className = 'mb-color';
+ const cinput = document.createElement('input');
+ cinput.type = 'color';
+ cinput.value = this.color || '#1e90ff';
+ const cstate = document.createElement('span');
+ cstate.style.flex = '1';
+ cstate.style.color = '#9a9aa5';
+ cstate.style.fontSize = '12px';
+ cstate.textContent = this.color ? this.color : 'not used';
+ cinput.addEventListener('input', () => {
+ this.color = cinput.value;
+ cstate.textContent = this.color;
+ this._syncApplyEnabled();
+ });
+ const cclear = document.createElement('button');
+ cclear.className = 'mb-swap';
+ cclear.type = 'button';
+ cclear.textContent = 'clear';
+ cclear.addEventListener('click', () => {
+ this.color = null;
+ this.render();
+ });
+ cwrap.append(cinput, cstate, cclear);
+ colorRow.appendChild(cwrap);
+ body.appendChild(colorRow);
+
+ // Status.
+ if (this.status) {
+ const s = document.createElement('div');
+ s.className = `mb-status is-${this.status.kind}`;
+ if (this.status.kind === 'busy') {
+ const sp = document.createElement('span');
+ sp.className = 'mb-spin';
+ s.appendChild(sp);
+ }
+ const t = document.createElement('span');
+ t.textContent = this.status.text;
+ s.appendChild(t);
+ body.appendChild(s);
+ }
+
+ // Actions.
+ const actions = document.createElement('div');
+ actions.className = 'mb-actions';
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'mb-btn mb-ghost';
+ clearBtn.textContent = 'Clear';
+ clearBtn.title = 'Clear the painted mask';
+ clearBtn.disabled = this.busy;
+ clearBtn.addEventListener('click', () => this._clearMask());
+ const applyBtn = document.createElement('button');
+ applyBtn.className = 'mb-btn mb-primary mb-apply';
+ applyBtn.textContent = this.busy ? 'Working…' : 'Apply';
+ applyBtn.addEventListener('click', () => this._apply());
+ actions.append(clearBtn, applyBtn);
+ body.appendChild(actions);
+
+ this._syncApplyEnabled();
+ }
+}
diff --git a/src/forge-optimize.js b/src/forge-optimize.js
new file mode 100644
index 000000000..6d2e78083
--- /dev/null
+++ b/src/forge-optimize.js
@@ -0,0 +1,398 @@
+// Topology optimizer layered onto the forge result viewer.
+//
+// When a model becomes available (forge.js dispatches `forge:model-ready`),
+// this panel lets the user produce game/animation-ready output from the live
+// GLB via the real /api/forge-remesh route:
+// • triangle — quadric (QEM) decimation, fast polygon reduction
+// • quad — field-aligned quad-dominant retopology (QuadriFlow): clean
+// edge loops that deform well for rigging & animation
+// • lowpoly — silhouette-preserving low-poly with the original texture
+// re-unwrapped + re-baked onto the new mesh
+//
+// GLB output renders inline (swaps the live <model-viewer> src); every other
+// format is download-only. Nothing fakes progress — the panel polls the job.
+//
+// The panel injects its own markup + styles so it survives independently of the
+// forge.html template: it only needs the result panel, viewer, and download
+// button to be present.
+
+const resultPanel = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+const download = document.getElementById('download');
+
+if (resultPanel && viewer) {
+ const OPT_POLL_MS = 2500;
+ const OPT_MAX_MS = 8 * 60 * 1000; // quad/lowpoly bakes can take a couple minutes
+
+ // Reuse the forge anonymous client id (set by forge.js) for rate-limit
+ // fairness; harmless if absent.
+ const CLIENT_HEADERS = (() => {
+ try {
+ const id = localStorage.getItem('forge:cid');
+ return id ? { 'x-forge-client': id } : {};
+ } catch {
+ return {};
+ }
+ })();
+
+ const MODE_HINTS = {
+ triangle:
+ 'Quadric (QEM) decimation. Fast, general-purpose polygon reduction — best for trimming size before download.',
+ quad:
+ 'Field-aligned quad-dominant retopology (QuadriFlow). Clean edge loops that deform well for rigging & animation. GLB triangulates for preview — pick OBJ for true quad faces.',
+ lowpoly:
+ 'Silhouette-preserving low-poly for real-time use. UVs are re-unwrapped and the original texture is re-baked onto the new mesh so it still renders correctly.',
+ };
+
+ const TARGETS = {
+ triangle: {
+ label: 'Target faces',
+ options: [
+ [5000, '5k'],
+ [10000, '10k'],
+ [20000, '20k'],
+ [50000, '50k'],
+ [100000, '100k'],
+ ],
+ default: 20000,
+ },
+ quad: {
+ label: 'Target quads',
+ options: [
+ [2500, '2.5k'],
+ [5000, '5k'],
+ [10000, '10k'],
+ [20000, '20k'],
+ [40000, '40k'],
+ ],
+ default: 10000,
+ },
+ lowpoly: {
+ label: 'Poly budget',
+ options: [
+ [1000, '1k — mobile'],
+ [5000, '5k — standard'],
+ [20000, '20k — hero'],
+ ],
+ default: 5000,
+ },
+ };
+
+ const FORMATS = [
+ ['glb', 'GLB (textured)'],
+ ['obj', 'OBJ (true quads)'],
+ ['fbx', 'FBX'],
+ ['stl', 'STL'],
+ ['ply', 'PLY'],
+ ['usdz', 'USDZ'],
+ ['3mf', '3MF'],
+ ];
+
+ // ── Styles ───────────────────────────────────────────────────────────────
+ if (!document.getElementById('forge-optimize-styles')) {
+ const style = document.createElement('style');
+ style.id = 'forge-optimize-styles';
+ style.textContent = `
+ .optimize { border-top: 1px solid var(--stroke); }
+ .optimize-toggle {
+ width: 100%; display: flex; align-items: center; justify-content: space-between;
+ gap: var(--space-sm); background: transparent; border: none; color: var(--ink);
+ font-family: var(--font-display); font-weight: 600; font-size: var(--text-sm);
+ padding: var(--space-sm) var(--space-md); cursor: pointer;
+ }
+ .optimize-toggle:hover { background: var(--surface-2); }
+ .optimize-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ .optimize-toggle .chev { transition: transform 0.18s ease; color: var(--ink-dim); }
+ .optimize[data-open='true'] .optimize-toggle .chev { transform: rotate(180deg); }
+ .optimize-body { display: none; flex-direction: column; gap: var(--space-md); padding: 0 var(--space-md) var(--space-md); }
+ .optimize[data-open='true'] .optimize-body { display: flex; }
+ .opt-field { display: flex; flex-direction: column; gap: 0.4rem; }
+ .opt-field > span {
+ font-size: var(--text-xs); color: var(--ink-dim); font-family: var(--font-mono);
+ text-transform: uppercase; letter-spacing: 0.04em;
+ }
+ .seg {
+ display: inline-flex; flex-wrap: wrap; gap: 2px; background: var(--surface-1);
+ border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: 2px;
+ }
+ .seg button {
+ flex: 1 1 auto; background: transparent; border: none; color: var(--ink-dim);
+ font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.4rem 0.7rem;
+ border-radius: var(--radius-sm); cursor: pointer; transition: background 0.15s, color 0.15s;
+ }
+ .seg button:hover { color: var(--ink); }
+ .seg button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .seg button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .opt-mode-hint { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; min-height: 1.4em; margin: 0; }
+ .opt-row { display: flex; gap: var(--space-md); flex-wrap: wrap; }
+ .opt-row .opt-field { flex: 1 1 140px; }
+ .opt-select {
+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md);
+ color: var(--ink); font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.45rem 0.6rem;
+ }
+ .opt-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .opt-actions { display: flex; align-items: center; gap: var(--space-md); flex-wrap: wrap; }
+ .opt-status { font-size: var(--text-xs); font-family: var(--font-mono); color: var(--ink-dim); }
+ .opt-status[data-kind='error'] { color: var(--danger); }
+ .opt-status[data-kind='done'] { color: var(--success); }
+ .opt-stats { display: flex; gap: var(--space-md); flex-wrap: wrap; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); }
+ .opt-stats strong { color: var(--ink); font-weight: 600; }
+ .opt-stats.is-hidden { display: none; }
+ `;
+ document.head.appendChild(style);
+ }
+
+ // ── DOM ────────────────────────────────────────────────────────────────────
+ const panel = document.createElement('div');
+ panel.className = 'optimize';
+ panel.dataset.open = 'false';
+ panel.innerHTML = `
+ <button class="optimize-toggle" type="button" aria-expanded="false">
+ <span>Optimize topology — quad remesh &amp; game-ready low-poly</span>
+ <svg class="chev" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
+ stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="6 9 12 15 18 9" />
+ </svg>
+ </button>
+ <div class="optimize-body">
+ <div class="opt-field">
+ <span>Mode</span>
+ <div class="seg opt-mode" role="group" aria-label="Remesh mode">
+ <button type="button" data-mode="triangle" aria-pressed="false">Triangle</button>
+ <button type="button" data-mode="quad" aria-pressed="true">Quad retopo</button>
+ <button type="button" data-mode="lowpoly" aria-pressed="false">Low-poly</button>
+ </div>
+ <p class="opt-mode-hint"></p>
+ </div>
+ <div class="opt-row">
+ <label class="opt-field">
+ <span class="opt-target-label">Target faces</span>
+ <select class="opt-select opt-target"></select>
+ </label>
+ <label class="opt-field">
+ <span>Format</span>
+ <select class="opt-select opt-format"></select>
+ </label>
+ <label class="opt-field opt-texsize-field">
+ <span>Texture</span>
+ <select class="opt-select opt-texsize">
+ <option value="512">512px</option>
+ <option value="1024" selected>1024px</option>
+ <option value="2048">2048px</option>
+ </select>
+ </label>
+ </div>
+ <div class="opt-actions">
+ <button class="btn opt-run" type="button"><span class="opt-run-label">Optimize</span></button>
+ <span class="opt-status" role="status" aria-live="polite"></span>
+ </div>
+ <div class="opt-stats is-hidden"></div>
+ </div>
+ `;
+ resultPanel.appendChild(panel);
+
+ const toggle = panel.querySelector('.optimize-toggle');
+ const modeGroup = panel.querySelector('.opt-mode');
+ const modeHint = panel.querySelector('.opt-mode-hint');
+ const targetSel = panel.querySelector('.opt-target');
+ const targetLabel = panel.querySelector('.opt-target-label');
+ const formatSel = panel.querySelector('.opt-format');
+ const texsizeField = panel.querySelector('.opt-texsize-field');
+ const texsizeSel = panel.querySelector('.opt-texsize');
+ const runBtn = panel.querySelector('.opt-run');
+ const runLabel = panel.querySelector('.opt-run-label');
+ const statusEl = panel.querySelector('.opt-status');
+ const stats = panel.querySelector('.opt-stats');
+
+ for (const [value, text] of FORMATS) {
+ const opt = document.createElement('option');
+ opt.value = value;
+ opt.textContent = text;
+ formatSel.appendChild(opt);
+ }
+
+ const state = {
+ glbUrl: null,
+ label: 'model',
+ mode: 'quad',
+ running: false,
+ pollAbort: false,
+ };
+
+ function setStatus(text, kind) {
+ statusEl.textContent = text || '';
+ if (kind) statusEl.dataset.kind = kind;
+ else statusEl.removeAttribute('data-kind');
+ }
+
+ function fillTargets(mode) {
+ const cfg = TARGETS[mode];
+ targetLabel.textContent = cfg.label;
+ targetSel.innerHTML = '';
+ for (const [value, text] of cfg.options) {
+ const opt = document.createElement('option');
+ opt.value = String(value);
+ opt.textContent = text;
+ if (value === cfg.default) opt.selected = true;
+ targetSel.appendChild(opt);
+ }
+ }
+
+ function applyMode(mode) {
+ state.mode = mode;
+ for (const b of modeGroup.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b.dataset.mode === mode));
+ }
+ modeHint.textContent = MODE_HINTS[mode];
+ fillTargets(mode);
+ // Texture re-bake only applies to quad/lowpoly.
+ texsizeField.classList.toggle('is-hidden', mode === 'triangle');
+ }
+
+ function reset(glbUrl, label) {
+ state.glbUrl = glbUrl;
+ state.label = label || 'model';
+ state.pollAbort = true; // cancel any in-flight poll for the previous model
+ setStatus('');
+ stats.classList.add('is-hidden');
+ stats.innerHTML = '';
+ // The source model is always the forged GLB — restore the default label
+ // in case a prior optimization repointed the download button.
+ if (download) download.textContent = 'Download GLB';
+ panel.dataset.open = 'false';
+ toggle.setAttribute('aria-expanded', 'false');
+ }
+
+ function setRunning(running) {
+ state.running = running;
+ runBtn.disabled = running;
+ runLabel.textContent = running ? 'Optimizing…' : 'Optimize';
+ }
+
+ function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+ }
+
+ async function startRemesh() {
+ const res = await fetch('/api/forge-remesh', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({
+ mesh_url: state.glbUrl,
+ remesh_mode: state.mode,
+ target_faces: Number(targetSel.value),
+ output_format: formatSel.value,
+ texture_size: Number(texsizeSel.value),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ throw new Error('Mesh optimization is not configured on this deployment yet.');
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ throw new Error(`Optimizer is busy. Try again in about ${secs}s.`);
+ }
+ if (!res.ok || !data.job_id) {
+ throw new Error(data.message || `Optimizer returned ${res.status}.`);
+ }
+ return data.job_id;
+ }
+
+ async function pollRemesh(jobId) {
+ const deadline = performance.now() + OPT_MAX_MS;
+ while (!state.pollAbort && performance.now() < deadline) {
+ await sleep(OPT_POLL_MS);
+ if (state.pollAbort) return null;
+ const res = await fetch(`/api/forge-remesh?job=${encodeURIComponent(jobId)}`, {
+ headers: CLIENT_HEADERS,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (data.status === 'done' && data.result_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Optimization failed.');
+ setStatus(data.status === 'running' ? 'Optimizing topology…' : 'Queued…');
+ }
+ if (state.pollAbort) return null;
+ throw new Error('Optimization timed out.');
+ }
+
+ function showStats(data, format) {
+ const parts = [];
+ if (typeof data.face_count === 'number') {
+ parts.push(
+ `<span><strong>${data.face_count.toLocaleString()}</strong> ${
+ state.mode === 'quad' ? 'quads' : 'faces'
+ }</span>`,
+ );
+ }
+ if (typeof data.quad_ratio === 'number' && data.quad_ratio > 0) {
+ parts.push(
+ `<span><strong>${Math.round(data.quad_ratio * 100)}%</strong> quad-dominant</span>`,
+ );
+ }
+ if (data.textured === true) parts.push('<span>texture re-baked ✓</span>');
+ parts.push(`<span>${format.toUpperCase()}</span>`);
+ stats.innerHTML = parts.join('');
+ stats.classList.remove('is-hidden');
+ }
+
+ function applyResult(data) {
+ const format = formatSel.value;
+ const result = data.result_url;
+ // GLB renders inline — swap the live viewer so the user sees the new
+ // topology immediately. Other formats are download-only.
+ if (format === 'glb') {
+ viewer.setAttribute('src', result);
+ state.glbUrl = result; // chain further optimizations from the new mesh
+ }
+ const safe =
+ state.label.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge';
+ if (download) {
+ download.href = result;
+ download.setAttribute('download', `${safe}-${state.mode}.${format}`);
+ download.textContent = `Download ${format.toUpperCase()}`;
+ }
+ showStats(data, format);
+ }
+
+ async function run() {
+ if (state.running || !state.glbUrl) return;
+ state.pollAbort = false;
+ setRunning(true);
+ setStatus('Starting…');
+ stats.classList.add('is-hidden');
+ try {
+ const jobId = await startRemesh();
+ const done = await pollRemesh(jobId);
+ if (!done) return; // superseded by a newer model / cancelled
+ applyResult(done);
+ setStatus('Done — optimized mesh ready to download.', 'done');
+ } catch (err) {
+ setStatus(err.message || 'Optimization failed.', 'error');
+ } finally {
+ setRunning(false);
+ }
+ }
+
+ // ── Wiring ───────────────────────────────────────────────────────────────
+ toggle.addEventListener('click', () => {
+ const open = panel.dataset.open === 'true';
+ panel.dataset.open = String(!open);
+ toggle.setAttribute('aria-expanded', String(!open));
+ });
+
+ modeGroup.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-mode]');
+ if (btn) applyMode(btn.dataset.mode);
+ });
+
+ runBtn.addEventListener('click', run);
+
+ // Pick up the live model whenever one is forged or loaded from the gallery.
+ document.addEventListener('forge:model-ready', (e) => {
+ const url = e.detail?.glbUrl;
+ if (url) reset(url, e.detail?.label);
+ });
+
+ applyMode('quad');
+}
diff --git a/src/forge-stylize.js b/src/forge-stylize.js
new file mode 100644
index 000000000..aad634461
--- /dev/null
+++ b/src/forge-stylize.js
@@ -0,0 +1,265 @@
+// Forge — Stylize panel (browser client).
+//
+// One-click geometric stylization layered onto the forge result viewer. When a
+// model becomes available (forge.js dispatches `forge:model-ready`), this panel
+// reveals a gallery of filters; clicking one runs a real geometry pass on
+// workers/stylize via /api/forge-stylize, polls to completion, and swaps the
+// live <model-viewer> to the stylized GLB. A density slider re-applies the
+// active filter; "Revert" restores the original. Nothing fakes progress — the
+// only timer is an honest elapsed counter.
+
+import { STYLIZE_FILTERS, STYLIZE_FILTER_BY_KEY } from './shared/stylize-filters.js';
+
+const POLL_INTERVAL_MS = 2000;
+const MAX_POLL_MS = 3 * 60 * 1000;
+
+const panel = document.getElementById('stylize-panel');
+const viewer = document.getElementById('viewer');
+if (panel && viewer) {
+ const gallery = document.getElementById('stylize-gallery');
+ const controls = document.getElementById('stylize-controls');
+ const slider = document.getElementById('stylize-res');
+ const resLabel = document.getElementById('stylize-res-label');
+ const resVal = document.getElementById('stylize-res-val');
+ const applyBtn = document.getElementById('stylize-apply');
+ const downloadBtn = document.getElementById('stylize-download');
+ const revertBtn = document.getElementById('stylize-revert');
+ const status = document.getElementById('stylize-status');
+
+ let originalGlbUrl = '';
+ let lastStylizedUrl = ''; // the GLB we swapped in; lets the src observer skip our own change
+ let baseLabel = '';
+ let activeKey = '';
+ let runToken = 0; // bumped on each apply/revert to abort stale polls
+ let elapsedTimer = null;
+ let unconfigured = false;
+
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+ function setStatus(text, kind = '') {
+ status.textContent = text || '';
+ status.dataset.kind = kind;
+ }
+
+ function stopElapsed() {
+ if (elapsedTimer) {
+ clearInterval(elapsedTimer);
+ elapsedTimer = null;
+ }
+ }
+
+ function startElapsed(label) {
+ stopElapsed();
+ const t0 = performance.now();
+ const tick = () => {
+ const s = Math.floor((performance.now() - t0) / 1000);
+ setStatus(`${label} — ${s}s`, 'busy');
+ };
+ tick();
+ elapsedTimer = setInterval(tick, 1000);
+ }
+
+ function setBusy(busy) {
+ for (const card of gallery.querySelectorAll('.stylize-card')) card.disabled = busy;
+ applyBtn.disabled = busy;
+ slider.disabled = busy;
+ revertBtn.disabled = busy;
+ panel.dataset.busy = busy ? 'true' : 'false';
+ }
+
+ // Build the filter gallery once. Cards are real buttons — keyboard reachable,
+ // with hover/active/focus states defined in the page stylesheet.
+ function buildGallery() {
+ gallery.innerHTML = '';
+ for (const f of STYLIZE_FILTERS) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'stylize-card';
+ card.dataset.style = f.key;
+ card.setAttribute('aria-pressed', 'false');
+ card.title = f.blurb;
+ card.innerHTML =
+ `<span class="stylize-thumb" aria-hidden="true">${f.icon}</span>` +
+ `<span class="stylize-name">${f.name}</span>` +
+ `<span class="stylize-blurb">${f.blurb}</span>`;
+ card.addEventListener('click', () => selectFilter(f.key, { apply: true }));
+ gallery.appendChild(card);
+ }
+ }
+
+ function markActive(key) {
+ activeKey = key;
+ for (const card of gallery.querySelectorAll('.stylize-card')) {
+ card.setAttribute('aria-pressed', String(card.dataset.style === key));
+ }
+ }
+
+ function syncSlider(key) {
+ const spec = STYLIZE_FILTER_BY_KEY[key].resolution;
+ slider.min = String(spec.min);
+ slider.max = String(spec.max);
+ slider.step = '1';
+ slider.value = String(spec.def);
+ resLabel.textContent = spec.label;
+ resVal.textContent = String(spec.def);
+ controls.classList.remove('is-hidden');
+ }
+
+ function selectFilter(key, { apply }) {
+ if (unconfigured || !STYLIZE_FILTER_BY_KEY[key]) return;
+ markActive(key);
+ syncSlider(key);
+ if (apply) runStylize(key, Number(slider.value));
+ }
+
+ async function startJob(meshUrl, style, resolution) {
+ const res = await fetch('/api/forge-stylize', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ mesh_url: meshUrl, style, resolution }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ const e = new Error(data.message || 'Stylization is not configured on this deployment.');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ throw new Error(`The stylizer is busy. Try again in about ${secs}s.`);
+ }
+ if (!res.ok || !data.job_id) {
+ throw new Error(data.message || `The stylizer returned ${res.status}.`);
+ }
+ return data;
+ }
+
+ async function pollUntilDone(jobId, token) {
+ const deadline = performance.now() + MAX_POLL_MS;
+ while (token === runToken && performance.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ if (token !== runToken) return null;
+ const res = await fetch(`/api/forge-stylize?job=${encodeURIComponent(jobId)}`);
+ const data = await res.json().catch(() => ({}));
+ if (data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (data.status === 'done' && data.result_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Stylization failed.');
+ }
+ if (token !== runToken) return null;
+ throw new Error('Stylization timed out. Try a lower resolution.');
+ }
+
+ async function runStylize(style, resolution) {
+ if (!originalGlbUrl) return;
+ const token = ++runToken;
+ const filter = STYLIZE_FILTER_BY_KEY[style];
+ setBusy(true);
+ startElapsed(`Stylizing — ${filter.name}`);
+ try {
+ const job = await startJob(originalGlbUrl, style, resolution);
+ const done = await pollUntilDone(job.job_id, token);
+ if (token !== runToken || !done) return; // superseded or reverted
+ stopElapsed();
+ lastStylizedUrl = done.result_url; // so the src observer ignores our own swap
+ viewer.setAttribute('src', done.result_url);
+ viewer.setAttribute('alt', `${baseLabel} — ${filter.name} stylization`);
+ downloadBtn.href = done.result_url;
+ downloadBtn.setAttribute(
+ 'download',
+ `${(baseLabel || 'forge').replace(/[^a-z0-9]+/gi, '-').slice(0, 40).replace(/^-|-$/g, '') || 'forge'}-${style}.glb`,
+ );
+ downloadBtn.hidden = false;
+ revertBtn.hidden = false;
+ const faces = Number(done.face_count) > 0 ? ` · ${Number(done.face_count).toLocaleString()} faces` : '';
+ setStatus(`${filter.name} applied${faces}. Adjust ${filter.resolution.label.toLowerCase()} and re-apply, or revert.`, 'done');
+ } catch (err) {
+ if (token !== runToken) return;
+ stopElapsed();
+ if (err.kind === 'unconfigured') {
+ unconfigured = true;
+ panel.dataset.state = 'unconfigured';
+ setStatus(
+ 'Stylization needs the stylize worker configured on this deployment (GCP_STYLIZE_URL). The filters above light up once it’s set.',
+ 'error',
+ );
+ // Permanently disable the gallery (nothing to apply) without leaving
+ // the thumbs in the busy spin state.
+ for (const card of gallery.querySelectorAll('.stylize-card')) card.disabled = true;
+ applyBtn.disabled = true;
+ slider.disabled = true;
+ panel.dataset.busy = 'false';
+ return;
+ }
+ setStatus(err.message || 'Stylization failed. Try another filter or a lower resolution.', 'error');
+ } finally {
+ if (token === runToken && !unconfigured) setBusy(false);
+ }
+ }
+
+ function revert() {
+ runToken++; // abort any in-flight poll
+ stopElapsed();
+ setBusy(false);
+ viewer.setAttribute('src', originalGlbUrl);
+ viewer.setAttribute('alt', baseLabel || '3D model');
+ downloadBtn.hidden = true;
+ revertBtn.hidden = true;
+ markActive('');
+ setStatus('Showing the original model.', '');
+ }
+
+ // A new source model became available (freshly forged or opened from the
+ // gallery): reset the panel to its idle gallery state for that mesh. Idempotent
+ // — re-firing with the current source is a no-op, so the event and the src
+ // observer below can both call it without double-resetting.
+ function onNewSource(glbUrl, label) {
+ if (!glbUrl || glbUrl === originalGlbUrl) return;
+ originalGlbUrl = glbUrl;
+ baseLabel = label || '';
+ runToken++; // abort polls tied to the previous model
+ stopElapsed();
+ controls.classList.add('is-hidden');
+ downloadBtn.hidden = true;
+ revertBtn.hidden = true;
+ markActive('');
+ setStatus(unconfigured ? '' : 'Pick a filter to restyle this model.', '');
+ if (!unconfigured) setBusy(false);
+ panel.hidden = false;
+ }
+
+ // Wiring -------------------------------------------------------------------
+ slider.addEventListener('input', () => {
+ resVal.textContent = slider.value;
+ });
+ applyBtn.addEventListener('click', () => {
+ if (activeKey) runStylize(activeKey, Number(slider.value));
+ });
+ revertBtn.addEventListener('click', revert);
+
+ // Primary signal: forge.js announces the model explicitly.
+ document.addEventListener('forge:model-ready', (e) => {
+ onNewSource(e.detail?.glbUrl, e.detail?.label);
+ });
+
+ // Resilient fallback: watch the live viewer's `src` directly so the panel
+ // reveals whenever a model loads, even if the explicit event isn't emitted.
+ // Our own stylize swaps (lastStylizedUrl) and reverts (== originalGlbUrl) are
+ // ignored so they don't get mistaken for a new source mesh.
+ const srcObserver = new MutationObserver(() => {
+ const url = viewer.getAttribute('src');
+ if (!url || url === originalGlbUrl || url === lastStylizedUrl) return;
+ onNewSource(url, document.getElementById('result-label')?.textContent?.trim() || '');
+ });
+ srcObserver.observe(viewer, { attributes: true, attributeFilter: ['src'] });
+
+ // Pick up a model that was already shown before this module finished loading.
+ if (viewer.getAttribute('src')) {
+ onNewSource(viewer.getAttribute('src'), document.getElementById('result-label')?.textContent?.trim() || '');
+ }
+
+ buildGallery();
+}
diff --git a/src/forge.js b/src/forge.js
index fae855cc4..725648174 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -1,17 +1,26 @@
-// Forge — text → 3D generator (browser client).
+// Forge — text / image / multi-view → 3D generator (browser client).
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
import { showSharePanel } from './shared/share.js';
ensureStateKitStyles();
//
-// Drives /api/forge: POST a prompt to start a job, then poll GET /api/forge?job
-// until it resolves to a GLB. State transitions are driven by real API
-// responses — the reference image appears the moment the text-to-image pass
-// returns, the "mesh" step lights up when the reconstruction job is actually
-// running, and the result panel shows the real downloadable GLB. The only timer
-// is the honest elapsed counter; nothing fakes progress.
+// Drives /api/forge. Two paths share one polling loop:
+// • Text → 3D — POST a prompt; FLUX paints a reference image, then TRELLIS
+// reconstructs the mesh.
+// • Image / multi-view → 3D — the user adds 1–4 photos of one object from
+// different angles. Each photo is uploaded straight to object storage via a
+// presigned URL (/api/forge-upload), then their public URLs are POSTed as
+// image_urls. With >1 view the backend fuses them (multi-view conditioning)
+// and reports how many views it used + which backend handled it.
+//
+// State transitions are driven by real API responses; the only timer is the
+// honest elapsed counter. Nothing fakes progress.
const POLL_INTERVAL_MS = 2500;
-const MAX_POLL_MS = 5 * 60 * 1000; // give the reconstruction a generous ceiling
+const MAX_POLL_MS = 5 * 60 * 1000; // generous ceiling for reconstruction
+const MAX_VIEWS = 4;
+const VIEW_LABELS = ['Front', 'Back', 'Left', 'Right'];
+const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
+const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
const els = {
form: document.getElementById('composer'),
@@ -21,6 +30,12 @@ const els = {
generateLabel: document.getElementById('generate-label'),
examples: document.getElementById('examples'),
stage: document.getElementById('stage'),
+ modeSwitch: document.getElementById('mode-switch'),
+ textPane: document.getElementById('text-pane'),
+ imagePane: document.getElementById('image-pane'),
+ viewsGrid: document.getElementById('views-grid'),
+ fileInput: document.getElementById('view-file-input'),
+ imagePrompt: document.getElementById('image-prompt'),
states: {
empty: document.getElementById('state-empty'),
generating: document.getElementById('state-generating'),
@@ -38,12 +53,14 @@ const els = {
cancel: document.getElementById('cancel'),
viewer: document.getElementById('viewer'),
resultLabel: document.getElementById('result-label'),
+ resultViews: document.getElementById('result-views'),
verdict: document.getElementById('verdict'),
download: document.getElementById('download'),
again: document.getElementById('again'),
retry: document.getElementById('retry'),
errorMessage: document.getElementById('error-message'),
forgeShareBtn: document.getElementById('forge-share-btn'),
+ segmentBtn: document.getElementById('forge-segment-btn'),
creations: document.getElementById('creations'),
creationsGrid: document.getElementById('creations-grid'),
creationsCount: document.getElementById('creations-count'),
@@ -52,9 +69,24 @@ const els = {
let aspectRatio = '1:1';
let elapsedTimer = null;
let pollAbort = false;
-let lastPrompt = '';
+let mode = 'text'; // 'text' | 'image'
+let lastJob = null; // { prompt, imageUrls } — for retry
let currentCreationId = null;
+// One entry per reference-view slot. `state` drives the slot's rendered region;
+// `url` is the durable public URL (what we send); `objectUrl` is the local
+// preview blob, revoked when the slot is cleared.
+const slots = VIEW_LABELS.map(() => ({
+ state: 'empty',
+ url: null,
+ objectUrl: null,
+ errorMsg: '',
+}));
+
+// File picker target: the slot index the picker was opened for, or null to fill
+// from the first free slot.
+let pickerTarget = null;
+
// Stable anonymous handle for this browser. /forge has no login, so durable
// creations + the gallery are scoped to this id (hashed server-side). Sent on
// every request via the x-forge-client header.
@@ -87,6 +119,11 @@ function setStep(step, state) {
if (els.steps[step]) els.steps[step].dataset.state = state;
}
+function setStepLabel(step, text) {
+ const node = els.steps[step]?.querySelector('span:last-child');
+ if (node) node.textContent = text;
+}
+
function startElapsed() {
const started = performance.now();
stopElapsed();
@@ -114,11 +151,277 @@ function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
-async function startJob(prompt) {
+// Mode switching --------------------------------------------------------------
+
+function setMode(next) {
+ if (next !== 'text' && next !== 'image') return;
+ mode = next;
+ els.textPane.classList.toggle('is-hidden', mode !== 'text');
+ els.imagePane.classList.toggle('is-hidden', mode !== 'image');
+ // Aspect ratio only shapes the synthesized reference image — irrelevant when
+ // the user supplies their own photos.
+ els.aspect.classList.toggle('is-hidden', mode !== 'text');
+ els.examples.classList.toggle('is-hidden', mode !== 'text');
+ for (const b of els.modeSwitch.querySelectorAll('button')) {
+ b.setAttribute('aria-selected', String(b.dataset.mode === mode));
+ }
+ if (mode === 'text') els.prompt.focus();
+}
+
+// View slots ------------------------------------------------------------------
+
+function buildSlots() {
+ els.viewsGrid.innerHTML = '';
+ slots.forEach((_, i) => {
+ const slot = document.createElement('div');
+ slot.className = 'view-slot';
+ slot.dataset.index = String(i);
+ slot.tabIndex = 0;
+ slot.setAttribute('role', 'button');
+
+ slot.innerHTML = `
+ <div class="vs-empty">
+ <span class="vs-icon" aria-hidden="true">+</span>
+ <span class="vs-label">${VIEW_LABELS[i]}</span>
+ </div>
+ <div class="vs-uploading">
+ <div class="shimmer" aria-hidden="true"></div>
+ <span>Uploading…</span>
+ </div>
+ <img class="vs-thumb" alt="" />
+ <span class="vs-badge">${VIEW_LABELS[i]}</span>
+ <button type="button" class="vs-remove" aria-label="Remove ${VIEW_LABELS[i]} view">×</button>
+ <div class="vs-error">
+ <span class="vs-error-msg">Upload failed</span>
+ <button type="button" class="vs-retry">Retry</button>
+ </div>`;
+
+ // Remove (stop click from also re-opening the picker).
+ slot.querySelector('.vs-remove').addEventListener('click', (e) => {
+ e.stopPropagation();
+ clearSlot(i);
+ });
+ // Retry re-opens the picker for this slot.
+ slot.querySelector('.vs-retry').addEventListener('click', (e) => {
+ e.stopPropagation();
+ openPicker(i);
+ });
+
+ // Click empty/error → browse for this slot.
+ slot.addEventListener('click', () => {
+ if (slots[i].state === 'empty' || slots[i].state === 'error') openPicker(i);
+ });
+ slot.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ if (slots[i].state === 'empty' || slots[i].state === 'error') openPicker(i);
+ }
+ });
+
+ // Drag to reorder (uploaded slots only).
+ slot.addEventListener('dragstart', (e) => {
+ if (slots[i].state !== 'uploaded') {
+ e.preventDefault();
+ return;
+ }
+ e.dataTransfer.setData('application/x-forge-slot', String(i));
+ e.dataTransfer.effectAllowed = 'move';
+ slot.classList.add('dragging');
+ });
+ slot.addEventListener('dragend', () => slot.classList.remove('dragging'));
+
+ // Drop target — accepts files OR a dragged thumbnail (reorder).
+ slot.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = e.dataTransfer.types.includes('application/x-forge-slot')
+ ? 'move'
+ : 'copy';
+ slot.classList.add('drop-target');
+ });
+ slot.addEventListener('dragleave', () => slot.classList.remove('drop-target'));
+ slot.addEventListener('drop', (e) => {
+ e.preventDefault();
+ slot.classList.remove('drop-target');
+ const from = e.dataTransfer.getData('application/x-forge-slot');
+ if (from !== '') {
+ swapSlots(Number(from), i);
+ } else if (e.dataTransfer.files?.length) {
+ handleFiles(i, e.dataTransfer.files);
+ }
+ });
+
+ els.viewsGrid.appendChild(slot);
+ renderSlot(i);
+ });
+}
+
+function slotEl(i) {
+ return els.viewsGrid.querySelector(`.view-slot[data-index="${i}"]`);
+}
+
+function renderSlot(i) {
+ const el = slotEl(i);
+ if (!el) return;
+ const s = slots[i];
+ el.dataset.state = s.state;
+ el.draggable = s.state === 'uploaded';
+
+ const img = el.querySelector('.vs-thumb');
+ if (s.objectUrl) {
+ img.src = s.objectUrl;
+ img.alt = `${VIEW_LABELS[i]} view`;
+ } else {
+ img.removeAttribute('src');
+ img.alt = '';
+ }
+ el.querySelector('.vs-error-msg').textContent = s.errorMsg || 'Upload failed';
+
+ const labels = {
+ empty: `${VIEW_LABELS[i]} view, empty — add a photo`,
+ uploading: `${VIEW_LABELS[i]} view, uploading`,
+ uploaded: `${VIEW_LABELS[i]} view, uploaded — drag to reorder`,
+ error: `${VIEW_LABELS[i]} view, upload failed`,
+ };
+ el.setAttribute('aria-label', labels[s.state] || VIEW_LABELS[i]);
+}
+
+function clearSlot(i) {
+ const s = slots[i];
+ if (s.objectUrl) URL.revokeObjectURL(s.objectUrl);
+ slots[i] = { state: 'empty', url: null, objectUrl: null, errorMsg: '' };
+ renderSlot(i);
+}
+
+function swapSlots(a, b) {
+ if (a === b) return;
+ const tmp = slots[a];
+ slots[a] = slots[b];
+ slots[b] = tmp;
+ renderSlot(a);
+ renderSlot(b);
+}
+
+function firstFreeSlot() {
+ return slots.findIndex((s) => s.state === 'empty' || s.state === 'error');
+}
+
+function nextFreeAfter(i) {
+ for (let j = i + 1; j < MAX_VIEWS; j++) {
+ if (slots[j].state === 'empty' || slots[j].state === 'error') return j;
+ }
+ return -1;
+}
+
+function openPicker(index) {
+ pickerTarget = index;
+ els.fileInput.value = '';
+ els.fileInput.click();
+}
+
+// Distribute dropped/picked files into slots, starting at `startIndex` (or the
+// first free slot when null), filling free slots up to MAX_VIEWS.
+function handleFiles(startIndex, fileList) {
+ const files = Array.from(fileList).filter((f) => f && f.type && f.type.startsWith('image/'));
+ if (!files.length) return;
+ let idx = startIndex == null ? firstFreeSlot() : startIndex;
+ for (const file of files) {
+ if (idx < 0 || idx >= MAX_VIEWS) idx = firstFreeSlot();
+ if (idx < 0) break; // all slots taken
+ uploadToSlot(idx, file);
+ idx = nextFreeAfter(idx);
+ }
+}
+
+// Upload one file into a slot: presign → PUT to object storage → record the
+// public URL. The slot moves empty/error → uploading → uploaded|error, each a
+// real, designed state. The local blob preview shows immediately.
+async function uploadToSlot(index, file) {
+ if (!ACCEPTED_TYPES.has(file.type)) {
+ setSlotError(index, 'Use PNG, JPG, or WebP.');
+ return;
+ }
+ if (file.size > MAX_UPLOAD_BYTES) {
+ setSlotError(index, 'Too large (max 8 MB).');
+ return;
+ }
+
+ const prev = slots[index];
+ if (prev.objectUrl) URL.revokeObjectURL(prev.objectUrl);
+ const objectUrl = URL.createObjectURL(file);
+ slots[index] = { state: 'uploading', url: null, objectUrl, errorMsg: '' };
+ renderSlot(index);
+
+ try {
+ const presignRes = await fetch('/api/forge-upload', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({ content_type: file.type, size_bytes: file.size }),
+ });
+ const presign = await presignRes.json().catch(() => ({}));
+ if (presignRes.status === 503) {
+ setSlotError(index, 'Uploads unavailable — paste a URL.');
+ return;
+ }
+ if (presignRes.status === 429) {
+ setSlotError(index, 'Rate limited — retry shortly.');
+ return;
+ }
+ if (!presignRes.ok || !presign.upload_url || !presign.public_url) {
+ setSlotError(index, presign.message || 'Upload failed.');
+ return;
+ }
+
+ const putRes = await fetch(presign.upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': file.type },
+ body: file,
+ });
+ if (!putRes.ok) {
+ setSlotError(index, `Storage rejected the file (${putRes.status}).`);
+ return;
+ }
+
+ // Success — keep the local blob preview, remember the public URL.
+ slots[index] = { state: 'uploaded', url: presign.public_url, objectUrl, errorMsg: '' };
+ renderSlot(index);
+ } catch {
+ setSlotError(index, 'Network error during upload.');
+ }
+}
+
+function setSlotError(index, message) {
+ const s = slots[index];
+ // Keep any local preview so the user sees what failed.
+ slots[index] = {
+ state: 'error',
+ url: null,
+ objectUrl: s.objectUrl || null,
+ errorMsg: message,
+ };
+ renderSlot(index);
+}
+
+function uploadedUrls() {
+ return slots.filter((s) => s.state === 'uploaded' && s.url).map((s) => s.url);
+}
+
+function firstPreviewUrl() {
+ const s = slots.find((x) => x.state === 'uploaded' && (x.objectUrl || x.url));
+ return s ? s.objectUrl || s.url : null;
+}
+
+// Job submission --------------------------------------------------------------
+
+async function startJob({ prompt, imageUrls }) {
+ const body =
+ Array.isArray(imageUrls) && imageUrls.length
+ ? { image_urls: imageUrls, prompt: prompt || undefined }
+ : { prompt, aspect_ratio: aspectRatio };
+
const res = await fetch('/api/forge', {
method: 'POST',
headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
- body: JSON.stringify({ prompt, aspect_ratio: aspectRatio }),
+ body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (res.status === 503 || data.error === 'unconfigured') {
@@ -159,11 +462,12 @@ async function pollUntilDone(jobId) {
if (data.status === 'running') setStep('mesh', 'active');
}
if (pollAbort) return null;
- throw new Error('Generation timed out. The model may be too complex — try a simpler prompt.');
+ throw new Error(
+ 'Generation timed out. The model may be too complex — try fewer views or a simpler prompt.',
+ );
}
// Post the human verdict on a creation — the labeled half of the data flywheel.
-// Fire-and-forget: a missing store or a network blip must never disrupt the UI.
function sendFeedback(payload) {
if (!currentCreationId) return;
fetch('/api/forge-feedback', {
@@ -181,34 +485,52 @@ function resetVerdict() {
}
}
-function showResult(glbUrl, prompt) {
+// Render the small "N views · backend" badge from job metadata.
+function setViewsBadge(meta) {
+ if (!els.resultViews) return;
+ const used = Number(meta?.views_used);
+ if (!Number.isFinite(used) || used < 1) {
+ els.resultViews.classList.add('is-hidden');
+ els.resultViews.textContent = '';
+ return;
+ }
+ const parts = [`${used} ${used === 1 ? 'view' : 'views'}`];
+ if (meta.multiview) parts.push('multi-view');
+ if (meta.backend) parts.push(meta.backend);
+ els.resultViews.textContent = parts.join(' · ');
+ els.resultViews.classList.remove('is-hidden');
+}
+
+function showResult(glbUrl, label, meta) {
stopElapsed();
resetVerdict();
els.viewer.setAttribute('src', glbUrl);
- els.viewer.setAttribute('alt', `3D model: ${prompt}`);
- els.resultLabel.textContent = prompt;
+ els.viewer.setAttribute('alt', `3D model: ${label}`);
+ els.resultLabel.textContent = label;
+ setViewsBadge(meta);
els.download.href = glbUrl;
els.download.setAttribute(
'download',
- `${prompt.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge'}.glb`,
+ `${label.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge'}.glb`,
);
+ // Cross-link into Parts Studio with this exact model pre-loaded.
+ if (els.segmentBtn) els.segmentBtn.href = `/segment?mesh=${encodeURIComponent(glbUrl)}`;
showState('result');
- // Surface adjacent features now that a model exists (embed it / drop it in a
- // world). The site-wide discovery layer (public/feature-discovery.js) renders
- // the contextual cross-link card; this just announces the moment.
+ // Hand the live model to the Stylize panel (src/forge-stylize.js) so its
+ // one-click geometric filters operate on the current source mesh.
+ document.dispatchEvent(
+ new CustomEvent('forge:model-ready', { detail: { glbUrl, label } }),
+ );
document.dispatchEvent(new CustomEvent('tws:feature-done', { detail: { feature: 'forge' } }));
- // Update share button label with creation context (non-blocking).
if (els.forgeShareBtn) {
- els.forgeShareBtn.dataset.sharePrompt = prompt;
+ els.forgeShareBtn.dataset.sharePrompt = label;
}
}
-// Load (or reload) the "Your creations" strip from durable storage. Hidden
-// entirely when persistence is off or the client has no creations yet.
+// Load (or reload) the "Your creations" strip from durable storage.
async function loadGallery() {
if (!els.creations) return;
- // Show skeleton while the real fetch is in flight.
els.creations.classList.remove('is-hidden');
els.creationsGrid.setAttribute('aria-busy', 'true');
els.creationsGrid.innerHTML = skeletonHTML(4, 'card');
@@ -218,7 +540,6 @@ async function loadGallery() {
const res = await fetch('/api/forge-gallery?limit=24', { headers: CLIENT_HEADERS });
data = await res.json().catch(() => ({}));
} catch {
- // On network error, show error state with a retry that reloads the gallery.
els.creationsGrid.removeAttribute('aria-busy');
els.creationsGrid.innerHTML = errorStateHTML({
title: "Couldn't load your creations",
@@ -265,6 +586,18 @@ async function loadGallery() {
card.appendChild(badge);
}
+ // Surface multi-view provenance so the gallery reflects how each model
+ // was conditioned.
+ if (Number(c.views_used) > 1) {
+ const mv = document.createElement('span');
+ mv.className = 'badge';
+ mv.style.left = '6px';
+ mv.style.right = 'auto';
+ mv.textContent = `${c.views_used}×`;
+ mv.title = `${c.views_used} reference views`;
+ card.appendChild(mv);
+ }
+
const meta = document.createElement('span');
meta.className = 'meta';
meta.textContent = c.prompt || 'Untitled';
@@ -272,9 +605,12 @@ async function loadGallery() {
card.addEventListener('click', () => {
currentCreationId = c.id;
- lastPrompt = c.prompt || '';
- showResult(c.glb_url, c.prompt || 'Forged model');
- // Reflect any verdict already on record.
+ lastJob = { prompt: c.prompt || '', imageUrls: [] };
+ showResult(c.glb_url, c.prompt || 'Forged model', {
+ views_used: c.views_used,
+ multiview: c.multiview,
+ backend: c.backend,
+ });
if (els.verdict) {
for (const b of els.verdict.querySelectorAll('button')) {
b.setAttribute('aria-pressed', String(b.dataset.outcome === c.outcome));
@@ -295,26 +631,47 @@ function showError(message) {
showState('error');
}
-async function run(prompt) {
- lastPrompt = prompt;
+// Run a job (text or image/multi-view). `cfg` = { prompt, imageUrls }.
+async function run(cfg) {
+ lastJob = cfg;
pollAbort = false;
currentCreationId = null;
setBusy(true);
- // Reset generating UI to its initial real state.
- els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';
- setStep('image', 'active');
- setStep('mesh', 'pending');
+ const isImage = Array.isArray(cfg.imageUrls) && cfg.imageUrls.length > 0;
+
+ // Reset the generating panel to its real starting state for this mode.
+ if (isImage) {
+ const n = cfg.imageUrls.length;
+ setStepLabel('image', `Conditioning on ${n} ${n === 1 ? 'view' : 'views'}`);
+ setStep('image', 'done');
+ setStep('mesh', 'active');
+ const preview = firstPreviewUrl();
+ els.genPreview.innerHTML = preview ? '' : '<div class="shimmer" aria-hidden="true"></div>';
+ if (preview) {
+ const img = new Image();
+ img.alt = 'Reference view';
+ img.src = preview;
+ els.genPreview.appendChild(img);
+ }
+ } else {
+ setStepLabel('image', 'Painting reference image');
+ els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';
+ setStep('image', 'active');
+ setStep('mesh', 'pending');
+ }
setStep('finish', 'pending');
startElapsed();
showState('generating');
+ const label = cfg.prompt || (isImage ? 'Multi-view reconstruction' : '');
+
try {
- const job = await startJob(prompt);
+ const job = await startJob(cfg);
if (job.creation_id) currentCreationId = job.creation_id;
- // Text-to-image really resolved before the POST returned: show it.
- if (job.preview_image_url) {
+ // Text→3D: the reference image resolved before the POST returned — show it.
+ if (!isImage && job.preview_image_url) {
setStep('image', 'done');
setStep('mesh', 'active');
const img = new Image();
@@ -329,11 +686,15 @@ async function run(prompt) {
const done = await pollUntilDone(job.job_id);
if (pollAbort || !done) return; // cancelled
- // Prefer the durable creation id resolved at completion time.
if (done.creation_id) currentCreationId = done.creation_id;
setStep('mesh', 'done');
setStep('finish', 'done');
- showResult(done.glb_url, prompt);
+ // Prefer the poll's recorded meta; fall back to the submit response.
+ showResult(done.glb_url, label || 'Forged model', {
+ views_used: done.views_used ?? job.views_used,
+ multiview: done.multiview ?? job.multiview,
+ backend: done.backend ?? job.backend,
+ });
loadGallery();
} catch (err) {
if (pollAbort) return;
@@ -342,35 +703,74 @@ async function run(prompt) {
showState('unconfigured');
return;
}
- showError(err.message || 'Something went wrong. Try a simpler, single-subject prompt.');
+ showError(
+ err.message ||
+ 'Something went wrong. Try a simpler, single-subject prompt or cleaner photos.',
+ );
} finally {
setBusy(false);
}
}
function submit() {
- const prompt = els.prompt.value.trim();
- if (prompt.length < 3) {
- els.prompt.focus();
+ if (mode === 'text') {
+ const prompt = els.prompt.value.trim();
+ if (prompt.length < 3) {
+ els.prompt.focus();
+ return;
+ }
+ run({ prompt, imageUrls: [] });
+ return;
+ }
+
+ // Image / multi-view mode.
+ if (slots.some((s) => s.state === 'uploading')) {
+ els.generateLabel.textContent = 'Waiting for uploads…';
+ setTimeout(() => {
+ if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';
+ }, 1600);
return;
}
- run(prompt);
+ const urls = uploadedUrls();
+ if (urls.length === 0) {
+ const first = slotEl(0);
+ first?.focus();
+ first?.classList.add('drop-target');
+ setTimeout(() => first?.classList.remove('drop-target'), 600);
+ return;
+ }
+ run({ prompt: els.imagePrompt.value.trim(), imageUrls: urls });
}
// Wiring ----------------------------------------------------------------------
+buildSlots();
+
+els.modeSwitch.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-mode]');
+ if (btn) setMode(btn.dataset.mode);
+});
+
+els.fileInput.addEventListener('change', () => {
+ handleFiles(pickerTarget, els.fileInput.files);
+ pickerTarget = null;
+ els.fileInput.value = '';
+});
+
els.form.addEventListener('submit', (e) => {
e.preventDefault();
submit();
});
-// Cmd/Ctrl+Enter submits from the textarea.
-els.prompt.addEventListener('keydown', (e) => {
+// Cmd/Ctrl+Enter submits from either text box.
+function submitOnModifierEnter(e) {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault();
submit();
}
-});
+}
+els.prompt.addEventListener('keydown', submitOnModifierEnter);
+els.imagePrompt.addEventListener('keydown', submitOnModifierEnter);
els.aspect.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-aspect]');
@@ -384,6 +784,7 @@ els.aspect.addEventListener('click', (e) => {
els.examples.addEventListener('click', (e) => {
const chip = e.target.closest('.chip');
if (!chip) return;
+ setMode('text');
els.prompt.value = chip.textContent.trim();
els.prompt.focus();
submit();
@@ -397,22 +798,24 @@ els.cancel.addEventListener('click', () => {
});
els.again.addEventListener('click', () => {
- els.prompt.focus();
- els.prompt.select();
showState('empty');
+ if (mode === 'text') {
+ els.prompt.focus();
+ els.prompt.select();
+ } else {
+ slotEl(0)?.focus();
+ }
});
els.retry.addEventListener('click', () => {
- if (lastPrompt) run(lastPrompt);
- else {
+ if (lastJob && (lastJob.prompt || (lastJob.imageUrls && lastJob.imageUrls.length))) {
+ run(lastJob);
+ } else {
showState('empty');
els.prompt.focus();
}
});
-// Keep / discard — the explicit training signal. Toggling re-records so a
-// mistaken click is correctable; the verdict is scoped server-side to the
-// creation this browser made.
if (els.verdict) {
els.verdict.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-outcome]');
@@ -425,21 +828,16 @@ if (els.verdict) {
});
}
-// A download is an implicit positive signal — capture it alongside the keep/
-// discard verdict without requiring a second click.
els.download.addEventListener('click', () => {
sendFeedback({ downloaded: true });
});
-// Share button — open share panel with copy-link, X, Farcaster, and remix CTA.
if (els.forgeShareBtn) {
els.forgeShareBtn.addEventListener('click', () => {
const origin = location.origin;
- const prompt = els.forgeShareBtn.dataset.sharePrompt || lastPrompt || '';
+ const prompt = els.forgeShareBtn.dataset.sharePrompt || lastJob?.prompt || '';
const id = currentCreationId;
- const shareUrl = id
- ? `${origin}/forge/share/${id}`
- : `${origin}/forge`;
+ const shareUrl = id ? `${origin}/forge/share/${id}` : `${origin}/forge`;
const remixUrl = prompt
? `${origin}/forge?prompt=${encodeURIComponent(prompt)}`
: `${origin}/forge`;
@@ -448,7 +846,7 @@ if (els.forgeShareBtn) {
kind: 'forge',
id: id || '',
title: prompt || 'Forged creation',
- description: 'A 3D model generated with text → 3D on three.ws',
+ description: 'A 3D model generated with text / image → 3D on three.ws',
shareUrl,
remixUrl,
},
@@ -457,22 +855,17 @@ if (els.forgeShareBtn) {
});
}
-// Handle ?prompt= (pre-fill the prompt box from a remix link)
-// and ?share= (load a shared creation from the gallery).
+// Handle ?prompt= (pre-fill from a remix link) and ?share= (open a creation).
(function handleQueryParams() {
const params = new URLSearchParams(location.search);
const promptParam = params.get('prompt');
const shareParam = params.get('share');
if (promptParam && els.prompt) {
+ setMode('text');
els.prompt.value = decodeURIComponent(promptParam).slice(0, 300);
els.prompt.focus();
}
if (shareParam) {
- // Attempt to load the shared creation once the gallery fetch completes.
- // We hook into the gallery load so the creation card is available.
- const origLoadGallery = loadGallery;
- // Override load to highlight the shared creation after gallery loads.
- // This is a one-shot intercept via a flag.
window.__forgeShareId = shareParam;
}
})();
@@ -481,7 +874,6 @@ if (els.forgeShareBtn) {
loadGallery().then(() => {
const shareId = window.__forgeShareId;
if (!shareId) return;
- // Find the creation card in the grid and trigger it.
const card = els.creationsGrid?.querySelector(`[data-creation-id="${shareId}"]`);
if (card) {
card.click();
diff --git a/src/pose-studio.js b/src/pose-studio.js
index d3eaec36c..4d36673ae 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -68,7 +68,8 @@ const el = (tag, attrs = {}, children = []) => {
for (const [k, v] of Object.entries(attrs)) {
if (k === 'class') node.className = v;
else if (k === 'text') node.textContent = v;
- else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
+ else if (k.startsWith('on') && typeof v === 'function')
+ node.addEventListener(k.slice(2), v);
else if (v !== false && v != null) node.setAttribute(k, v);
}
for (const child of children) {
@@ -92,7 +93,12 @@ const FLOOR_PROPS = {
seat.receiveShadow = true;
g.add(seat);
const legGeom = new BoxGeometry(0.05, 0.45, 0.05);
- for (const [x, z] of [[+0.19, +0.19], [+0.19, -0.19], [-0.19, +0.19], [-0.19, -0.19]]) {
+ for (const [x, z] of [
+ [+0.19, +0.19],
+ [+0.19, -0.19],
+ [-0.19, +0.19],
+ [-0.19, -0.19],
+ ]) {
const leg = new Mesh(legGeom, wood);
leg.position.set(x, 0.225, z);
leg.castShadow = true;
@@ -121,7 +127,7 @@ const FLOOR_PROPS = {
post.position.y = 0.21;
post.castShadow = true;
g.add(post);
- const base = new Mesh(new CylinderGeometry(0.18, 0.20, 0.03, 24), mat);
+ const base = new Mesh(new CylinderGeometry(0.18, 0.2, 0.03, 24), mat);
base.position.y = 0.015;
base.receiveShadow = true;
g.add(base);
@@ -171,7 +177,12 @@ const FLOOR_PROPS = {
// Shared IK target-handle assets (cloned per handle for per-instance opacity).
const handleGeom = new SphereGeometry(0.045, 16, 12);
-const handleMat = new MeshBasicMaterial({ color: '#22d3ee', transparent: true, opacity: 0.9, depthTest: false });
+const handleMat = new MeshBasicMaterial({
+ color: '#22d3ee',
+ transparent: true,
+ opacity: 0.9,
+ depthTest: false,
+});
// ─── Scene setup ────────────────────────────────────────────────────────
function setupScene(canvas, hudStatus) {
@@ -268,15 +279,27 @@ function setupScene(canvas, hudStatus) {
hudStatus.dataset.kind = kind;
}
- return { scene, camera, renderer, controls, gizmo, key, hemi, ambient, propLayer, ikLayer, setStatus };
+ return {
+ scene,
+ camera,
+ renderer,
+ controls,
+ gizmo,
+ key,
+ hemi,
+ ambient,
+ propLayer,
+ ikLayer,
+ setStatus,
+ };
}
// ─── State ──────────────────────────────────────────────────────────────
const state = {
- rig: null, // current Rig (MannequinRig | GltfRig)
- selectedBone: null, // canonical bone key
- poseMode: 'fk', // 'fk' (gizmo + sliders) | 'ik' (drag end-effectors)
- avatar: null, // { id, name } when a GLB is loaded, else null
+ rig: null, // current Rig (MannequinRig | GltfRig)
+ selectedBone: null, // canonical bone key
+ poseMode: 'fk', // 'fk' (gizmo + sliders) | 'ik' (drag end-effectors)
+ avatar: null, // { id, name } when a GLB is loaded, else null
loadingAvatar: false,
prop: 'none',
propGroup: null,
@@ -285,26 +308,45 @@ const state = {
keyElevation: 0.95,
keyDistance: 5.8,
ikHandles: new Map(), // effectorKey → Mesh
- draggingIK: null, // { effectorKey, plane }
- anim: null, // timeline controller handle (set on boot)
+ draggingIK: null, // { effectorKey, plane }
+ anim: null, // timeline controller handle (set on boot)
+ animLibrary: null, // AnimationLibrary (preset gallery) handle (set on boot)
};
// Studio handle exposed for later tasks (save/library/monetize) to share the
// rig, scene, and the current animation document without re-importing internals.
export const studio = {
- get rig() { return state.rig; },
- get scene() { return state.ctx?.scene || null; },
- get camera() { return state.ctx?.camera || null; },
- get renderer() { return state.ctx?.renderer || null; },
- get avatar() { return state.avatar; },
+ get rig() {
+ return state.rig;
+ },
+ get scene() {
+ return state.ctx?.scene || null;
+ },
+ get camera() {
+ return state.ctx?.camera || null;
+ },
+ get renderer() {
+ return state.ctx?.renderer || null;
+ },
+ get avatar() {
+ return state.avatar;
+ },
// ── Animation handoff API (Task 4/5/6) ───────────────────────────────────
- get document() { return state.anim?.doc || null; },
+ get document() {
+ return state.anim?.doc || null;
+ },
/** Bake the current document to a THREE.AnimationClip (canonical bone names). */
- bake() { return state.anim ? state.anim.bake() : null; },
+ bake() {
+ return state.anim ? state.anim.bake() : null;
+ },
/** The documented clip-JSON ({ name, duration, tracks }). */
- serializeClip() { return state.anim ? state.anim.serialize() : null; },
+ serializeClip() {
+ return state.anim ? state.anim.serialize() : null;
+ },
/** PNG data URL of the current viewport (reuses the screenshot pipeline). */
- captureThumbnail() { return state.anim ? state.anim.captureThumbnail() : null; },
+ captureThumbnail() {
+ return state.anim ? state.anim.captureThumbnail() : null;
+ },
};
// ─── App boot ───────────────────────────────────────────────────────────
@@ -433,7 +475,10 @@ function boot() {
const sx = (_v.x * 0.5 + 0.5) * rect.width;
const sy = (-_v.y * 0.5 + 0.5) * rect.height;
const d = Math.hypot(sx - px, sy - py);
- if (d < bestDist) { bestDist = d; best = key; }
+ if (d < bestDist) {
+ bestDist = d;
+ best = key;
+ }
}
return bestDist < 80 ? best : null;
}
@@ -469,7 +514,9 @@ function boot() {
function endIKDrag(ev) {
if (!state.draggingIK) return;
- try { canvas.releasePointerCapture(ev.pointerId); } catch {}
+ try {
+ canvas.releasePointerCapture(ev.pointerId);
+ } catch {}
state.draggingIK = null;
controls.enabled = true;
syncIKHandles();
@@ -590,7 +637,11 @@ function boot() {
return;
}
const rot = state.rig.getBoneEuler(key);
- const AXES = [['x', 'Bend / Pitch'], ['y', 'Twist / Yaw'], ['z', 'Tilt / Roll']];
+ const AXES = [
+ ['x', 'Bend / Pitch'],
+ ['y', 'Twist / Yaw'],
+ ['z', 'Tilt / Roll'],
+ ];
for (const [axis, label] of AXES) {
const value = rot[axis];
const row = el('div', { class: 'pose-slider-row' }, [
@@ -619,7 +670,9 @@ function boot() {
row.appendChild(slider);
sliderHost.appendChild(row);
}
- const resetBtn = el('button', { class: 'pose-btn pose-btn-ghost', type: 'button' }, ['Reset this bone']);
+ const resetBtn = el('button', { class: 'pose-btn pose-btn-ghost', type: 'button' }, [
+ 'Reset this bone',
+ ]);
resetBtn.addEventListener('click', () => {
state.rig.setBoneEuler(key, { x: 0, y: 0, z: 0 });
renderControlsPanel();
@@ -632,20 +685,30 @@ function boot() {
if (!boneListHost) return;
const q = (boneSearch?.value || '').trim().toLowerCase();
boneListHost.innerHTML = '';
- const bones = state.rig.getBones().filter(({ key, label }) =>
- !q || key.toLowerCase().includes(q) || label.toLowerCase().includes(q));
+ const bones = state.rig
+ .getBones()
+ .filter(
+ ({ key, label }) =>
+ !q || key.toLowerCase().includes(q) || label.toLowerCase().includes(q),
+ );
if (!bones.length) {
- boneListHost.appendChild(el('p', { class: 'pose-hint' }, ['No bones match your search.']));
+ boneListHost.appendChild(
+ el('p', { class: 'pose-hint' }, ['No bones match your search.']),
+ );
return;
}
const row = el('div', { class: 'pose-joint-row' }, []);
for (const { key, label } of bones) {
- const btn = el('button', {
- class: 'pose-joint-btn',
- type: 'button',
- 'data-bone': key,
- 'aria-pressed': String(state.selectedBone === key),
- }, [label]);
+ const btn = el(
+ 'button',
+ {
+ class: 'pose-joint-btn',
+ type: 'button',
+ 'data-bone': key,
+ 'aria-pressed': String(state.selectedBone === key),
+ },
+ [label],
+ );
btn.addEventListener('click', () => selectBone(key));
row.appendChild(btn);
}
@@ -662,7 +725,11 @@ function boot() {
presetHost.appendChild(el('div', { class: 'pose-preset-group' }, [groupName]));
const wrap = el('div', { class: 'pose-preset-grid' }, []);
for (const preset of presets) {
- const btn = el('button', { class: 'pose-preset-btn', type: 'button', 'data-preset': preset.id }, [preset.label]);
+ const btn = el(
+ 'button',
+ { class: 'pose-preset-btn', type: 'button', 'data-preset': preset.id },
+ [preset.label],
+ );
btn.addEventListener('click', () => {
state.rig.applyPose(poseFromMannequinPreset(preset.pose));
if (state.poseMode === 'fk') attachGizmo();
@@ -712,7 +779,9 @@ function boot() {
const scn = gltf.scene || gltf.scenes?.[0];
const rig = scn && makeGltfRig(scn);
if (!rig) {
- throw new Error('That model has no recognizable humanoid skeleton — pick a rigged avatar.');
+ throw new Error(
+ 'That model has no recognizable humanoid skeleton — pick a rigged avatar.',
+ );
}
mountRig(rig);
state.avatar = { id: meta.id || null, name: meta.name || 'Avatar', model_url: modelUrl };
@@ -723,8 +792,11 @@ function boot() {
async function loadAvatarById(id) {
setStatus('Resolving avatar…');
- const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });
- if (!res.ok) throw new Error(`Couldn't load avatar (${res.status}). It may be private or removed.`);
+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, {
+ credentials: 'include',
+ });
+ if (!res.ok)
+ throw new Error(`Couldn't load avatar (${res.status}). It may be private or removed.`);
const { avatar } = await res.json();
const url = avatar?.model_url || avatar?.url;
if (!url) throw new Error('That avatar has no downloadable model.');
@@ -859,16 +931,24 @@ function boot() {
$('#pose-constraints')?.addEventListener('change', (ev) => {
if (state.rig.kind !== 'mannequin') return;
state.rig.setConstraintsEnabled(ev.target.checked);
- setStatus(ev.target.checked ? 'Biological constraints on.' : 'Constraints off — full rotation allowed.');
+ setStatus(
+ ev.target.checked
+ ? 'Biological constraints on.'
+ : 'Constraints off — full rotation allowed.',
+ );
});
- $('#pose-bg')?.addEventListener('input', (ev) => { scene.background = new Color(ev.target.value); });
+ $('#pose-bg')?.addEventListener('input', (ev) => {
+ scene.background = new Color(ev.target.value);
+ });
$('#pose-fov')?.addEventListener('input', (ev) => {
camera.fov = parseFloat(ev.target.value);
camera.updateProjectionMatrix();
});
$('#pose-grid')?.addEventListener('change', (ev) => {
- scene.traverse((o) => { if (o.isGridHelper) o.visible = ev.target.checked; });
+ scene.traverse((o) => {
+ if (o.isGridHelper) o.visible = ev.target.checked;
+ });
});
function syncKeyLight() {
@@ -881,20 +961,43 @@ function boot() {
state.keyLight.target.updateMatrixWorld();
}
syncKeyLight();
- $('#pose-light-azimuth')?.addEventListener('input', (ev) => { state.keyAzimuth = (parseFloat(ev.target.value) / 180) * Math.PI; syncKeyLight(); });
- $('#pose-light-elevation')?.addEventListener('input', (ev) => { state.keyElevation = (parseFloat(ev.target.value) / 180) * Math.PI; syncKeyLight(); });
- $('#pose-light-intensity')?.addEventListener('input', (ev) => { state.keyLight.intensity = parseFloat(ev.target.value); });
+ $('#pose-light-azimuth')?.addEventListener('input', (ev) => {
+ state.keyAzimuth = (parseFloat(ev.target.value) / 180) * Math.PI;
+ syncKeyLight();
+ });
+ $('#pose-light-elevation')?.addEventListener('input', (ev) => {
+ state.keyElevation = (parseFloat(ev.target.value) / 180) * Math.PI;
+ syncKeyLight();
+ });
+ $('#pose-light-intensity')?.addEventListener('input', (ev) => {
+ state.keyLight.intensity = parseFloat(ev.target.value);
+ });
// ── Floor props ────────────────────────────────────────────────────────
const propHost = $('#pose-prop-host');
if (propHost) {
for (const [id, def] of Object.entries(FLOOR_PROPS)) {
- const btn = el('button', { class: 'pose-prop-btn', type: 'button', 'data-prop': id, 'aria-pressed': String(state.prop === id) }, [def.label]);
+ const btn = el(
+ 'button',
+ {
+ class: 'pose-prop-btn',
+ type: 'button',
+ 'data-prop': id,
+ 'aria-pressed': String(state.prop === id),
+ },
+ [def.label],
+ );
btn.addEventListener('click', () => {
state.prop = id;
propLayer.clear();
- if (def.build) { const g = def.build(); propLayer.add(g); state.propGroup = g; }
- document.querySelectorAll('[data-prop]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.prop === id)));
+ if (def.build) {
+ const g = def.build();
+ propLayer.add(g);
+ state.propGroup = g;
+ }
+ document
+ .querySelectorAll('[data-prop]')
+ .forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.prop === id)));
});
propHost.appendChild(btn);
}
@@ -904,10 +1007,27 @@ function boot() {
window.addEventListener('keydown', (ev) => {
if (ev.target.matches('input, textarea, select')) return;
const k = ev.key.toLowerCase();
- if (k === 'f') { state.poseMode = 'fk'; applyPoseMode(); renderControlsPanel(); }
- else if (k === 'i') { const b = document.querySelector('[data-posemode="ik"]'); if (b && !b.disabled) { state.poseMode = 'ik'; applyPoseMode(); renderControlsPanel(); } }
- else if (k === 'r' && state.selectedBone) { state.rig.setBoneEuler(state.selectedBone, { x: 0, y: 0, z: 0 }); renderControlsPanel(); }
- else if (k === 'escape') { state.selectedBone = null; gizmo.detach(); renderControlsPanel(); renderBoneList(); updateSelectionLabel(); }
+ if (k === 'f') {
+ state.poseMode = 'fk';
+ applyPoseMode();
+ renderControlsPanel();
+ } else if (k === 'i') {
+ const b = document.querySelector('[data-posemode="ik"]');
+ if (b && !b.disabled) {
+ state.poseMode = 'ik';
+ applyPoseMode();
+ renderControlsPanel();
+ }
+ } else if (k === 'r' && state.selectedBone) {
+ state.rig.setBoneEuler(state.selectedBone, { x: 0, y: 0, z: 0 });
+ renderControlsPanel();
+ } else if (k === 'escape') {
+ state.selectedBone = null;
+ gizmo.detach();
+ renderControlsPanel();
+ renderBoneList();
+ updateSelectionLabel();
+ }
});
// ── Animation timeline ───────────────────────────────────────────────────
@@ -916,18 +1036,57 @@ function boot() {
// keyframes and plays the result; export bakes a THREE.AnimationClip.
timeline = setupTimeline();
+ // ── Animation preset library ─────────────────────────────────────────────
+ // A curated gallery of ready-to-apply motion clips. Picking one retargets it
+ // onto the loaded rig and plays it live in this same viewport, then offers an
+ // animated-GLB export. While a preset previews it drives the figure, so we
+ // pause the keyframe timeline and stow the FK gizmo.
+ const animLibraryHost = $('#pose-anim-library');
+ if (animLibraryHost) {
+ const animLibrary = new AnimationLibrary({
+ host: animLibraryHost,
+ getRig: () => state.rig,
+ setStatus,
+ onPreviewStart: () => {
+ timeline?.pause?.();
+ gizmo.detach();
+ gizmo.enabled = false;
+ gizmo.visible = false;
+ },
+ onPreviewStop: () => {
+ if (state.poseMode === 'fk' && state.selectedBone) attachGizmo();
+ renderControlsPanel();
+ },
+ });
+ state.animLibrary = animLibrary;
+ animLibrary.mount();
+ }
+
function setupTimeline() {
const doc = createDocument();
const anim = { doc, playing: false, playhead: 0, selectedId: null };
state.anim = anim;
const tl = {
- track: $('#tl-track'), lane: $('#tl-lane'), ruler: $('#tl-ruler'),
- playhead: $('#tl-playhead'), empty: $('#tl-empty'), time: $('#tl-time'),
- play: $('#tl-play'), stop: $('#tl-stop'), start: $('#tl-start'), end: $('#tl-end'),
- loop: $('#tl-loop'), add: $('#tl-add-key'), del: $('#tl-del-key'),
- easing: $('#tl-easing'), name: $('#tl-name'), duration: $('#tl-duration'), fps: $('#tl-fps'),
- exportJson: $('#tl-export-json'), exportGlb: $('#tl-export-glb'),
+ track: $('#tl-track'),
+ lane: $('#tl-lane'),
+ ruler: $('#tl-ruler'),
+ playhead: $('#tl-playhead'),
+ empty: $('#tl-empty'),
+ time: $('#tl-time'),
+ play: $('#tl-play'),
+ stop: $('#tl-stop'),
+ start: $('#tl-start'),
+ end: $('#tl-end'),
+ loop: $('#tl-loop'),
+ add: $('#tl-add-key'),
+ del: $('#tl-del-key'),
+ easing: $('#tl-easing'),
+ name: $('#tl-name'),
+ duration: $('#tl-duration'),
+ fps: $('#tl-fps'),
+ exportJson: $('#tl-export-json'),
+ exportGlb: $('#tl-export-glb'),
};
if (!tl.track) return null; // page without the timeline markup — no-op
@@ -939,7 +1098,11 @@ function boot() {
return clamp((clientX - rect.left) / rect.width, 0, 1) * doc.duration;
};
const safeName = () =>
- (doc.name || 'animation').replace(/[^a-z0-9._-]+/gi, '-').replace(/-+/g, '-').replace(/^-|-$/g, '').slice(0, 60) || 'animation';
+ (doc.name || 'animation')
+ .replace(/[^a-z0-9._-]+/gi, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 60) || 'animation';
// Sync the static control values from the document defaults.
tl.name.value = doc.name;
@@ -969,7 +1132,10 @@ function boot() {
// ── Transport ────────────────────────────────────────────────────────────
function play() {
- if (!doc.keyframes.length) { setStatus('Add a keyframe first, then play.', 'error'); return; }
+ if (!doc.keyframes.length) {
+ setStatus('Add a keyframe first, then play.', 'error');
+ return;
+ }
if (!doc.loop && anim.playhead >= doc.duration - 1e-3) anim.playhead = 0;
anim.playing = true;
tl.play.textContent = '⏸';
@@ -980,15 +1146,24 @@ function boot() {
tl.play.textContent = '▶';
tl.play.setAttribute('aria-pressed', 'false');
}
- function toggle() { anim.playing ? pause() : play(); }
- function stop() { pause(); setPlayhead(0, { render: true }); }
+ function toggle() {
+ anim.playing ? pause() : play();
+ }
+ function stop() {
+ pause();
+ setPlayhead(0, { render: true });
+ }
function advance(dt) {
if (!anim.playing) return;
let t = anim.playhead + dt;
if (t >= doc.duration) {
if (doc.loop) t = doc.duration > 0 ? t % doc.duration : 0;
- else { setPlayhead(doc.duration); pause(); return; }
+ else {
+ setPlayhead(doc.duration);
+ pause();
+ return;
+ }
}
setPlayhead(t);
}
@@ -1004,7 +1179,11 @@ function boot() {
for (let t = 0; t <= doc.duration + 1e-6; t += step) {
const left = pct(t);
tl.ruler.appendChild(el('div', { class: 'tl-tick', style: `left:${left}%` }));
- tl.ruler.appendChild(el('div', { class: 'tl-tick-label', style: `left:${left}%` }, [`${(+t.toFixed(3))}s`]));
+ tl.ruler.appendChild(
+ el('div', { class: 'tl-tick-label', style: `left:${left}%` }, [
+ `${+t.toFixed(3)}s`,
+ ]),
+ );
}
}
@@ -1040,8 +1219,14 @@ function boot() {
});
diamond.addEventListener('pointerdown', (ev) => startKeyDrag(ev, kf, diamond));
diamond.addEventListener('keydown', (ev) => {
- if (ev.key === 'Delete' || ev.key === 'Backspace') { ev.preventDefault(); select(kf.id); deleteSelected(); }
- else if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); select(kf.id); }
+ if (ev.key === 'Delete' || ev.key === 'Backspace') {
+ ev.preventDefault();
+ select(kf.id);
+ deleteSelected();
+ } else if (ev.key === 'Enter' || ev.key === ' ') {
+ ev.preventDefault();
+ select(kf.id);
+ }
});
tl.lane.appendChild(diamond);
}
@@ -1063,9 +1248,11 @@ function boot() {
const kf = upsertKeyframe(doc, anim.playhead, state.rig.getPose(), DEFAULT_EASING);
anim.selectedId = kf.id;
renderKeyframes();
- setStatus(existed
- ? `Keyframe updated at ${kf.time.toFixed(2)}s.`
- : `Keyframe added at ${kf.time.toFixed(2)}s · ${doc.keyframes.length} total.`);
+ setStatus(
+ existed
+ ? `Keyframe updated at ${kf.time.toFixed(2)}s.`
+ : `Keyframe added at ${kf.time.toFixed(2)}s · ${doc.keyframes.length} total.`,
+ );
}
function deleteSelected() {
@@ -1096,7 +1283,9 @@ function boot() {
diamond.removeEventListener('pointermove', onMove);
diamond.removeEventListener('pointerup', onUp);
diamond.removeEventListener('pointercancel', onUp);
- try { diamond.releasePointerCapture(e.pointerId); } catch {}
+ try {
+ diamond.releasePointerCapture(e.pointerId);
+ } catch {}
renderKeyframes();
if (state.selectedBone) renderControlsPanel();
};
@@ -1120,24 +1309,43 @@ function boot() {
const endScrub = (ev) => {
if (!scrubbing) return;
scrubbing = false;
- try { tl.track.releasePointerCapture(ev.pointerId); } catch {}
+ try {
+ tl.track.releasePointerCapture(ev.pointerId);
+ } catch {}
if (state.selectedBone) renderControlsPanel();
};
tl.track.addEventListener('pointerup', endScrub);
tl.track.addEventListener('pointercancel', endScrub);
tl.track.addEventListener('keydown', (ev) => {
const stepDt = 1 / clamp(doc.fps || 30, 1, 120);
- if (ev.key === 'ArrowLeft') { ev.preventDefault(); pause(); setPlayhead(anim.playhead - stepDt, { render: true }); }
- else if (ev.key === 'ArrowRight') { ev.preventDefault(); pause(); setPlayhead(anim.playhead + stepDt, { render: true }); }
- else if (ev.key === 'Home') { ev.preventDefault(); setPlayhead(0, { render: true }); }
- else if (ev.key === 'End') { ev.preventDefault(); setPlayhead(doc.duration, { render: true }); }
+ if (ev.key === 'ArrowLeft') {
+ ev.preventDefault();
+ pause();
+ setPlayhead(anim.playhead - stepDt, { render: true });
+ } else if (ev.key === 'ArrowRight') {
+ ev.preventDefault();
+ pause();
+ setPlayhead(anim.playhead + stepDt, { render: true });
+ } else if (ev.key === 'Home') {
+ ev.preventDefault();
+ setPlayhead(0, { render: true });
+ } else if (ev.key === 'End') {
+ ev.preventDefault();
+ setPlayhead(doc.duration, { render: true });
+ }
});
// ── Controls ────────────────────────────────────────────────────────────────
tl.play.addEventListener('click', toggle);
tl.stop.addEventListener('click', stop);
- tl.start.addEventListener('click', () => { pause(); setPlayhead(0, { render: true }); });
- tl.end.addEventListener('click', () => { pause(); setPlayhead(doc.duration, { render: true }); });
+ tl.start.addEventListener('click', () => {
+ pause();
+ setPlayhead(0, { render: true });
+ });
+ tl.end.addEventListener('click', () => {
+ pause();
+ setPlayhead(doc.duration, { render: true });
+ });
tl.loop.addEventListener('click', () => {
doc.loop = !doc.loop;
tl.loop.setAttribute('aria-pressed', String(doc.loop));
@@ -1151,7 +1359,9 @@ function boot() {
applyPreview();
setStatus(`Easing set to ${tl.easing.value}.`);
});
- tl.name.addEventListener('input', () => { doc.name = tl.name.value.trim() || 'animation'; });
+ tl.name.addEventListener('input', () => {
+ doc.name = tl.name.value.trim() || 'animation';
+ });
tl.duration.addEventListener('change', () => {
doc.duration = clamp(parseFloat(tl.duration.value) || 4, 0.25, 120);
tl.duration.value = String(doc.duration);
@@ -1193,7 +1403,10 @@ function boot() {
btn.textContent = 'Failed';
setStatus(`${label} failed: ${err.message}`, 'error');
} finally {
- setTimeout(() => { btn.classList.remove('is-ok', 'is-err'); btn.textContent = original; }, 2200);
+ setTimeout(() => {
+ btn.classList.remove('is-ok', 'is-err');
+ btn.textContent = original;
+ }, 2200);
}
}
@@ -1201,7 +1414,11 @@ function boot() {
pause();
withBusy(tl.exportJson, 'Clip JSON', async () => {
const json = serializeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' });
- downloadBlob(JSON.stringify(json, null, 2), `${safeName()}.json`, 'application/json');
+ downloadBlob(
+ JSON.stringify(json, null, 2),
+ `${safeName()}.json`,
+ 'application/json',
+ );
});
});
tl.exportGlb.addEventListener('click', () => {
@@ -1224,12 +1441,21 @@ function boot() {
// ── Keyboard (timeline) ──────────────────────────────────────────────────────
window.addEventListener('keydown', (ev) => {
- if (ev.target.matches('input, textarea, select') || ev.target.closest('.tl-key')) return;
- if (ev.key === ' ') { ev.preventDefault(); toggle(); }
- else if (ev.key === 'k' || ev.key === 'K') { captureKeyframe(); }
- else if ((ev.key === 'Delete' || ev.key === 'Backspace') && anim.selectedId) { ev.preventDefault(); deleteSelected(); }
- else if (ev.key === 'Home') { setPlayhead(0, { render: true }); }
- else if (ev.key === 'End') { setPlayhead(doc.duration, { render: true }); }
+ if (ev.target.matches('input, textarea, select') || ev.target.closest('.tl-key'))
+ return;
+ if (ev.key === ' ') {
+ ev.preventDefault();
+ toggle();
+ } else if (ev.key === 'k' || ev.key === 'K') {
+ captureKeyframe();
+ } else if ((ev.key === 'Delete' || ev.key === 'Backspace') && anim.selectedId) {
+ ev.preventDefault();
+ deleteSelected();
+ } else if (ev.key === 'Home') {
+ setPlayhead(0, { render: true });
+ } else if (ev.key === 'End') {
+ setPlayhead(doc.duration, { render: true });
+ }
});
// ── Init ────────────────────────────────────────────────────────────────────
@@ -1272,7 +1498,10 @@ function boot() {
easing: EASINGS[k.easing] ? k.easing : DEFAULT_EASING,
pose:
k.pose && k.pose.bones
- ? { bones: { ...k.pose.bones }, rootPosition: k.pose.rootPosition || { x: 0, y: 0, z: 0 } }
+ ? {
+ bones: { ...k.pose.bones },
+ rootPosition: k.pose.rootPosition || { x: 0, y: 0, z: 0 },
+ }
: { bones: {} },
}))
.sort((a, b) => a.time - b.time);
@@ -1290,10 +1519,15 @@ function boot() {
return {
update: advance,
pause,
- onRigChanged: () => { if (doc.keyframes.length) applyPreview(); },
+ onRigChanged: () => {
+ if (doc.keyframes.length) applyPreview();
+ },
bake: () => bakeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),
serialize: () => serializeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),
- captureThumbnail: () => { renderer.render(scene, camera); return renderer.domElement.toDataURL('image/png'); },
+ captureThumbnail: () => {
+ renderer.render(scene, camera);
+ return renderer.domElement.toDataURL('image/png');
+ },
getDocument,
loadDocument,
keyframeCount: () => doc.keyframes.length,
diff --git a/src/remesh-convert.js b/src/remesh-convert.js
new file mode 100644
index 000000000..3e39d16b8
--- /dev/null
+++ b/src/remesh-convert.js
@@ -0,0 +1,130 @@
+/**
+ * Server-side mesh conversion via /api/forge-remesh.
+ *
+ * FBX is the one export format we can't build in the browser — there is no
+ * Three.js FBX exporter, and a rigged FBX needs Blender's exporter to write the
+ * bone hierarchy + skin weights. So FBX goes through the remesh worker: we hand
+ * it a public GLB URL, it runs a `convert` (which preserves the skeleton), and
+ * returns a downloadable FBX URL.
+ *
+ * Two entry points depending on what the caller already has:
+ * - fbxFromUrl(glbUrl, …) — saved avatars already host a public GLB.
+ * - fbxFromBlob(glbBlob, …) — the create/review flow has only an in-memory
+ * blob, so we presign-upload it first.
+ */
+
+const POLL_INTERVAL_MS = 2500;
+const POLL_TIMEOUT_MS = 180_000;
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+/**
+ * Upload a GLB blob to R2 and return its public https URL. Reuses the same
+ * presign endpoint the /play "bring your own avatar" drop zone uses.
+ */
+async function uploadGlbForConversion(blob, filename) {
+ const presignRes = await fetch('/api/avatar/presign-glb', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ filename: `${filename}.glb`,
+ content_type: 'model/gltf-binary',
+ bytes: blob.size,
+ }),
+ });
+ const presign = await presignRes.json().catch(() => ({}));
+ if (presignRes.status === 413) {
+ throw new Error('Model is too large to convert to FBX (16 MB max). Download GLB instead.');
+ }
+ if (!presignRes.ok || !presign?.upload_url || !presign?.public_url) {
+ throw new Error(presign?.message || 'Could not get an upload URL for conversion.');
+ }
+
+ const put = await fetch(presign.upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': 'model/gltf-binary' },
+ body: blob,
+ });
+ if (!put.ok) throw new Error(`Upload failed (${put.status}).`);
+
+ return presign.public_url;
+}
+
+async function startRemeshConvert(meshUrl, format) {
+ const res = await fetch('/api/forge-remesh', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ mesh_url: meshUrl, operation: 'convert', output_format: format }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503) {
+ throw new Error(`${format.toUpperCase()} conversion isn't available right now.`);
+ }
+ if (!res.ok || !data?.job_id) {
+ throw new Error(data?.message || `Couldn't start ${format.toUpperCase()} conversion.`);
+ }
+ return data.job_id;
+}
+
+async function pollRemesh(jobId, onStatus) {
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ const res = await fetch(`/api/forge-remesh?job=${encodeURIComponent(jobId)}`);
+ const data = await res.json().catch(() => ({}));
+ if (data?.status === 'done' && data.result_url) return data.result_url;
+ if (data?.status === 'failed') throw new Error(data.error || 'Conversion failed.');
+ onStatus?.('Converting…');
+ }
+ throw new Error('Conversion timed out — try again.');
+}
+
+/**
+ * Convert a public GLB URL to another server-side format. Returns the result
+ * URL to download. Currently used for FBX.
+ *
+ * @param {string} glbUrl — public https URL of the source GLB
+ * @param {object} opts
+ * @param {string} [opts.format='fbx']
+ * @param {(msg: string) => void} [opts.onStatus]
+ * @returns {Promise<string>} downloadable result URL
+ */
+export async function fbxFromUrl(glbUrl, { format = 'fbx', onStatus } = {}) {
+ if (!glbUrl) throw new Error('No source GLB to convert.');
+ onStatus?.('Converting…');
+ const jobId = await startRemeshConvert(glbUrl, format);
+ return pollRemesh(jobId, onStatus);
+}
+
+/**
+ * Convert an in-memory GLB blob: upload it for a public URL, then convert.
+ *
+ * @param {Blob} glbBlob
+ * @param {object} opts
+ * @param {string} [opts.filename='avatar']
+ * @param {string} [opts.format='fbx']
+ * @param {(msg: string) => void} [opts.onStatus]
+ * @returns {Promise<string>} downloadable result URL
+ */
+export async function fbxFromBlob(glbBlob, { filename = 'avatar', format = 'fbx', onStatus } = {}) {
+ if (!(glbBlob instanceof Blob)) throw new Error('No GLB source for conversion.');
+ onStatus?.('Uploading…');
+ const meshUrl = await uploadGlbForConversion(glbBlob, filename);
+ onStatus?.('Converting…');
+ const jobId = await startRemeshConvert(meshUrl, format);
+ return pollRemesh(jobId, onStatus);
+}
+
+/** Trigger a browser download of a remote URL with a suggested filename. */
+export function downloadUrl(href, filename) {
+ const a = document.createElement('a');
+ a.href = href;
+ a.download = filename;
+ a.rel = 'noopener';
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+}
diff --git a/src/segment.js b/src/segment.js
new file mode 100644
index 000000000..d01c18a96
--- /dev/null
+++ b/src/segment.js
@@ -0,0 +1,642 @@
+// Parts Studio — split a 3D model into selectable, addressable parts.
+//
+// Drives /api/forge-segment: POST a mesh URL to start a segmentation job, poll
+// until it resolves to a segmented GLB (every part is a named node) plus a parts
+// manifest. The result is loaded into a real Three.js scene where each part can
+// be clicked to isolate, toggled for visibility, recoloured for inspection, and
+// exported on its own. Nothing here is faked — the parts, colours, and counts
+// all come from the worker's geometry segmentation.
+
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+
+const POLL_INTERVAL_MS = 2000;
+const MAX_POLL_MS = 4 * 60 * 1000;
+const HIGHLIGHT = new THREE.Color(0x4f8cff);
+const HOVER = new THREE.Color(0x1d3a66);
+
+const els = {
+ form: document.getElementById('composer'),
+ meshUrl: document.getElementById('mesh-url'),
+ method: document.getElementById('method'),
+ maxParts: document.getElementById('max-parts'),
+ segment: document.getElementById('segment-btn'),
+ segmentLabel: document.getElementById('segment-label'),
+ stage: document.getElementById('stage'),
+ states: {
+ empty: document.getElementById('state-empty'),
+ loading: document.getElementById('state-loading'),
+ result: document.getElementById('state-result'),
+ error: document.getElementById('state-error'),
+ unconfigured: document.getElementById('state-unconfigured'),
+ },
+ loadingMeta: document.getElementById('loading-meta'),
+ loadingNote: document.getElementById('loading-note'),
+ cancel: document.getElementById('cancel'),
+ viewport: document.getElementById('viewport'),
+ partsList: document.getElementById('parts-list'),
+ partsCount: document.getElementById('parts-count'),
+ showAll: document.getElementById('show-all'),
+ downloadGlb: document.getElementById('download-glb'),
+ resetView: document.getElementById('reset-view'),
+ selectionLabel: document.getElementById('selection-label'),
+ errorMessage: document.getElementById('error-message'),
+ retry: document.getElementById('retry'),
+};
+
+let pollAbort = false;
+let elapsedTimer = null;
+
+// ── three.js scene ────────────────────────────────────────────────────────────
+
+let renderer, scene, camera, controls, pmrem, raycaster, pointer;
+let modelRoot = null;
+let parts = []; // { id, name, faceCount, color, object, baseEmissive, visible }
+let selectedId = null;
+let hoveredId = null;
+let frameRequested = false;
+
+function initThree() {
+ if (renderer) return;
+ const mount = els.viewport;
+
+ renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: false });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ renderer.setSize(mount.clientWidth, mount.clientHeight, false);
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.05;
+ mount.appendChild(renderer.domElement);
+ renderer.domElement.style.display = 'block';
+ renderer.domElement.style.touchAction = 'none';
+
+ scene = new THREE.Scene();
+
+ pmrem = new THREE.PMREMGenerator(renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+
+ camera = new THREE.PerspectiveCamera(45, mount.clientWidth / mount.clientHeight, 0.01, 1000);
+ camera.position.set(0, 1.2, 4);
+
+ const hemi = new THREE.HemisphereLight(0xffffff, 0x202028, 0.9);
+ scene.add(hemi);
+ const key = new THREE.DirectionalLight(0xffffff, 1.6);
+ key.position.set(3, 6, 4);
+ scene.add(key);
+
+ controls = new OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.08;
+ controls.addEventListener('change', requestFrame);
+
+ raycaster = new THREE.Raycaster();
+ pointer = new THREE.Vector2();
+
+ const ro = new ResizeObserver(() => onResize());
+ ro.observe(mount);
+
+ renderer.domElement.addEventListener('pointermove', onPointerMove);
+ renderer.domElement.addEventListener('pointerdown', onPointerDown);
+ renderer.domElement.addEventListener('pointerleave', () => setHover(null));
+
+ animate();
+}
+
+function animate() {
+ requestAnimationFrame(animate);
+ const damping = controls?.update();
+ // Render on demand: whenever damping is active or a frame was requested.
+ if (frameRequested || damping) {
+ frameRequested = false;
+ renderer.render(scene, camera);
+ }
+}
+
+function requestFrame() {
+ frameRequested = true;
+}
+
+function onResize() {
+ if (!renderer) return;
+ const { clientWidth: w, clientHeight: h } = els.viewport;
+ if (w === 0 || h === 0) return;
+ renderer.setSize(w, h, false);
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ requestFrame();
+}
+
+function clearModel() {
+ if (modelRoot) {
+ scene.remove(modelRoot);
+ modelRoot.traverse((o) => {
+ if (o.isMesh) {
+ o.geometry?.dispose?.();
+ if (Array.isArray(o.material)) o.material.forEach((m) => m.dispose?.());
+ else o.material?.dispose?.();
+ }
+ });
+ }
+ modelRoot = null;
+ parts = [];
+ selectedId = null;
+ hoveredId = null;
+}
+
+// Frame the camera to the model's bounding sphere.
+function frameModel() {
+ const box = new THREE.Box3().setFromObject(modelRoot);
+ const sphere = box.getBoundingSphere(new THREE.Sphere());
+ const center = sphere.center;
+ const radius = sphere.radius || 1;
+
+ controls.target.copy(center);
+ const fov = (camera.fov * Math.PI) / 180;
+ const dist = (radius / Math.sin(fov / 2)) * 1.25;
+ const dir = new THREE.Vector3(0.6, 0.45, 1).normalize();
+ camera.position.copy(center).addScaledVector(dir, dist);
+ camera.near = dist / 100;
+ camera.far = dist * 100;
+ camera.updateProjectionMatrix();
+ controls.update();
+ requestFrame();
+}
+
+// Find the part id (node name like "part_03") that owns a mesh.
+function partIdFor(obj) {
+ let cur = obj;
+ while (cur) {
+ if (/^part_\d+$/i.test(cur.name)) return cur.name.toLowerCase();
+ cur = cur.parent;
+ }
+ return obj.name || null;
+}
+
+function loadSegmentedModel(glbUrl, manifest) {
+ return new Promise((resolve, reject) => {
+ const loader = new GLTFLoader();
+ loader.load(
+ glbUrl,
+ (gltf) => {
+ clearModel();
+ modelRoot = gltf.scene;
+ scene.add(modelRoot);
+
+ const manifestById = new Map(
+ (manifest?.parts || []).map((p) => [String(p.id).toLowerCase(), p]),
+ );
+
+ // Collect one Part record per addressable node, cloning materials so
+ // per-part highlight/recolour never bleeds across shared materials.
+ const byId = new Map();
+ modelRoot.traverse((o) => {
+ if (!o.isMesh) return;
+ o.material = o.material.clone();
+ o.material.vertexColors = true;
+ const id = partIdFor(o);
+ if (!byId.has(id)) {
+ const man = manifestById.get(id);
+ const faceCount =
+ man?.face_count ?? Math.floor((o.geometry.index?.count || o.geometry.attributes.position.count) / 3);
+ const color = man?.color || '#888888';
+ byId.set(id, {
+ id,
+ name: man?.name || id,
+ faceCount,
+ color,
+ object: o,
+ meshes: [o],
+ baseEmissive: o.material.emissive.getHex(),
+ visible: true,
+ });
+ } else {
+ byId.get(id).meshes.push(o);
+ }
+ });
+
+ parts = Array.from(byId.values());
+ // Order to match the manifest (top→bottom, larger→smaller) when present.
+ if (manifest?.parts?.length) {
+ const order = new Map(manifest.parts.map((p, i) => [String(p.id).toLowerCase(), i]));
+ parts.sort((a, b) => (order.get(a.id) ?? 999) - (order.get(b.id) ?? 999));
+ } else {
+ parts.sort((a, b) => b.faceCount - a.faceCount);
+ }
+
+ frameModel();
+ resolve();
+ },
+ undefined,
+ (err) => reject(new Error(`Could not load the segmented model: ${err?.message || err}`)),
+ );
+ });
+}
+
+// ── selection / visibility ────────────────────────────────────────────────────
+
+function applyHighlights() {
+ for (const p of parts) {
+ const hex =
+ p.id === selectedId ? HIGHLIGHT.getHex() : p.id === hoveredId ? HOVER.getHex() : p.baseEmissive;
+ const intensity = p.id === selectedId ? 0.9 : p.id === hoveredId ? 0.45 : 1;
+ for (const m of p.meshes) {
+ m.material.emissive.setHex(hex);
+ if (m.material.emissiveIntensity !== undefined) m.material.emissiveIntensity = intensity;
+ }
+ }
+ requestFrame();
+}
+
+function setSelected(id) {
+ selectedId = selectedId === id ? null : id;
+ applyHighlights();
+ syncListSelection();
+ updateSelectionLabel();
+}
+
+function setHover(id) {
+ if (hoveredId === id) return;
+ hoveredId = id;
+ renderer.domElement.style.cursor = id ? 'pointer' : 'default';
+ applyHighlights();
+}
+
+function setPartVisible(id, visible) {
+ const p = parts.find((x) => x.id === id);
+ if (!p) return;
+ p.visible = visible;
+ for (const m of p.meshes) m.visible = visible;
+ if (!visible && selectedId === id) setSelected(id); // deselect a hidden part
+ requestFrame();
+}
+
+function isolate(id) {
+ const onlyThis = parts.every((p) => (p.id === id ? p.visible : !p.visible));
+ for (const p of parts) setPartVisible(p.id, onlyThis ? true : p.id === id);
+ if (!onlyThis) {
+ selectedId = id;
+ applyHighlights();
+ updateSelectionLabel();
+ }
+ syncListVisibility();
+ syncListSelection();
+}
+
+function showAll() {
+ for (const p of parts) setPartVisible(p.id, true);
+ syncListVisibility();
+}
+
+function updateSelectionLabel() {
+ const p = parts.find((x) => x.id === selectedId);
+ els.selectionLabel.textContent = p
+ ? `${p.name} · ${p.faceCount.toLocaleString()} faces`
+ : `${parts.length} parts · click one to inspect`;
+}
+
+// ── parts panel ───────────────────────────────────────────────────────────────
+
+function renderPartsPanel() {
+ els.partsCount.textContent = `${parts.length}`;
+ els.partsList.innerHTML = '';
+ for (const p of parts) {
+ const row = document.createElement('div');
+ row.className = 'part-row';
+ row.dataset.partId = p.id;
+ row.setAttribute('role', 'listitem');
+
+ row.innerHTML = `
+ <button class="part-main" type="button" data-act="select" aria-label="Select ${p.name}">
+ <span class="swatch" style="background:${p.color}"></span>
+ <span class="part-text">
+ <span class="part-name">${escapeHtml(p.name)}</span>
+ <span class="part-sub">${p.id} · ${p.faceCount.toLocaleString()} faces</span>
+ </span>
+ </button>
+ <span class="part-actions">
+ <button class="icon-btn" type="button" data-act="isolate" title="Isolate this part" aria-label="Isolate ${p.name}">⤢</button>
+ <button class="icon-btn" type="button" data-act="visibility" title="Toggle visibility" aria-label="Toggle visibility of ${p.name}" aria-pressed="true">👁</button>
+ <button class="icon-btn" type="button" data-act="download" title="Download this part as GLB" aria-label="Download ${p.name}">⭳</button>
+ </span>`;
+
+ row.addEventListener('mouseenter', () => setHover(p.id));
+ row.addEventListener('mouseleave', () => setHover(null));
+ els.partsList.appendChild(row);
+ }
+ syncListSelection();
+ syncListVisibility();
+ updateSelectionLabel();
+}
+
+function syncListSelection() {
+ for (const row of els.partsList.querySelectorAll('.part-row')) {
+ row.classList.toggle('is-selected', row.dataset.partId === selectedId);
+ }
+}
+
+function syncListVisibility() {
+ for (const row of els.partsList.querySelectorAll('.part-row')) {
+ const p = parts.find((x) => x.id === row.dataset.partId);
+ if (!p) continue;
+ row.classList.toggle('is-hidden-part', !p.visible);
+ const eye = row.querySelector('[data-act="visibility"]');
+ if (eye) {
+ eye.textContent = p.visible ? '👁' : '🚫';
+ eye.setAttribute('aria-pressed', String(p.visible));
+ }
+ }
+}
+
+// Per-part export — clone the part's geometry/material into a fresh scene and
+// serialize it to a standalone .glb with the real GLTFExporter.
+function downloadPart(id) {
+ const p = parts.find((x) => x.id === id);
+ if (!p) return;
+ const exportScene = new THREE.Scene();
+ for (const m of p.meshes) {
+ const mat = m.material.clone();
+ mat.emissive.setHex(p.baseEmissive); // strip any highlight before export
+ if (mat.emissiveIntensity !== undefined) mat.emissiveIntensity = 1;
+ const clone = new THREE.Mesh(m.geometry, mat);
+ clone.applyMatrix4(m.matrixWorld);
+ clone.name = p.id;
+ exportScene.add(clone);
+ }
+ const exporter = new GLTFExporter();
+ exporter.parse(
+ exportScene,
+ (glb) => {
+ const blob = new Blob([glb], { type: 'model/gltf-binary' });
+ triggerDownload(blob, `${safeFileName(p.name)}.glb`);
+ },
+ (err) => showError(`Export failed: ${err?.message || err}`),
+ { binary: true },
+ );
+}
+
+// ── job lifecycle ─────────────────────────────────────────────────────────────
+
+function showState(name) {
+ for (const [key, node] of Object.entries(els.states)) {
+ if (node) node.classList.toggle('is-hidden', key !== name);
+ }
+ if (name === 'result') onResize();
+}
+
+function setBusy(busy) {
+ els.segment.disabled = busy;
+ els.segmentLabel.textContent = busy ? 'Segmenting…' : 'Segment';
+}
+
+function startElapsed() {
+ const started = performance.now();
+ stopElapsed();
+ const tick = () => {
+ els.loadingMeta.textContent = `Elapsed ${Math.floor((performance.now() - started) / 1000)}s`;
+ };
+ tick();
+ elapsedTimer = window.setInterval(tick, 1000);
+}
+
+function stopElapsed() {
+ if (elapsedTimer) {
+ window.clearInterval(elapsedTimer);
+ elapsedTimer = null;
+ }
+}
+
+function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+async function startJob(meshUrl) {
+ const res = await fetch('/api/forge-segment', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ mesh_url: meshUrl,
+ method: els.method.value,
+ max_parts: Math.max(2, Math.min(64, Number(els.maxParts.value) || 24)),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ throw new Error(`The segmenter is busy. Try again in about ${secs} seconds.`);
+ }
+ if (!res.ok) throw new Error(data.message || `The segmenter returned ${res.status}.`);
+ return data;
+}
+
+async function pollUntilDone(jobId) {
+ const deadline = performance.now() + MAX_POLL_MS;
+ while (!pollAbort && performance.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ if (pollAbort) return null;
+ const res = await fetch(`/api/forge-segment?job=${encodeURIComponent(jobId)}`);
+ const data = await res.json().catch(() => ({}));
+ if (data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (data.status === 'done' && data.result_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Segmentation failed.');
+ if (data.status === 'running') els.loadingNote.textContent = 'Splitting at shells and concave creases…';
+ }
+ if (pollAbort) return null;
+ throw new Error('Segmentation timed out. Try a simpler mesh or fewer parts.');
+}
+
+async function fetchManifest(url) {
+ if (!url) return null;
+ try {
+ const res = await fetch(url);
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+async function run(meshUrl) {
+ pollAbort = false;
+ setBusy(true);
+ els.loadingNote.textContent = 'Fetching and analysing the mesh…';
+ startElapsed();
+ showState('loading');
+
+ try {
+ const job = await startJob(meshUrl);
+ const done = await pollUntilDone(job.job_id);
+ if (pollAbort || !done) return;
+
+ // Prefer the inline parts list; fall back to the manifest URL.
+ let manifest = done.parts ? { parts: done.parts } : null;
+ if (!manifest && done.manifest_url) manifest = await fetchManifest(done.manifest_url);
+
+ initThree();
+ showState('result');
+ await loadSegmentedModel(done.result_url, manifest);
+ renderPartsPanel();
+
+ els.downloadGlb.href = done.result_url;
+ els.downloadGlb.setAttribute('download', `${safeFileName('segmented')}.glb`);
+ stopElapsed();
+ document.dispatchEvent(new CustomEvent('tws:feature-done', { detail: { feature: 'segment' } }));
+ } catch (err) {
+ if (pollAbort) return;
+ stopElapsed();
+ if (err.kind === 'unconfigured') {
+ showState('unconfigured');
+ return;
+ }
+ showError(err.message || 'Something went wrong while segmenting.');
+ } finally {
+ setBusy(false);
+ }
+}
+
+function showError(message) {
+ stopElapsed();
+ els.errorMessage.textContent = message;
+ showState('error');
+}
+
+// ── interactions ──────────────────────────────────────────────────────────────
+
+function setPointer(e) {
+ const rect = renderer.domElement.getBoundingClientRect();
+ pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
+ pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
+}
+
+function pick() {
+ raycaster.setFromCamera(pointer, camera);
+ const visibleMeshes = parts.filter((p) => p.visible).flatMap((p) => p.meshes);
+ const hits = raycaster.intersectObjects(visibleMeshes, false);
+ return hits.length ? partIdFor(hits[0].object) : null;
+}
+
+let downX = 0;
+let downY = 0;
+function onPointerDown(e) {
+ downX = e.clientX;
+ downY = e.clientY;
+}
+function onPointerMove(e) {
+ if (!parts.length) return;
+ setPointer(e);
+ setHover(pick());
+}
+function onPointerUp(e) {
+ if (!parts.length) return;
+ // Ignore drags (orbit) — only treat a near-stationary release as a click.
+ if (Math.abs(e.clientX - downX) > 4 || Math.abs(e.clientY - downY) > 4) return;
+ setPointer(e);
+ setSelected(pick());
+}
+
+function escapeHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+function safeFileName(s) {
+ return String(s).replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '').slice(0, 48) || 'part';
+}
+function triggerDownload(blob, name) {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = name;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
+}
+
+// ── wiring ────────────────────────────────────────────────────────────────────
+
+els.form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const url = els.meshUrl.value.trim();
+ if (!url.startsWith('https://')) {
+ els.meshUrl.focus();
+ showError('Enter a public https URL to a GLB/OBJ/STL/PLY mesh.');
+ return;
+ }
+ run(url);
+});
+
+els.cancel.addEventListener('click', () => {
+ pollAbort = true;
+ stopElapsed();
+ setBusy(false);
+ showState(parts.length ? 'result' : 'empty');
+});
+
+els.retry.addEventListener('click', () => {
+ const url = els.meshUrl.value.trim();
+ if (url.startsWith('https://')) run(url);
+ else {
+ showState('empty');
+ els.meshUrl.focus();
+ }
+});
+
+els.showAll.addEventListener('click', showAll);
+els.resetView.addEventListener('click', () => modelRoot && frameModel());
+
+// Delegated part-row actions.
+els.partsList.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-act]');
+ const row = e.target.closest('.part-row');
+ if (!btn || !row) return;
+ const id = row.dataset.partId;
+ switch (btn.dataset.act) {
+ case 'select':
+ setSelected(id);
+ break;
+ case 'isolate':
+ isolate(id);
+ break;
+ case 'visibility': {
+ const p = parts.find((x) => x.id === id);
+ if (p) {
+ setPartVisible(id, !p.visible);
+ syncListVisibility();
+ }
+ break;
+ }
+ case 'download':
+ downloadPart(id);
+ break;
+ }
+});
+
+// pointerup is registered on window so a release outside the canvas still ends a drag.
+window.addEventListener('pointerup', onPointerUp);
+
+document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape') {
+ if (selectedId) setSelected(selectedId);
+ else showAll();
+ }
+});
+
+// Deep-link: /segment?mesh=<glb_url> (e.g. from the forge result panel).
+(function handleQuery() {
+ const params = new URLSearchParams(location.search);
+ const mesh = params.get('mesh');
+ if (mesh && mesh.startsWith('https://')) {
+ els.meshUrl.value = mesh;
+ run(mesh);
+ }
+})();
diff --git a/src/shared/stylize-filters.js b/src/shared/stylize-filters.js
new file mode 100644
index 000000000..04439ae10
--- /dev/null
+++ b/src/shared/stylize-filters.js
@@ -0,0 +1,98 @@
+// Canonical client-side catalog for the one-click stylization filters.
+//
+// Mirrors workers/stylize STYLE_CATALOG and api/forge-stylize.js STYLE_BOUNDS —
+// keep the keys, bounds, and copy in lockstep with those. Each entry carries the
+// human-facing copy, its single density knob (bounds + label), and a compact
+// inline SVG that depicts the style on a generic form for the gallery thumbnail.
+//
+// Adding a filter is a matter of appending here, registering its transform in the
+// worker, and widening the enum/bounds in forge-stylize.js + the MCP tool schema.
+
+const icon = {
+ // Stacked grid of cubes — the blocky voxel rebuild.
+ voxel: `
+ <svg viewBox="0 0 64 64" fill="none" aria-hidden="true">
+ <g stroke="currentColor" stroke-width="2" stroke-linejoin="round">
+ <rect x="12" y="28" width="13" height="13" rx="1"/>
+ <rect x="25" y="28" width="13" height="13" rx="1"/>
+ <rect x="38" y="28" width="13" height="13" rx="1"/>
+ <rect x="19" y="15" width="13" height="13" rx="1"/>
+ <rect x="32" y="15" width="13" height="13" rx="1"/>
+ <rect x="25" y="41" width="13" height="13" rx="1"/>
+ </g>
+ </svg>`,
+ // Bricks with studs on the top face.
+ brick: `
+ <svg viewBox="0 0 64 64" fill="none" aria-hidden="true">
+ <g stroke="currentColor" stroke-width="2" stroke-linejoin="round">
+ <circle cx="24" cy="22" r="3" fill="currentColor" stroke="none"/>
+ <circle cx="40" cy="22" r="3" fill="currentColor" stroke="none"/>
+ <rect x="16" y="26" width="32" height="14" rx="2"/>
+ <circle cx="20" cy="40" r="2.4" fill="currentColor" stroke="none"/>
+ <circle cx="44" cy="40" r="2.4" fill="currentColor" stroke="none"/>
+ <rect x="14" y="42" width="36" height="12" rx="2"/>
+ </g>
+ </svg>`,
+ // Strut-and-node lattice — open Voronoi shell.
+ voronoi: `
+ <svg viewBox="0 0 64 64" fill="none" aria-hidden="true">
+ <g stroke="currentColor" stroke-width="2" stroke-linejoin="round">
+ <path d="M20 18 L44 16 L52 34 L38 50 L16 44 L12 26 Z"/>
+ <path d="M20 18 L32 32 M44 16 L32 32 M52 34 L32 32 M38 50 L32 32 M16 44 L32 32 M12 26 L32 32"/>
+ </g>
+ <g fill="currentColor">
+ <circle cx="20" cy="18" r="2.6"/><circle cx="44" cy="16" r="2.6"/>
+ <circle cx="52" cy="34" r="2.6"/><circle cx="38" cy="50" r="2.6"/>
+ <circle cx="16" cy="44" r="2.6"/><circle cx="12" cy="26" r="2.6"/>
+ <circle cx="32" cy="32" r="3"/>
+ </g>
+ </svg>`,
+ // Hard facets — low-poly flat shading.
+ lowpoly: `
+ <svg viewBox="0 0 64 64" fill="none" aria-hidden="true">
+ <g stroke="currentColor" stroke-width="2" stroke-linejoin="round">
+ <path d="M32 12 L50 26 L42 48 L20 46 L14 24 Z"/>
+ <path d="M32 12 L14 24 L26 34 Z" fill="currentColor" fill-opacity="0.16"/>
+ <path d="M32 12 L50 26 L34 30 Z" fill="currentColor" fill-opacity="0.28"/>
+ <path d="M26 34 L20 46 L34 42 Z" fill="currentColor" fill-opacity="0.10"/>
+ <path d="M34 30 L42 48 L34 42 Z" fill="currentColor" fill-opacity="0.22"/>
+ <path d="M32 12 L26 34 L34 30 Z"/>
+ <path d="M26 34 L34 42 L34 30 Z"/>
+ </g>
+ </svg>`,
+};
+
+export const STYLIZE_FILTERS = [
+ {
+ key: 'voxel',
+ name: 'Voxel',
+ blurb: 'Blocky cubes on a 3D grid — a clean Minecraft-style rebuild.',
+ resolution: { label: 'Grid resolution', def: 32, min: 8, max: 96 },
+ icon: icon.voxel,
+ },
+ {
+ key: 'brick',
+ name: 'Brick',
+ blurb: 'Voxels topped with studs — a buildable toy-brick look.',
+ resolution: { label: 'Brick resolution', def: 24, min: 8, max: 64 },
+ icon: icon.brick,
+ },
+ {
+ key: 'voronoi',
+ name: 'Voronoi shell',
+ blurb: 'An open lattice of struts and nodes — light and sculptural.',
+ resolution: { label: 'Cell density', def: 48, min: 12, max: 120 },
+ icon: icon.voronoi,
+ },
+ {
+ key: 'lowpoly',
+ name: 'Low-poly',
+ blurb: 'Crisp facets with hard flat shading — stylized game-asset look.',
+ resolution: { label: 'Detail', def: 40, min: 8, max: 120 },
+ icon: icon.lowpoly,
+ },
+];
+
+export const STYLIZE_FILTER_BY_KEY = Object.fromEntries(
+ STYLIZE_FILTERS.map((f) => [f.key, f]),
+);
diff --git a/tests/animation-retarget.test.js b/tests/animation-retarget.test.js
new file mode 100644
index 000000000..0f01f2acd
--- /dev/null
+++ b/tests/animation-retarget.test.js
@@ -0,0 +1,188 @@
+/**
+ * Runtime animation retargeting — unit tests.
+ *
+ * Builds synthetic skeletons and clips in-memory (no GLB fixtures), so the
+ * suite is fast and deterministic. Covers the contract that lets a canonical
+ * preset clip drive an arbitrarily-named, arbitrarily-proportioned rig:
+ * - track bone names rewritten to the target's actual node names,
+ * - vendor-prefixed rigs (mixamorig:, DEF-, snake_case) still map,
+ * - tracks for bones the rig lacks are dropped + reported,
+ * - coverage gating returns a null clip below MIN_COVERAGE,
+ * - hip translation scaling and speed resampling are applied.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ Bone,
+ SkinnedMesh,
+ Skeleton,
+ BufferGeometry,
+ QuaternionKeyframeTrack,
+ VectorKeyframeTrack,
+ AnimationClip,
+ Object3D,
+} from 'three';
+import {
+ canonicalNodeMapFromObject,
+ retargetClip,
+ retargetClipToObject,
+ scaleClipSpeed,
+ MIN_COVERAGE,
+} from '../src/animation-retarget.js';
+
+// Build a SkinnedMesh-rooted skeleton from a list of bone names so
+// canonicalNodeMapFromObject finds it the way it would in a real GLB.
+function makeRig(boneNames) {
+ const root = new Object3D();
+ const bones = boneNames.map((name) => {
+ const b = new Bone();
+ b.name = name;
+ return b;
+ });
+ // Parent them all under root (flat is fine for name-mapping tests).
+ for (const b of bones) root.add(b);
+ const mesh = new SkinnedMesh(new BufferGeometry());
+ mesh.add(bones[0]);
+ mesh.bind(new Skeleton(bones));
+ root.add(mesh);
+ return root;
+}
+
+// A canonical clip: quaternion tracks on a few bones + a Hips position track.
+function makeCanonicalClip() {
+ const q = new QuaternionKeyframeTrack('Hips.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]);
+ const spine = new QuaternionKeyframeTrack('Spine.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]);
+ const arm = new QuaternionKeyframeTrack('LeftArm.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]);
+ // Hips at world Y = 1.0 (authoring rig height).
+ const pos = new VectorKeyframeTrack('Hips.position', [0, 1], [0, 1, 0, 0, 1.1, 0]);
+ return new AnimationClip('test', 1, [q, spine, arm, pos]);
+}
+
+const CANONICAL_RIG = ['Hips', 'Spine', 'LeftArm', 'RightArm', 'Head'];
+
+describe('canonicalNodeMapFromObject', () => {
+ it('maps canonical bone names to themselves', () => {
+ const map = canonicalNodeMapFromObject(makeRig(CANONICAL_RIG));
+ expect(map.get('Hips')).toBe('Hips');
+ expect(map.get('LeftArm')).toBe('LeftArm');
+ });
+
+ it('maps vendor-prefixed and separator variants to canonical → real node name', () => {
+ const map = canonicalNodeMapFromObject(
+ makeRig(['mixamorig:Hips', 'DEF-spine', 'left_arm', 'Armature_Head']),
+ );
+ expect(map.get('Hips')).toBe('mixamorig:Hips');
+ expect(map.get('Spine')).toBe('DEF-spine');
+ expect(map.get('LeftArm')).toBe('left_arm');
+ expect(map.get('Head')).toBe('Armature_Head');
+ });
+
+ it('returns an empty map for a rig with no recognizable humanoid bones', () => {
+ const map = canonicalNodeMapFromObject(makeRig(['root', 'wheel_fl', 'wheel_fr']));
+ expect(map.size).toBe(0);
+ });
+});
+
+describe('retargetClip', () => {
+ it('rewrites track bone names onto an identically-named rig (100% coverage)', () => {
+ const clip = makeCanonicalClip();
+ const map = canonicalNodeMapFromObject(makeRig(CANONICAL_RIG));
+ const r = retargetClip(clip, map, { hipScale: 1 });
+ expect(r.coverage).toBe(1);
+ expect(r.matched).toBe(4);
+ expect(r.clip.tracks.map((t) => t.name).sort()).toEqual(
+ ['Hips.position', 'Hips.quaternion', 'LeftArm.quaternion', 'Spine.quaternion'].sort(),
+ );
+ });
+
+ it('rewrites onto a differently-named (Mixamo) rig', () => {
+ const clip = makeCanonicalClip();
+ const map = canonicalNodeMapFromObject(
+ makeRig([
+ 'mixamorig:Hips',
+ 'mixamorig:Spine',
+ 'mixamorig:LeftArm',
+ 'mixamorig:RightArm',
+ ]),
+ );
+ const r = retargetClip(clip, map, { hipScale: 1 });
+ const names = r.clip.tracks.map((t) => t.name);
+ expect(names).toContain('mixamorig:Hips.quaternion');
+ expect(names).toContain('mixamorig:LeftArm.quaternion');
+ expect(names).toContain('mixamorig:Hips.position');
+ });
+
+ it('drops tracks for bones the rig lacks and reports them', () => {
+ const clip = makeCanonicalClip(); // addresses Hips, Spine, LeftArm
+ const map = canonicalNodeMapFromObject(makeRig(['Hips', 'Spine'])); // no LeftArm
+ const r = retargetClip(clip, map, { hipScale: 1, minCoverage: 0.1 });
+ expect(r.dropped).toContain('LeftArm');
+ expect(r.clip.tracks.find((t) => t.name.includes('LeftArm'))).toBeUndefined();
+ });
+
+ it('returns a null clip when coverage is below the threshold', () => {
+ const clip = makeCanonicalClip(); // 4 tracks (Hips ×2, Spine, LeftArm)
+ const map = canonicalNodeMapFromObject(makeRig(['Spine'])); // only 1 of 4 maps
+ const r = retargetClip(clip, map);
+ expect(r.coverage).toBeLessThan(MIN_COVERAGE);
+ expect(r.clip).toBeNull();
+ });
+
+ it('scales the hip position track by hipScale', () => {
+ const clip = makeCanonicalClip();
+ const map = canonicalNodeMapFromObject(makeRig(CANONICAL_RIG));
+ const r = retargetClip(clip, map, { hipScale: 2 });
+ const pos = r.clip.tracks.find((t) => t.name === 'Hips.position');
+ // Original Y values were 1 and 1.1 → doubled.
+ expect(pos.values[1]).toBeCloseTo(2, 5);
+ expect(pos.values[4]).toBeCloseTo(2.2, 5);
+ });
+
+ it('does not mutate the source clip', () => {
+ const clip = makeCanonicalClip();
+ const before = clip.tracks.map((t) => t.name);
+ const map = canonicalNodeMapFromObject(
+ makeRig(['mixamorig:Hips', 'mixamorig:Spine', 'mixamorig:LeftArm']),
+ );
+ retargetClip(clip, map, { hipScale: 3 });
+ expect(clip.tracks.map((t) => t.name)).toEqual(before);
+ expect(clip.tracks.find((t) => t.name === 'Hips.position').values[1]).toBe(1);
+ });
+});
+
+describe('retargetClipToObject', () => {
+ it('retargets straight onto an Object3D graph', () => {
+ const clip = makeCanonicalClip();
+ const rig = makeRig([
+ 'mixamorig:Hips',
+ 'mixamorig:Spine',
+ 'mixamorig:LeftArm',
+ 'mixamorig:RightArm',
+ ]);
+ const r = retargetClipToObject(clip, rig, { minCoverage: 0.5 });
+ expect(r.clip).not.toBeNull();
+ expect(r.clip.tracks.some((t) => t.name === 'mixamorig:LeftArm.quaternion')).toBe(true);
+ });
+});
+
+describe('scaleClipSpeed', () => {
+ it('1.8× shortens duration and times proportionally', () => {
+ const clip = makeCanonicalClip(); // duration 1
+ const fast = scaleClipSpeed(clip, 1.8);
+ expect(fast.duration).toBeCloseTo(1 / 1.8, 5);
+ const t = fast.tracks[0].times;
+ expect(t[t.length - 1]).toBeCloseTo(1 / 1.8, 5);
+ });
+
+ it('factor of 1 returns the clip unchanged', () => {
+ const clip = makeCanonicalClip();
+ expect(scaleClipSpeed(clip, 1)).toBe(clip);
+ });
+
+ it('does not mutate the source clip', () => {
+ const clip = makeCanonicalClip();
+ const origDur = clip.duration;
+ scaleClipSpeed(clip, 2);
+ expect(clip.duration).toBe(origDur);
+ });
+});
diff --git a/tests/api/mcp-3d.test.js b/tests/api/mcp-3d.test.js
index 980c7901a..7e0c9e4e8 100644
--- a/tests/api/mcp-3d.test.js
+++ b/tests/api/mcp-3d.test.js
@@ -119,9 +119,25 @@ describe('3D Studio MCP', () => {
const ok = await call('image_to_3d', { image_url: 'https://img.test/in.png' });
expect(ok.result.structuredContent.job_id).toBe('pred_123');
+ expect(ok.result.structuredContent.views_requested).toBe(1);
expect(providerState.submit).toHaveBeenCalledWith({
mode: 'reconstruct',
- params: { image: 'https://img.test/in.png', prompt: undefined },
+ sourceUrl: 'https://img.test/in.png',
+ params: { images: ['https://img.test/in.png'], prompt: undefined },
+ });
+ });
+
+ it('image_to_3d accepts multiple views for multi-view reconstruction', async () => {
+ providerState.submit.mockClear();
+ const views = ['https://img.test/front.png', 'https://img.test/back.png'];
+ const ok = await call('image_to_3d', { image_urls: views });
+ expect(ok.result.structuredContent.job_id).toBe('pred_123');
+ expect(ok.result.structuredContent.views_requested).toBe(2);
+ expect(ok.result.structuredContent.source_image_urls).toEqual(views);
+ expect(providerState.submit).toHaveBeenCalledWith({
+ mode: 'reconstruct',
+ sourceUrl: views[0],
+ params: { images: views, prompt: undefined },
});
});
@@ -165,4 +181,62 @@ describe('3D Studio MCP', () => {
const resource = r.result.content.find((c) => c.type === 'resource');
expect(resource.resource.text).toContain('https://cdn.test/x.glb');
});
+
+ it('segment_model requires a public https url', async () => {
+ const bad = await call('segment_model', { mesh_url: 'http://localhost/m.glb' });
+ expect(bad.result.isError).toBe(true);
+ expect(providerState.submit).not.toHaveBeenCalled();
+ });
+
+ it('segment_model submits a segment job with the resolved params', async () => {
+ const r = await call('segment_model', {
+ mesh_url: 'https://cdn.test/m.glb',
+ method: 'crease',
+ max_parts: 12,
+ });
+ expect(providerState.submit).toHaveBeenCalledWith({
+ mode: 'segment',
+ sourceUrl: 'https://cdn.test/m.glb',
+ params: {
+ method: 'crease',
+ max_parts: 12,
+ min_part_faces: 64,
+ crease_angle: 40,
+ only_part: undefined,
+ },
+ });
+ expect(r.result.structuredContent).toMatchObject({
+ job_id: 'pred_123',
+ status: 'queued',
+ method: 'crease',
+ });
+ });
+
+ it('generation_status surfaces the parts manifest for a segmentation job', async () => {
+ providerState.status.mockResolvedValue({
+ status: 'done',
+ resultGlbUrl: 'https://cdn.test/seg.glb',
+ manifestUrl: 'https://cdn.test/seg.parts.json',
+ partCount: 2,
+ sourceFaces: 1500,
+ segmentMethod: 'auto',
+ parts: [
+ { id: 'part_01', name: 'top', face_count: 1280, color: '#f2a45c' },
+ { id: 'part_02', name: 'core', face_count: 220, color: '#785cf2' },
+ ],
+ });
+ const r = await call('generation_status', { job_id: 'pred_123' });
+ expect(r.result.structuredContent).toMatchObject({
+ status: 'done',
+ glb_url: 'https://cdn.test/seg.glb',
+ manifest_url: 'https://cdn.test/seg.parts.json',
+ part_count: 2,
+ method: 'auto',
+ });
+ expect(r.result.structuredContent.parts).toHaveLength(2);
+ // The named parts are listed in the human-readable text, too.
+ const text = r.result.content.find((c) => c.type === 'text').text;
+ expect(text).toContain('part_01');
+ expect(text).toContain('top');
+ });
});
diff --git a/tests/api/mcp.test.js b/tests/api/mcp.test.js
index 2ca484001..3f231744a 100644
--- a/tests/api/mcp.test.js
+++ b/tests/api/mcp.test.js
@@ -520,8 +520,11 @@ describe('Tool: render_avatar', () => {
it('returns an HTML snippet containing <model-viewer>', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
+ // render_avatar's inputSchema requires id to match uuid format — real
+ // avatar ids are uuids, so the fixture must be one too.
+ const avatarId = '11111111-1111-4111-8111-111111111111';
avatarState.avatar = {
- id: 'avatar-1',
+ id: avatarId,
name: 'Test Avatar',
slug: 'test',
visibility: 'public',
@@ -530,7 +533,7 @@ describe('Tool: render_avatar', () => {
// sql returns [] by default → _readMcpPolicyByAvatar returns null (no restriction)
const { body } = await invoke(
- rpc('tools/call', { name: 'render_avatar', arguments: { id: 'avatar-1' } }),
+ rpc('tools/call', { name: 'render_avatar', arguments: { id: avatarId } }),
);
expect(body.result).toBeDefined();
diff --git a/vercel.json b/vercel.json
index b7de80ac5..b3be4744c 100644
--- a/vercel.json
+++ b/vercel.json
@@ -479,6 +479,10 @@
"src": "/forge/?",
"dest": "/forge.html"
},
+ {
+ "src": "/segment/?",
+ "dest": "/segment.html"
+ },
{
"src": "/xr/?",
"dest": "/xr.html"
diff --git a/vite.config.js b/vite.config.js
index bde4c96d9..e6d4fed5a 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -251,6 +251,7 @@ const appConfig = {
create: resolve(__dirname, 'pages/create.html'),
'create-agent': resolve(__dirname, 'pages/create-agent.html'),
forge: resolve(__dirname, 'pages/forge.html'),
+ segment: resolve(__dirname, 'pages/segment.html'),
'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),
'create-prompt': resolve(__dirname, 'pages/create-prompt.html'),
'create-character': resolve(__dirname, 'pages/create-character.html'),
diff --git a/workers/README.md b/workers/README.md
index 9113b453d..8036384bd 100644
--- a/workers/README.md
+++ b/workers/README.md
@@ -32,6 +32,16 @@ Standalone face-to-avatar service running InstantMesh: accepts 1–6 face photos
### `longcat/` (GPU L4)
FastAPI service running LongCat-Video-Avatar-1.5 (MIT). Takes a reference image + audio URL and renders a lip-synced talking-avatar MP4 to Cloud Storage. API: `POST /generate` -> `202 { job_id }`, `GET /jobs/:id`, `GET /health`; bearer-auth on every request. Full deploy + cost guide in `longcat/README.md`.
+## Mesh stylization (Cloud Run, CPU)
+
+### `stylize/` (CPU)
+One-click geometric stylization filters — turns any mesh into a stylized variant with pure geometry processing (trimesh + numpy + scipy; no GPU, no model inference). Filters: `voxel` (blocky cubes on a grid), `brick` (voxels + studs, LEGO-like), `voronoi` (open strut-and-node lattice shell), `lowpoly` (decimated + hard flat-shaded facets). Source color is preserved per output element where the style allows. API: `POST /process` (`{ mesh, style, resolution?, output_format? }`) -> `202 { task_id }`, `GET /tasks/:id`, `GET /styles` (filter catalog for the UI), `GET /health`; bearer-auth on `/process` + `/tasks`. Routed via `api/_providers/gcp.js` (`stylize` mode, `GCP_STYLIZE_URL`); exposed to the web at `/api/forge-stylize` and to agents over MCP as `stylize_model`.
+
+## Part segmentation (Cloud Run, CPU)
+
+### `segment/` (CPU)
+Splits a 3D model into meaningful, separable parts with clean boundaries (head/torso/limbs on a character; body/wheels/glass on a vehicle) using pure geometry — trimesh + numpy + scipy, no GPU, no model inference. The engine combines connected-component splitting (physically disjoint shells become parts immediately) with the **minima rule** — region growing that cuts the face-adjacency graph at concave creases, where human perception sees part seams — then merges shards and caps the part count to a meaningful handful. Each part is named by its spatial region, tinted a distinct colour, and emitted as a separate named node in the output GLB so it can be hidden, recoloured, replaced, or exported individually. `POST /segment` (`{ mesh, method?, max_parts?, min_part_faces?, crease_angle?, only_part? }`) -> `202 { task_id }`, `GET /tasks/:id` -> `{ status, result_url?, manifest_url?, parts?, part_count?, source_faces?, method?, error? }` (the parts manifest carries each part's id, name, region, bbox, centroid, face/vertex counts, and colour), `GET /health`; bearer-auth on `/segment` + `/tasks`. Routed via `api/_providers/gcp.js` (`segment` mode, `GCP_SEGMENT_URL`); exposed to the web at `/api/forge-segment` (and the `/segment` Parts Studio viewer) and to agents over MCP as the x402-priced `segment_model`.
+
## Cloudflare Worker
### `pump-fun-mcp/`
diff --git a/workers/remesh/Dockerfile b/workers/remesh/Dockerfile
index 05c859942..a38c5a7fc 100644
--- a/workers/remesh/Dockerfile
+++ b/workers/remesh/Dockerfile
@@ -19,11 +19,15 @@ RUN git clone --depth 1 --recursive https://github.com/hjwdzh/QuadriFlow /tmp/qu
&& install -m 0755 /tmp/quadriflow/build/quadriflow /usr/local/bin/quadriflow \
&& rm -rf /tmp/quadriflow
-# ── Runtime deps for trimesh / open3d / assimp / usd ─────────────────────────
+# ── Runtime deps for trimesh / open3d / assimp / usd / Blender ───────────────
+# The X11/GL libs are for the `bpy` (Blender) module, which links against them
+# even when running headless for FBX export.
RUN apt-get update && apt-get install -y --no-install-recommends \
libgl1 libglib2.0-0 libgomp1 \
libassimp-dev libassimp5 \
libopenblas-dev \
+ libegl1 libxrender1 libxi6 libxxf86vm1 libxfixes3 libxkbcommon0 \
+ libxrandr2 libxcursor1 libxinerama1 libsm6 libice6 libxext6 \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt /app/requirements.txt
@@ -31,6 +35,8 @@ RUN pip install -r /app/requirements.txt
WORKDIR /app
COPY worker_security.py /app/worker_security.py
+COPY blender_fbx.py /app/blender_fbx.py
+COPY verify_fbx.py /app/verify_fbx.py
COPY main.py /app/main.py
EXPOSE 8080
diff --git a/workers/remesh/__pycache__/main.cpython-312.pyc b/workers/remesh/__pycache__/main.cpython-312.pyc
deleted file mode 100644
index 3327d9873..000000000
Binary files a/workers/remesh/__pycache__/main.cpython-312.pyc and /dev/null differ
diff --git a/workers/remesh/blender_fbx.py b/workers/remesh/blender_fbx.py
index e8e7bf22e..7f72165fc 100644
--- a/workers/remesh/blender_fbx.py
+++ b/workers/remesh/blender_fbx.py
@@ -29,10 +29,11 @@ from pathlib import Path
import bpy
-# Input extensions Blender can import directly (preserving rig where present).
-# `.off` is intentionally excluded — Blender has no OFF importer, so the worker
-# round-trips those through trimesh → GLB before calling us.
-_IMPORTERS = {".glb", ".gltf", ".fbx", ".obj", ".stl", ".ply", ".dae"}
+# Input extensions whose importers ship in the standalone `bpy` wheel. `.dae`
+# (Collada) and `.off` are excluded — the wheel doesn't bundle the Collada
+# importer and has no OFF importer, so the worker bridges those through a
+# trimesh-written GLB before calling us.
+_IMPORTERS = {".glb", ".gltf", ".fbx", ".obj", ".stl", ".ply"}
def _reset_scene() -> None:
@@ -63,8 +64,6 @@ def _import_source(path: Path) -> None:
bpy.ops.wm.stl_import(filepath=str(path))
elif suffix == ".ply":
bpy.ops.wm.ply_import(filepath=str(path))
- elif suffix == ".dae":
- bpy.ops.wm.collada_import(filepath=str(path))
else:
raise SystemExit(f"blender_fbx: unsupported input format '{suffix}'")
diff --git a/workers/remesh/main.py b/workers/remesh/main.py
index 46c185860..f0659ced6 100644
--- a/workers/remesh/main.py
+++ b/workers/remesh/main.py
@@ -1,8 +1,13 @@
"""
Mesh processing service — remesh, simplify, repair, retopologize, and convert 3D files.
-Wraps trimesh + open3d + QuadriFlow + xatlas. No GPU required; runs on CPU. Handles:
+Wraps trimesh + open3d + QuadriFlow + xatlas, with Blender (bpy) for FBX export.
+No GPU required; runs on CPU. Handles:
- Format conversion (GLB ↔ OBJ ↔ FBX ↔ STL ↔ PLY ↔ USDZ ↔ 3MF)
+ - FBX export with skeletons — a `convert` of a rigged GLB keeps its bone
+ hierarchy, skin weights, and blendshapes (via headless Blender; see
+ blender_fbx.py). trimesh has no FBX writer, so this is the only path that
+ round-trips a rig.
- Triangle decimation (quadric error metric via open3d)
- Quad remeshing (field-aligned quad-dominant topology via QuadriFlow, MIT)
- Smart low-poly (silhouette-preserving decimation + UV re-unwrap + texture re-bake)
@@ -25,7 +30,7 @@ API contract:
operation: "convert"|"simplify"|"repair"|"full", # default: "full" (triangle mode only)
target_faces?: int, # default: 50000, range: 1000–500000
texture_size?: int, # 512|1024|2048, default 1024 (bake atlas size)
- output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf", # default: "glb"
+ output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf"|"fbx", # default: "glb"
} → 202 { task_id, status }
GET /tasks/:id → {
@@ -40,6 +45,7 @@ Environment variables:
GCS_BUCKET — output bucket (required)
MAX_CONCURRENT — default 2
QUADRIFLOW_BIN — path to the quadriflow executable (default: "quadriflow")
+ BLENDER_TIMEOUT — seconds before a Blender FBX export is killed (default: 300)
"""
from __future__ import annotations
@@ -50,6 +56,7 @@ import logging
import os
import shutil
import subprocess
+import sys
import tempfile
import time
import uuid
@@ -84,11 +91,24 @@ _sem: Optional[asyncio.Semaphore] = None
_tasks: dict[str, dict] = {}
SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".off", ".dae"}
-SUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply", "usdz", "3mf"}
+SUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply", "usdz", "3mf", "fbx"}
VALID_MODES = {"triangle", "quad", "lowpoly"}
VALID_TEXTURE_SIZES = {512, 1024, 2048}
MAX_MESH_BYTES = 128 * 1024 * 1024
+# Headless-Blender FBX export. Blender is the only tool here that writes an FBX
+# with a real skeleton; we run it as a one-shot subprocess (bpy holds global,
+# non-thread-safe state — a fresh process per job is the safe pattern).
+BLENDER_FBX_SCRIPT = Path(__file__).parent / "blender_fbx.py"
+BLENDER_TIMEOUT = int(os.environ.get("BLENDER_TIMEOUT", "300"))
+# Formats the `bpy` wheel imports reliably as a single self-contained file, so
+# Blender can read (and keep) their rig directly. Excluded and bridged through a
+# trimesh-written GLB instead:
+# .gltf — JSON with external .bin/texture refs a single fetched file can't carry
+# .dae — Collada importer isn't bundled in the standalone bpy wheel
+# .off — Blender has no OFF importer at all
+BLENDER_IMPORT_FORMATS = {".glb", ".fbx", ".obj", ".stl", ".ply"}
+
@asynccontextmanager
async def lifespan(app: FastAPI):
@@ -506,20 +526,85 @@ def _write_textured_quad_obj(verts, polys, uvs, image, task_id: str) -> list:
return artifacts
+def _blender_to_fbx(in_path: Path, out_path: Path, static: bool) -> int:
+ """Convert a local model file to FBX via headless Blender, preserving the
+ skeleton, skin weights, and blendshapes when the input carries them.
+
+ Returns the exported polygon count. Raises RuntimeError with a clipped log
+ tail on failure. `static=True` skips animation baking (used when the upstream
+ geometry op already discarded any rig)."""
+ cmd = [sys.executable, str(BLENDER_FBX_SCRIPT), str(in_path), str(out_path)]
+ if static:
+ cmd.append("--static")
+ try:
+ proc = subprocess.run(
+ cmd, capture_output=True, text=True, timeout=BLENDER_TIMEOUT, check=False,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise RuntimeError(f"FBX export timed out after {BLENDER_TIMEOUT}s") from exc
+
+ if proc.returncode != 0 or not out_path.exists():
+ tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-6:]
+ raise RuntimeError("FBX export failed: " + " | ".join(tail))
+
+ faces = 0
+ for line in proc.stdout.splitlines():
+ if line.startswith("FACE_COUNT:"):
+ try:
+ faces = int(line.split(":", 1)[1].strip())
+ except ValueError:
+ faces = 0
+ return faces
+
+
+def _convert_to_fbx_preserving_rig(data: bytes, suffix: str, task_id: str) -> tuple[list, dict]:
+ """`convert` → FBX without touching geometry, so a rigged GLB keeps its bone
+ hierarchy, skin weights, and blendshapes. Blender imports the source
+ directly when it can read it as one self-contained file; the rest
+ (`.gltf`/`.dae`/`.off` — see BLENDER_IMPORT_FORMATS) are bridged through a
+ trimesh-written GLB, which yields a static FBX."""
+ with tempfile.TemporaryDirectory() as tmp:
+ out_path = Path(tmp) / f"{task_id}.fbx"
+ if suffix in BLENDER_IMPORT_FORMATS:
+ src_path = Path(tmp) / f"input{suffix}"
+ src_path.write_bytes(data)
+ faces = _blender_to_fbx(src_path, out_path, static=False)
+ else:
+ import trimesh
+ mesh = _load_concatenated(data, suffix)
+ glb_path = Path(tmp) / "bridge.glb"
+ trimesh.scene.scene.Scene(geometry={"mesh": mesh}).export(str(glb_path))
+ faces = _blender_to_fbx(glb_path, out_path, static=True)
+ fbx_bytes = out_path.read_bytes()
+ meta = {"quad_ratio": 0.0, "textured": False, "face_count": faces}
+ return [Artifact(f"{task_id}.fbx", fbx_bytes, "application/octet-stream", "model")], meta
+
+
def _export_simple(mesh, output_format: str, task_id: str) -> list:
- """Export a Trimesh to a single self-contained file (GLB embeds textures)."""
+ """Export a Trimesh to a single self-contained file (GLB embeds textures).
+
+ FBX has no trimesh writer, so it is bridged through a temp GLB and handed to
+ Blender. This path always yields a static FBX — the Trimesh has already lost
+ any rig by the time geometry ops produce it; the rig-preserving route is
+ `_convert_to_fbx_preserving_rig`."""
import trimesh
fmt = output_format.lower()
with tempfile.TemporaryDirectory() as tmpdir:
out_path = Path(tmpdir) / f"{task_id}.{fmt}"
- if fmt in ("glb", "usdz"):
+ if fmt == "fbx":
+ glb_path = Path(tmpdir) / f"{task_id}.glb"
+ trimesh.scene.scene.Scene(geometry={"mesh": mesh}).export(str(glb_path))
+ _blender_to_fbx(glb_path, out_path, static=True)
+ elif fmt in ("glb", "usdz"):
trimesh.scene.scene.Scene(geometry={"mesh": mesh}).export(str(out_path))
else:
mesh.export(str(out_path))
data = out_path.read_bytes()
- ct = "model/gltf-binary" if fmt == "glb" else (
- "model/vnd.usdz+zip" if fmt == "usdz" else "application/octet-stream"
- )
+ ct = {
+ "glb": "model/gltf-binary",
+ "usdz": "model/vnd.usdz+zip",
+ "fbx": "application/octet-stream",
+ }.get(fmt, "application/octet-stream")
return [Artifact(f"{task_id}.{fmt}", data, ct, "model")]
@@ -615,6 +700,13 @@ def _run_processing(
) -> tuple[list, dict]:
data, suffix = _fetch_mesh(mesh_url)
+ # A plain `convert` to FBX must keep the skeleton, so it never enters the
+ # trimesh pipelines (which flatten the scene and drop the rig) — Blender
+ # reads the source directly. Geometry-changing FBX requests fall through to
+ # the pipelines below and emit a static FBX via _export_simple.
+ if output_format == "fbx" and remesh_mode == "triangle" and operation == "convert":
+ return _convert_to_fbx_preserving_rig(data, suffix, task_id)
+
if remesh_mode == "quad":
source = _load_textured(data, suffix)
return _process_quad(source, target_faces, output_format, texture_size, task_id)
diff --git a/workers/remesh/requirements.txt b/workers/remesh/requirements.txt
index 45ef22907..2e4ce8b5e 100644
--- a/workers/remesh/requirements.txt
+++ b/workers/remesh/requirements.txt
@@ -10,7 +10,11 @@ Pillow==11.0.0
google-cloud-storage==2.19.0
httpx==0.27.2
pydantic==2.10.3
-# FBX support via assimp python bindings
+# FBX/DAE input loading via the assimp python bindings (trimesh backend).
pyassimp==5.2.5
# USD / USDZ support
usd-core==24.11
+# FBX *export* with skeletons via headless Blender (io_scene_fbx). trimesh/assimp
+# can't write a rigged FBX; Blender 4.2 LTS ships the Python 3.11 ABI this image
+# uses. See blender_fbx.py and output_format=fbx.
+bpy==4.2.0
diff --git a/workers/remesh/verify_fbx.py b/workers/remesh/verify_fbx.py
new file mode 100644
index 000000000..7f5833178
--- /dev/null
+++ b/workers/remesh/verify_fbx.py
@@ -0,0 +1,73 @@
+"""
+Verify that an exported FBX kept its rig — re-imports the file in headless
+Blender and asserts the skeleton, skin weights, and (optionally) blendshapes
+survived the GLB → FBX conversion. This is the round-trip check behind the
+"rigged FBX imports into Blender/Unity with its skeleton intact" requirement.
+
+A Unity import of the same file lights up the identical data: the armature
+becomes an Avatar's bone hierarchy, the per-vertex groups become skin weights,
+and shape keys become blendshapes — so a clean Blender re-import is the
+authoritative, automatable proxy for the Unity check.
+
+Usage:
+ python verify_fbx.py <model.fbx>
+
+Exit code 0 and a "PASS" report when a bone hierarchy + skin weights are
+present; non-zero with the reason otherwise. Run it anywhere `bpy` is
+installed — the remesh worker image already has it (see requirements.txt).
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import bpy
+
+
+def _reset() -> None:
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+
+
+def main() -> None:
+ if len(sys.argv) != 2:
+ raise SystemExit("usage: verify_fbx.py <model.fbx>")
+ path = Path(sys.argv[1])
+ if not path.exists():
+ raise SystemExit(f"verify_fbx: no such file: {path}")
+
+ _reset()
+ try:
+ bpy.ops.preferences.addon_enable(module="io_scene_fbx")
+ except Exception:
+ pass
+ bpy.ops.import_scene.fbx(filepath=str(path))
+
+ armatures = [o for o in bpy.data.objects if o.type == "ARMATURE"]
+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+
+ bone_count = sum(len(a.data.bones) for a in armatures)
+ skinned = [m for m in meshes if m.vertex_groups and len(m.vertex_groups) > 0]
+ shape_keys = sum(
+ (len(m.data.shape_keys.key_blocks) - 1) # minus the Basis key
+ for m in meshes
+ if m.data.shape_keys and m.data.shape_keys.key_blocks
+ )
+
+ print(f"armatures={len(armatures)} bones={bone_count} "
+ f"skinned_meshes={len(skinned)} blendshapes={shape_keys}")
+
+ problems = []
+ if bone_count == 0:
+ problems.append("no bones found (skeleton lost)")
+ if not skinned:
+ problems.append("no mesh has vertex groups (skin weights lost)")
+
+ if problems:
+ raise SystemExit("FAIL: " + "; ".join(problems))
+
+ print("PASS: skeleton + skin weights intact")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/workers/segment/__pycache__/main.cpython-312.pyc b/workers/segment/__pycache__/main.cpython-312.pyc
deleted file mode 100644
index 6ffab0c11..000000000
Binary files a/workers/segment/__pycache__/main.cpython-312.pyc and /dev/null differ
diff --git a/workers/segment/__pycache__/segment_core.cpython-312.pyc b/workers/segment/__pycache__/segment_core.cpython-312.pyc
deleted file mode 100644
index 8cbad8160..000000000
Binary files a/workers/segment/__pycache__/segment_core.cpython-312.pyc and /dev/null differ
diff --git a/workers/segment/__pycache__/worker_security.cpython-312.pyc b/workers/segment/__pycache__/worker_security.cpython-312.pyc
deleted file mode 100644
index 6b8be2088..000000000
Binary files a/workers/segment/__pycache__/worker_security.cpython-312.pyc and /dev/null differ
diff --git a/workers/stylize/__pycache__/main.cpython-312.pyc b/workers/stylize/__pycache__/main.cpython-312.pyc
deleted file mode 100644
index 4e7a54e49..000000000
Binary files a/workers/stylize/__pycache__/main.cpython-312.pyc and /dev/null differ
diff --git a/workers/stylize/__pycache__/worker_security.cpython-312.pyc b/workers/stylize/__pycache__/worker_security.cpython-312.pyc
deleted file mode 100644
index e635c5f4a..000000000
Binary files a/workers/stylize/__pycache__/worker_security.cpython-312.pyc and /dev/null differ
diff --git a/workers/texture/main.py b/workers/texture/main.py
index 70bcea92c..44b36f2ea 100644
--- a/workers/texture/main.py
+++ b/workers/texture/main.py
@@ -442,34 +442,261 @@ def _run_texturing(
return buf.getvalue()
-async def _process(
- task_id: str,
+# ── Region retexture (magic brush) ───────────────────────────────────────────────
+
+def _parse_hex_color(value: Optional[str]) -> Optional[tuple[int, int, int]]:
+ """Parse "#rrggbb" / "rrggbb" → (r, g, b). Returns None for falsy/invalid."""
+ if not value:
+ return None
+ s = value.strip().lstrip("#")
+ if len(s) == 3:
+ s = "".join(c * 2 for c in s)
+ if len(s) != 6:
+ return None
+ try:
+ return (int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
+ except ValueError:
+ return None
+
+
+def _decode_mask_bytes(mask_b64: Optional[str], mask_url: Optional[str]) -> bytes:
+ """Resolve the UV mask payload from inline base64 or a public URL."""
+ if mask_b64:
+ raw = mask_b64.strip()
+ # Tolerate a data: URL prefix from the browser canvas toDataURL().
+ if raw.startswith("data:"):
+ raw = raw.split(",", 1)[-1]
+ try:
+ data = base64.b64decode(raw, validate=False)
+ except (binascii.Error, ValueError) as exc:
+ raise ValueError("mask_b64 is not valid base64") from exc
+ if not data:
+ raise ValueError("mask_b64 decoded to empty bytes")
+ if len(data) > MAX_MASK_BYTES:
+ raise ValueError("mask exceeds size limit")
+ return data
+ if mask_url:
+ return fetch_remote_bytes(mask_url, timeout=30, max_bytes=MAX_MASK_BYTES)
+ raise ValueError("a region mask is required (mask_b64 or mask)")
+
+
+def _build_masks(
+ mask_bytes: bytes, size: tuple[int, int], feather: int
+) -> tuple[Image.Image, Image.Image]:
+ """Turn a raw mask PNG into (inpaint_mask, blend_alpha) at `size`.
+
+ inpaint_mask — a slightly dilated hard mask (white = regenerate). The dilation
+ gives SDXL a margin past the painted edge so the new content transitions
+ into the surrounding texture instead of butting hard against it.
+ blend_alpha — a feathered 0–255 ramp used to composite the inpaint result
+ back over the untouched base, so the interior is fully replaced and the
+ boundary fades out smoothly (invisible seam). Texels at alpha 0 are left
+ bit-identical.
+ """
+ src = Image.open(io.BytesIO(mask_bytes)).convert("L").resize(size, Image.LANCZOS)
+ arr = np.asarray(src, dtype=np.uint8)
+ hard = (arr > 127).astype(np.uint8) * 255
+ if not hard.any():
+ raise ValueError("mask is empty — paint a region before applying")
+
+ feather = max(1, int(feather))
+ hard_img = Image.fromarray(hard, mode="L")
+
+ # Dilate via MaxFilter (odd kernel) then a light blur for the inpaint mask.
+ k = max(3, (feather // 2) * 2 + 1)
+ inpaint_mask = hard_img.filter(ImageFilter.MaxFilter(min(k, 25)))
+ inpaint_mask = inpaint_mask.point(lambda p: 255 if p > 40 else 0)
+
+ # Feathered alpha for the final composite.
+ blend_alpha = hard_img.filter(ImageFilter.GaussianBlur(radius=feather))
+ return inpaint_mask, blend_alpha
+
+
+def _load_textured_mesh(url: str):
+ """Load a GLB preserving its original UVs/material (no unwrap, no repack).
+
+ Region edits must operate in the exact UV space the caller painted against,
+ so we deliberately avoid trimesh's processing/concatenation here. Returns
+ (scene, geometry_name, mesh) — for a bare mesh we wrap it in a one-item
+ scene so the export path is uniform.
+ """
+ import trimesh
+
+ data = fetch_remote_bytes(url, timeout=60, max_bytes=128 * 1024 * 1024)
+ suffix = Path(url.split("?")[0]).suffix.lower() or ".glb"
+ loaded = trimesh.load(
+ io.BytesIO(data), file_type=suffix.lstrip("."), process=False
+ )
+
+ if isinstance(loaded, trimesh.Scene):
+ geoms = [
+ (name, g)
+ for name, g in loaded.geometry.items()
+ if isinstance(g, trimesh.Trimesh)
+ ]
+ if not geoms:
+ raise ValueError("GLB contains no mesh geometry")
+ # Prefer a geometry that already carries UVs + a texture; among those
+ # (or all, as a fallback) pick the largest by face count.
+ textured = [
+ (n, g)
+ for n, g in geoms
+ if getattr(g.visual, "uv", None) is not None
+ ]
+ name, mesh = max(textured or geoms, key=lambda ng: len(ng[1].faces))
+ return loaded, name, mesh
+
+ scene = trimesh.Scene(geometry={"mesh": loaded})
+ return scene, "mesh", loaded
+
+
+def _existing_base_texture(mesh, texture_size: int) -> Image.Image:
+ """Pull the mesh's baseColour texture, or synthesize a flat base from its
+ base-colour factor / vertex colours so unmasked regions stay coherent."""
+ visual = mesh.visual
+ mat = getattr(visual, "material", None)
+ base_img = None
+ if mat is not None:
+ base_img = getattr(mat, "baseColorTexture", None) or getattr(mat, "image", None)
+
+ if base_img is not None:
+ return base_img.convert("RGB")
+
+ # No texture present — fall back to a solid base from the material factor.
+ color = (180, 180, 180)
+ factor = getattr(mat, "baseColorFactor", None) if mat is not None else None
+ if factor is not None and len(factor) >= 3:
+ color = tuple(int(max(0.0, min(1.0, float(c))) * 255) for c in factor[:3])
+ return Image.new("RGB", (texture_size, texture_size), color)
+
+
+def _inpaint_region(
+ base_rgb: Image.Image,
+ inpaint_mask: Image.Image,
+ blend_alpha: Image.Image,
+ prompt: str,
+ negative_prompt: str,
+ color: Optional[tuple[int, int, int]],
+ strength: float,
+ seed: int,
+) -> Image.Image:
+ """Run SDXL inpainting on the masked region and composite it back over the
+ base atlas through the feathered alpha. Returns the new full-size atlas."""
+ work_size = base_rgb.size # (w, h) of the working atlas
+
+ init = base_rgb.copy()
+ # A colour hint primes the region so SDXL respects the requested hue.
+ if color is not None:
+ tint = Image.new("RGB", work_size, color)
+ init = Image.composite(tint, init, inpaint_mask)
+
+ infer = (INPAINT_INFER_SIZE, INPAINT_INFER_SIZE)
+ init_small = init.resize(infer, Image.LANCZOS)
+ mask_small = inpaint_mask.resize(infer, Image.NEAREST)
+
+ generator = torch.Generator(device="cuda").manual_seed(seed)
+ result = _inpaint_pipe(
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ image=init_small,
+ mask_image=mask_small,
+ strength=float(strength),
+ num_inference_steps=30,
+ guidance_scale=7.5,
+ width=infer[0],
+ height=infer[1],
+ generator=generator,
+ )
+ painted = result.images[0].resize(work_size, Image.LANCZOS).convert("RGB")
+
+ # Composite: interior fully painted, boundary ramps, exterior untouched.
+ return Image.composite(painted, base_rgb, blend_alpha.resize(work_size, Image.LANCZOS))
+
+
+def _run_region_texturing(
mesh_url: str,
prompt: str,
negative_prompt: str,
- num_views: int,
+ mask_b64: Optional[str],
+ mask_url: Optional[str],
+ color_hex: Optional[str],
texture_size: int,
-) -> None:
+ strength: float,
+ feather: int,
+ seed: int,
+) -> bytes:
+ import trimesh
+
+ color = _parse_hex_color(color_hex)
+ if not prompt and color is None:
+ raise ValueError("provide a prompt and/or a color for the region")
+
+ scene, geom_name, mesh = _load_textured_mesh(mesh_url)
+
+ uv = getattr(mesh.visual, "uv", None)
+ base_rgb = _existing_base_texture(mesh, texture_size)
+ # Work at the larger of the requested size and the existing texture so we
+ # never throw away detail the source already has outside the edit region.
+ work = max(texture_size, min(max(base_rgb.size), 2048))
+ base_rgb = base_rgb.resize((work, work), Image.LANCZOS)
+
+ if uv is None:
+ # No UVs at all — we can still texture, but the painted mask can't be
+ # trusted to align, so unwrap and treat this as a flat fill of the region.
+ mesh = mesh.unwrap()
+ uv = mesh.visual.uv
+
+ mask_bytes = _decode_mask_bytes(mask_b64, mask_url)
+ inpaint_mask, blend_alpha = _build_masks(mask_bytes, (work, work), feather)
+
+ log.info(
+ "Region inpaint: atlas=%dpx feather=%d strength=%.2f color=%s",
+ work, feather, strength, color_hex or "none",
+ )
+ _load_inpaint_pipeline()
+ full_prompt = prompt
+ if color is not None and prompt:
+ full_prompt = f"{prompt}, predominantly {color_hex} colour"
+ new_atlas = _inpaint_region(
+ base_rgb, inpaint_mask, blend_alpha, full_prompt, negative_prompt,
+ color, strength, seed,
+ )
+
+ # Preserve the existing material; swap only the baseColour texture.
+ mat = getattr(mesh.visual, "material", None)
+ if isinstance(mat, trimesh.visual.material.PBRMaterial):
+ mat.baseColorTexture = new_atlas
+ else:
+ mat = trimesh.visual.material.PBRMaterial(
+ baseColorTexture=new_atlas, metallicFactor=0.0, roughnessFactor=0.9
+ )
+ mesh.visual = trimesh.visual.TextureVisuals(uv=uv, material=mat)
+ scene.geometry[geom_name] = mesh
+
+ buf = io.BytesIO()
+ scene.export(buf, file_type="glb")
+ return buf.getvalue()
+
+
+# ── Task runner ───────────────────────────────────────────────────────────────────
+
+async def _run_task(task_id: str, runner: Callable[[], bytes], label: str) -> None:
+ """Shared async wrapper: run a blocking GLB-producing job on the executor,
+ upload the result to GCS, and record terminal status on the task."""
async with _sem:
_tasks[task_id]["status"] = "running"
loop = asyncio.get_event_loop()
t0 = time.time()
try:
- glb_bytes = await loop.run_in_executor(
- None,
- _run_texturing,
- mesh_url,
- prompt,
- negative_prompt,
- num_views,
- texture_size,
- )
+ glb_bytes = await loop.run_in_executor(None, runner)
blob_name = f"textured/{task_id}.glb"
blob = _bucket.blob(blob_name)
await loop.run_in_executor(
None,
- lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),
+ lambda: blob.upload_from_string(
+ glb_bytes, content_type="model/gltf-binary"
+ ),
)
result_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"
@@ -480,16 +707,54 @@ async def _process(
"bytes": len(glb_bytes),
"elapsed_ms": int(elapsed * 1000),
})
- log.info("[%s] done in %.1fs — %d bytes", task_id, elapsed, len(glb_bytes))
+ log.info("[%s] %s done in %.1fs — %d bytes", task_id, label, elapsed, len(glb_bytes))
except Exception as exc:
_tasks[task_id].update({
"status": "failed",
- "error": safe_error(exc, context=f"[{task_id}] texture"),
+ "error": safe_error(exc, context=f"[{task_id}] {label}"),
"elapsed_ms": int((time.time() - t0) * 1000),
})
+async def _process(
+ task_id: str,
+ mesh_url: str,
+ prompt: str,
+ negative_prompt: str,
+ num_views: int,
+ texture_size: int,
+) -> None:
+ await _run_task(
+ task_id,
+ lambda: _run_texturing(mesh_url, prompt, negative_prompt, num_views, texture_size),
+ label="texture",
+ )
+
+
+async def _process_region(
+ task_id: str,
+ mesh_url: str,
+ prompt: str,
+ negative_prompt: str,
+ mask_b64: Optional[str],
+ mask_url: Optional[str],
+ color_hex: Optional[str],
+ texture_size: int,
+ strength: float,
+ feather: int,
+ seed: int,
+) -> None:
+ await _run_task(
+ task_id,
+ lambda: _run_region_texturing(
+ mesh_url, prompt, negative_prompt, mask_b64, mask_url,
+ color_hex, texture_size, strength, feather, seed,
+ ),
+ label="retexture_region",
+ )
+
+
class TextureRequest(BaseModel):
mesh: str = Field(..., description="https URL to input GLB mesh")
prompt: str = Field(..., min_length=3, max_length=500)
@@ -530,6 +795,61 @@ async def texture_mesh(
return {"task_id": task_id, "status": "queued"}
+class RegionTextureRequest(BaseModel):
+ mesh: str = Field(..., description="https URL to a textured GLB mesh")
+ prompt: str = Field(default="", max_length=500, description="What to paint into the region")
+ negative_prompt: str = Field(default="blurry, low quality, distorted, watermark, seam")
+ mask_b64: Optional[str] = Field(default=None, description="UV-space mask PNG, base64 (white = edit)")
+ mask: Optional[str] = Field(default=None, description="Public https URL to the UV mask PNG")
+ color: Optional[str] = Field(default=None, max_length=9, description='Target colour "#rrggbb"')
+ texture_size: int = Field(default=1024)
+ strength: float = Field(default=0.85, ge=0.2, le=1.0)
+ feather: int = Field(default=24, ge=1, le=128)
+ seed: int = Field(default=0, ge=0)
+
+ @field_validator("texture_size")
+ @classmethod
+ def validate_size(cls, v: int) -> int:
+ if v not in (512, 1024, 2048):
+ raise ValueError("texture_size must be 512, 1024, or 2048")
+ return v
+
+
[email protected]("/retexture_region", status_code=202)
+async def retexture_region(
+ body: RegionTextureRequest,
+ background_tasks: BackgroundTasks,
+ authorization: str = Header(...),
+) -> dict:
+ _require_api_key(authorization)
+ if not body.mask_b64 and not body.mask:
+ raise HTTPException(status_code=400, detail="a region mask is required (mask_b64 or mask)")
+ if not body.prompt and not _parse_hex_color(body.color):
+ raise HTTPException(status_code=400, detail="provide a prompt and/or a valid color")
+ task_id = str(uuid.uuid4())
+ _tasks[task_id] = {
+ "task_id": task_id,
+ "status": "queued",
+ "prompt": body.prompt,
+ "kind": "region",
+ }
+ background_tasks.add_task(
+ _process_region,
+ task_id,
+ body.mesh,
+ body.prompt,
+ body.negative_prompt,
+ body.mask_b64,
+ body.mask,
+ body.color,
+ body.texture_size,
+ body.strength,
+ body.feather,
+ body.seed,
+ )
+ return {"task_id": task_id, "status": "queued"}
+
+
@app.get("/tasks/{task_id}")
async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
_require_api_key(authorization)
@@ -546,4 +866,5 @@ async def health() -> dict:
"service": "texture",
"gpu_available": torch.cuda.is_available(),
"model_loaded": _pipe is not None,
+ "inpaint_loaded": _inpaint_pipe is not None,
}