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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add GLB thumbnail rendering scripts and asset R2 client
nirholas5b492eb1e5ce
diff --git a/prompts/roadmap/avatar-parametric-editor.md b/prompts/roadmap/avatar-parametric-editor.mdnew file mode 100644index 000000000..2c4666659--- /dev/null+++ b/prompts/roadmap/avatar-parametric-editor.md@@ -0,0 +1,111 @@+# Parametric Avatar Editor: the Avaturn-and-beyond plan++Goal: an avatar editor where **every parameter of the character is editable**, minor and major: face regions (nose, ears, mouth, eyes, jaw, brow, cheeks), body shape (weight, muscle, proportions), individual limbs, hair, clothing, skin, and animation. Avaturn exposes a fixed template with a curated slider set and a paid catalog. We go past it on three axes: parameter depth (hundreds of sliders plus free sculpt), an AI-generated infinite asset catalog, and identity lanes (selfie and text prompt) that resolve into the same parameter space instead of a black-box mesh.++## The one architectural decision everything hangs on++**One canonical parametric body. Everything else is a parameter over it.**++Avaturn, MetaHuman, MakeHuman, and Daz all converge on this: a single fixed-topology base mesh where++- shape = morph targets (vertex deltas),+- proportions = skeleton parameters (per-bone scale/offset),+- hair/clothes = conforming attachments that inherit the body's skinning and morphs,+- skin = layered textures over a fixed UV layout,+- identity capture (selfie, text) = a solver that outputs a parameter vector, not a mesh.++Fixed topology is what makes "change everything" tractable: every asset, morph, texture layer, and identity solver targets the same vertex ordering and UV space, so they all compose. Our current composer mixes baked parts across 4 RPM bodies; that gives variety but can never give sliders, because the bases have no morph library. The parametric backbone is the missing piece the composer README and `docs/avatar-reconstruction.md` v3 both already name.++## What we already have (do not rebuild)++| Layer | Exists today | Where |+|---|---|---|+| Slider UI | Morph slider panel, grouped, renders ANY morphs a GLB exposes; MetaHuman-style 2D face blend wheel | `src/avatar-sculpt.js` |+| Studio shell | Create/edit modes, live scene, export | `src/avatar-studio.js`, `/avatar-studio` |+| Part composition | Cross-base skinned-part grafting on a shared 67-joint skeleton, recolor, scale | `api/_lib/avatar-composer/` |+| Wardrobe UI | Layered garment recolor + hide/show | `src/avatar-wardrobe.js`, `src/avatar-edit.js` |+| Accessories | Bone-attached GLB merge bake | `api/_lib/bake.js`, `public/accessories/` |+| Animation | 111 baked clips, universal retarget, additive overlays, ARKit-52 runtime, lipsync, face mocap | `src/animation-manager.js`, `src/animation-retarget.js`, `src/glb-canonicalize.js` |+| Rigging | Auto-rig worker (Mixamo skeleton + skinning + ARKit-52) | `workers/rig/` |+| Selfie face | MediaPipe 468-landmark shape morph onto template, `register_head_to_target` dense-registration primitive validated | `workers/avatar-reconstruction/` |+| Export/bake | Morph bake, accessory merge, weld/quantize/meshopt, GLB/VRM/USDZ | `api/_lib/bake.js`, `src/avatar-export.js` |+| Economy | Cosmetics shop, ownership, x402 settlement | `api/_lib/cosmetics*.js` |++Key leverage: `avatar-sculpt.js` renders sliders for whatever morphs the loaded GLB carries. Ship a base with 300 morphs and the editor lights up with 300 sliders with zero UI work.++## The build, in phases++### Phase 1: the parametric backbone (unlocks everything)++Adopt a commercially-clean parametric base and port a large morph library onto it.++- **Base mesh + rig: Anny** (Apache-2.0 code, CC0 assets). Humanoid, game-ready topology, designed for morph-based customization.+- **Face topology + ARKit: ICT-FaceKit** (MIT). Gives ARKit-52 + identity basis on a clean license; deformation-transfer its expression set onto the Anny head so lipsync/mocap keep working.+- **Body morph library: MakeHuman targets** (CC0 output). Hundreds of body/face targets (per-region nose, ears, jaw, lips, eyes, torso, limbs, age, weight, muscle, gender spectrum). Port via one offline Blender/gltf-transform script that maps targets onto the Anny topology (nearest-surface + RBF, same math as `register_head_to_target`).+- **Statistical prior: GHUM** (Apache-2.0) later, for realistic covariance ("heavier build also thickens wrists") behind a "realism lock" toggle. Not needed for v1.+- Bake the result to `public/avatars/parametric-base.glb` (or one per build preset) with the full morph set. Three.js handles hundreds of morphs via texture-based morph targets; only nonzero influences cost anything at runtime.++Output: the studio loads the parametric base and every slider is real. This single phase beats Avaturn's slider depth.++### Phase 2: skeleton-space proportions (limbs, height, frame)++Morphs cannot lengthen an arm without breaking skinning; bone parameters can.++- Parameter set: height, leg/arm length, shoulder width, neck length, head size, hand/foot scale, hip width. Implemented as per-bone scale + rest-pose offsets on the canonical skeleton, applied at load and baked at export.+- Verify against the retarget stack: clips play through `animation-retarget.js` hip-translation rescale already; extend its hip rescale to honor per-bone leg scale so walks don't foot-slide.+- UI: a "Proportions" group in the sculpt panel (sliders already generic).++### Phase 3: conforming assets + the AI catalog flywheel (the moat)++Hair, clothes, shoes, facial hair as **conforming attachments**: assets authored (or generated) once against the canonical body, auto-fitted forever after.++- **Auto-fit tool** (offline + on-upload): bind garment vertices to nearest body surface, transfer skin weights and all morph deltas (deformation transfer). A garment then follows every slider automatically: widen the hips, the pants widen.+- **Layering**: slot taxonomy (hair, headwear, top, outerwear, bottom, footwear, gloves, facial-hair, accessories xN) with per-slot body-hide masks (vertex groups) so layered clothing never clips.+- **The flywheel**: wire the forge text-to-3D lane to generate garments/hair against the canonical body ("generate a cyberpunk jacket"), pipe results through auto-fit, land them in the catalog and cosmetics shop. Avaturn has a fixed paid catalog; we have an infinite prompted one, priced in $THREE via the existing cosmetics economy.+- Migrate the 4 RPM bases' hair/outfits through auto-fit so the composer's existing variety carries over; this also deletes the rest-pose-group restriction (composer v2 vertex rebinding falls out for free).++### Phase 4: free sculpt (change literally anything)++Brush-drag directly on the mesh: radius/falloff brush edits vertex positions, recorded as a per-avatar **custom delta morph** (so it exports, serializes, and composes with the library morphs). Symmetry toggle on/off (asymmetry is a feature Avaturn lacks). This is the "every single minor thing" guarantee: anything no slider covers, the brush does.++### Phase 5: identity lanes resolve into parameters++- **Selfie**: MICA+FLAME dense fit (owner approved paying MPI for the commercial FLAME license; blocked on that signature) feeding `register_head_to_target`, then project the result INTO the morph library (least-squares fit over slider space + residual as a custom morph). The user gets their face AND every slider still works on it. Avaturn gives you a locked scanned head.+- **Text**: LLM maps a prompt ("older, sharper jaw, elvish ears, lean runner's build") to a parameter vector over the named slider set. Cheap, no GPU, huge demo value; ship early behind the same parameter API.+- **Randomize/seed**: composer-style seeded recipes become parameter-vector presets.++### Phase 6: skin and texture layers++Layered material system over the canonical UVs: base tone, complexion (freckles/redness), makeup, tattoos/decals (project-on-click), scars, age maps, nail/lip/eye color, heterochromia. Live as separate layers in the editor; composited to a single atlas at export by extending `api/_lib/bake.js` (sharp is already in the pipeline). Optional AI restyle pass (existing restyle lane) as a layer, not a replacement.++### Phase 7: animation personality++The clip library and retargeter already outclass Avaturn. Add per-avatar animation identity: default idle/walk pick, gesture intensity, mood-blend defaults (embodiment/emotion.js already blends), and saved emote loadouts. Because everything sits on one canonical skeleton, retarget cost for the parametric base is zero.++## Parameter model (the contract)++One serializable document per avatar; this is what saves, shares, forks, and mints:++```json+{+ "base": "parametric-v1",+ "morphs": { "noseWidth": 0.3, "earPoint": 0.8, "...": 0 },+ "skeleton": { "height": 1.78, "armLength": 1.02, "...": 1 },+ "sculpt": "r2://sculpt-deltas/<id>.bin",+ "slots": { "hair": "asset:curly-04", "top": "asset:forge-8fa2", "...": null },+ "layers": [ { "type": "tattoo", "decal": "...", "uv": [0.4, 0.6] } ],+ "animation": { "idle": "breathing-02", "walk": "confident", "mood": "warm" }+}+```++Spec lands in `specs/` when Phase 1 ships (it is a load-bearing wire format: editor, baker, shop, and embeds all consume it).++## Licensing gates (the only external blockers)++- FLAME commercial license: owner signs with MPI (Phase 5 selfie lane only; nothing else waits on it).+- MakeHuman targets are CC0 with a community caveat on fully-automated pipelines: port via our own one-time conversion script and commit the converted artifacts, which is the accepted clean pattern.+- Everything else chosen (Anny, ICT-FaceKit, GHUM) is Apache/MIT/CC0.++## Build order rationale++Phase 1 alone is a visible leap (the studio goes from ~10 usable morphs to hundreds). Phases 2 and 4 complete "change everything". Phase 3 is the competitive moat and revenue surface. 5 to 7 are compounding differentiators. Each phase ships independently behind the existing studio UI; no phase requires a rewrite of the animation, export, or economy stacks.diff --git a/public/changelog.json b/public/changelog.jsonindex 9727ad6c0..9bfe41895 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-21T08:05:17.525Z",+ "generated_at": "2026-07-21T08:11:10.641Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex 042b4d53f..e34f2db04 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-21T08:05:17.512Z",+ "generated_at": "2026-07-21T08:11:10.629Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/llms-full.txt b/public/llms-full.txtindex f4ead801b..8ff078d4b 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -2248,6 +2248,12 @@ URL: https://three.ws/docs/nvidia-inceptionthree.ws is a member of the NVIDIA Inception program: what the platform runs on NVIDIA today, what membership adds (GPU credits, ACE/NIM migration, ecosystem access), and who is building it.+### Cookbook: self-correcting 3D with function calling++URL: https://three.ws/cookbook++An executable tutorial: an AI art director turns a one-line brief into a themed set of real 3D props with parallel function calls, inspects each render with vision, and rebuilds what fails. Read it with interactive galleries, or download the notebook and run it.+## BlogLong-form announcements, launches, and writing from three.ws.diff --git a/scripts/glb-thumbnail-harness.html b/scripts/glb-thumbnail-harness.htmlnew file mode 100644index 000000000..6cf0917d7--- /dev/null+++ b/scripts/glb-thumbnail-harness.html@@ -0,0 +1,61 @@+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <style>+ html, body { margin: 0; height: 100%; background: #0e0f16; }+ model-viewer {+ width: 100vw; height: 100vh;+ --poster-color: transparent;+ background: radial-gradient(120% 120% at 50% 20%, #1a1b26, #0a0b12);+ }+ </style>+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>+ </head>+ <body>+ <model-viewer+ id="mv"+ camera-controls="false"+ interaction-prompt="none"+ disable-zoom+ environment-image="neutral"+ shadow-intensity="0.6"+ shadow-softness="1"+ exposure="1.1"+ camera-orbit="25deg 82deg auto"+ field-of-view="30deg"+ ></model-viewer>+ <script type="module">+ const mv = document.getElementById('mv');++ // Load a GLB by (same-origin) URL, wait for it to render, frame it, and+ // return a PNG data URL. Called by the playwright driver via evaluate().+ window.__renderGlb = async (url) => {+ return new Promise((resolve, reject) => {+ const to = setTimeout(() => reject(new Error('load timeout')), 45000);+ const onError = (e) => { clearTimeout(to); reject(new Error('model-viewer error: ' + (e?.detail?.type || 'unknown'))); };+ mv.addEventListener('error', onError, { once: true });+ mv.addEventListener('load', async () => {+ clearTimeout(to);+ mv.removeEventListener('error', onError);+ try {+ // Let a couple of frames settle so lighting/framing is stable.+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));+ mv.dismissPoster?.();+ await new Promise((r) => setTimeout(r, 250));+ const blob = await mv.toBlob({ mimeType: 'image/png', idealAspect: true });+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result);+ reader.onerror = () => reject(new Error('blob read failed'));+ reader.readAsDataURL(blob);+ } catch (err) {+ reject(err);+ }+ }, { once: true });+ mv.src = url;+ });+ };+ window.__ready = true;+ </script>+ </body>+</html>diff --git a/scripts/lib/asset-r2.mjs b/scripts/lib/asset-r2.mjsnew file mode 100644index 000000000..c0bc36e26--- /dev/null+++ b/scripts/lib/asset-r2.mjs@@ -0,0 +1,89 @@+// Shared R2 client for the asset-ingestion pipelines (Mixamo, Quaternius, CMU,+// Poly Pizza, …). Every puller/converter/thumbnailer/manifest-publisher uses+// this so the credential loading and S3 wiring live in one place.+//+// Reads S3_* (with older R2_* names as a fallback) from process.env, then+// .env.local. Same names production (Cloud Run) uses.++import { readFileSync, existsSync } from 'node:fs';+import { join, dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { S3Client, GetObjectCommand, PutObjectCommand, HeadObjectCommand, ListObjectsV2Command } from '@aws-sdk/client-s3';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..', '..');++export function loadEnvVar(key) {+ if (process.env[key]) return process.env[key].trim();+ const p = join(ROOT, '.env.local');+ if (existsSync(p)) {+ const line = readFileSync(p, 'utf8').split('\n').find((l) => l.startsWith(`${key}=`));+ if (line) return line.slice(key.length + 1).trim().replace(/^["']|["']$/g, '');+ }+ return null;+}++export const S3_ENDPOINT = loadEnvVar('S3_ENDPOINT') ||+ (loadEnvVar('R2_ACCOUNT_ID') ? `https://${loadEnvVar('R2_ACCOUNT_ID')}.r2.cloudflarestorage.com` : null);+export const S3_ACCESS_KEY_ID = loadEnvVar('S3_ACCESS_KEY_ID') || loadEnvVar('R2_ACCESS_KEY_ID');+export const S3_SECRET_ACCESS_KEY = loadEnvVar('S3_SECRET_ACCESS_KEY') || loadEnvVar('R2_SECRET_ACCESS_KEY');+export const S3_BUCKET = loadEnvVar('S3_BUCKET') || loadEnvVar('R2_BUCKET') || 'test';+export const S3_PUBLIC_DOMAIN = (loadEnvVar('S3_PUBLIC_DOMAIN') || '').replace(/\/+$/, '');++export function haveR2Creds() {+ return !!(S3_ENDPOINT && S3_ACCESS_KEY_ID && S3_SECRET_ACCESS_KEY);+}++let _client = null;+export function r2() {+ if (_client) return _client;+ if (!haveR2Creds()) throw new Error('R2 creds missing — need S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY');+ _client = new S3Client({+ region: 'auto',+ endpoint: S3_ENDPOINT,+ credentials: { accessKeyId: S3_ACCESS_KEY_ID, secretAccessKey: S3_SECRET_ACCESS_KEY },+ });+ return _client;+}++/** Absolute CDN URL for an R2 key. */+export function cdnUrl(key) {+ return `${S3_PUBLIC_DOMAIN}/${key}`;+}++export async function getObject(key) {+ const res = await r2().send(new GetObjectCommand({ Bucket: S3_BUCKET, Key: key }));+ return Buffer.from(await res.Body.transformToByteArray());+}++export async function putObject(key, body, contentType, cacheControl = 'public, max-age=86400') {+ await r2().send(new PutObjectCommand({+ Bucket: S3_BUCKET, Key: key, Body: body, ContentType: contentType, CacheControl: cacheControl,+ }));+}++export async function objectExists(key) {+ try { await r2().send(new HeadObjectCommand({ Bucket: S3_BUCKET, Key: key })); return true; }+ catch { return false; }+}++/** List every object key under a prefix (handles pagination). */+export async function listKeys(prefix) {+ const keys = [];+ let token;+ do {+ const res = await r2().send(new ListObjectsV2Command({ Bucket: S3_BUCKET, Prefix: prefix, ContinuationToken: token }));+ for (const o of res.Contents || []) keys.push({ key: o.Key, size: o.Size });+ token = res.IsTruncated ? res.NextContinuationToken : null;+ } while (token);+ return keys;+}++/**+ * Publish a library manifest to R2 (the shape /api/<...>/library endpoints read).+ * @param {string} key e.g. 'avatars/library/manifest.json' or 'objects/library/manifest.json'+ * @param {object} manifest e.g. { generated_at, total, items:[…] }+ */+export async function publishManifest(key, manifest) {+ await putObject(key, JSON.stringify(manifest), 'application/json', 'public, max-age=300');+}diff --git a/scripts/render-glb-thumbnails.mjs b/scripts/render-glb-thumbnails.mjsnew file mode 100644index 000000000..1f5d5de6b--- /dev/null+++ b/scripts/render-glb-thumbnails.mjs@@ -0,0 +1,109 @@+#!/usr/bin/env node+/**+ * Generic GLB → PNG poster renderer for the asset-ingestion pipelines.+ *+ * Sources that don't ship their own thumbnails (Quaternius, Kenney, most 3D+ * objects) need a poster for the gallery/marketplace cards. This renders each+ * GLB in a headless model-viewer and uploads the PNG to R2.+ *+ * To dodge R2 CORS on non-production origins, each GLB is fetched from R2+ * server-side and served to the harness from a same-origin temp dir.+ *+ * Input: a JSON array on stdin (or --manifest=<file>) of+ * [{ glbKey: 'objects/quaternius/glb/robot.glb', thumbKey: 'objects/quaternius/thumbs/robot.png' }, …]+ * Skips any thumbKey already present in R2 unless --force.+ *+ * Usage:+ * echo '[{"glbKey":"…","thumbKey":"…"}]' | node scripts/render-glb-thumbnails.mjs+ * node scripts/render-glb-thumbnails.mjs --manifest=jobs.json --concurrency=2 --force+ */+import { readFileSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';+import { join, dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { tmpdir } from 'node:os';+import { createServer } from 'node:http';+import { getObject, putObject, objectExists } from './lib/asset-r2.mjs';++const __dirname = dirname(fileURLToPath(import.meta.url));+const HARNESS = resolve(__dirname, 'glb-thumbnail-harness.html');++const args = Object.fromEntries(process.argv.slice(2).map((a) => {+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);+ return m ? [m[1], m[2] ?? true] : [a, true];+}));+const FORCE = !!args.force;+const CONCURRENCY = Number(args.concurrency) || 2;++async function readJobs() {+ if (args.manifest) return JSON.parse(readFileSync(args.manifest, 'utf8'));+ const chunks = [];+ for await (const c of process.stdin) chunks.push(c);+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '[]');+}++(async () => {+ const jobs = await readJobs();+ if (!Array.isArray(jobs) || jobs.length === 0) {+ console.log('No jobs.'); return;+ }++ // Temp dir served same-origin so model-viewer can load GLBs without CORS.+ const scratch = mkdtempSync(join(tmpdir(), 'glb-thumb-'));+ const harnessHtml = readFileSync(HARNESS, 'utf8');++ const server = createServer((req, res) => {+ if (req.url === '/' || req.url === '/harness.html') {+ res.setHeader('content-type', 'text/html'); res.end(harnessHtml); return;+ }+ const path = join(scratch, decodeURIComponent(req.url.replace(/^\//, '').split('?')[0]));+ try {+ const buf = readFileSync(path);+ res.setHeader('content-type', 'model/gltf-binary');+ res.setHeader('access-control-allow-origin', '*');+ res.end(buf);+ } catch { res.statusCode = 404; res.end('not found'); }+ });+ await new Promise((r) => server.listen(0, r));+ const port = server.address().port;++ const { chromium } = await import('playwright');+ const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-dev-shm-usage', '--enable-unsafe-swiftshader'] });++ let ok = 0, fail = 0, skipped = 0, cursor = 0;++ async function worker(wi) {+ const page = await browser.newPage({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 2 });+ page.on('pageerror', () => {});+ await page.goto(`http://localhost:${port}/harness.html`, { waitUntil: 'domcontentloaded' });+ await page.waitForFunction('window.__ready === true', { timeout: 20000 });++ while (cursor < jobs.length) {+ const i = cursor++;+ const { glbKey, thumbKey } = jobs[i];+ const label = `[${i + 1}/${jobs.length}]`;+ try {+ if (!FORCE && await objectExists(thumbKey)) { skipped++; continue; }+ const glb = await getObject(glbKey);+ const local = `m${wi}-${i}.glb`;+ writeFileSync(join(scratch, local), glb);+ const dataUrl = await page.evaluate((u) => window.__renderGlb(u), `http://localhost:${port}/${local}`);+ rmSync(join(scratch, local), { force: true });+ const png = Buffer.from(String(dataUrl).replace(/^data:image\/png;base64,/, ''), 'base64');+ if (png.length < 1000) throw new Error('empty render');+ await putObject(thumbKey, png, 'image/png', 'public, max-age=604800');+ ok++;+ if (ok % 20 === 0) process.stdout.write(`\r ${ok} rendered, ${skipped} skipped, ${fail} failed…`);+ } catch (err) {+ fail++;+ console.warn(`${label} render fail ${glbKey}: ${err.message.split('\n')[0]}`);+ }+ }+ await page.close();+ }++ await Promise.all(Array.from({ length: CONCURRENCY }, (_, i) => worker(i)));+ await browser.close();+ server.close();+ rmSync(scratch, { recursive: true, force: true });+ console.log(`\nThumbnails: ${ok} rendered, ${skipped} skipped, ${fail} failed.`);+})().catch((err) => { console.error(err); process.exit(1); });