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.

Animations page, forge game-ready, pose studio, skill purchase, avatar updates

nirholasf97683241155
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fd32b477a..542695172 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Every agent now has a dedicated wallet hub** — Each 3D agent's self-custodied Solana wallet now has one home: a tabbed Agent Wallet hub — Balance, Deposit, Trade, Snipe, Pay, and Withdraw — reachable from the agent's profile and right after you create one. The Balance tab is live now, showing the real on-chain SOL balance with a USD estimate and recent activity, refreshing on its own and degrading gracefully if the network is briefly unreachable. Behind the scenes every agent is guaranteed a wallet: older agents that predated automatic wallets are backfilled, and the agent API now reports whether each agent's wallet is ready. The remaining tabs are wired up across the next releases. `[feature]`
- **Everyone at a location now sees your IRL agent in the same real spot** — three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry. (`/irl`) `[feature, improvement]`
- **Filter the marketplace by Free or Paid** — The marketplace now has working Free / Paid filters. "Paid" surfaces every agent that charges in any way — a one-time price to own it or per-call pricing on its skills — and "Free" shows the rest. Filtering happens on the server, so the result count and "load more" stay accurate no matter how many pages deep you browse, and your choice is saved in the URL so you can bookmark or share a filtered view. (`/marketplace`) `[feature, improvement]`
+- **Game-Ready export in Forge — one click to engine-ready GLB + FBX** — Any model you generate or upload in Forge can now be turned into a clean, engine-ready asset in one click. Pick Quad retopology (field-aligned QuadriFlow edge loops that rig and animate well) or Tri low-poly (silhouette-preserving, with the texture re-baked), set a poly budget with 5k / 15k / 50k presets, and export a textured GLB plus an FBX for Unity and Unreal together. You see the before→after poly count (e.g. 28,400 → 5,012) and can flip on a live wireframe to inspect the new topology right in the viewer. Files are served from our own CDN. (`/forge`) `[feature]`
- **iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk** — iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated. (`/irl`) `[improvement]`
- **IRL agents now materialize as you walk up to them** — On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going. (`/irl`) `[fix, improvement]`
- **IRL agents now visibly react when someone engages them** — Walk past an agent placed in the real world and it now feels alive: the moment anyone standing nearby taps it, leaves it a message, or pays it, the agent does a little perk-up and a reaction floats up off its head — a 💜 for a glance, a ✨ 'paid' burst for a real on-chain payment, a 💬 for a message — and everyone viewing that spot sees it at once, not just the person who acted. A busy agent looks busy, which is the whole point of putting one somewhere public. Rapid taps are smoothed so the same person can't spam the reaction, while payments and messages always come through. The reaction is purely a visual flourish — it carries no one's location or wallet — and if your connection drops to the slower fallback the interaction is still recorded for the owner; only the live animation is skipped. (`/irl`) `[feature]`
diff --git a/PROGRESS.md b/PROGRESS.md
new file mode 100644
index 000000000..02486044f
--- /dev/null
+++ b/PROGRESS.md
@@ -0,0 +1,28 @@
+# Progress
+
+Running log of notable product work. Newest first.
+
+## 2026-06-17 — Game-Ready export tier in Forge
+
+Surfaced the topology pipeline that already shipped in `workers/remesh/`
+(QuadriFlow quad retopology + silhouette-preserving smart low-poly with UV
+re-unwrap and texture re-bake) as a one-click **Game-Ready** output in Forge.
+
+- `api/forge-gameready.js` — follow-up endpoint that drives the remesh worker:
+ quad → QuadriFlow, tri → smart low-poly, poly budget → `target_faces`, PBR
+ re-bake at the chosen texture size. Fans out one worker task per requested
+ format so GLB and FBX are produced together, mirrors the results into R2 under
+ the model's namespace, and exposes a single aggregated poll. A rigged FBX is
+ available via the worker's geometry-preserving `convert` path (retopology
+ rebuilds geometry, so a retopologized FBX is a clean re-riggable mesh).
+- `api/_lib/forge-tiers.js` — Game-Ready registered as a catalog-visible export
+ option (`OUTPUTS`), advertised in `GET /api/forge?catalog` with honest ETA +
+ price and a `configured` flag tied to the remesh worker env.
+- `src/forge-gameready.js` + `pages/forge.html` — Game-Ready action in the result
+ view: topology toggle, poly-budget slider with 5k/15k/50k presets defaulted to
+ the model's current size, texture-size + format pickers, real job polling, the
+ before→after poly delta game devs screenshot, per-format downloads, and a live
+ Three.js wireframe toggle to inspect the new topology in the viewer.
+- Tests: `tests/api/forge-gameready.test.js` (multi-format fan-out, poll
+ aggregation, R2 mirror, rig-preserving FBX path) and Game-Ready catalog cases
+ in `tests/api/forge-tiers.test.js`.
diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.js
index 414a5531c..a15b8a146 100644
--- a/api/_lib/purchase-confirm.js
+++ b/api/_lib/purchase-confirm.js
@@ -440,9 +440,34 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfo
UPDATE skill_purchases
SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now()
WHERE id = ${pur.id} AND status = 'pending'
- RETURNING id
+ RETURNING id, kind, valid_until
`;
if (updated.length > 0) {
+ // Grant skill access. Permanent purchases get a non-expiring grant;
+ // time-passes expire at their valid_until window. The skill_access_grants
+ // table is the authoritative access record; skill_purchases tracks payment.
+ const confirmedRow = updated[0];
+ const grantExpiresAt = confirmedRow.kind === 'time_pass' && confirmedRow.valid_until
+ ? confirmedRow.valid_until
+ : null;
+ try {
+ await sql`
+ INSERT INTO skill_access_grants
+ (user_id, agent_id, skill_name, purchase_id, expires_at)
+ VALUES
+ (${pur.user_id}, ${pur.agent_id}, ${pur.skill}, ${pur.id}, ${grantExpiresAt})
+ ON CONFLICT (user_id, agent_id, skill_name) DO UPDATE
+ SET expires_at = EXCLUDED.expires_at,
+ purchase_id = EXCLUDED.purchase_id,
+ updated_at = now()
+ `;
+ } catch (e) {
+ // If the table doesn't exist (pre-migration) don't block payment confirm —
+ // access is still tracked via skill_purchases status = 'confirmed'.
+ if (!e?.message?.includes('does not exist')) throw e;
+ console.warn('[purchase-confirm] skill_access_grants table missing, skipping grant');
+ }
+
await sql`
INSERT INTO agent_payment_intents
(id, payer_user_id, agent_id, currency_mint, amount, status, expires_at,
diff --git a/api/payments/prepare-skill-purchase.js b/api/payments/prepare-skill-purchase.js
index 7f2f2fe21..729c47c71 100644
--- a/api/payments/prepare-skill-purchase.js
+++ b/api/payments/prepare-skill-purchase.js
@@ -1,20 +1,33 @@
/**
* POST /api/payments/prepare-skill-purchase
- * Builds and returns a base64-serialised Solana legacy transaction that the
- * browser wallet can sign and send. The buyer's public key must be provided
- * in the request body so the fee-payer and ATA source can be set correctly.
+ * Builds and returns a base64-serialised Solana VersionedTransaction that the
+ * browser wallet signs and sends. The platform pre-signs as fee-payer so the
+ * buyer needs no SOL — only the USDC for the skill price.
+ *
+ * Fee split: (price - platform_fee) → creator, platform_fee → treasury.
+ * Both legs ride in one atomic transaction alongside the reference key.
*
* Body: { agentId, skillName, buyerPublicKey }
- * Returns: { transaction (base64), reference, recipient, amount, currency_mint }
+ * Returns: { transaction (base64), reference, recipient, amount, creator_amount,
+ * currency_mint, fee? }
*/
-import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
-import { solanaConnection } from '../_lib/solana/connection.js';
-import { getAssociatedTokenAddressSync, createTransferCheckedInstruction, getMint } from '@solana/spl-token';
+import {
+ Keypair, PublicKey,
+ TransactionMessage, VersionedTransaction,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ createTransferCheckedInstruction,
+ getMint,
+} from '@solana/spl-token';
+import { solanaConnection } from '../_lib/solana/connection.js';
import { sql } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
+import { resolveMarketplaceFee } from '../_lib/marketplace-platform-fee.js';
+import { decodeSecretKey } from '../_lib/solana-signers.js';
import { z } from 'zod';
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -27,6 +40,28 @@ const bodySchema = z.object({
const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+// Load the platform payer keypair that co-signs as fee-payer (gasless UX).
+// Prefers MARKETPLACE_PAYER_KEYPAIR; falls back to PLATFORM_TREASURY_KEYPAIR.
+// When neither is configured the endpoint still works but the buyer pays gas.
+let _payerKeypair = undefined; // undefined = not yet resolved, null = not configured
+async function resolvePlatformPayer() {
+ if (_payerKeypair !== undefined) return _payerKeypair;
+ const secret =
+ process.env.MARKETPLACE_PAYER_KEYPAIR ||
+ process.env.PLATFORM_TREASURY_KEYPAIR ||
+ process.env.TREASURY_KEYPAIR ||
+ '';
+ if (!secret) { _payerKeypair = null; return null; }
+ const bytes = await decodeSecretKey(secret);
+ if (!bytes) { _payerKeypair = null; return null; }
+ try {
+ _payerKeypair = Keypair.fromSecretKey(bytes);
+ } catch {
+ _payerKeypair = null;
+ }
+ return _payerKeypair;
+}
+
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
@@ -55,7 +90,7 @@ export default wrap(async (req, res) => {
// Fetch active price
const [price] = await sql`
- SELECT amount, currency_mint, chain
+ SELECT amount, currency_mint, chain, mint_decimals
FROM agent_skill_prices
WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true
LIMIT 1
@@ -84,61 +119,104 @@ export default wrap(async (req, res) => {
}
if (!recipient) return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');
- // Mint a reference keypair for Solana Pay tracking
+ // Platform fee
+ const grossAtomics = BigInt(price.amount);
+ const feeInfo = await resolveMarketplaceFee({ grossAtomics });
+ const platformFeeAtomics = feeInfo ? feeInfo.feeAtomics : 0n;
+ const creatorAtomics = grossAtomics - platformFeeAtomics;
+
+ // Reference keypair for Solana Pay tracking
const referenceKeypair = Keypair.generate();
const referenceKey = referenceKeypair.publicKey;
const reference = referenceKey.toBase58();
- // Record pending purchase before building tx so confirm can find it
+ // Record pending purchase
await sql`
- INSERT INTO skill_purchases (user_id, agent_id, skill, status, reference, amount, currency_mint, chain)
- VALUES (${auth.userId}, ${agentId}, ${skillName}, 'pending', ${reference},
- ${price.amount}, ${price.currency_mint}, 'solana')
+ INSERT INTO skill_purchases
+ (user_id, agent_id, skill, status, reference, amount, currency_mint, chain,
+ platform_fee_amount, platform_fee_wallet)
+ VALUES
+ (${auth.userId}, ${agentId}, ${skillName}, 'pending', ${reference},
+ ${price.amount}, ${price.currency_mint}, 'solana',
+ ${platformFeeAtomics.toString()},
+ ${feeInfo ? feeInfo.recipient.toBase58() : null})
ON CONFLICT DO NOTHING
`;
- // Build the SPL token transfer transaction
+ // Build the SPL token transfer instructions
const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
- const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));
- const decimals = mintInfo.decimals;
+ const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));
+ const decimals = mintInfo.decimals;
- const buyer = new PublicKey(buyerPublicKey);
- const recipientKey = new PublicKey(recipient);
- const mintKey = new PublicKey(price.currency_mint);
+ const buyer = new PublicKey(buyerPublicKey);
+ const mintKey = new PublicKey(price.currency_mint);
+ const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);
- const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);
- const toAta = getAssociatedTokenAddressSync(mintKey, recipientKey);
+ const creatorKey = new PublicKey(recipient);
+ const toAta = getAssociatedTokenAddressSync(mintKey, creatorKey);
- const ix = createTransferCheckedInstruction(
- fromAta,
- mintKey,
- toAta,
- buyer,
- BigInt(price.amount),
- decimals,
+ // Creator leg — append reference key so findReference can locate this tx
+ const creatorIx = createTransferCheckedInstruction(
+ fromAta, mintKey, toAta, buyer, creatorAtomics, decimals,
);
- // Append reference key as non-signer so findReference can locate this tx
- ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
+ creatorIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
+
+ const instructions = [creatorIx];
+
+ // Platform fee leg (same tx — atomic)
+ if (platformFeeAtomics > 0n && feeInfo?.recipient) {
+ const treasuryAta = getAssociatedTokenAddressSync(mintKey, feeInfo.recipient);
+ instructions.push(
+ createTransferCheckedInstruction(
+ fromAta, mintKey, treasuryAta, buyer, platformFeeAtomics, decimals,
+ ),
+ );
+ }
+
+ // Platform co-signs as fee-payer (gasless for the buyer).
+ // Falls back to buyer-pays if no payer keypair is configured.
+ const platformPayer = await resolvePlatformPayer();
+ const feePayer = platformPayer ? platformPayer.publicKey : buyer;
+
+ const messageV0 = new TransactionMessage({
+ payerKey: feePayer,
+ recentBlockhash: blockhash,
+ instructions,
+ }).compileToV0Message();
+
+ const tx = new VersionedTransaction(messageV0);
+
+ if (platformPayer) {
+ tx.sign([platformPayer]);
+ }
- const tx = new Transaction({
- feePayer: buyer,
- recentBlockhash: blockhash,
- lastValidBlockHeight,
- }).add(ix);
+ const serialized = Buffer.from(tx.serialize());
- const serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });
+ const feeBlock = platformFeeAtomics > 0n && feeInfo
+ ? {
+ fee: {
+ recipient: feeInfo.recipient.toBase58(),
+ amount: platformFeeAtomics.toString(),
+ bps: feeInfo.bps,
+ },
+ }
+ : {};
return json(res, 200, {
data: {
- transaction: serialized.toString('base64'),
+ transaction: serialized.toString('base64'),
reference,
recipient,
- amount: String(price.amount),
- currency_mint: price.currency_mint,
- label: `Skill: ${skillName.slice(0, 40)}`,
- message: `Unlock '${skillName}' for this agent`,
+ amount: String(price.amount),
+ creator_amount: creatorAtomics.toString(),
+ currency_mint: price.currency_mint,
+ mint_decimals: price.mint_decimals ?? decimals,
+ gasless: !!platformPayer,
+ label: `Skill: ${skillName.slice(0, 40)}`,
+ message: `Unlock '${skillName}' for this agent`,
+ ...feeBlock,
},
});
});
diff --git a/data/changelog.json b/data/changelog.json
index 209082aad..679d33c18 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-17",
+ "title": "Game-Ready export in Forge — one click to engine-ready GLB + FBX",
+ "summary": "Any model you generate or upload in Forge can now be turned into a clean, engine-ready asset in one click. Pick Quad retopology (field-aligned QuadriFlow edge loops that rig and animate well) or Tri low-poly (silhouette-preserving, with the texture re-baked), set a poly budget with 5k / 15k / 50k presets, and export a textured GLB plus an FBX for Unity and Unreal together. You see the before→after poly count (e.g. 28,400 → 5,012) and can flip on a live wireframe to inspect the new topology right in the viewer. Files are served from our own CDN.",
+ "tags": ["feature"],
+ "link": "/forge"
+ },
{
"date": "2026-06-17",
"title": "Buy a skill, get an on-chain NFT receipt in your wallet",
diff --git a/pages/agent-edit.html b/pages/agent-edit.html
index 533dc7bb5..cef67a7c3 100644
--- a/pages/agent-edit.html
+++ b/pages/agent-edit.html
@@ -1256,6 +1256,47 @@
aria-live="polite"
></span>
</div>
+
+ <!-- Subscription Plans -->
+ <div class="form-group" style="margin-top: 2rem; border-top: 1px solid rgba(255,255,255,0.08); padding-top: 1.5rem;">
+ <label class="form-label">Subscription Plans</label>
+ <p class="note" style="font-size: 0.764rem; color: rgba(255,255,255,0.4); margin-top: -0.5rem; margin-bottom: 1rem;">Offer recurring access to your agent's skills. Subscribers pay a fixed USDC amount monthly or weekly. Up to 3 active plans.</p>
+ <div id="subscription-plans-list" style="display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 0.75rem;">
+ <div class="muted">Loading plans…</div>
+ </div>
+ <button class="btn-ghost" id="show-create-plan-btn" style="align-self: flex-start;">+ New Plan</button>
+ </div>
+
+ <!-- Plan editor (hidden until triggered) -->
+ <div id="plan-editor" style="display:none; margin-top: 1rem; padding: 1rem; border: 1px solid rgba(255,255,255,0.12); border-radius: 8px; background: rgba(255,255,255,0.03);">
+ <input type="hidden" id="plan-editor-id">
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; margin-bottom: 0.75rem;">
+ <div class="form-group" style="margin: 0;">
+ <label class="form-label" style="font-size: 0.764rem;" for="plan-name-input">Plan Name</label>
+ <input class="form-input" id="plan-name-input" type="text" placeholder="e.g. Pro" maxlength="80">
+ </div>
+ <div class="form-group" style="margin: 0;">
+ <label class="form-label" style="font-size: 0.764rem;" for="plan-interval-input">Billing</label>
+ <select class="form-input" id="plan-interval-input">
+ <option value="monthly">Monthly</option>
+ <option value="weekly">Weekly</option>
+ </select>
+ </div>
+ </div>
+ <div class="form-group" style="margin-bottom: 0.75rem;">
+ <label class="form-label" style="font-size: 0.764rem;" for="plan-price-input">Price (USD)</label>
+ <input class="form-input" id="plan-price-input" type="number" min="0.99" max="999" step="0.01" placeholder="9.99" style="max-width: 140px;">
+ </div>
+ <div class="form-group" style="margin-bottom: 0.75rem;">
+ <label class="form-label" style="font-size: 0.764rem;" for="plan-perks-input">Perks (one per line)</label>
+ <textarea class="form-textarea" id="plan-perks-input" rows="3" placeholder="Unlimited API calls&#10;Priority queue&#10;Early access to new skills" style="font-size: 0.764rem;"></textarea>
+ </div>
+ <div style="display: flex; gap: 0.5rem; align-items: center;">
+ <button class="btn-primary" id="plan-save-btn" style="font-size: 0.764rem; padding: 0.4rem 0.9rem;">Save Plan</button>
+ <button class="btn-ghost" id="plan-cancel-btn" style="font-size: 0.764rem; padding: 0.4rem 0.9rem;">Cancel</button>
+ <span class="form-status" id="plan-status" role="status" aria-live="polite" style="font-size: 0.764rem;"></span>
+ </div>
+ </div>
</section>
<!-- Autopilot tab -->
diff --git a/pages/animations.html b/pages/animations.html
new file mode 100644
index 000000000..45a193389
--- /dev/null
+++ b/pages/animations.html
@@ -0,0 +1,494 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Animation Gallery · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="Browse community-authored animations for three.ws avatars. Preview, remix, and use any public animation in the studio." />
+ <meta name="theme-color" content="#000000" />
+ <link rel="canonical" href="https://three.ws/animations" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Animation Gallery · three.ws" />
+ <meta property="og:description" content="Browse community animations for three.ws avatars. Preview and use in the Animation Studio." />
+ <meta property="og:url" content="https://three.ws/animations" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Animation Gallery · three.ws" />
+ <meta name="twitter:description" content="Browse community animations for three.ws avatars." />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+
+ <style>
+ :root {
+ --ag-card-w: 280px;
+ --ag-preview-h: 340px;
+ }
+
+ .ag-page {
+ min-height: 100vh;
+ background: var(--bg, #000);
+ color: var(--text, #fafafa);
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ }
+
+ /* ── Hero ──────────────────────────────────────────────────────── */
+ .ag-hero {
+ padding: 64px 24px 40px;
+ max-width: 900px;
+ margin: 0 auto;
+ }
+ .ag-hero-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 10px;
+ background: rgba(255,255,255,0.06);
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: 20px;
+ font-size: 11px;
+ color: var(--text-2, #a1a1aa);
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ margin-bottom: 18px;
+ }
+ .ag-hero-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #4ade80;
+ animation: ag-pulse 2.4s ease-out infinite;
+ }
+ @keyframes ag-pulse {
+ 0%,100% { opacity: 1; }
+ 50% { opacity: 0.35; }
+ }
+ .ag-hero h1 {
+ font-size: clamp(28px, 5vw, 44px);
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin: 0 0 12px;
+ line-height: 1.1;
+ }
+ .ag-hero p {
+ color: var(--text-2, #a1a1aa);
+ font-size: 15px;
+ margin: 0 0 24px;
+ max-width: 520px;
+ }
+ .ag-hero-actions {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+ }
+ .ag-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 9px 18px;
+ border-radius: 8px;
+ font-size: 13px;
+ font-weight: 500;
+ text-decoration: none;
+ border: none;
+ cursor: pointer;
+ transition: opacity 0.15s, background 0.15s;
+ }
+ .ag-btn:focus-visible {
+ outline: 2px solid var(--focus-ring-color, #fff);
+ outline-offset: 2px;
+ }
+ .ag-btn--primary {
+ background: #fff;
+ color: #000;
+ }
+ .ag-btn--primary:hover { background: #e5e5e5; }
+ .ag-btn--secondary {
+ background: rgba(255,255,255,0.08);
+ color: var(--text, #fafafa);
+ border: 1px solid rgba(255,255,255,0.12);
+ }
+ .ag-btn--secondary:hover { background: rgba(255,255,255,0.12); }
+
+ /* ── Toolbar ──────────────────────────────────────────────────── */
+ .ag-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0 24px 24px;
+ max-width: 1200px;
+ margin: 0 auto;
+ flex-wrap: wrap;
+ }
+ .ag-search-wrap {
+ position: relative;
+ flex: 1;
+ min-width: 200px;
+ max-width: 360px;
+ }
+ .ag-search {
+ width: 100%;
+ padding: 9px 34px 9px 36px;
+ background: rgba(255,255,255,0.06);
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: 8px;
+ color: var(--text, #fafafa);
+ font-size: 13px;
+ outline: none;
+ box-sizing: border-box;
+ transition: border-color 0.15s;
+ }
+ .ag-search:focus { border-color: rgba(255,255,255,0.3); }
+ .ag-search::placeholder { color: var(--text-3, #71717a); }
+ .ag-search-icon {
+ position: absolute;
+ left: 11px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--text-3, #71717a);
+ pointer-events: none;
+ }
+ .ag-filter-chips {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .ag-chip {
+ padding: 6px 12px;
+ border-radius: 20px;
+ font-size: 12px;
+ border: 1px solid rgba(255,255,255,0.1);
+ background: transparent;
+ color: var(--text-2, #a1a1aa);
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+ }
+ .ag-chip:hover { background: rgba(255,255,255,0.06); color: var(--text, #fafafa); }
+ .ag-chip[aria-selected="true"] {
+ background: #fff;
+ color: #000;
+ border-color: #fff;
+ }
+ .ag-chip:focus-visible {
+ outline: 2px solid var(--focus-ring-color, #fff);
+ outline-offset: 2px;
+ }
+
+ /* ── Grid ──────────────────────────────────────────────────────── */
+ .ag-content {
+ max-width: 1200px;
+ margin: 0 auto;
+ padding: 0 24px 80px;
+ }
+ .ag-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(var(--ag-card-w), 1fr));
+ gap: 20px;
+ }
+
+ /* ── Card ──────────────────────────────────────────────────────── */
+ .ag-card {
+ background: rgba(255,255,255,0.03);
+ border: 1px solid rgba(255,255,255,0.08);
+ border-radius: 14px;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ transition: border-color 0.2s, transform 0.2s;
+ position: relative;
+ }
+ .ag-card:hover {
+ border-color: rgba(255,255,255,0.18);
+ transform: translateY(-2px);
+ }
+ .ag-card:focus-within {
+ outline: 2px solid rgba(255,255,255,0.4);
+ outline-offset: 2px;
+ }
+
+ /* Thumbnail / preview */
+ .ag-card-preview {
+ position: relative;
+ aspect-ratio: 3/4;
+ background: rgba(255,255,255,0.04);
+ overflow: hidden;
+ cursor: pointer;
+ }
+ .ag-card-thumb {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .ag-card-thumb-placeholder {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 48px;
+ color: rgba(255,255,255,0.15);
+ }
+ /* Hover overlay with live preview iframe */
+ .ag-card-preview-overlay {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ transition: opacity 0.3s;
+ pointer-events: none;
+ }
+ .ag-card:hover .ag-card-preview-overlay,
+ .ag-card-preview-overlay.is-active {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ .ag-card-preview-overlay iframe {
+ width: 100%;
+ height: 100%;
+ border: none;
+ display: block;
+ }
+ .ag-play-hint {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(0,0,0,0.3);
+ transition: opacity 0.2s;
+ pointer-events: none;
+ }
+ .ag-card:hover .ag-play-hint { opacity: 0; }
+ .ag-play-icon {
+ width: 40px;
+ height: 40px;
+ background: rgba(255,255,255,0.15);
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ backdrop-filter: blur(6px);
+ }
+
+ /* Meta */
+ .ag-card-meta {
+ padding: 14px 16px 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ flex: 1;
+ }
+ .ag-card-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text, #fafafa);
+ margin: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .ag-card-badges {
+ display: flex;
+ gap: 5px;
+ flex-wrap: wrap;
+ }
+ .ag-badge {
+ padding: 2px 7px;
+ border-radius: 4px;
+ font-size: 10px;
+ font-weight: 500;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ background: rgba(255,255,255,0.07);
+ color: var(--text-2, #a1a1aa);
+ }
+ .ag-badge--loop { color: #34d399; background: rgba(52,211,153,0.12); }
+ .ag-badge--once { color: #fbbf24; background: rgba(251,191,36,0.12); }
+ .ag-badge--price { color: #60a5fa; background: rgba(96,165,250,0.12); }
+ .ag-card-tags {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+ }
+ .ag-tag {
+ padding: 2px 6px;
+ border-radius: 4px;
+ font-size: 10px;
+ background: rgba(255,255,255,0.05);
+ color: var(--text-3, #71717a);
+ }
+ .ag-card-actions {
+ display: flex;
+ gap: 6px;
+ margin-top: auto;
+ padding-top: 4px;
+ }
+ .ag-card-btn {
+ flex: 1;
+ padding: 7px 10px;
+ border-radius: 7px;
+ font-size: 12px;
+ font-weight: 500;
+ text-align: center;
+ text-decoration: none;
+ border: 1px solid rgba(255,255,255,0.1);
+ background: rgba(255,255,255,0.05);
+ color: var(--text-2, #a1a1aa);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+ }
+ .ag-card-btn:hover { background: rgba(255,255,255,0.1); color: var(--text, #fafafa); }
+ .ag-card-btn:focus-visible {
+ outline: 2px solid var(--focus-ring-color, #fff);
+ outline-offset: 2px;
+ }
+ .ag-card-btn--primary {
+ background: rgba(255,255,255,0.12);
+ color: var(--text, #fafafa);
+ border-color: rgba(255,255,255,0.15);
+ }
+ .ag-card-btn--primary:hover { background: rgba(255,255,255,0.2); }
+
+ /* ── Skeleton loading ──────────────────────────────────────────── */
+ .ag-skeleton-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(var(--ag-card-w), 1fr));
+ gap: 20px;
+ }
+ .ag-skeleton {
+ border-radius: 14px;
+ aspect-ratio: 3/5;
+ background: linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.08) 50%, rgba(255,255,255,0.04) 75%);
+ background-size: 400% 100%;
+ animation: ag-shimmer 1.3s linear infinite;
+ }
+ @keyframes ag-shimmer {
+ 0% { background-position: 100% 0; }
+ 100% { background-position: -100% 0; }
+ }
+
+ /* ── Empty / error states ──────────────────────────────────────── */
+ .ag-state {
+ text-align: center;
+ padding: 80px 24px;
+ }
+ .ag-state-icon { font-size: 48px; margin-bottom: 16px; }
+ .ag-state h2 { font-size: 20px; font-weight: 600; margin: 0 0 8px; }
+ .ag-state p { color: var(--text-2, #a1a1aa); font-size: 14px; margin: 0 0 24px; }
+
+ /* ── Load more ─────────────────────────────────────────────────── */
+ .ag-load-more {
+ display: flex;
+ justify-content: center;
+ padding: 32px 0 0;
+ }
+ .ag-sentinel { height: 1px; }
+
+ /* ── Responsive ────────────────────────────────────────────────── */
+ @media (max-width: 600px) {
+ :root { --ag-card-w: 260px; }
+ .ag-hero { padding: 40px 16px 24px; }
+ .ag-toolbar, .ag-content { padding-left: 16px; padding-right: 16px; }
+ .ag-hero h1 { font-size: 28px; }
+ }
+ </style>
+ </head>
+ <body class="ag-page">
+ <header>
+ <div id="nav-container"></div>
+ </header>
+ <script src="/nav.js"></script>
+
+ <main>
+ <section class="ag-hero">
+ <div>
+ <div class="ag-hero-chip">
+ <span class="ag-hero-dot" aria-hidden="true"></span>
+ <span>Animation Gallery</span>
+ </div>
+ </div>
+ <h1>Community Animations</h1>
+ <p>Browse animations authored by the three.ws community. Preview on a live avatar, open in the Studio to remix, or apply to your own avatar.</p>
+ <div class="ag-hero-actions">
+ <a href="/pose" class="ag-btn ag-btn--primary">Open Animation Studio</a>
+ <a href="/gallery" class="ag-btn ag-btn--secondary">Avatar Gallery</a>
+ </div>
+ </section>
+
+ <div class="ag-toolbar" role="toolbar" aria-label="Filter animations">
+ <div class="ag-search-wrap">
+ <svg class="ag-search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
+ <input
+ type="search"
+ class="ag-search"
+ placeholder="Search animations…"
+ aria-label="Search animations"
+ autocomplete="off"
+ data-role="search"
+ />
+ </div>
+ <div class="ag-filter-chips" role="tablist" aria-label="Filter by type" data-role="chips">
+ <button class="ag-chip" role="tab" aria-selected="true" data-filter="">All</button>
+ <button class="ag-chip" role="tab" aria-selected="false" data-filter="loop">Loops</button>
+ <button class="ag-chip" role="tab" aria-selected="false" data-filter="once">One-shot</button>
+ </div>
+ </div>
+
+ <div class="ag-content">
+ <div data-role="loading" class="ag-skeleton-grid">
+ <div class="ag-skeleton"></div>
+ <div class="ag-skeleton"></div>
+ <div class="ag-skeleton"></div>
+ <div class="ag-skeleton"></div>
+ <div class="ag-skeleton"></div>
+ <div class="ag-skeleton"></div>
+ </div>
+ <div data-role="grid" class="ag-grid" hidden></div>
+ <div data-role="empty" class="ag-state" hidden>
+ <div class="ag-state-icon">🎬</div>
+ <h2>No animations yet</h2>
+ <p>Be the first to publish an animation. Open the Studio, author a clip, and set it to public.</p>
+ <a href="/pose" class="ag-btn ag-btn--primary">Open Studio</a>
+ </div>
+ <div data-role="empty-search" class="ag-state" hidden>
+ <div class="ag-state-icon">🔍</div>
+ <h2>No matches</h2>
+ <p data-role="empty-search-msg">No animations match your search.</p>
+ <button class="ag-btn ag-btn--secondary" data-role="clear-search">Clear search</button>
+ </div>
+ <div data-role="error" class="ag-state" hidden>
+ <div class="ag-state-icon">⚠️</div>
+ <h2>Couldn't load animations</h2>
+ <p>Check your connection and try again.</p>
+ <button class="ag-btn ag-btn--secondary" data-role="retry">Retry</button>
+ </div>
+ <div class="ag-load-more" data-role="load-more" hidden>
+ <button class="ag-btn ag-btn--secondary" data-role="load-more-btn">Load more</button>
+ </div>
+ <div class="ag-sentinel" data-role="sentinel" aria-hidden="true"></div>
+ </div>
+ </main>
+
+ <footer>
+ <div id="footer-container"></div>
+ </footer>
+ <script src="/footer.js" defer></script>
+
+ <script type="module" src="/src/animations-gallery.js"></script>
+ </body>
+</html>
diff --git a/pages/avatar-page.html b/pages/avatar-page.html
index 525a8aae1..dcf20e644 100644
--- a/pages/avatar-page.html
+++ b/pages/avatar-page.html
@@ -625,6 +625,13 @@
border-color: rgba(255, 255, 255, 0.5);
box-shadow: 0 0 18px -4px rgba(255, 255, 255, 0.3);
}
+ .av-ar-btn:active {
+ transform: translateY(1px);
+ }
+ .av-ar-btn:focus-visible {
+ outline: 2px solid rgba(255, 255, 255, 0.7);
+ outline-offset: 2px;
+ }
/* ── Owner actions row ───────────────────────── */
.av-owner-row {
diff --git a/prompts/monetization/21-platform-fee-mechanism.md b/prompts/monetization/21-platform-fee-mechanism.md
deleted file mode 100644
index 116119fed..000000000
--- a/prompts/monetization/21-platform-fee-mechanism.md
+++ /dev/null
@@ -1,93 +0,0 @@
----
-status: not-started
----
-
-# Prompt 21: Platform Fee Mechanism
-
-## Objective
-Implement a mechanism in the backend to automatically take a platform fee from every successful transaction (skill purchase or subscription payment).
-
-## Explanation
-A platform fee is a primary business model for a marketplace. This requires modifying the transaction-building logic to split the payment between the creator and the platform. On Solana, this is typically done using multiple transfer instructions within the same transaction.
-
-## Instructions
-1. **Configuration:**
- * Store the platform fee percentage and the platform's treasury wallet address in a secure configuration file or environment variables. Do not hardcode them.
- * Example: `PLATFORM_FEE_BPS=500` (500 basis points = 5%) and `PLATFORM_TREASURY_WALLET="YOUR_WALLET_ADDRESS"`.
-
-2. **Modify Transaction-Building Logic:**
- * Locate all the places where you create a Solana Pay transaction (`/api/purchase/details`, `/api/subscribe/details`, `/api/tip/details`).
- * For each transaction, calculate the fee amount.
- * `totalAmount` = price of the item.
- * `feeAmount` = `totalAmount * (PLATFORM_FEE_BPS / 10000)`.
- * `creatorAmount` = `totalAmount - feeAmount`.
- * Ensure you are working with integers (lamports) to avoid floating-point errors.
-
-3. **Add a Second Transfer Instruction:**
- * Instead of a single transfer instruction from the user to the creator, the transaction will now have two:
- * **Instruction 1:** Transfer `creatorAmount` from the user's wallet to the creator's wallet.
- * **Instruction 2:** Transfer `feeAmount` from the user's wallet to the platform's treasury wallet (`PLATFORM_TREASURY_WALLET`).
- * Add both of these instructions to the same `Transaction` object.
-
-4. **Atomic Transactions:**
- * The beauty of this approach is that the transaction is atomic. If either transfer fails, the entire transaction fails. The user pays once, and the funds are split and distributed in a single, on-chain event.
-
-5. **Update Verification Logic:**
- * Your transaction verification logic must now be updated to look for and validate *both* transfer instructions. It needs to confirm that the creator received the correct amount and the platform received its fee.
-
-## Code Example (Backend - Modified Details Endpoint)
-
-```javascript
-// Inside a Solana Pay details endpoint (e.g., POST /api/purchase/details)
-app.post('/api/purchase/details', async (req, res) => {
- // ... fetch priceInfo { amount, currency_mint, owner_wallet } ...
- const totalAmount = priceInfo.amount;
-
- // 1. Calculate split
- const PLATFORM_FEE_BPS = 500; // 5%
- const PLATFORM_TREASURY_WALLET = new solanaWeb3.PublicKey('...');
- const feeAmount = Math.floor(totalAmount * (PLATFORM_FEE_BPS / 10000));
- const creatorAmount = totalAmount - feeAmount;
-
- // ... build transaction, get blockhash ...
- const transaction = new solanaWeb3.Transaction();
-
- // 2. Add two transfer instructions
- // Transfer to creator
- transaction.add(
- splToken.createTransferInstruction(
- userTokenAccount, // From: user's token account
- creatorTokenAccount, // To: creator's token account
- userPublicKey, // User is the owner/signer
- creatorAmount
- )
- );
- // Transfer to platform treasury
- transaction.add(
- splToken.createTransferInstruction(
- userTokenAccount, // From: user's token account
- platformTokenAccount, // To: platform's token account
- userPublicKey, // User is the owner/signer
- feeAmount
- )
- );
-
- // ... add memo, set fee payer, serialize and return ...
-});
-```
-
-**Note:** This requires you to know the correct SPL Token accounts for the user, creator, and platform. You may need to use `splToken.getAssociatedTokenAddress()` to find or create them as part of the transaction logic. This can get complex, especially if an account doesn't exist yet. An alternative for SOL transfers is to use `SystemProgram.transfer`.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/21-platform-fee-mechanism.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/prompt-1-asset-compression.md b/prompts/prompt-1-asset-compression.md
deleted file mode 100644
index 26e37da3d..000000000
--- a/prompts/prompt-1-asset-compression.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# Task: GLB Asset Compression Pipeline
-
-## Project overview
-
-This is a Three.js / Vite app at `/workspaces/3D-Agent`. It renders 3D avatars and animations for an AI agent marketplace. The frontend stack is vanilla JS modules + Vite (`npm run dev` on port 3000). Backend is Vercel functions in `api/`. All 3D work uses Three.js (latest) with GLB/GLTF assets.
-
-## Problem
-
-The avatar GLB files served to browsers are **uncompressed**. Sizes today:
-
-- `public/avatars/default.glb` — 2.8 MB
-- `public/avatars/cz.glb` — 2.1 MB
-- `public/animations/soldier.glb` — 2.1 MB
-- `public/animations/robotexpressive.glb` — 454 KB
-- `rider/assets/avatars/cz.glb` — copy of above
-- `rider/assets/avatars/soldier.glb` — copy of above
-- `rider/assets/avatars/default.glb` — copy of above
-- `rider/assets/avatars/robotexpressive.glb` — copy of above
-
-EXT_meshopt_compression typically achieves **10–15× compression** on avatar geometry. Draco achieves 40–60%. The project already has `@gltf-transform/core` and `@gltf-transform/extensions` in `package.json` (versions ^4.3.0). The `@gltf-transform/functions` package is not yet installed. Neither is the CLI.
-
-The main viewer (`src/viewer.js`) already has Draco + KTX2 + MeshoptDecoder wired via `getDecoders()` in `src/viewer/internal.js` — so compressed GLBs will decompress automatically when loaded there. The marketplace lobby (`src/marketplace-lobby.js`) uses a bare `GLTFLoader` with no decoders (that is fixed in a separate task); the compression script must therefore produce **meshopt-compressed** output (not Draco-only), because meshopt is the decoder already imported in the main viewer and the lobby task will add it too.
-
-## What to implement
-
-### 1. Install required packages
-
-```bash
-npm install --save-dev @gltf-transform/functions @gltf-transform/cli meshoptimizer
-```
-
-`meshoptimizer` is the native WASM backing for gltf-transform's meshopt encoder.
-
-### 2. Create `scripts/compress-glbs.mjs`
-
-Write a Node ESM script that:
-
-1. Accepts an optional list of GLB paths as CLI args. If none provided, defaults to compressing every `.glb` file under `public/` and `rider/assets/` (recursive, excluding `dist/`).
-2. For each GLB:
- a. Reads the file with `@gltf-transform/core` `NodeIO`.
- b. Applies the following transforms **in order** using `@gltf-transform/functions`:
- - `dedup()` — deduplicate accessors and textures
- - `prune()` — remove unused nodes, skins, textures
- - `resample()` — resample animation curves to remove redundant keyframes
- - `quantize()` — quantize vertex attributes (position, normal, texcoord) to reduce precision to what's perceptually lossless
- - `meshopt({ encoder: MeshoptEncoder })` — apply EXT_meshopt_compression
- - `textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 85 })` if `sharp` is available; otherwise skip texture compression with a console.warn (do not throw)
- c. Writes the result back to the **same path**, overwriting the original.
- d. Logs: original size, compressed size, % reduction, and whether the file grew (which would indicate something went wrong — warn and skip writing in that case).
-3. At the end, prints a summary table of all files processed.
-
-Use `MeshoptEncoder` from `meshoptimizer/meshopt_encoder.js` (the ESM export). The encoder must be initialized with `await MeshoptEncoder.ready` before use.
-
-**Do not use `sharp`** — skip the `textureCompress` step entirely for now (it requires a native binary and adds CI complexity). Leave a `// TODO: add textureCompress once sharp is added to devDependencies` comment.
-
-### 3. Add an npm script in `package.json`
-
-Add to the `"scripts"` block:
-
-```json
-"compress:glbs": "node scripts/compress-glbs.mjs"
-```
-
-### 4. Run the compression
-
-Run `npm run compress:glbs` and let it process all GLBs in `public/` and `rider/assets/`. Print the before/after sizes for each file. If any file grows in size, skip writing it and log a warning.
-
-### 5. Update `.gitignore` if needed
-
-The compressed GLBs replace the originals in-place, so no `.gitignore` change is needed. But add a comment near the GLB section of `.gitignore` (if one exists) noting that GLBs are committed in compressed form.
-
-### 6. Verify the main viewer still loads avatars correctly
-
-- Run `npm run dev`
-- Open `http://localhost:3000` in a browser
-- Confirm the default avatar loads and animates without console errors
-- Confirm the network tab shows the compressed GLB sizes (should be significantly smaller)
-- Check that morph targets (facial expressions) still work — the Empathy Layer in `src/agent-avatar.js` drives them
-
-## Constraints
-
-- Do not modify any `.js` source files in `src/` — this is purely an asset pipeline task.
-- Do not remove the original FBX files in `public/animations/` — they are source files used by the build pipeline, not served to browsers.
-- The animation clips in `public/animations/clips/*.json` are pre-retargeted JSON data, not GLBs — do not touch them.
-- The script must be idempotent: running it twice on already-compressed files should result in files of similar or smaller size, not growth.
-- Use `NodeIO` from `@gltf-transform/core` for all file I/O — do not use raw `fs.readFileSync` on GLBs.
-- The script must be pure ESM (`.mjs` extension, `import` statements, no `require`).
-
-## Definition of done
-
-- `npm run compress:glbs` runs without errors.
-- `public/avatars/default.glb` and `public/avatars/cz.glb` are measurably smaller (at minimum 20% smaller; expect 50–80%).
-- `npm run dev` starts successfully.
-- The avatar renders in the browser with no console errors.
-- The morph-target empathy layer (eye squint, mouth smile, brow raise) still visually responds to agent events.
-- `git diff --stat` shows only the compressed GLB binaries changed plus `package.json`, `package-lock.json`, and the new script file.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/prompt-1-asset-compression.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/public/changelog.json b/public/changelog.json
index 1a3b73407..a64e82578 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T15:37:08.858Z",
+ "generated_at": "2026-06-17T15:57:44.274Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -181,6 +181,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "Game-Ready export in Forge — one click to engine-ready GLB + FBX",
+ "summary": "Any model you generate or upload in Forge can now be turned into a clean, engine-ready asset in one click. Pick Quad retopology (field-aligned QuadriFlow edge loops that rig and animate well) or Tri low-poly (silhouette-preserving, with the texture re-baked), set a poly budget with 5k / 15k / 50k presets, and export a textured GLB plus an FBX for Unity and Unreal together. You see the before→after poly count (e.g. 28,400 → 5,012) and can flip on a live wireframe to inspect the new topology right in the viewer. Files are served from our own CDN.",
+ "link": "/forge",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 12760a4ef..ed6441948 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -142,6 +142,14 @@
<category>feature</category>
<description>The marketplace now has working Free / Paid filters. &quot;Paid&quot; surfaces every agent that charges in any way — a one-time price to own it or per-call pricing on its skills — and &quot;Free&quot; shows the rest. Filtering happens on the server, so the result count and &quot;load more&quot; stay accurate no matter how many pages deep you browse, and your choice is saved in the URL so you can bookmark or share a filtered view.</description>
</item>
+ <item>
+ <title>Game-Ready export in Forge — one click to engine-ready GLB + FBX</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-06-17:Game-Ready export in Forge — one click to engine-ready GLB + FBX</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Any model you generate or upload in Forge can now be turned into a clean, engine-ready asset in one click. Pick Quad retopology (field-aligned QuadriFlow edge loops that rig and animate well) or Tri low-poly (silhouette-preserving, with the texture re-baked), set a poly budget with 5k / 15k / 50k presets, and export a textured GLB plus an FBX for Unity and Unreal together. You see the before→after poly count (e.g. 28,400 → 5,012) and can flip on a live wireframe to inspect the new topology right in the viewer. Files are served from our own CDN.</description>
+ </item>
<item>
<title>iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk</title>
<link>https://three.ws/irl</link>
diff --git a/public/features.json b/public/features.json
index 52b9c2c6e..bc3ca4a97 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T15:37:07.903Z",
+ "generated_at": "2026-06-17T15:57:44.255Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-edit.js b/src/agent-edit.js
index d052bc776..8c0458796 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -1028,6 +1028,129 @@ $('autopilot-save').addEventListener('click', async () => {
}
});
+// ─────────────────────────────────────────────────────────────────────────────
+// Subscription Plans (Monetization tab)
+// ─────────────────────────────────────────────────────────────────────────────
+
+let plansLoaded = false;
+
+function escHtml(s) {
+ return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+}
+
+async function loadSubscriptionPlans() {
+ const list = $('subscription-plans-list');
+ if (!list) return;
+ try {
+ const r = await apiFetch(`${API_BASE}/subscriptions/plans?agent_id=${encodeURIComponent(agentId)}`, { credentials: 'include' });
+ const j = await r.json().catch(() => ({}));
+ const plans = j.plans || [];
+ plansLoaded = true;
+ renderPlansList(plans);
+ } catch (err) {
+ const list2 = $('subscription-plans-list');
+ if (list2) list2.innerHTML = `<span class="muted">Could not load plans.</span>`;
+ }
+}
+
+function renderPlansList(plans) {
+ const list = $('subscription-plans-list');
+ if (!list) return;
+ if (!plans.length) {
+ list.innerHTML = `<span class="muted" style="font-size:0.764rem;">No plans yet — create one below.</span>`;
+ return;
+ }
+ list.innerHTML = plans.map(p => `
+ <div class="plan-row" style="display:flex; align-items:center; justify-content:space-between; padding:0.5rem 0.75rem; border:1px solid rgba(255,255,255,0.08); border-radius:6px; background:rgba(255,255,255,0.02);">
+ <div>
+ <span style="font-weight:600; font-size:0.875rem;">${escHtml(p.name)}</span>
+ <span style="color:rgba(255,255,255,0.45); font-size:0.764rem; margin-left:0.5rem;">$${Number(p.price_usd).toFixed(2)} / ${p.interval}</span>
+ ${p.perks?.length ? `<div style="font-size:0.7rem; color:rgba(255,255,255,0.35); margin-top:0.15rem;">${escHtml(p.perks.join(' · '))}</div>` : ''}
+ </div>
+ <div style="display:flex; gap:0.4rem;">
+ <button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="openPlanEditor(${JSON.stringify(p).replace(/"/g, '&quot;')})">Edit</button>
+ <button class="btn-ghost danger" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="deletePlan('${p.id}')">Delete</button>
+ </div>
+ </div>
+ `).join('');
+}
+
+window.openPlanEditor = function openPlanEditor(plan) {
+ const editor = $('plan-editor');
+ if (!editor) return;
+ $('plan-editor-id').value = plan?.id ?? '';
+ $('plan-name-input').value = plan?.name ?? '';
+ $('plan-price-input').value = plan?.price_usd ?? '';
+ $('plan-interval-input').value = plan?.interval ?? 'monthly';
+ $('plan-perks-input').value = (plan?.perks ?? []).join('\n');
+ $('plan-status').textContent = '';
+ editor.style.display = 'block';
+ $('show-create-plan-btn').style.display = 'none';
+ $('plan-name-input').focus();
+};
+
+window.deletePlan = async function deletePlan(planId) {
+ if (!confirm('Delete this plan? Subscribers will keep access until their period ends.')) return;
+ try {
+ const r = await apiFetch(`${API_BASE}/subscriptions/plans/${planId}`, { method: 'DELETE', credentials: 'include' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ loadSubscriptionPlans();
+ } catch (err) {
+ alert(`Error deleting plan: ${err.message}`);
+ }
+};
+
+$('show-create-plan-btn')?.addEventListener('click', () => {
+ openPlanEditor(null);
+});
+
+$('plan-cancel-btn')?.addEventListener('click', () => {
+ $('plan-editor').style.display = 'none';
+ $('show-create-plan-btn').style.display = '';
+});
+
+$('plan-save-btn')?.addEventListener('click', async () => {
+ const status = $('plan-status');
+ const planId = $('plan-editor-id').value.trim();
+ const name = $('plan-name-input').value.trim();
+ const price_usd = parseFloat($('plan-price-input').value);
+ const interval = $('plan-interval-input').value;
+ const perks = $('plan-perks-input').value.split('\n').map(s => s.trim()).filter(Boolean);
+
+ if (!name) { status.textContent = 'Name is required.'; status.className = 'form-status err'; return; }
+ if (!price_usd || price_usd < 0.99) { status.textContent = 'Price must be at least $0.99.'; status.className = 'form-status err'; return; }
+
+ status.textContent = 'Saving…'; status.className = 'form-status';
+ try {
+ const payload = { name, price_usd, interval, perks, agent_id: agentId };
+ const url = planId ? `${API_BASE}/subscriptions/plans/${planId}` : `${API_BASE}/subscriptions/plans`;
+ const r = await apiFetch(url, {
+ method: planId ? 'PATCH' : 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify(planId ? { name, price_usd, interval, perks } : payload),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ }
+ $('plan-editor').style.display = 'none';
+ $('show-create-plan-btn').style.display = '';
+ status.textContent = '';
+ loadSubscriptionPlans();
+ } catch (err) {
+ status.textContent = `Error: ${err.message}`;
+ status.className = 'form-status err';
+ }
+});
+
+// Load plans when monetization tab is first activated
+document.addEventListener('tabchange', (e) => {
+ if (e.detail?.tab === 'monetization' && !plansLoaded) loadSubscriptionPlans();
+});
+// Also load on init if already on monetization tab
+if (!document.querySelector('#panel-monetization[hidden]')) loadSubscriptionPlans();
+
// ─────────────────────────────────────────────────────────────────────────────
// Voice tab
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 47ca31a87..2cd42beb7 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -269,6 +269,22 @@ export class AnimationManager {
this._animationDefs = defs;
}
+ /**
+ * Append additional defs (e.g. user/public clips from the API) without
+ * replacing the manifest-sourced ones. Skips defs whose name is already
+ * registered to avoid duplicates when called multiple times.
+ * @param {Array<{name:string, url:string, label?:string, icon?:string, loop?:boolean}>} defs
+ */
+ appendAnimationDefs(defs) {
+ const existing = new Set(this._animationDefs.map((d) => d.name));
+ for (const def of defs) {
+ if (!existing.has(def.name)) {
+ this._animationDefs.push(def);
+ existing.add(def.name);
+ }
+ }
+ }
+
/** @returns {Array} */
getAnimationDefs() {
return this._animationDefs;
@@ -313,27 +329,59 @@ export class AnimationManager {
* Load a single clip from a pre-baked JSON URL and register it.
* Idempotent — returns the cached clip if already loaded.
*
+ * Handles two response shapes:
+ * - Static clip JSON: { name, duration, tracks } (manifest clips)
+ * - API clip response: { clip: { clip: { name, duration, tracks } } }
+ * (/api/animations/clips/:id — detected by URL containing /api/animations/)
+ *
* @param {string} name
- * @param {string} url URL to a clip JSON produced by build-animations.mjs
+ * @param {string} url URL to a clip JSON or /api/animations/clips/:id endpoint
* @param {{ loop?: boolean }} [opts]
* @returns {Promise<THREE.AnimationClip>}
*/
async loadAnimation(name, url, opts = {}) {
if (this.clips.has(name)) return this.clips.get(name);
+ const isApiClip = url.includes('/api/animations/');
const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 10_000);
+ const timeoutId = setTimeout(() => controller.abort(), 15_000);
let res;
try {
- res = await fetch(url, { signal: controller.signal });
+ res = await fetch(url, {
+ signal: controller.signal,
+ credentials: isApiClip ? 'include' : 'omit',
+ });
} finally {
clearTimeout(timeoutId);
}
if (!res.ok) throw new Error(`HTTP ${res.status} loading animation ${name}`);
const json = await res.json();
- const clip = AnimationClip.parse(json);
+ // API responses wrap the baked clip one level deeper.
+ const clipJson = isApiClip ? json?.clip?.clip : json;
+ if (!clipJson) throw new Error(`clip payload missing from ${url}`);
+ const clip = AnimationClip.parse(clipJson);
clip.name = name;
+ return this._registerParsedClip(name, clip, opts);
+ }
+
+ /**
+ * Register an already-parsed AnimationClip directly without fetching a URL.
+ * Creates an action if a model is currently attached. Idempotent.
+ *
+ * @param {string} name
+ * @param {THREE.AnimationClip} clip
+ * @param {{ loop?: boolean }} [opts]
+ * @returns {THREE.AnimationClip}
+ */
+ registerClipDirect(name, clip, opts = {}) {
+ if (this.clips.has(name)) return this.clips.get(name);
+ clip.name = name;
+ return this._registerParsedClip(name, clip, opts);
+ }
+
+ /** @private Shared finalization for both load paths. */
+ _registerParsedClip(name, clip, opts) {
this.clips.set(name, clip);
if (this.model && this.mixer) {
diff --git a/src/animations-gallery.js b/src/animations-gallery.js
new file mode 100644
index 000000000..2641b5335
--- /dev/null
+++ b/src/animations-gallery.js
@@ -0,0 +1,282 @@
+// /animations — public animation gallery.
+//
+// Lists public animation clips via GET /api/animations/clips?include_public=true
+// filtered to public visibility. Supports search, loop/once filter, infinite
+// scroll via cursor pagination, and live preview iframes on hover/click.
+//
+// Card actions:
+// • Preview (hover) — inline iframe with CZ avatar + the clip playing
+// • Open in Studio — /pose?anim=<id> (open in editor for remixing)
+// • Use on my avatar — /pose?anim=<id> (same, user loads their own avatar)
+
+const PREVIEW_MODEL = '/avatars/cz.glb';
+const API_BASE = '/api/animations/clips';
+
+const els = {
+ loading: document.querySelector('[data-role="loading"]'),
+ grid: document.querySelector('[data-role="grid"]'),
+ empty: document.querySelector('[data-role="empty"]'),
+ emptySearch: document.querySelector('[data-role="empty-search"]'),
+ emptySearchMsg: document.querySelector('[data-role="empty-search-msg"]'),
+ clearSearch: document.querySelector('[data-role="clear-search"]'),
+ error: document.querySelector('[data-role="error"]'),
+ retry: document.querySelector('[data-role="retry"]'),
+ search: document.querySelector('[data-role="search"]'),
+ chips: document.querySelector('[data-role="chips"]'),
+ loadMore: document.querySelector('[data-role="load-more"]'),
+ loadMoreBtn: document.querySelector('[data-role="load-more-btn"]'),
+ sentinel: document.querySelector('[data-role="sentinel"]'),
+};
+
+const state = {
+ query: new URLSearchParams(location.search).get('q') || '',
+ filter: new URLSearchParams(location.search).get('filter') || '',
+ cursor: null,
+ loading: false,
+ items: [],
+ hasMore: false,
+};
+
+if (state.query) els.search.value = state.query;
+syncChips();
+
+// ── URL state ──────────────────────────────────────────────────────────────
+
+function syncUrl() {
+ const p = new URLSearchParams();
+ if (state.query) p.set('q', state.query);
+ if (state.filter) p.set('filter', state.filter);
+ const qs = p.toString();
+ const next = qs ? `${location.pathname}?${qs}` : location.pathname;
+ if (next !== location.pathname + location.search) {
+ history.replaceState(null, '', next);
+ }
+}
+
+function syncChips() {
+ els.chips?.querySelectorAll('[data-filter]').forEach((btn) => {
+ const active = btn.dataset.filter === state.filter;
+ btn.setAttribute('aria-selected', String(active));
+ });
+}
+
+// ── Fetch ──────────────────────────────────────────────────────────────────
+
+async function load(reset = false) {
+ if (state.loading) return;
+ if (reset) {
+ state.cursor = null;
+ state.items = [];
+ state.hasMore = false;
+ showState('loading');
+ }
+ state.loading = true;
+
+ const params = new URLSearchParams({ include_public: 'true', visibility: 'public', limit: '24' });
+ if (state.cursor) params.set('cursor', state.cursor);
+ if (state.query) params.set('q', state.query);
+ // loop filter maps to kind: 'loop' or 'animation'
+ if (state.filter === 'loop') params.set('kind', 'loop');
+ if (state.filter === 'once') params.set('kind', 'animation');
+
+ try {
+ const res = await fetch(`${API_BASE}?${params}`, { credentials: 'include' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ const incoming = Array.isArray(data.items) ? data.items : [];
+ state.items = reset ? incoming : [...state.items, ...incoming];
+ state.cursor = data.next_cursor || null;
+ state.hasMore = !!data.next_cursor;
+ renderGrid(reset);
+ } catch {
+ showState('error');
+ } finally {
+ state.loading = false;
+ }
+}
+
+// ── Render ─────────────────────────────────────────────────────────────────
+
+function renderGrid(reset) {
+ if (state.items.length === 0) {
+ showState(state.query || state.filter ? 'empty-search' : 'empty');
+ if (state.query && els.emptySearchMsg) {
+ els.emptySearchMsg.textContent = `No animations match "${state.query}".`;
+ }
+ return;
+ }
+
+ showState('grid');
+
+ if (reset) els.grid.innerHTML = '';
+
+ const startIdx = reset ? 0 : els.grid.children.length;
+ const fragment = document.createDocumentFragment();
+ for (let i = startIdx; i < state.items.length; i++) {
+ fragment.appendChild(buildCard(state.items[i]));
+ }
+ els.grid.appendChild(fragment);
+
+ if (state.hasMore) {
+ els.loadMore.hidden = false;
+ } else {
+ els.loadMore.hidden = true;
+ }
+}
+
+function fmtDuration(ms) {
+ const s = ms / 1000;
+ if (s < 60) return `${s.toFixed(1)}s`;
+ const m = Math.floor(s / 60);
+ return `${m}m ${Math.round(s % 60)}s`;
+}
+
+function buildCard(clip) {
+ const card = document.createElement('article');
+ card.className = 'ag-card';
+ card.setAttribute('aria-label', clip.name || 'Animation');
+
+ const previewId = `ag-preview-${clip.id}`;
+ const studioUrl = `/pose?anim=${encodeURIComponent(clip.id)}`;
+ const loopBadge = clip.loop !== false;
+ const hasThumb = !!clip.thumbnail_url;
+
+ card.innerHTML = `
+ <div class="ag-card-preview" role="button" tabindex="0"
+ aria-label="Preview ${clip.name || 'animation'}"
+ data-clip-id="${clip.id}">
+ ${hasThumb
+ ? `<img class="ag-card-thumb" src="${escHtml(clip.thumbnail_url)}" alt="" loading="lazy" />`
+ : `<div class="ag-card-thumb-placeholder" aria-hidden="true">🎬</div>`
+ }
+ <div class="ag-card-preview-overlay" id="${previewId}"></div>
+ <div class="ag-play-hint" aria-hidden="true">
+ <div class="ag-play-icon">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
+ </div>
+ </div>
+ </div>
+ <div class="ag-card-meta">
+ <h3 class="ag-card-title" title="${escHtml(clip.name || '')}">${escHtml(clip.name || 'Untitled')}</h3>
+ <div class="ag-card-badges">
+ <span class="ag-badge ${loopBadge ? 'ag-badge--loop' : 'ag-badge--once'}">${loopBadge ? 'loop' : 'once'}</span>
+ ${clip.duration_ms ? `<span class="ag-badge">${fmtDuration(clip.duration_ms)}</span>` : ''}
+ ${clip.price ? `<span class="ag-badge ag-badge--price">$${(Number(clip.price.amount) / 1_000_000).toFixed(2)}</span>` : ''}
+ </div>
+ ${clip.tags?.length ? `<div class="ag-card-tags">${clip.tags.slice(0, 5).map((t) => `<span class="ag-tag">${escHtml(t)}</span>`).join('')}</div>` : ''}
+ <div class="ag-card-actions">
+ <a href="${escHtml(studioUrl)}" class="ag-card-btn ag-card-btn--primary"
+ title="Open this animation in the Studio to remix or apply to your avatar">
+ Open in Studio
+ </a>
+ <button class="ag-card-btn" data-preview="${clip.id}"
+ title="Preview this animation on a live avatar"
+ aria-label="Preview ${clip.name || 'animation'}">
+ Preview
+ </button>
+ </div>
+ </div>
+ `;
+
+ // Preview on hover (desktop) — lazy-load the iframe
+ const previewZone = card.querySelector('.ag-card-preview');
+ const overlay = card.querySelector('.ag-card-preview-overlay');
+ let iframeLoaded = false;
+
+ const launchPreview = () => {
+ if (!iframeLoaded) {
+ iframeLoaded = true;
+ const iframe = document.createElement('iframe');
+ iframe.src = `/avatar-embed?model=${encodeURIComponent(PREVIEW_MODEL)}&anim=${encodeURIComponent(clip.id)}&animPicker=0&idle=off&bg=transparent&name=0`;
+ iframe.title = `Preview: ${clip.name || 'animation'}`;
+ iframe.setAttribute('loading', 'lazy');
+ iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
+ overlay.appendChild(iframe);
+ }
+ overlay.classList.add('is-active');
+ };
+
+ previewZone.addEventListener('mouseenter', launchPreview);
+ previewZone.addEventListener('click', launchPreview);
+ previewZone.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ launchPreview();
+ }
+ });
+ previewZone.addEventListener('mouseleave', () => {
+ overlay.classList.remove('is-active');
+ });
+
+ // "Preview" button — same behavior as hover
+ card.querySelector('[data-preview]')?.addEventListener('click', (e) => {
+ e.preventDefault();
+ launchPreview();
+ });
+
+ return card;
+}
+
+function escHtml(s) {
+ return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+}
+
+// ── State display ──────────────────────────────────────────────────────────
+
+function showState(which) {
+ els.loading.hidden = which !== 'loading';
+ els.grid.hidden = which !== 'grid';
+ els.empty.hidden = which !== 'empty';
+ els.emptySearch.hidden = which !== 'empty-search';
+ els.error.hidden = which !== 'error';
+ if (which !== 'grid') els.loadMore.hidden = true;
+}
+
+// ── Controls ───────────────────────────────────────────────────────────────
+
+let searchDebounce;
+els.search?.addEventListener('input', () => {
+ clearTimeout(searchDebounce);
+ searchDebounce = setTimeout(() => {
+ state.query = els.search.value.trim();
+ syncUrl();
+ load(true);
+ }, 280);
+});
+
+els.chips?.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-filter]');
+ if (!btn) return;
+ state.filter = btn.dataset.filter;
+ syncUrl();
+ syncChips();
+ load(true);
+});
+
+els.clearSearch?.addEventListener('click', () => {
+ state.query = '';
+ els.search.value = '';
+ syncUrl();
+ load(true);
+});
+
+els.retry?.addEventListener('click', () => load(true));
+
+els.loadMoreBtn?.addEventListener('click', () => load(false));
+
+// Infinite scroll sentinel
+if ('IntersectionObserver' in window && els.sentinel) {
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries[0].isIntersecting && state.hasMore && !state.loading) {
+ load(false);
+ }
+ },
+ { rootMargin: '200px' },
+ );
+ observer.observe(els.sentinel);
+}
+
+// ── Boot ───────────────────────────────────────────────────────────────────
+
+load(true);
diff --git a/src/app.js b/src/app.js
index 2c78f6f5d..c9a9fc62b 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1928,6 +1928,9 @@ class App {
}
if (!hasSkeleton) return;
+ // Check for ?anim= URL param: play a specific animation (manifest name or API id)
+ const _animParam = new URLSearchParams(location.search).get('anim');
+
// Fetch the animation manifest
fetch('/animations/manifest.json')
.then((r) => {
@@ -1937,6 +1940,15 @@ class App {
.then((manifest) => {
if (Array.isArray(manifest) && manifest.length > 0) {
viewer.setAnimationDefs(manifest);
+ if (_animParam) {
+ // API id (UUID) → load from API; manifest name → normal path
+ const isApiId = /^[0-9a-f-]{36}$/i.test(_animParam);
+ if (isApiId) {
+ viewer.playAnimationById(_animParam).catch(() => {});
+ } else {
+ viewer.animationManager.crossfadeTo(_animParam).catch(() => {});
+ }
+ }
}
})
.catch(() => {
diff --git a/src/avatar-embed.js b/src/avatar-embed.js
index 993da27e9..79e4e5af3 100644
--- a/src/avatar-embed.js
+++ b/src/avatar-embed.js
@@ -166,9 +166,16 @@ async function main() {
log.warn('[avatar-embed] animation manifest load failed', err?.message);
}
- const startAnim = params.get('animation') || params.get('pose');
+ // ?animation= / ?anim= — supports both manifest clip names and API clip ids/slugs.
+ const startAnim = params.get('animation') || params.get('anim') || params.get('pose');
if (startAnim) {
- animMgr.crossfadeTo(startAnim, 0.3).catch(() => {});
+ const isApiId = /^[0-9a-f-]{36}$/i.test(startAnim) || startAnim.startsWith('user:');
+ if (isApiId) {
+ viewer.playAnimationById(startAnim.startsWith('user:') ? startAnim.slice(5) : startAnim)
+ .catch(() => animMgr.crossfadeTo('idle', 0.3).catch(() => {}));
+ } else {
+ animMgr.crossfadeTo(startAnim, 0.3).catch(() => {});
+ }
}
const pickerEnabled = params.get('animPicker') !== '0' && !overlayMode && !hideChrome;
diff --git a/src/forge-gameready.js b/src/forge-gameready.js
new file mode 100644
index 000000000..ae1c345f4
--- /dev/null
+++ b/src/forge-gameready.js
@@ -0,0 +1,651 @@
+// Game-Ready export — the one-click engine-ready output for the forge result
+// view. Layered onto the live model (forge.js dispatches `forge:model-ready`),
+// it drives the real /api/forge-gameready route to retopologize the current mesh
+// to a poly budget and deliver a textured GLB + an FBX for Unity/Unreal in one
+// job.
+//
+// • Quad — field-aligned QuadriFlow retopology: clean edge loops that deform
+// well for rigging & animation.
+// • Tri — silhouette-preserving low-poly with the source texture re-unwrapped
+// and re-baked onto the new mesh.
+//
+// The panel proves its value the way game devs screenshot it: the before→after
+// poly delta and a live wireframe of the retopologized mesh. Nothing fakes
+// progress — it polls the job; the wireframe is the real returned GLB.
+
+const resultPanel = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+const viewerShell = document.getElementById('viewer-shell');
+const triggerBtn = document.getElementById('forge-gameready-btn');
+
+if (resultPanel && viewer && triggerBtn) {
+ const POLL_MS = 2500;
+ const MAX_MS = 8 * 60 * 1000; // quad/lowpoly bakes can take a couple of 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 PRESETS = [
+ [5_000, '5k', 'mobile'],
+ [15_000, '15k', 'standard'],
+ [50_000, '50k', 'hero'],
+ ];
+ const SLIDER_MIN = 1_000;
+ const SLIDER_MAX = 200_000;
+
+ const TOPO_HINTS = {
+ quad: 'Field-aligned QuadriFlow retopology — clean quad-dominant edge loops that deform well for rigging & animation.',
+ tri: 'Silhouette-preserving low-poly. UVs are re-unwrapped and the original texture re-baked onto the new mesh for real-time engines.',
+ };
+
+ // ── Styles ─────────────────────────────────────────────────────────────────
+ if (!document.getElementById('forge-gameready-styles')) {
+ const style = document.createElement('style');
+ style.id = 'forge-gameready-styles';
+ style.textContent = `
+ .gameready { border-top: 1px solid var(--stroke); display: none; flex-direction: column; gap: var(--space-md); padding: var(--space-md); }
+ .gameready[data-open='true'] { display: flex; }
+ .gr-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm); }
+ .gr-head h3 { font-family: var(--font-display); font-size: var(--text-md); font-weight: 700; margin: 0; }
+ .gr-sub { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.5; margin: 0; max-width: 60ch; }
+ .gr-field { display: flex; flex-direction: column; gap: 0.45rem; }
+ .gr-field > span.gr-label { font-size: var(--text-xs); color: var(--ink-dim); font-family: var(--font-mono); text-transform: uppercase; letter-spacing: 0.04em; }
+ .gr-seg { display: inline-flex; gap: 2px; background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: 2px; }
+ .gr-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.45rem 0.9rem; border-radius: var(--radius-sm); cursor: pointer; transition: background 0.15s, color 0.15s; }
+ .gr-seg button:hover { color: var(--ink); }
+ .gr-seg button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .gr-seg button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .gr-topo-hint { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; min-height: 1.4em; margin: 0; }
+ .gr-budget-row { display: flex; align-items: center; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-budget-row input[type='range'] { flex: 1 1 200px; accent-color: var(--accent); cursor: pointer; min-width: 160px; }
+ .gr-budget-row input[type='range']:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
+ .gr-budget-val { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink); font-weight: 600; min-width: 7ch; text-align: right; }
+ .gr-presets { display: inline-flex; gap: 2px; background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: 2px; }
+ .gr-presets button { background: transparent; border: none; color: var(--ink-dim); font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.35rem 0.6rem; border-radius: var(--radius-sm); cursor: pointer; transition: background 0.15s, color 0.15s; }
+ .gr-presets button:hover { color: var(--ink); }
+ .gr-presets button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .gr-presets button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .gr-row { display: flex; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-row .gr-field { flex: 1 1 150px; }
+ .gr-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; }
+ .gr-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .gr-formats { display: flex; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-check { display: inline-flex; align-items: center; gap: 0.45rem; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink); cursor: pointer; }
+ .gr-check input { accent-color: var(--accent); width: 1rem; height: 1rem; cursor: pointer; }
+ .gr-check input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .gr-rig { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; margin: 0; padding-left: 1.45rem; }
+ .gr-rig.is-hidden { display: none; }
+ .gr-actions { display: flex; align-items: center; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-status { font-size: var(--text-xs); font-family: var(--font-mono); color: var(--ink-dim); }
+ .gr-status[data-kind='error'] { color: var(--danger); }
+ .gr-status[data-kind='done'] { color: var(--success); }
+ .gr-skeleton { display: none; height: 4px; border-radius: 2px; overflow: hidden; background: var(--surface-1); position: relative; }
+ .gameready[data-busy='true'] .gr-skeleton { display: block; }
+ .gr-skeleton::after { content: ''; position: absolute; inset: 0; width: 40%; border-radius: 2px; background: linear-gradient(90deg, transparent, var(--accent), transparent); animation: gr-sweep 1.1s ease-in-out infinite; }
+ @keyframes gr-sweep { 0% { transform: translateX(-120%); } 100% { transform: translateX(320%); } }
+ .gr-delta { display: none; flex-wrap: wrap; align-items: center; gap: 0.5rem; font-family: var(--font-mono); font-size: var(--text-sm); }
+ .gr-delta.is-shown { display: flex; }
+ .gr-delta .gr-from { color: var(--ink-dim); }
+ .gr-delta .gr-arrow { color: var(--ink-dim); }
+ .gr-delta .gr-to { color: var(--ink); font-weight: 700; }
+ .gr-delta .gr-tag { font-size: var(--text-xs); color: var(--ink-dim); border: 1px solid var(--stroke); border-radius: var(--radius-sm); padding: 0.1rem 0.45rem; }
+ .gr-downloads { display: none; gap: var(--space-sm); flex-wrap: wrap; }
+ .gr-downloads.is-shown { display: flex; }
+ .gr-wire-toggle { margin-left: auto; }
+ .gr-wire-toggle[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .gr-wire-overlay { position: absolute; inset: 0; z-index: 4; display: none; background: var(--surface-0, #0b0b10); }
+ .gr-wire-overlay.is-shown { display: block; }
+ .gr-wire-overlay canvas { width: 100% !important; height: 100% !important; display: block; }
+ .gr-wire-badge { position: absolute; top: 10px; left: 10px; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); background: color-mix(in srgb, var(--surface-1) 80%, transparent); border: 1px solid var(--stroke); border-radius: var(--radius-sm); padding: 0.2rem 0.5rem; pointer-events: none; }
+ `;
+ document.head.appendChild(style);
+ }
+
+ // ── DOM ──────────────────────────────────────────────────────────────────
+ const panel = document.createElement('section');
+ panel.className = 'gameready';
+ panel.dataset.open = 'false';
+ panel.dataset.busy = 'false';
+ panel.setAttribute('aria-label', 'Game-Ready export');
+ panel.innerHTML = `
+ <div class="gr-head">
+ <h3>Game-Ready export</h3>
+ </div>
+ <p class="gr-sub">Retopologize this model to a poly budget and export an engine-ready asset — a textured GLB plus an FBX for Unity &amp; Unreal — in one click.</p>
+ <div class="gr-field">
+ <span class="gr-label">Topology</span>
+ <div class="gr-seg gr-topo" role="group" aria-label="Topology">
+ <button type="button" data-topo="quad" aria-pressed="true">Quad retopo</button>
+ <button type="button" data-topo="tri" aria-pressed="false">Tri low-poly</button>
+ </div>
+ <p class="gr-topo-hint"></p>
+ </div>
+ <div class="gr-field">
+ <span class="gr-label">Poly budget — <span class="gr-budget-unit">target faces</span></span>
+ <div class="gr-budget-row">
+ <input class="gr-budget" type="range" min="${SLIDER_MIN}" max="${SLIDER_MAX}" step="1000" value="15000"
+ aria-label="Poly budget (target faces)" />
+ <span class="gr-budget-val" aria-live="polite">15k</span>
+ <div class="gr-presets" role="group" aria-label="Poly budget presets">
+ ${PRESETS.map(
+ ([v, short, tag]) =>
+ `<button type="button" data-budget="${v}" aria-pressed="false" title="${tag}">${short}</button>`,
+ ).join('')}
+ </div>
+ </div>
+ </div>
+ <div class="gr-row">
+ <label class="gr-field">
+ <span class="gr-label">Texture</span>
+ <select class="gr-select gr-texsize">
+ <option value="1024" selected>1024px</option>
+ <option value="2048">2048px</option>
+ </select>
+ </label>
+ <div class="gr-field">
+ <span class="gr-label">Formats</span>
+ <div class="gr-formats">
+ <label class="gr-check"><input type="checkbox" class="gr-fmt" value="glb" checked /> GLB (preview)</label>
+ <label class="gr-check"><input type="checkbox" class="gr-fmt" value="fbx" checked /> FBX</label>
+ </div>
+ </div>
+ </div>
+ <label class="gr-check gr-rig-toggle"><input type="checkbox" class="gr-rig-check" /> Preserve rig on FBX</label>
+ <p class="gr-rig is-hidden">Retopology rebuilds geometry, so a retopologized FBX is a clean re-riggable mesh. Tick this only if your source is skinned and you need the existing skeleton kept — the FBX is then exported at the original topology.</p>
+ <div class="gr-actions">
+ <button class="btn gr-run" type="button"><span class="gr-run-label">Export game-ready</span></button>
+ <button class="btn btn-ghost gr-wire-toggle" type="button" aria-pressed="false" hidden title="Show the retopologized wireframe">Wireframe</button>
+ <span class="gr-status" role="status" aria-live="polite"></span>
+ </div>
+ <div class="gr-skeleton" aria-hidden="true"></div>
+ <div class="gr-delta" aria-live="polite"></div>
+ <div class="gr-downloads"></div>
+ `;
+ resultPanel.appendChild(panel);
+
+ // Wireframe overlay lives inside the viewer shell, above the model-viewer.
+ const wireOverlay = document.createElement('div');
+ wireOverlay.className = 'gr-wire-overlay';
+ wireOverlay.innerHTML = `<span class="gr-wire-badge">Retopology wireframe</span>`;
+ (viewerShell || viewer.parentElement)?.appendChild(wireOverlay);
+
+ const topoGroup = panel.querySelector('.gr-topo');
+ const topoHint = panel.querySelector('.gr-topo-hint');
+ const budgetSlider = panel.querySelector('.gr-budget');
+ const budgetVal = panel.querySelector('.gr-budget-val');
+ const presetGroup = panel.querySelector('.gr-presets');
+ const texsizeSel = panel.querySelector('.gr-texsize');
+ const fmtChecks = [...panel.querySelectorAll('.gr-fmt')];
+ const rigToggle = panel.querySelector('.gr-rig-toggle');
+ const rigCheck = panel.querySelector('.gr-rig-check');
+ const rigHint = panel.querySelector('.gr-rig');
+ const runBtn = panel.querySelector('.gr-run');
+ const runLabel = panel.querySelector('.gr-run-label');
+ const wireBtn = panel.querySelector('.gr-wire-toggle');
+ const statusEl = panel.querySelector('.gr-status');
+ const deltaEl = panel.querySelector('.gr-delta');
+ const downloadsEl = panel.querySelector('.gr-downloads');
+
+ const state = {
+ glbUrl: null,
+ label: 'model',
+ topology: 'quad',
+ sourceFaces: null,
+ running: false,
+ pollAbort: false,
+ previewUrl: null, // retopologized GLB used by the wireframe preview
+ };
+
+ // ── Helpers ────────────────────────────────────────────────────────────────
+ function fmtCount(n) {
+ if (!Number.isFinite(n)) return '—';
+ if (n >= 10_000) return `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1).replace(/\.0$/, '')}k`;
+ return n.toLocaleString();
+ }
+
+ function setStatus(text, kind) {
+ statusEl.textContent = text || '';
+ if (kind) statusEl.dataset.kind = kind;
+ else statusEl.removeAttribute('data-kind');
+ }
+
+ function setRunning(running) {
+ state.running = running;
+ runBtn.disabled = running;
+ panel.dataset.busy = String(running);
+ runLabel.textContent = running ? 'Exporting…' : 'Export game-ready';
+ }
+
+ function selectedFormats() {
+ return fmtChecks.filter((c) => c.checked).map((c) => c.value);
+ }
+
+ function syncRigVisibility() {
+ const fbx = fmtChecks.find((c) => c.value === 'fbx')?.checked;
+ rigToggle.style.display = fbx ? 'inline-flex' : 'none';
+ rigHint.classList.toggle('is-hidden', !(fbx && rigCheck.checked));
+ }
+
+ function snapPresets(value) {
+ for (const b of presetGroup.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(Number(b.dataset.budget) === value));
+ }
+ }
+
+ function setBudget(value, { snap = true } = {}) {
+ const v = Math.max(SLIDER_MIN, Math.min(SLIDER_MAX, Math.round(value / 1000) * 1000));
+ budgetSlider.value = String(v);
+ budgetVal.textContent = fmtCount(v);
+ if (snap) snapPresets(v);
+ }
+
+ // Default the budget to a fraction of the model's current size — a real
+ // reduction target, not a fixed number — snapped to the nearest preset.
+ function defaultBudgetFor(sourceFaces) {
+ if (!Number.isFinite(sourceFaces) || sourceFaces <= 0) return 15_000;
+ const target = Math.round(sourceFaces * 0.3);
+ let nearest = PRESETS[0][0];
+ let best = Infinity;
+ for (const [v] of PRESETS) {
+ const d = Math.abs(v - target);
+ if (d < best) {
+ best = d;
+ nearest = v;
+ }
+ }
+ // Never propose a budget above the source — that would add, not reduce.
+ return Math.min(nearest, Math.max(SLIDER_MIN, Math.round(sourceFaces)));
+ }
+
+ function applyTopology(topo) {
+ state.topology = topo;
+ for (const b of topoGroup.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b.dataset.topo === topo));
+ }
+ topoHint.textContent = TOPO_HINTS[topo];
+ panel.querySelector('.gr-budget-unit').textContent = topo === 'quad' ? 'target quads' : 'target faces';
+ }
+
+ // Count triangles in a GLB without a full 3D parse: read the JSON chunk and
+ // sum each mesh primitive's index (or position) accessor count. Accurate for
+ // the TRIANGLES-mode meshes forge produces; returns null if it can't tell.
+ function countGlbTriangles(buffer) {
+ try {
+ const dv = new DataView(buffer);
+ if (dv.getUint32(0, true) !== 0x46546c67) return null; // 'glTF'
+ let offset = 12;
+ let json = null;
+ while (offset < dv.byteLength) {
+ const chunkLen = dv.getUint32(offset, true);
+ const chunkType = dv.getUint32(offset + 4, true);
+ if (chunkType === 0x4e4f534a) {
+ // 'JSON'
+ json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, offset + 8, chunkLen)));
+ break;
+ }
+ offset += 8 + chunkLen;
+ }
+ if (!json?.meshes || !json?.accessors) return null;
+ let tris = 0;
+ for (const mesh of json.meshes) {
+ for (const prim of mesh.primitives || []) {
+ if (prim.mode !== undefined && prim.mode !== 4) continue; // not TRIANGLES
+ const accIdx = prim.indices !== undefined ? prim.indices : prim.attributes?.POSITION;
+ const count = json.accessors[accIdx]?.count;
+ if (Number.isFinite(count)) tris += Math.floor(count / 3);
+ }
+ }
+ return tris > 0 ? tris : null;
+ } catch {
+ return null;
+ }
+ }
+
+ async function loadSourceFaceCount(url) {
+ state.sourceFaces = null;
+ try {
+ const res = await fetch(url);
+ if (!res.ok) return;
+ const buf = await res.arrayBuffer();
+ const tris = countGlbTriangles(buf);
+ if (tris && state.glbUrl === url) {
+ state.sourceFaces = tris;
+ setBudget(defaultBudgetFor(tris));
+ }
+ } catch {
+ // Network/CORS hiccup — leave the sensible default budget in place.
+ }
+ }
+
+ function safeLabel() {
+ return state.label.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge';
+ }
+
+ function renderDownloads(outputs) {
+ downloadsEl.innerHTML = '';
+ const order = ['glb', 'fbx'];
+ const budget = Number(budgetSlider.value);
+ for (const fmt of order) {
+ const out = outputs[fmt];
+ if (!out?.url) continue;
+ const a = document.createElement('a');
+ a.className = 'btn';
+ a.href = out.url;
+ a.setAttribute('download', `${safeLabel()}-${state.topology}-${fmtCount(budget)}.${fmt}`);
+ a.textContent = `Download ${fmt.toUpperCase()}`;
+ a.rel = 'noopener';
+ downloadsEl.appendChild(a);
+ }
+ downloadsEl.classList.toggle('is-shown', downloadsEl.childElementCount > 0);
+ }
+
+ function renderDelta(data) {
+ const after = data.face_count;
+ const unit = state.topology === 'quad' ? (data.quad_ratio > 0 ? 'quads' : 'faces') : 'tris';
+ const parts = [];
+ if (Number.isFinite(state.sourceFaces)) {
+ parts.push(`<span class="gr-from">${state.sourceFaces.toLocaleString()} tris</span><span class="gr-arrow">→</span>`);
+ }
+ parts.push(`<span class="gr-to">${Number.isFinite(after) ? after.toLocaleString() : '—'} ${unit}</span>`);
+ if (Number.isFinite(state.sourceFaces) && Number.isFinite(after) && after > 0 && after < state.sourceFaces) {
+ const pct = Math.round((1 - after / state.sourceFaces) * 100);
+ parts.push(`<span class="gr-tag">−${pct}%</span>`);
+ }
+ if (Number.isFinite(data.quad_ratio) && data.quad_ratio > 0) {
+ parts.push(`<span class="gr-tag">${Math.round(data.quad_ratio * 100)}% quad-dominant</span>`);
+ }
+ if (data.textured === true) parts.push('<span class="gr-tag">texture re-baked ✓</span>');
+ deltaEl.innerHTML = parts.join(' ');
+ deltaEl.classList.add('is-shown');
+ }
+
+ // ── Network ──────────────────────────────────────────────────────────────
+ function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+ }
+
+ async function startExport(formats) {
+ const res = await fetch('/api/forge-gameready', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({
+ mesh_url: state.glbUrl,
+ topology: state.topology,
+ poly_budget: Number(budgetSlider.value),
+ texture_size: Number(texsizeSel.value),
+ formats,
+ preserve_rig: rigCheck.checked && formats.includes('fbx'),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ throw new Error('Game-Ready export 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(`The exporter is busy. Try again in about ${secs}s.`);
+ }
+ if (!res.ok || !data.job_id) {
+ throw new Error(data.message || `The exporter returned ${res.status}.`);
+ }
+ return data.job_id;
+ }
+
+ async function pollExport(jobId) {
+ const deadline = performance.now() + MAX_MS;
+ while (!state.pollAbort && performance.now() < deadline) {
+ await sleep(POLL_MS);
+ if (state.pollAbort) return null;
+ const res = await fetch(`/api/forge-gameready?job=${encodeURIComponent(jobId)}`, {
+ headers: CLIENT_HEADERS,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (data.status === 'done' && data.outputs) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Game-Ready export failed.');
+ setStatus(data.status === 'running' ? 'Retopologizing & baking…' : 'Queued…');
+ }
+ if (state.pollAbort) return null;
+ throw new Error('Export timed out. Try a lower poly budget.');
+ }
+
+ function applyResult(data) {
+ const outputs = data.outputs || {};
+ // GLB renders inline — swap the live viewer so the new topology shows
+ // immediately and feeds the wireframe preview.
+ if (outputs.glb?.url) {
+ viewer.setAttribute('src', outputs.glb.url);
+ state.previewUrl = outputs.glb.url;
+ wireBtn.hidden = false;
+ resetWireframe();
+ } else {
+ // FBX-only export: no inline GLB to preview, so the wireframe stays off.
+ wireBtn.hidden = true;
+ hideWireframe();
+ }
+ renderDelta(data);
+ renderDownloads(outputs);
+ }
+
+ async function run() {
+ if (state.running || !state.glbUrl) return;
+ const formats = selectedFormats();
+ if (formats.length === 0) {
+ setStatus('Pick at least one format (GLB or FBX).', 'error');
+ return;
+ }
+ state.pollAbort = false;
+ setRunning(true);
+ setStatus('Starting…');
+ deltaEl.classList.remove('is-shown');
+ downloadsEl.classList.remove('is-shown');
+ try {
+ const jobId = await startExport(formats);
+ const done = await pollExport(jobId);
+ if (!done) return; // superseded by a newer model / cancelled
+ applyResult(done);
+ setStatus('Done — engine-ready asset is ready to download.', 'done');
+ } catch (err) {
+ setStatus(err.message || 'Export failed.', 'error');
+ } finally {
+ setRunning(false);
+ }
+ }
+
+ // ── Wireframe preview (lazy three.js overlay) ──────────────────────────────
+ const wire = {
+ ready: false,
+ loading: false,
+ THREE: null,
+ renderer: null,
+ scene: null,
+ camera: null,
+ controls: null,
+ group: null,
+ raf: 0,
+ ro: null,
+ loadedUrl: null,
+ };
+
+ function sizeWireRenderer() {
+ if (!wire.renderer) return;
+ const w = wireOverlay.clientWidth || 1;
+ const h = wireOverlay.clientHeight || 1;
+ wire.renderer.setSize(w, h, false);
+ wire.camera.aspect = w / h;
+ wire.camera.updateProjectionMatrix();
+ }
+
+ async function ensureWireEngine() {
+ if (wire.ready || wire.loading) return wire.ready;
+ wire.loading = true;
+ try {
+ const [THREE, { GLTFLoader }, { OrbitControls }] = await Promise.all([
+ import('three'),
+ import('three/addons/loaders/GLTFLoader.js'),
+ import('three/addons/controls/OrbitControls.js'),
+ ]);
+ wire.THREE = THREE;
+ wire.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
+ wire.renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));
+ wireOverlay.appendChild(wire.renderer.domElement);
+ wire.scene = new THREE.Scene();
+ wire.camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000);
+ wire.camera.position.set(0, 0, 3);
+ wire.controls = new OrbitControls(wire.camera, wire.renderer.domElement);
+ wire.controls.enableDamping = true;
+ wire.controls.autoRotate = true;
+ wire.controls.autoRotateSpeed = 1.4;
+ wire.group = new THREE.Group();
+ wire.scene.add(wire.group);
+ wire._loader = new GLTFLoader();
+ sizeWireRenderer();
+ wire.ro = new ResizeObserver(sizeWireRenderer);
+ wire.ro.observe(wireOverlay);
+ const tick = () => {
+ wire.raf = requestAnimationFrame(tick);
+ wire.controls.update();
+ wire.renderer.render(wire.scene, wire.camera);
+ };
+ tick();
+ wire.ready = true;
+ } catch {
+ wire.ready = false;
+ } finally {
+ wire.loading = false;
+ }
+ return wire.ready;
+ }
+
+ function clearWireGroup() {
+ if (!wire.group) return;
+ for (const child of [...wire.group.children]) {
+ wire.group.remove(child);
+ child.traverse?.((n) => {
+ n.geometry?.dispose?.();
+ if (Array.isArray(n.material)) n.material.forEach((m) => m.dispose?.());
+ else n.material?.dispose?.();
+ });
+ }
+ }
+
+ function frameWireModel(root) {
+ const THREE = wire.THREE;
+ const box = new THREE.Box3().setFromObject(root);
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ const maxDim = Math.max(size.x, size.y, size.z) || 1;
+ root.position.sub(center);
+ const dist = maxDim * 2.2;
+ wire.camera.position.set(dist * 0.6, dist * 0.3, dist);
+ wire.camera.near = maxDim / 100;
+ wire.camera.far = maxDim * 100;
+ wire.camera.updateProjectionMatrix();
+ wire.controls.target.set(0, 0, 0);
+ wire.controls.update();
+ }
+
+ async function loadWireModel(url) {
+ if (!(await ensureWireEngine())) return;
+ if (wire.loadedUrl === url && wire.group.children.length) return;
+ const THREE = wire.THREE;
+ wire._loader.load(
+ url,
+ (gltf) => {
+ clearWireGroup();
+ const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#7c9cff';
+ const wireMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(accent), wireframe: true });
+ gltf.scene.traverse((node) => {
+ if (node.isMesh) node.material = wireMat;
+ });
+ wire.group.add(gltf.scene);
+ frameWireModel(gltf.scene);
+ wire.loadedUrl = url;
+ },
+ undefined,
+ () => {
+ /* load error — keep the overlay hidden, user still has the textured viewer */
+ hideWireframe();
+ },
+ );
+ }
+
+ function showWireframe() {
+ if (!state.previewUrl) return;
+ wireOverlay.classList.add('is-shown');
+ wireBtn.setAttribute('aria-pressed', 'true');
+ loadWireModel(state.previewUrl);
+ }
+ function hideWireframe() {
+ wireOverlay.classList.remove('is-shown');
+ wireBtn.setAttribute('aria-pressed', 'false');
+ }
+ function resetWireframe() {
+ // A new export invalidates the previously loaded wireframe model.
+ wire.loadedUrl = null;
+ if (wireOverlay.classList.contains('is-shown')) showWireframe();
+ }
+
+ // ── Wiring ─────────────────────────────────────────────────────────────────
+ function openPanel(open) {
+ panel.dataset.open = String(open);
+ triggerBtn.setAttribute('aria-expanded', String(open));
+ if (open) panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ else hideWireframe();
+ }
+
+ triggerBtn.addEventListener('click', () => {
+ openPanel(panel.dataset.open !== 'true');
+ });
+
+ topoGroup.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-topo]');
+ if (btn) applyTopology(btn.dataset.topo);
+ });
+
+ budgetSlider.addEventListener('input', () => setBudget(Number(budgetSlider.value)));
+
+ presetGroup.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-budget]');
+ if (btn) setBudget(Number(btn.dataset.budget));
+ });
+
+ for (const c of fmtChecks) c.addEventListener('change', syncRigVisibility);
+ rigCheck.addEventListener('change', syncRigVisibility);
+
+ runBtn.addEventListener('click', run);
+
+ wireBtn.addEventListener('click', () => {
+ if (wireOverlay.classList.contains('is-shown')) hideWireframe();
+ else showWireframe();
+ });
+
+ // 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) return;
+ state.glbUrl = url;
+ state.label = e.detail?.label || 'model';
+ state.previewUrl = null;
+ state.pollAbort = true; // cancel any in-flight poll for the previous model
+ setStatus('');
+ deltaEl.classList.remove('is-shown');
+ downloadsEl.classList.remove('is-shown');
+ wireBtn.hidden = true;
+ hideWireframe();
+ openPanel(false);
+ loadSourceFaceCount(url);
+ });
+
+ // Initial render.
+ applyTopology('quad');
+ setBudget(15_000);
+ syncRigVisibility();
+}
diff --git a/src/pose-library.js b/src/pose-library.js
index e4797ee81..3df34b067 100644
--- a/src/pose-library.js
+++ b/src/pose-library.js
@@ -420,6 +420,16 @@ export class PoseLibrary {
this.api.setStatus(`Opened “${full.name}” — ${full.editor_doc ? 'keyframes restored' : 'rebuilt from clip'}.`);
}
+ /**
+ * Open a saved animation by its API id into the timeline editor.
+ * Used by the ?anim= URL param boot path so linking directly to an animation
+ * drops it straight into the editor without opening the library drawer.
+ * @param {string} id animation_clips.id (UUID)
+ */
+ async openById(id) {
+ return this._open({ id });
+ }
+
_editMeta(clip, ev) {
const overlay = this._overlay();
const nameInput = el('input', { class: 'pl-input', type: 'text', maxlength: '120', value: clip.name, 'aria-label': 'Name' });
diff --git a/src/pose-studio.js b/src/pose-studio.js
index eb826e82c..ab7036764 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -1605,15 +1605,29 @@ function boot() {
state.library = library;
library.mount();
- // ── Boot: honor ?avatar= ─────────────────────────────────────────────────
- const requestedAvatar = new URL(window.location.href).searchParams.get('avatar');
+ // ── Boot: honor ?avatar= and ?anim= ─────────────────────────────────────
+ const _params = new URL(window.location.href).searchParams;
+ const requestedAvatar = _params.get('avatar');
+ const requestedAnim = _params.get('anim');
+
if (requestedAvatar) {
loadAvatarById(requestedAvatar).catch((err) => {
setStatus(`${err.message} Showing the mannequin instead.`, 'error');
switchToMannequin();
+ }).then(() => {
+ if (requestedAnim) {
+ library.openById(requestedAnim).catch((err) => {
+ setStatus(`Could not load animation: ${err?.message || 'unknown error'}`, 'error');
+ });
+ }
});
} else {
setStatus('Ready. Click a body part to pose, or load an avatar.');
+ if (requestedAnim) {
+ library.openById(requestedAnim).catch((err) => {
+ setStatus(`Could not load animation: ${err?.message || 'unknown error'}`, 'error');
+ });
+ }
}
}
diff --git a/src/viewer.js b/src/viewer.js
index 3a728edd1..782909d9d 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -338,7 +338,20 @@ export class Viewer {
async onGesture(payload) {
if (!payload || !payload.name) return;
const { name, loop } = payload;
- const ready = await this.animationManager.ensureLoaded(name);
+
+ // If the name looks like an API clip id (uuid or user:<id> prefix), load it
+ // from the API before trying the manifest. This lets embeds trigger user
+ // animations by id through the same postMessage channel as built-ins.
+ let ready = await this.animationManager.ensureLoaded(name);
+ if (!ready && (name.startsWith('user:') || /^[0-9a-f-]{36}$/i.test(name))) {
+ try {
+ const clipId = name.startsWith('user:') ? name.slice(5) : name;
+ await this.playAnimationById(clipId);
+ return;
+ } catch {
+ /* fall through — clip not found or private */
+ }
+ }
if (!ready) return;
const action = this.animationManager.actions.get(name);
@@ -1728,6 +1741,10 @@ export class Viewer {
this._renderAnimButtons();
});
+ // Fetch user-owned and public animations from the API and append them
+ // to the panel alongside the built-in manifest clips.
+ this._fetchAndAppendUserAnimations();
+
// Stop button
panel.querySelector('.anim-panel__stop').addEventListener('click', () => {
this.animationManager.stopAll();
@@ -1741,6 +1758,71 @@ export class Viewer {
};
}
+ /**
+ * Fetch user-owned and public animation clips from the API and append them
+ * to the animation panel so they appear alongside the manifest built-ins.
+ * Non-fatal: if the API is unavailable or the user isn't signed in the panel
+ * still shows the built-in clips.
+ * @private
+ */
+ async _fetchAndAppendUserAnimations() {
+ try {
+ const res = await fetch('/api/animations/clips?include_public=true&limit=100', {
+ credentials: 'include',
+ });
+ if (!res.ok) return;
+ const { items } = await res.json();
+ if (!Array.isArray(items) || items.length === 0) return;
+
+ const defs = items.map((c) => ({
+ name: `user:${c.id}`,
+ url: `/api/animations/clips/${encodeURIComponent(c.id)}?play=1`,
+ label: c.name || c.slug || 'Animation',
+ icon: c.visibility === 'public' ? '🌐' : '🔒',
+ loop: c.loop !== false,
+ source: 'user',
+ }));
+ this.animationManager.appendAnimationDefs(defs);
+ this._renderAnimButtons();
+ } catch {
+ /* Non-fatal — user clips just won't appear in the panel */
+ }
+ }
+
+ /**
+ * Load a user or public animation clip by its API id (or slug) and play it
+ * on the currently attached avatar. Increments play_count on the server.
+ * Safe to call before setAnimationDefs; registers the clip directly.
+ *
+ * @param {string} clipId — animation_clips.id (UUID) or slug
+ * @returns {Promise<string>} the internal clip name used by the manager
+ */
+ async playAnimationById(clipId) {
+ const name = `user:${clipId}`;
+ // If already registered as a def, use the normal ensureLoaded path.
+ const existing = this.animationManager.getAnimationDefs().find(
+ (d) => d.name === name || d.url?.includes(`/${encodeURIComponent(clipId)}`),
+ );
+ if (!existing) {
+ // Register the def so the manager knows how to lazy-load it.
+ this.animationManager.appendAnimationDefs([{
+ name,
+ url: `/api/animations/clips/${encodeURIComponent(clipId)}?play=1`,
+ label: 'Animation',
+ icon: '🎬',
+ loop: true,
+ source: 'user',
+ }]);
+ }
+ const ready = await this.animationManager.ensureLoaded(name);
+ if (!ready) throw new Error(`animation ${clipId} unavailable`);
+ await this.animationManager.crossfadeTo(name);
+ this.invalidate();
+ this._recomputeAnimating?.();
+ this._updateRenderLoop?.();
+ return name;
+ }
+
/**
* Render / re-render animation buttons in the panel.
* @private
diff --git a/tests/api/forge-gameready.test.js b/tests/api/forge-gameready.test.js
new file mode 100644
index 000000000..8fa515fbc
--- /dev/null
+++ b/tests/api/forge-gameready.test.js
@@ -0,0 +1,272 @@
+/**
+ * Tests for the Game-Ready export endpoint (api/forge-gameready.js).
+ *
+ * The remesh worker is stubbed at the provider boundary (createRegenProvider from
+ * api/_providers/gcp.js) and R2 is stubbed at the storage boundary, so this
+ * exercises the endpoint's own logic: validation, the multi-format fan-out
+ * (one worker task per requested format), the composite job id, the aggregated
+ * poll, and the R2 mirror of finished artifacts. The retopology itself is
+ * covered by the worker's own Python tests.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Stub the GCP provider — each submit returns a distinct upstream task id so the
+// composite job id packs both formats; status() returns a done remesh result.
+const submit = vi.fn(async (req) => ({
+ extJobId: `task-${req.params.output_format}-${'x'.repeat(20)}`,
+ eta: 30,
+}));
+const status = vi.fn(async (extJobId) => ({
+ status: 'done',
+ resultGlbUrl: `https://storage.googleapis.com/bucket/remesh/${extJobId}.out`,
+ faceCount: 5_012,
+ quadRatio: 0.92,
+ textured: true,
+}));
+let supportsRemesh = true;
+
+vi.mock('../../api/_providers/gcp.js', () => ({
+ createRegenProvider: () => ({
+ supportsMode: (m) => m === 'remesh' && supportsRemesh,
+ submit,
+ status,
+ }),
+}));
+
+// Stub R2 so the mirror writes to memory instead of a real bucket.
+const putObject = vi.fn(async () => {});
+const publicUrl = vi.fn((key) => `https://cdn.three.ws/${key}`);
+vi.mock('../../api/_lib/r2.js', () => ({
+ putObject,
+ publicUrl,
+}));
+
+// Stub SSRF so no DNS resolution happens in tests; passthrough public https URLs.
+vi.mock('../../api/_lib/ssrf.js', async (importOriginal) => {
+ const mod = await importOriginal();
+ return {
+ ...mod,
+ assertPublicHttpsUrl: vi.fn(async (url) => {
+ const parsed = new URL(url);
+ if (parsed.protocol !== 'https:') throw new mod.SsrfError('https required');
+ return url;
+ }),
+ };
+});
+
+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ clientIp: () => '203.0.113.9',
+ limits: {
+ ...actual.limits,
+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcp3dStatus: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ };
+});
+
+// fetch is used by the R2 mirror to pull the finished worker artifact.
+const realFetch = globalThis.fetch;
+beforeEach(() => {
+ submit.mockClear();
+ status.mockClear();
+ putObject.mockClear();
+ publicUrl.mockClear();
+ supportsRemesh = true;
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ arrayBuffer: async () => new Uint8Array([0x67, 0x6c, 0x54, 0x46]).buffer,
+ }));
+});
+
+const { default: handler } = await import('../../api/forge-gameready.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(n, v) {
+ this.headers[String(n).toLowerCase()] = v;
+ },
+ end(b) {
+ this.body = b ?? null;
+ },
+ };
+}
+
+function makeReq({ method = 'POST', url = '/api/forge-gameready', headers = {}, body = null } = {}) {
+ const payload = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);
+ const stream = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);
+ stream.method = method;
+ stream.url = url;
+ stream.headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', ...headers };
+ return stream;
+}
+
+const MESH = 'https://storage.googleapis.com/bucket/forge/model.glb';
+
+describe('POST /api/forge-gameready', () => {
+ it('fans out one quad-retopo task per requested format', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({ body: { mesh_url: MESH, topology: 'quad', poly_budget: 5000, formats: ['glb', 'fbx'] } }),
+ res,
+ );
+ expect(res.statusCode).toBe(202);
+ const body = JSON.parse(res.body);
+ expect(body.status).toBe('queued');
+ expect(body.topology).toBe('quad');
+ expect(body.poly_budget).toBe(5000);
+ expect(body.formats).toEqual(['glb', 'fbx']);
+ expect(body.eta_seconds).toBeGreaterThan(0);
+ expect(typeof body.job_id).toBe('string');
+
+ // One worker task per format, both with quad mode + the requested budget.
+ expect(submit).toHaveBeenCalledTimes(2);
+ const calls = submit.mock.calls.map((c) => c[0]);
+ const glb = calls.find((c) => c.params.output_format === 'glb');
+ const fbx = calls.find((c) => c.params.output_format === 'fbx');
+ expect(glb.mode).toBe('remesh');
+ expect(glb.params.remesh_mode).toBe('quad');
+ expect(glb.params.operation).toBe('full');
+ expect(glb.params.target_faces).toBe(5000);
+ expect(fbx.params.remesh_mode).toBe('quad');
+ expect(fbx.params.output_format).toBe('fbx');
+ });
+
+ it('maps tri topology to the silhouette-preserving low-poly worker mode', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { mesh_url: MESH, topology: 'tri', poly_budget: 15000, formats: ['glb'] } }), res);
+ expect(res.statusCode).toBe(202);
+ const call = submit.mock.calls.at(-1)[0];
+ expect(call.params.remesh_mode).toBe('lowpoly');
+ expect(call.params.target_faces).toBe(15000);
+ });
+
+ it('routes a rig-preserving FBX through the geometry-preserving convert path', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({ body: { mesh_url: MESH, topology: 'quad', formats: ['glb', 'fbx'], preserve_rig: true } }),
+ res,
+ );
+ expect(res.statusCode).toBe(202);
+ const calls = submit.mock.calls.map((c) => c[0]);
+ const fbx = calls.find((c) => c.params.output_format === 'fbx');
+ // Rig survives only when geometry is untouched: triangle + convert.
+ expect(fbx.params.remesh_mode).toBe('triangle');
+ expect(fbx.params.operation).toBe('convert');
+ // The GLB still retopologizes to the chosen topology.
+ const glb = calls.find((c) => c.params.output_format === 'glb');
+ expect(glb.params.remesh_mode).toBe('quad');
+ expect(glb.params.operation).toBe('full');
+ });
+
+ it('clamps an out-of-range poly budget', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { mesh_url: MESH, poly_budget: 9_000_000, formats: ['glb'] } }), res);
+ const body = JSON.parse(res.body);
+ expect(body.poly_budget).toBe(500_000);
+ });
+
+ it('rejects a non-https mesh url', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { mesh_url: 'http://insecure.example/model.glb' } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_mesh_url');
+ });
+
+ it('rejects an empty format list', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { mesh_url: MESH, formats: ['stp'] } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_formats');
+ });
+
+ it('503s when the remesh worker is not configured', async () => {
+ supportsRemesh = false;
+ const res = makeRes();
+ await handler(makeReq({ body: { mesh_url: MESH } }), res);
+ expect(res.statusCode).toBe(503);
+ expect(JSON.parse(res.body).error).toBe('unconfigured');
+ });
+});
+
+describe('GET /api/forge-gameready?job=', () => {
+ async function submitJob(body) {
+ const res = makeRes();
+ await handler(makeReq({ body: { mesh_url: MESH, ...body } }), res);
+ return JSON.parse(res.body).job_id;
+ }
+
+ it('aggregates both formats, mirrors to R2, and returns the poly delta', async () => {
+ const jobId = await submitJob({ topology: 'quad', poly_budget: 5000, formats: ['glb', 'fbx'] });
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: `/api/forge-gameready?job=${encodeURIComponent(jobId)}` }), res);
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.status).toBe('done');
+ expect(body.face_count).toBe(5_012);
+ expect(body.quad_ratio).toBe(0.92);
+ expect(body.textured).toBe(true);
+ // Both formats present and rehosted on our CDN.
+ expect(body.outputs.glb.url).toMatch(/^https:\/\/cdn\.three\.ws\/forge\/gameready\//);
+ expect(body.outputs.fbx.url).toMatch(/\.fbx$/);
+ // Each finished artifact was written to R2.
+ expect(putObject).toHaveBeenCalledTimes(2);
+ const keys = putObject.mock.calls.map((c) => c[0].key);
+ expect(keys.some((k) => k.endsWith('quad-5000.glb'))).toBe(true);
+ expect(keys.some((k) => k.endsWith('quad-5000.fbx'))).toBe(true);
+ });
+
+ it('falls back to the worker URL when R2 mirroring fails', async () => {
+ putObject.mockRejectedValueOnce(new Error('r2 down'));
+ const jobId = await submitJob({ formats: ['glb'] });
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: `/api/forge-gameready?job=${encodeURIComponent(jobId)}` }), res);
+ const body = JSON.parse(res.body);
+ expect(body.status).toBe('done');
+ expect(body.outputs.glb.url).toMatch(/^https:\/\/storage\.googleapis\.com\//);
+ });
+
+ it('reports running while any sub-task is still processing', async () => {
+ status.mockResolvedValueOnce({ status: 'running' });
+ const jobId = await submitJob({ formats: ['glb', 'fbx'] });
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: `/api/forge-gameready?job=${encodeURIComponent(jobId)}` }), res);
+ const body = JSON.parse(res.body);
+ expect(body.status).toBe('running');
+ expect(body.outputs).toBeUndefined();
+ expect(putObject).not.toHaveBeenCalled();
+ });
+
+ it('fails the whole export when a sub-task fails', async () => {
+ status.mockResolvedValueOnce({ status: 'failed', error: 'budget impossible' });
+ const jobId = await submitJob({ formats: ['glb', 'fbx'] });
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: `/api/forge-gameready?job=${encodeURIComponent(jobId)}` }), res);
+ const body = JSON.parse(res.body);
+ expect(body.status).toBe('failed');
+ expect(body.error).toMatch(/budget impossible/);
+ });
+
+ it('400s without a job id', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: '/api/forge-gameready' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('missing_job');
+ });
+
+ it('400s on a malformed job id', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: '/api/forge-gameready?job=not-base64-envelope' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_job');
+ });
+});
+
+globalThis.fetch = realFetch;
diff --git a/tests/api/forge-tiers.test.js b/tests/api/forge-tiers.test.js
index 12f837f52..04e50200d 100644
--- a/tests/api/forge-tiers.test.js
+++ b/tests/api/forge-tiers.test.js
@@ -8,8 +8,10 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
BACKENDS,
+ OUTPUTS,
resolveBackendId,
backendIsConfigured,
+ outputIsConfigured,
buildCatalog,
} from '../../api/_lib/forge-tiers.js';
@@ -155,3 +157,64 @@ describe('forge-tiers — Hunyuan3D self-host configuration', () => {
expect(buildCatalog().backends.find((b) => b.id === 'hunyuan3d').configured).toBe(true);
});
});
+
+// Game-Ready is a post-generation export option (not a generation backend). It
+// must appear in the public catalog's `outputs` with honest ETA + price fields
+// so the result view can advertise it, and report configured only when the
+// remesh worker env is present.
+describe('forge-tiers — Game-Ready export output', () => {
+ const saved = {};
+ const VARS = ['GCP_REMESH_URL', 'GCP_RECONSTRUCTION_KEY'];
+ beforeEach(() => {
+ for (const v of VARS) {
+ saved[v] = process.env[v];
+ delete process.env[v];
+ }
+ });
+ afterEach(() => {
+ for (const v of VARS) {
+ if (saved[v] === undefined) delete process.env[v];
+ else process.env[v] = saved[v];
+ }
+ });
+
+ it('registers a remesh-worker-backed export with quad + tri topologies and GLB/FBX formats', () => {
+ const gr = OUTPUTS.gameready;
+ expect(gr).toBeTruthy();
+ expect(gr.topologies).toEqual(['quad', 'tri']);
+ expect(gr.formats).toEqual(['glb', 'fbx']);
+ expect(gr.requiresEnv).toEqual(['GCP_REMESH_URL', 'GCP_RECONSTRUCTION_KEY']);
+ expect(gr.baseEta).toBeGreaterThan(0);
+ expect(gr.priceUsdcAtomics).toBeGreaterThan(0);
+ expect(gr.polyPresets.length).toBeGreaterThan(0);
+ });
+
+ it('reports configured only when the remesh worker URL and key are set', () => {
+ expect(outputIsConfigured('gameready')).toBe(false);
+ process.env.GCP_REMESH_URL = 'https://remesh.example.run.app';
+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';
+ expect(outputIsConfigured('gameready')).toBe(true);
+ });
+
+ it('advertises the option in the public catalog with valid ETA + cost fields', () => {
+ process.env.GCP_REMESH_URL = 'https://remesh.example.run.app';
+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';
+ const cat = buildCatalog();
+ expect(Array.isArray(cat.outputs)).toBe(true);
+ const gr = cat.outputs.find((o) => o.id === 'gameready');
+ expect(gr).toBeTruthy();
+ expect(gr.label).toBe('Game-Ready');
+ expect(gr.topologies).toEqual(['quad', 'tri']);
+ expect(gr.formats).toEqual(['glb', 'fbx']);
+ expect(gr.eta_seconds).toBeGreaterThan(0);
+ expect(gr.price_usdc_atomics).toBeGreaterThan(0);
+ expect(gr.price_usdc).toMatch(/^\d+\.\d{2}$/);
+ expect(gr.poly_presets.length).toBeGreaterThan(0);
+ expect(gr.configured).toBe(true);
+ });
+
+ it('reports the catalog output as not configured when the worker env is absent', () => {
+ const gr = buildCatalog().outputs.find((o) => o.id === 'gameready');
+ expect(gr.configured).toBe(false);
+ });
+});