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
feat(avatar-studio): add a walk-preview tab and drive paired limb sliders from one control
nirholas482a12381cae
diff --git a/api/_lib/bake-proportions.js b/api/_lib/bake-proportions.jsnew file mode 100644index 000000000..7c3ccb7ee--- /dev/null+++ b/api/_lib/bake-proportions.js@@ -0,0 +1,168 @@+// Server-side skeleton-proportions baker.+//+// The runtime counterpart is src/avatar-proportions.js: it rewrites the rest+// transforms of a live three.js skeleton while the user drags the Proportions+// sliders in Avatar Studio. This module performs the SAME rewrite on a+// @gltf-transform Document inside bakeAppearance(), so `appearance.proportions`+// reaches every consumer that never runs our runtime: embeds, AR quick-look,+// /play, Blender, Unreal.+//+// Why it has to exist: Avatar Studio saves by exporting the live scene, so a+// build sculpted there bakes in for free. The avatar editor at /avatars/:id/edit+// does not. It PATCHes the appearance record and lets the server render the GLB+// from the pristine base, and until this module ran in that path a proportion+// edit persisted, reloaded and re-applied in the editor while the GLB everyone+// else downloaded stayed at default height.+//+// The maths is not duplicated. `computeProportionTransforms` in+// src/avatar-proportions.js is dependency-free precisely so it can run here, in+// the browser, and in vitest against the same table; this file is only the+// glTF-shaped adapter around it:+// 1. resolve the skin's joints to canonical bone names (glb-canonicalize.js),+// 2. read their rest translation/rotation/scale into the shared RestBone form,+// 3. hand that to the shared solver,+// 4. write the returned locals back, plus the stature factor onto the node+// that parents the skeleton.+//+// Rotations are never written, matching the client, which is what keeps the+// pre-baked clip library and the bind-space morph deltas valid.++import { canonicalizeBoneName } from '../../src/glb-canonicalize.js';+import {+ PROPORTION_BONES,+ computeProportionTransforms,+ normalizeProportions,+} from '../../src/avatar-proportions.js';++/** True when this appearance carries a non-default build worth baking. */+export function hasProportions(appearance) {+ return Object.keys(normalizeProportions(appearance?.proportions)).length > 0;+}++/**+ * Canonical bone name → glTF node, taken from the document's skins. Joints are+ * the only nodes we trust: a mesh node called "Head" is a mesh, not a bone, and+ * scaling it would be a silent disfigurement. The skin deforming the most+ * vertices wins when a document carries several (an avatar plus a garment).+ *+ * @param {import('@gltf-transform/core').Document} doc+ * @returns {Map<string, import('@gltf-transform/core').Node>}+ */+function resolveJoints(doc) {+ const skins = doc.getRoot().listSkins();+ if (!skins.length) return new Map();++ const weightOf = new Map();+ for (const node of doc.getRoot().listNodes()) {+ const skin = node.getSkin();+ const mesh = node.getMesh();+ if (!skin || !mesh) continue;+ let count = 0;+ for (const prim of mesh.listPrimitives()) {+ count += prim.getAttribute('POSITION')?.getCount() || 0;+ }+ weightOf.set(skin, (weightOf.get(skin) || 0) + count);+ }+ const ordered = [...skins].sort((a, b) => (weightOf.get(b) || 0) - (weightOf.get(a) || 0));++ const wanted = new Set(PROPORTION_BONES);+ const out = new Map();+ for (const skin of ordered) {+ for (const joint of skin.listJoints()) {+ const canonical = canonicalizeBoneName(joint.getName() || '');+ if (!canonical || !wanted.has(canonical) || out.has(canonical)) continue;+ out.set(canonical, joint);+ }+ }+ return out;+}++const v3 = (a, fallback = 0) => ({+ x: Number.isFinite(a?.[0]) ? a[0] : fallback,+ y: Number.isFinite(a?.[1]) ? a[1] : fallback,+ z: Number.isFinite(a?.[2]) ? a[2] : fallback,+});++const v4 = (a) => ({+ x: Number.isFinite(a?.[0]) ? a[0] : 0,+ y: Number.isFinite(a?.[1]) ? a[1] : 0,+ z: Number.isFinite(a?.[2]) ? a[2] : 0,+ w: Number.isFinite(a?.[3]) ? a[3] : 1,+});++/**+ * Apply `proportions` to the document's skeleton in place.+ *+ * Never throws on a rig that cannot honour a parameter: a bone that is absent+ * is reported in `missing` and its parameter is dropped, mirroring the client,+ * where a slider whose bones are missing is simply not offered.+ *+ * @param {import('@gltf-transform/core').Document} doc+ * @param {Record<string, number>} proportions+ * @returns {{ applied: string[], stature: number, missing: string[] }}+ */+export function applyProportions(doc, proportions) {+ const values = normalizeProportions(proportions);+ const result = { applied: [], stature: 1, missing: [] };+ if (!Object.keys(values).length) return result;++ const joints = resolveJoints(doc);+ if (!joints.has('Hips')) {+ result.missing = [...Object.keys(values)];+ return result;+ }++ // Nearest canonical ancestor of each joint, so the shared solver can walk+ // chains without knowing anything about the glTF node graph.+ const nodeToCanonical = new Map();+ for (const [canonical, node] of joints) nodeToCanonical.set(node, canonical);+ const parentOf = (node) => {+ for (let n = node.getParentNode(); n; n = n.getParentNode()) {+ const canonical = nodeToCanonical.get(n);+ if (canonical) return canonical;+ }+ return null;+ };++ const rest = new Map();+ for (const [canonical, node] of joints) {+ rest.set(canonical, {+ position: v3(node.getTranslation()),+ quaternion: v4(node.getRotation()),+ scale: v3(node.getScale(), 1),+ parent: parentOf(node),+ });+ }++ const { bones, stature, applied } = computeProportionTransforms(rest, values);++ for (const [canonical, local] of bones) {+ const node = joints.get(canonical);+ if (!node) continue;+ node.setTranslation([local.position.x, local.position.y, local.position.z]);+ node.setScale([local.scale.x, local.scale.y, local.scale.z]);+ }++ // Stature scales the node that parents the whole skeleton. Per the glTF+ // spec a skinned mesh node's own transform is ignored, so the skin follows+ // the joints rather than needing its own scale, and scaling the armature is+ // the one edit that moves every joint at once. When the Hips are a scene+ // root there is no such node and the parameter is dropped, exactly as the+ // client drops the Height slider on the same rig.+ const armature = joints.get('Hips').getParentNode();+ if (stature !== 1) {+ if (armature) {+ const s = v3(armature.getScale(), 1);+ armature.setScale([s.x * stature, s.y * stature, s.z * stature]);+ result.stature = stature;+ } else {+ result.missing.push('height');+ }+ }++ result.applied = applied.filter((id) => id !== 'height' || result.stature !== 1);+ for (const id of Object.keys(values)) {+ if (!result.applied.includes(id) && !result.missing.includes(id)) result.missing.push(id);+ }+ return result;+}diff --git a/api/_lib/bake.js b/api/_lib/bake.jsindex e4cc5ee83..af5a49461 100644--- a/api/_lib/bake.js+++ b/api/_lib/bake.js@@ -61,6 +61,11 @@ export function isBakeable(appearance) {// Additive catalog garments (specs/GARMENT_MANIFEST.md) bake via// bake-garments.js — a garments-only outfit is absolutely bakeable.if (Array.isArray(appearance.garments) && appearance.garments.length > 0) return true;+ // Skeleton-space build (src/avatar-proportions.js, baked by+ // bake-proportions.js). A body edited only in the Proportions group carries+ // nothing else, and treating that as "no customisation" is what left the+ // baked GLB at default height while the editor showed the edit.+ if (appearance.proportions && Object.keys(appearance.proportions).length > 0) return true;return false;}@@ -68,7 +73,7 @@ export function isBakeable(appearance) {* Bake `appearance` into a copy of the base GLB. Returns Uint8Array of the GLB.** @param {Uint8Array|Buffer} baseGlbBytes- * @param {object} appearance — { outfit?, accessories?, morphs? }+ * @param {object} appearance — { outfit?, accessories?, morphs?, proportions?, garments? }* @returns {Promise<Uint8Array>}*/export async function bakeAppearance(baseGlbBytes, appearance) {@@ -117,6 +122,28 @@ export async function bakeAppearance(baseGlbBytes, appearance) {applyHidden(doc, appearance.hidden);}+ // 1d) Skeleton-space proportions: height, limb lengths, shoulder/hip width,+ // head/hand/foot size. Applied before anything reads the skeleton, so+ // accessories mount to the moved bones and garments bind to the final+ // rig. Lazy-imported to keep the module graph light for the common+ // default-body bake, matching the bake-garments.js pattern.+ if (appearance?.proportions && Object.keys(appearance.proportions).length > 0) {+ try {+ const { applyProportions } = await import('./bake-proportions.js');+ const { applied, missing, stature } = applyProportions(doc, appearance.proportions);+ if (applied.length) {+ console.log(+ `[bake] proportions baked: ${applied.join(', ')}${stature !== 1 ? ` (stature ${stature})` : ''}`,+ );+ }+ if (missing.length) {+ console.warn(`[bake] proportions skipped (rig lacks the bones): ${missing.join(', ')}`);+ }+ } catch (err) {+ console.warn(`[bake] proportion pass failed, baking without it: ${err.message}`);+ }+ }+// 2) Bone-mounted accessory GLBs.for (let i = 0; i < presetIds.length; i++) {const id = presetIds[i];diff --git a/pages/avatar-edit.html b/pages/avatar-edit.htmlindex 376584cb5..66f788b7c 100644--- a/pages/avatar-edit.html+++ b/pages/avatar-edit.html@@ -669,100 +669,9 @@gap: 8px;justify-content: flex-end;}- /* ── Animate / rig panel ───────────────────────────────── */- .ae-rig { display: flex; flex-direction: column; gap: 16px; padding: 4px 2px; }- .ae-rig-pill {- display: inline-flex;- align-items: center;- gap: 8px;- align-self: flex-start;- padding: 5px 12px;- border-radius: 999px;- font-size: 12px;- font-weight: 600;- letter-spacing: 0.01em;- border: 1px solid var(--border-2);- color: var(--text-2);- }- .ae-rig-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-3); }- .ae-rig-pill.ok { color: #34d399; border-color: rgba(52, 211, 153, 0.35); }- .ae-rig-pill.ok .ae-rig-dot { background: #34d399; box-shadow: 0 0 8px rgba(52, 211, 153, 0.6); }- .ae-rig-pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); }- .ae-rig-pill.warn .ae-rig-dot { background: var(--warn); }- .ae-rig-pill.unknown { color: var(--text-3); }- .ae-rig-detail { margin: 0; font-size: 13px; line-height: 1.5; color: var(--text-2); }- .ae-rig-action { display: flex; flex-direction: column; gap: 10px; }- .ae-rig-action .ae-btn { align-self: flex-start; }- .ae-rig-note { margin: 0; font-size: 12px; line-height: 1.5; color: var(--text-3); }- .ae-rig-error {- font-size: 13px;- line-height: 1.5;- color: var(--danger);- padding: 10px 12px;- border: 1px solid rgba(244, 63, 94, 0.3);- border-radius: 10px;- background: rgba(244, 63, 94, 0.06);- }- .ae-rig-busy { display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 28px 8px; text-align: center; }- .ae-rig-spinner {- width: 28px; height: 28px;- border-radius: 50%;- border: 3px solid var(--border-2);- border-top-color: var(--text);- animation: ae-spin 0.9s linear infinite;- }- .ae-rig-busy-msg { margin: 0; font-size: 14px; font-weight: 600; color: var(--text); }- .ae-rig-busy-hint { margin: 0; font-size: 12px; color: var(--text-3); }- .ae-rig-bar { width: 100%; height: 6px; border-radius: 999px; background: var(--panel-2); overflow: hidden; }- .ae-rig-bar-fill { height: 100%; background: var(--text); border-radius: 999px; transition: width 0.4s ease; }- .ae-rig-done { display: flex; flex-direction: column; gap: 14px; padding: 8px 2px; }-- /* ── Walk preview panel ─────────────────────────────────── */- .ae-walk { display: flex; flex-direction: column; gap: 16px; padding: 4px 2px; }- .ae-walk-lede { margin: 0; font-size: 13px; line-height: 1.6; color: var(--text-2); }- .ae-walk-lede kbd {- display: inline-block;- min-width: 18px;- padding: 1px 5px;- margin: 0 1px;- font-family: ui-monospace, 'SF Mono', monospace;- font-size: 11px;- text-align: center;- color: var(--text);- background: var(--panel-2);- border: 1px solid var(--border-2);- border-bottom-width: 2px;- border-radius: 5px;- }- .ae-walk-field { display: flex; flex-direction: column; gap: 6px; }- .ae-walk-field-label {- font-size: 11px;- text-transform: uppercase;- letter-spacing: 0.07em;- color: var(--text-3);- }- .ae-walk-select {- width: 100%;- background: var(--panel-2);- border: 1px solid var(--border-2);- border-radius: 8px;- color: var(--text);- padding: 9px 12px;- font-size: 13px;- font-family: inherit;- outline: none;- cursor: pointer;- transition: border-color 0.15s;- }- .ae-walk-select:focus { border-color: var(--accent); }- .ae-walk-open { align-self: flex-start; }- .ae-walk-note {- margin: 0;- font-size: 12px;- line-height: 1.5;- color: var(--text-3);- min-height: 16px;- }+ /* The Animate/rig and Walk panels ship their own CSS from+ src/avatar-rig.js and src/avatar-walk-panel.js, so Avatar Studio+ renders them identically without duplicating this block. */</style></head><body>diff --git a/pages/avatar-studio.html b/pages/avatar-studio.htmlindex 0035f7222..adb888902 100644--- a/pages/avatar-studio.html+++ b/pages/avatar-studio.html@@ -1053,6 +1053,10 @@transition: width 0.3s ease;width: 0%;}+ /* The Wardrobe tab stacks the closet racks under the layer cards;+ both panels ship their own CSS from src/avatar-wardrobe.js and+ src/garment-closet.js, this only sets the gap between them. */+ .as-closet-mount { margin-top: 18px; }</style><link rel="canonical" href="https://three.ws/avatar-studio">@@ -1084,6 +1088,7 @@<span class="as-btn-label">Randomise</span></button><button class="as-btn" id="as-reset" type="button" data-i18n="avatar_studio.reset">Reset</button>+ <button class="as-btn" id="as-play" type="button" hidden title="Drop into /play as this avatar" data-i18n="avatar_studio.play_as_this" data-i18n-attr="title:avatar_studio.drop_into_play_as_this_avatar_title">▶ Play as this</button><button class="as-btn primary" id="as-save" type="button" data-i18n="avatar_studio.save_avatar">Save avatar</button></div></header>diff --git a/public/avatars/parametric-base.glb b/public/avatars/parametric-base.glbindex b1c70f925..652ee3882 100644Binary files a/public/avatars/parametric-base.glb and b/public/avatars/parametric-base.glb differdiff --git a/scripts/build-parametric-base.mjs b/scripts/build-parametric-base.mjsindex 4ce2a6f51..80fcfc1aa 100644--- a/scripts/build-parametric-base.mjs+++ b/scripts/build-parametric-base.mjs@@ -19,7 +19,7 @@// Run: node scripts/build-parametric-base.mjs// Data provenance and license: avatar-sources/anny/README.md (all CC0).-import { readFileSync, writeFileSync, statSync } from 'node:fs';+import { readFileSync, writeFileSync, statSync, existsSync } from 'node:fs';import { gunzipSync } from 'node:zlib';import { resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';@@ -50,6 +50,12 @@ const PAIR = (root, filePattern, ...extra) => [M(`${root}Right`, filePattern.replace('{s}', 'r'), ...extra.map((f) => f.replace('{s}', 'r'))),];+// L+R merged helper: ONE slider that drives both sides. Limb width, depth and+// length reads as a defect when it lands on one arm only, so those collapse+// here instead of expanding through PAIR.+const BOTH = (name, ...patterns) =>+ M(name, ...patterns.flatMap((p) => [p.replace('{s}', 'l'), p.replace('{s}', 'r')]));+const MACRO = 'macrodetails';// Gender-averaged recipe entries: one target per gender at weight s each.const g2 = (fn, s = 0.5) => ['female', 'male'].map((g) => [fn(g), s]);@@ -198,7 +204,212 @@ const MORPHS = [M('calvesMuscular', ['legs/l-lowerleg-muscle-incr', 1], ['legs/r-lowerleg-muscle-incr', 1]),M('legsLonger', 'legs/upperlegs-height-incr', 'legs/lowerlegs-height-incr'),M('legsShorter', 'legs/upperlegs-height-decr', 'legs/lowerlegs-height-decr'),-];++ /* ── Curation pass 2 (2026-09-03) ────────────────────────────────────────+ * The vendored MakeHuman set carries far more shape data than pass 1 used.+ * Everything below comes from targets that were already on disk: face+ * regions stay per-side (PAIR) because asymmetry is an identity feature,+ * limbs collapse to one symmetric slider (BOTH) because a one-armed edit is+ * a bug report, not a look. Targets that only translate a centred feature+ * sideways (nose-trans-in/out, head-trans-in/out) are deliberately skipped:+ * they read as "broken face", not as a control.+ * ──────────────────────────────────────────────────────────────────────── */++ // Nose, continued+ M('noseBridgeWider', 'nose/nose-width1-incr'),+ M('noseBridgeNarrower', 'nose/nose-width1-decr'),+ M('noseMidWider', 'nose/nose-width2-incr'),+ M('noseMidNarrower', 'nose/nose-width2-decr'),+ M('noseBaseWider', 'nose/nose-width3-incr'),+ M('noseBaseNarrower', 'nose/nose-width3-decr'),+ M('noseDeeper', 'nose/nose-scale-depth-incr'),+ M('noseShallower', 'nose/nose-scale-depth-decr'),+ M('noseTipWider', 'nose/nose-point-width-incr'),+ M('noseTipNarrower', 'nose/nose-point-width-decr'),+ M('noseFlaring', 'nose/nose-flaring-incr'),+ M('noseFlaringLess', 'nose/nose-flaring-decr'),+ M('noseNostrilsAngleUp', 'nose/nose-nostrils-angle-up'),+ M('noseNostrilsAngleDown', 'nose/nose-nostrils-angle-down'),+ M('noseBaseUp', 'nose/nose-base-up'),+ M('noseBaseDown', 'nose/nose-base-down'),+ M('noseGreek', 'nose/nose-greek-incr'),+ M('noseConvex', 'nose/nose-curve-convex'),+ M('noseHumpLess', 'nose/nose-hump-decr'),+ M('noseCompressed', 'nose/nose-compression-compress'),+ M('noseForward', 'nose/nose-trans-forward'),+ M('noseBackward', 'nose/nose-trans-backward'),+ M('noseHigher', 'nose/nose-trans-up'),+ M('noseLower', 'nose/nose-trans-down'),+ // Mouth, continued+ M('mouthTaller', 'mouth/mouth-scale-vert-incr'),+ M('mouthShorter', 'mouth/mouth-scale-vert-decr'),+ M('mouthDeeper', 'mouth/mouth-scale-depth-incr'),+ M('mouthShallower', 'mouth/mouth-scale-depth-decr'),+ M('mouthUpperLipWider', 'mouth/mouth-upperlip-width-incr'),+ M('mouthUpperLipNarrower', 'mouth/mouth-upperlip-width-decr'),+ M('mouthLowerLipWider', 'mouth/mouth-lowerlip-width-incr'),+ M('mouthLowerLipNarrower', 'mouth/mouth-lowerlip-width-decr'),+ M('mouthUpperLipTaller', 'mouth/mouth-upperlip-height-incr'),+ M('mouthUpperLipShorter', 'mouth/mouth-upperlip-height-decr'),+ M('mouthLowerLipTaller', 'mouth/mouth-lowerlip-height-incr'),+ M('mouthLowerLipShorter', 'mouth/mouth-lowerlip-height-decr'),+ M('mouthUpperLipMiddleUp', 'mouth/mouth-upperlip-middle-up'),+ M('mouthUpperLipMiddleDown', 'mouth/mouth-upperlip-middle-down'),+ M('mouthLowerLipMiddleUp', 'mouth/mouth-lowerlip-middle-up'),+ M('mouthLowerLipMiddleDown', 'mouth/mouth-lowerlip-middle-down'),+ M('mouthCupidsBowWider', 'mouth/mouth-cupidsbow-width-incr'),+ M('mouthCupidsBowNarrower', 'mouth/mouth-cupidsbow-width-decr'),+ M('mouthPhiltrumDeeper', 'mouth/mouth-philtrum-volume-incr'),+ M('mouthPhiltrumShallower', 'mouth/mouth-philtrum-volume-decr'),+ M('mouthLaughLines', 'mouth/mouth-laugh-lines-out'),+ M('mouthHigher', 'mouth/mouth-trans-up'),+ M('mouthLower', 'mouth/mouth-trans-down'),+ // Ears, continued+ ...PAIR('earTaller', 'ears/{s}-ear-scale-vert-incr'),+ ...PAIR('earShorter', 'ears/{s}-ear-scale-vert-decr'),+ ...PAIR('earRound', 'ears/{s}-ear-shape-round'),+ ...PAIR('earSquare', 'ears/{s}-ear-shape-square'),+ ...PAIR('earTriangle', 'ears/{s}-ear-shape-triangle'),+ ...PAIR('earLobeSmaller', 'ears/{s}-ear-lobe-decr'),+ ...PAIR('earFlapMore', 'ears/{s}-ear-flap-incr'),+ ...PAIR('earTiltForward', 'ears/{s}-ear-rot-forward'),+ ...PAIR('earTiltBack', 'ears/{s}-ear-rot-backward'),+ // Eye sockets, continued+ ...PAIR('eyeHigher', 'eyes/{s}-eye-trans-up'),+ ...PAIR('eyeLower', 'eyes/{s}-eye-trans-down'),+ ...PAIR('eyeInnerUp', 'eyes/{s}-eye-corner1-up'),+ ...PAIR('eyeInnerDown', 'eyes/{s}-eye-corner1-down'),+ ...PAIR('eyeUpperLidUp', 'eyes/{s}-eye-height1-incr'),+ ...PAIR('eyeUpperLidDown', 'eyes/{s}-eye-height1-decr'),+ ...PAIR('eyeLowerLidUp', 'eyes/{s}-eye-height3-incr'),+ ...PAIR('eyeLowerLidDown', 'eyes/{s}-eye-height3-decr'),+ ...PAIR('eyeFoldUp', 'eyes/{s}-eye-eyefold-up'),+ ...PAIR('eyeFoldDown', 'eyes/{s}-eye-eyefold-down'),+ ...PAIR('eyeEpicanthusIn', 'eyes/{s}-eye-epicanthus-in'),+ ...PAIR('eyeEpicanthusOut', 'eyes/{s}-eye-epicanthus-out'),+ ...PAIR('eyeDeepSet', 'eyes/{s}-eye-push1-in'),+ ...PAIR('eyeProtruding', 'eyes/{s}-eye-push1-out'),+ // Brows, continued+ M('browsForward', 'eyebrows/eyebrows-trans-forward'),+ M('browsBackward', 'eyebrows/eyebrows-trans-backward'),+ // Cheeks, continued+ ...PAIR('cheekFlatter', 'cheek/{s}-cheek-bones-decr'),+ ...PAIR('cheekInnerFuller', 'cheek/{s}-cheek-inner-incr'),+ ...PAIR('cheekInnerHollow', 'cheek/{s}-cheek-inner-decr'),+ ...PAIR('cheekHigher', 'cheek/{s}-cheek-trans-up'),+ ...PAIR('cheekLower', 'cheek/{s}-cheek-trans-down'),+ // Jaw and chin, continued+ M('jawBonesStronger', 'chin/chin-bones-incr'),+ M('jawBonesSofter', 'chin/chin-bones-decr'),+ M('jawChinProminent', 'chin/chin-prominent-incr'),+ M('jawChinRecessed', 'chin/chin-prominent-decr'),+ M('jawDrop', 'chin/chin-jaw-drop-incr'),+ M('jawChinCleftLess', 'chin/chin-cleft-decr'),+ // Head and forehead, continued+ M('headTriangular', 'head/head-triangular'),+ M('headInvertedTriangular', 'head/head-invertedtriangular'),+ M('headRectangular', 'head/head-rectangular'),+ M('headDiamond', 'head/head-diamond'),+ M('headFuller', 'head/head-fat-incr'),+ M('headLeaner', 'head/head-fat-decr'),+ M('headAged', 'head/head-age-incr'),+ M('headYouthful', 'head/head-age-decr'),+ M('headBackDeeper', 'head/head-back-scale-depth-incr'),+ M('headBackFlatter', 'head/head-back-scale-depth-decr'),+ M('foreheadTaller', 'forehead/forehead-scale-vert-incr'),+ M('foreheadShorter', 'forehead/forehead-scale-vert-decr'),+ M('foreheadForward', 'forehead/forehead-trans-forward'),+ M('foreheadBackward', 'forehead/forehead-trans-backward'),+ M('foreheadTemplesWider', 'forehead/forehead-temple-incr'),+ M('foreheadTemplesNarrower', 'forehead/forehead-temple-decr'),+ // Neck, continued+ M('neckBackDeeper', 'neck/neck-back-scale-depth-incr'),+ M('neckBackFlatter', 'neck/neck-back-scale-depth-decr'),+ M('neckDoubleChin', 'neck/neck-double-incr'),+ M('neckDoubleChinLess', 'neck/neck-double-decr'),+ M('neckForward', 'neck/neck-trans-forward'),+ M('neckBackward', 'neck/neck-trans-backward'),+ // Torso, continued+ M('chestShallower', 'torso/torso-scale-depth-decr'),+ M('chestTaller', 'torso/torso-scale-vert-incr'),+ M('chestShorter', 'torso/torso-scale-vert-decr'),+ M('chestVShapeLess', 'torso/torso-vshape-decr'),+ M('chestPectoralsLess', 'torso/torso-muscle-pectoral-decr'),+ M('torsoLatsWider', 'torso/torso-muscle-dorsi-incr'),+ M('torsoLatsNarrower', 'torso/torso-muscle-dorsi-decr'),+ M('torsoFrontChestWider', 'torso/measure-frontchest-dist-incr'),+ M('torsoFrontChestNarrower', 'torso/measure-frontchest-dist-decr'),+ M('torsoUnderbustWider', 'torso/measure-underbust-circ-incr'),+ M('torsoUnderbustNarrower', 'torso/measure-underbust-circ-decr'),+ // Hips and stomach, continued+ M('hipsCircWider', 'torso/measure-hips-circ-incr'),+ M('hipsCircNarrower', 'torso/measure-hips-circ-decr'),+ M('hipsDeeper', 'hip/hip-scale-depth-incr'),+ M('hipsTaller', 'hip/hip-scale-vert-incr'),+ M('hipsShorter', 'hip/hip-scale-vert-decr'),+ M('hipsWaistUp', 'hip/hip-waist-up'),+ M('hipsWaistDown', 'hip/hip-waist-down'),+ M('bellySmaller', 'stomach/stomach-pregnant-decr'),+ M('bellySoft', 'stomach/stomach-tone-decr'),+ M('bellyNavelUp', 'stomach/stomach-navel-up'),+ M('bellyNavelDown', 'stomach/stomach-navel-down'),+ // Arms, continued (symmetric: one slider drives both sides)+ BOTH('armsUpperWider', 'arms/{s}-upperarm-scale-horiz-incr'),+ BOTH('armsUpperNarrower', 'arms/{s}-upperarm-scale-horiz-decr'),+ BOTH('armsLowerWider', 'arms/{s}-lowerarm-scale-horiz-incr'),+ BOTH('armsLowerNarrower', 'arms/{s}-lowerarm-scale-horiz-decr'),+ BOTH('armsUpperDeeper', 'arms/{s}-upperarm-scale-depth-incr'),+ BOTH('armsLowerDeeper', 'arms/{s}-lowerarm-scale-depth-incr'),+ BOTH('armsUpperTaller', 'arms/{s}-upperarm-scale-vert-incr'),+ BOTH('armsLowerTaller', 'arms/{s}-lowerarm-scale-vert-incr'),+ BOTH('armsLessMuscular', 'arms/{s}-upperarm-muscle-decr', 'arms/{s}-lowerarm-muscle-decr'),+ BOTH('armsShouldersLessMuscular', 'arms/{s}-upperarm-shoulder-muscle-decr'),+ // Legs, continued (symmetric)+ BOTH('legsThighsWider', 'legs/{s}-upperleg-scale-horiz-incr'),+ BOTH('legsThighsNarrower', 'legs/{s}-upperleg-scale-horiz-decr'),+ BOTH('legsCalvesWider', 'legs/{s}-lowerleg-scale-horiz-incr'),+ BOTH('legsCalvesNarrower', 'legs/{s}-lowerleg-scale-horiz-decr'),+ BOTH('legsThighsDeeper', 'legs/{s}-upperleg-scale-depth-incr'),+ BOTH('legsCalvesDeeper', 'legs/{s}-lowerleg-scale-depth-incr'),+ BOTH('legsKneesIn', 'legs/{s}-leg-valgus-incr'),+ BOTH('legsKneesOut', 'legs/{s}-leg-valgus-decr'),+ BOTH('calvesThicker', 'legs/{s}-lowerleg-fat-incr'),+ BOTH('calvesThinner', 'legs/{s}-lowerleg-fat-decr'),+ BOTH('thighsLessMuscular', 'legs/{s}-upperleg-muscle-decr'),+ BOTH('calvesLessMuscular', 'legs/{s}-lowerleg-muscle-decr'),+ M('legsUpperLonger', 'legs/measure-upperleg-height-incr'),+ M('legsUpperShorter', 'legs/measure-upperleg-height-decr'),+ M('legsLowerLonger', 'legs/measure-lowerleg-height-incr'),+ M('legsLowerShorter', 'legs/measure-lowerleg-height-decr'),+ // Phenotype macros, continued: one slider per ethnicity anchor, gender+ // averaged, so a user can dial an ancestry cue without also flipping sex.+ M('bodyAfrican', ...g2((g) => `${MACRO}/african-${g}-young`)),+ M('bodyAsian', ...g2((g) => `${MACRO}/asian-${g}-young`)),+ M('bodyCaucasian', ...g2((g) => `${MACRO}/caucasian-${g}-young`)),];++/* ────────────────────────────────────────────────────────────────────────── *+ * Preflight: a mistyped target path or a duplicated slider name is a typo, and+ * a typo that survives to the bake either throws 900 lines later or silently+ * ships a slider that shadows another. Catch both here, listing everything+ * wrong in one pass instead of failing on the first.+ * ────────────────────────────────────────────────────────────────────────── */++function preflight() {+ const problems = [];+ const seen = new Set();+ for (const { name, files } of MORPHS) {+ if (seen.has(name)) problems.push(`duplicate morph name: ${name}`);+ seen.add(name);+ for (const { file } of files) {+ const abs = resolve(SRC, 'targets', `${file}.target.gz`);+ if (!existsSync(abs)) problems.push(`${name}: missing target file ${file}.target.gz`);+ }+ }+ if (problems.length) {+ throw new Error(`morph table preflight failed:\n ${problems.join('\n ')}`);+ }+ return seen.size;+}/* ────────────────────────────────────────────────────────────────────────── ** OBJ parsing (positions in source space, faces per group, v/vt indexing)@@ -245,11 +456,31 @@ function loadTarget(relPath) {return deltas;}+/* ────────────────────────────────────────────────────────────────────────── *+ * Budgets. The file size one is obvious. The VRAM one is not, and it is the+ * real ceiling on how many sliders this base can carry: three.js uploads morph+ * targets as an RGBA32F DataArrayTexture with ONE DENSE LAYER PER TARGET+ * (node_modules/three/src/renderers/webgl/WebGLMorphtargets.js), so cost is+ * targets x vertices x 16 bytes whether a slider is at zero or not. Sparse glTF+ * accessors keep the download small; they do nothing for VRAM. Every embed of+ * every avatar built on this base pays it, so it is a shipped-product budget,+ * not a dev-machine one.+ * ────────────────────────────────────────────────────────────────────────── */++const FILE_SIZE_BUDGET_MB = 12;+const MORPH_VRAM_BUDGET_MB = 96;++/** Bytes three.js will allocate for this GLB's morph textures. */+function morphTextureBytes(stats) {+ return stats.reduce((sum, s) => sum + s.verts * s.morphs * 16, 0);+}+/* ────────────────────────────────────────────────────────────────────────── ** Build* ────────────────────────────────────────────────────────────────────────── */function main() {+ preflight();const obj = parseObj(readFileSync(resolve(SRC, '3dobjs/base.obj'), 'utf8'));const vertexGroups = JSON.parse(readFileSync(resolve(SRC, 'mesh_metadata/basemesh_vertex_groups.json'), 'utf8'),@@ -538,7 +769,18 @@ function main() {for (const s of stats) console.log(` ${s.name}: ${s.verts} verts, ${s.tris} tris, ${s.morphs} morphs`);const hips = jointWorld.get('mixamorig:Hips');console.log(` hips rest height: ${hips[1].toFixed(3)} m`);- if (size > 8 * 1024 * 1024) throw new Error('output unexpectedly large; check sparse encoding');+ console.log(` morph texture: ${(morphTextureBytes(stats) / 1024 / 1024).toFixed(1)} MB VRAM (budget ${MORPH_VRAM_BUDGET_MB} MB)`);+ if (size > FILE_SIZE_BUDGET_MB * 1024 * 1024) {+ throw new Error(`output ${(size / 1024 / 1024).toFixed(2)} MB exceeds the ${FILE_SIZE_BUDGET_MB} MB budget; check sparse encoding`);+ }+ const vram = morphTextureBytes(stats) / 1024 / 1024;+ if (vram > MORPH_VRAM_BUDGET_MB) {+ throw new Error(+ `morph targets would need ${vram.toFixed(1)} MB of VRAM, over the ${MORPH_VRAM_BUDGET_MB} MB budget. ` ++ 'Every viewer of every avatar on this base pays that, not just the editor. ' ++ 'Cut sliders, or land the bake-side identity-morph fold first (specs/PARAMETRIC_AVATAR.md).',+ );+ }});}diff --git a/src/avatar-edit.js b/src/avatar-edit.jsindex e443bf5ec..8dff0d794 100644--- a/src/avatar-edit.js+++ b/src/avatar-edit.js@@ -28,7 +28,7 @@ import { canonicalBoneNodesFromObject } from './animation-retarget.js';import { renderWardrobePanel } from './avatar-wardrobe.js';import { GarmentCloset, renderClosetSection } from './garment-closet.js';import { renderRigPanel } from './avatar-rig.js';-import { AvatarWalkPreview } from './avatar-edit-walk.js';+import { createWalkPanel } from './avatar-walk-panel.js';import { apiFetch } from './api.js';import { playAs } from './game/play-handoff.js';import { log } from './shared/log.js';@@ -527,12 +527,15 @@ function renderActivePanel() {// ── Walk preview ─────────────────────────────────────────────────────────+// The panel itself lives in src/avatar-walk-panel.js so Avatar Studio mounts+// the identical control. This editor supplies the scene, the ambient-idle+// pause/resume hooks, and the draft handoff into /walk.function getWalkPreview() {if (walkPreview) return walkPreview;if (!scene?.root) return null;- walkPreview = new AvatarWalkPreview({- scene,- stageEl: $('ae-stage'),+ walkPreview = createWalkPanel({+ getScene: () => scene,+ getStageEl: () => $('ae-stage'),// The editor's ambient idle layer writes bone rotations every frame; pause// it while a retargeted walk clip owns the skeleton, resume on exit.pauseAmbient: () => {@@ -546,116 +549,43 @@ function getWalkPreview() {idleDispose = scene.addOnTick((dt) => idle.update(dt));}},- });- walkPreview.onStatus((msg) => {- const el = $('ae-walk-status');- if (el) el.textContent = msg || '';+ openWalkUrl: buildWalkDraftUrl,});return walkPreview;}function renderWalkPanel(panel) {- if (!scene?.root) {- panel.innerHTML = `<div class="ae-empty">Waiting for avatar to load…</div>`;- return;- }- // Don't rebuild the panel (and lose the env selection) if it's already up —- // renderActivePanel can re-fire while the Walk tab stays active (e.g. on save).- if (panel.querySelector('#ae-walk-panel')) {- enterWalkMode();+ const preview = getWalkPreview();+ if (!preview) {+ panel.innerHTML = `<div class="ae-empty">Waiting for avatar to load...</div>`;return;}-- panel.innerHTML = `- <div class="ae-walk" id="ae-walk-panel">- <p class="ae-walk-lede">- See your avatar in motion. It auto-walks a circle around the stage —- take over any time with <kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd>- or the arrow keys. Every sculpt, outfit, and accessory edit shows up here live.- </p>-- <label class="ae-walk-field">- <span class="ae-walk-field-label">Environment</span>- <select class="ae-walk-select" id="ae-walk-env">- <option value="void">Void</option>- </select>- </label>-- <button class="ae-btn primary ae-walk-open" id="ae-walk-open" type="button">- Open in Walk page →- </button>- <p class="ae-walk-note" id="ae-walk-status"></p>- </div>- `;-- const envSel = panel.querySelector('#ae-walk-env');- envSel.addEventListener('change', () => {- getWalkPreview()?.setEnvironment(envSel.value);- });- panel.querySelector('#ae-walk-open').addEventListener('click', openInWalkPage);-- enterWalkMode();-- // Backfill the real environment list once the manifest resolves.- const preview = getWalkPreview();- preview?.listEnvironments().then((envs) => {- if (!envs || envs.length <= 1) return;- const current = preview.envName || 'void';- envSel.innerHTML = envs- .map(- (e) =>- `<option value="${esc(e.name)}"${e.name === current ? ' selected' : ''}>${esc(e.label)}</option>`,- )- .join('');- });-}--function enterWalkMode() {- const preview = getWalkPreview();- if (!preview || preview.active) return;- preview.enter().catch((err) => {- log.warn('[avatar-edit] walk preview enter failed:', err?.message);- const el = $('ae-walk-status');- if (el) el.textContent = `Could not start walk: ${err.message}`;- });+ preview.render(panel);}function exitWalkMode() {- if (walkPreview?.active) walkPreview.exit();+ walkPreview?.exit();}-async function openInWalkPage() {- const btn = $('ae-walk-open');- const status = $('ae-walk-status');- if (btn) btn.disabled = true;- if (status) status.textContent = 'Preparing preview…';- try {- // Mint an unguessable draft id and stash the *current* (unsaved) look so the- // walk page renders exactly what's on the editor stage — not the last save.- const draftId = (crypto.randomUUID?.() || `${Date.now()}-${Math.random()}`)- .replace(/[^a-z0-9]/gi, '')- .slice(0, 40);- const r = await apiFetch(`/api/avatars/draft/${encodeURIComponent(draftId)}`, {- method: 'PUT',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- avatar_id: avatar.id,- appearance: collapseAppearance(workingAppearance),- }),- });- if (!r.ok) {- const j = await r.json().catch(() => ({}));- throw new Error(j.error_description || `Could not save draft (${r.status})`);- }- const env = $('ae-walk-env')?.value || 'void';- const url = `/walk?avatar=${encodeURIComponent(draftId)}&preview=true&env=${encodeURIComponent(env)}`;- window.open(url, '_blank', 'noopener');- if (status) status.textContent = 'Opened in a new tab.';- } catch (err) {- if (status) status.textContent = err.message;- } finally {- if (btn) btn.disabled = false;+// Mint an unguessable draft id and stash the *current* (unsaved) look so the+// walk page renders exactly what's on the editor stage, not the last save.+async function buildWalkDraftUrl(env) {+ const draftId = (crypto.randomUUID?.() || `${Date.now()}-${Math.random()}`)+ .replace(/[^a-z0-9]/gi, '')+ .slice(0, 40);+ const r = await apiFetch(`/api/avatars/draft/${encodeURIComponent(draftId)}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ avatar_id: avatar.id,+ appearance: collapseAppearance(workingAppearance),+ }),+ });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || `Could not save draft (${r.status})`);}+ return `/walk?avatar=${encodeURIComponent(draftId)}&preview=true&env=${encodeURIComponent(env)}`;}function tilePreviewMarkup(preset) {diff --git a/src/avatar-rig.js b/src/avatar-rig.jsindex 14fa2f27d..ace62c6b8 100644--- a/src/avatar-rig.js+++ b/src/avatar-rig.js@@ -1,5 +1,6 @@/**- * Avatar rigging panel — /avatars/:id/edit → "Animate" tab.+ * Avatar rigging panel, shared by /avatars/:id/edit ("Animate" tab) and the+ * Avatar Studio edit mode ("Rig" tab).** A static (un-rigged) mesh can't play the pre-baked animation library: it has* no skeleton to drive. This panel turns such a mesh into an animation-ready@@ -64,8 +65,12 @@ async function isRiggingAvailable() {* @param {HTMLElement} options.container* @param {Object} options.avatar - the avatar being edited* @param {(newAvatar: Object) => void} options.onRigged - called with the new rigged avatar+ * @param {string} [options.buttonClass] - host page's button class, so the+ * action button inherits the surrounding editor's chrome. Defaults to the+ * avatar editor's `ae-btn`; Avatar Studio passes `as-btn`.*/-export function renderRigPanel({ container, avatar, onRigged }) {+export function renderRigPanel({ container, avatar, onRigged, buttonClass = 'ae-btn' }) {+ injectRigCss();const status = getRigStatus(avatar);const state = { phase: 'idle', message: null, progress: 0, jobId: null };let cancelled = false;@@ -237,7 +242,7 @@ export function renderRigPanel({ container, avatar, onRigged }) {}const btn = document.createElement('button');- btn.className = `ae-btn ${status.rigged ? '' : 'primary'}`.trim();+ btn.className = `${buttonClass} ${status.rigged ? '' : 'primary'}`.trim();btn.textContent = status.rigged ? 'Re-rig anyway' : 'Rig this model';el.appendChild(btn);@@ -294,3 +299,54 @@ export function renderRigPanel({ container, avatar, onRigged }) {paint();return { unmount: cleanup };}++/* ── styles ──────────────────────────────────────────────────────────────── */++// The panel is mounted by two different editors, so it owns its own chrome+// rather than assuming the host page declared `.ae-rig-*`. Every token carries+// a literal fallback: Avatar Studio does not define `--warn`, and a spinner+// that silently loses its keyframes reads as a hung job.+let rigCssInjected = false;+function injectRigCss() {+ if (rigCssInjected || typeof document === 'undefined') return;+ rigCssInjected = true;+ const style = document.createElement('style');+ style.id = 'ae-rig-css';+ style.textContent = `+ .ae-rig { display: flex; flex-direction: column; gap: 16px; padding: 4px 2px; }+ .ae-rig-pill {+ display: inline-flex; align-items: center; gap: 8px; align-self: flex-start;+ padding: 5px 12px; border-radius: 999px; font-size: 12px; font-weight: 600;+ letter-spacing: 0.01em; border: 1px solid var(--border-2, #2a2a2a); color: var(--text-2, #a1a1aa);+ }+ .ae-rig-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-3, #71717a); }+ .ae-rig-pill.ok { color: #34d399; border-color: rgba(52, 211, 153, 0.35); }+ .ae-rig-pill.ok .ae-rig-dot { background: #34d399; box-shadow: 0 0 8px rgba(52, 211, 153, 0.6); }+ .ae-rig-pill.warn { color: var(--warn, #f59e0b); border-color: color-mix(in srgb, var(--warn, #f59e0b) 35%, transparent); }+ .ae-rig-pill.warn .ae-rig-dot { background: var(--warn, #f59e0b); }+ .ae-rig-pill.unknown { color: var(--text-3, #71717a); }+ .ae-rig-detail { margin: 0; font-size: 13px; line-height: 1.5; color: var(--text-2, #a1a1aa); }+ .ae-rig-action { display: flex; flex-direction: column; gap: 10px; }+ .ae-rig-action button { align-self: flex-start; }+ .ae-rig-note { margin: 0; font-size: 12px; line-height: 1.5; color: var(--text-3, #71717a); }+ .ae-rig-error {+ font-size: 13px; line-height: 1.5; color: var(--danger, #f43f5e);+ padding: 10px 12px; border: 1px solid rgba(244, 63, 94, 0.3);+ border-radius: 10px; background: rgba(244, 63, 94, 0.06);+ }+ .ae-rig-busy { display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 28px 8px; text-align: center; }+ .ae-rig-spinner {+ width: 28px; height: 28px; border-radius: 50%;+ border: 3px solid var(--border-2, #2a2a2a); border-top-color: var(--text, #fafafa);+ animation: ae-rig-spin 0.9s linear infinite;+ }+ @keyframes ae-rig-spin { to { transform: rotate(360deg); } }+ @media (prefers-reduced-motion: reduce) { .ae-rig-spinner { animation-duration: 2.4s; } }+ .ae-rig-busy-msg { margin: 0; font-size: 14px; font-weight: 600; color: var(--text, #fafafa); }+ .ae-rig-busy-hint { margin: 0; font-size: 12px; color: var(--text-3, #71717a); }+ .ae-rig-bar { width: 100%; height: 6px; border-radius: 999px; background: var(--panel-2, #161616); overflow: hidden; }+ .ae-rig-bar-fill { height: 100%; background: var(--text, #fafafa); border-radius: 999px; transition: width 0.4s ease; }+ .ae-rig-done { display: flex; flex-direction: column; gap: 14px; padding: 8px 2px; }+ `;+ document.head.appendChild(style);+}diff --git a/src/avatar-sculpt.js b/src/avatar-sculpt.jsindex a1e5d9865..06e79ecc4 100644--- a/src/avatar-sculpt.js+++ b/src/avatar-sculpt.js@@ -110,10 +110,44 @@ const CATEGORIES = [// tongueOut intentionally omitted — RPM/Avaturn bake the morph but nobody// wants a "Tongue Out" slider on their face customizer. Drivers that need// it (lipsync, mocap) still hit it via runtime APIs.+ // Body regions of the parametric base. These sit BEFORE the catch-all Body+ // group on purpose: its regex would otherwise swallow every one of them.+ // They default to collapsed because the parametric base carries hundreds of+ // body sliders and an all-open panel is a wall, not a control surface.+ {+ id: 'neck',+ label: 'Neck',+ match: /^neck/,+ collapsed: true,+ },+ {+ id: 'torso',+ label: 'Torso',+ match: /^(torso|chest|bust|breast|waist|shoulders)/,+ collapsed: true,+ },+ {+ id: 'midsection',+ label: 'Hips & Midsection',+ match: /^(hips|hip|gluteus|buttocks|belly|stomach)/,+ collapsed: true,+ },+ {+ id: 'arms',+ label: 'Arms',+ match: /^(arms|forearm|upperarm|hands)/,+ collapsed: true,+ },+ {+ id: 'legs',+ label: 'Legs',+ match: /^(legs|thighs|calves|knees|feet)/,+ collapsed: true,+ },{id: 'body',label: 'Body',- match: /^(body|shape|height|breast|chest|waist|hip|muscle|weight|bust|gluteus|figure|thighs|arms|neck|belly|shoulders|calves|legs)/i,+ match: /^(body|shape|height|muscle|weight|figure)/i,},{id: 'visemes',@@ -132,6 +166,11 @@ const ARKIT52 = new Set(['eyeBlinkLeft','eyeBlinkRight','eyeLookDownLeft','eyeLookDownRight','eyeLookInLeft','eyeLookInRight','eyeLookOutLeft','eyeLookOutRight','eyeLookUpLeft','eyeLookUpRight','eyeSquintLeft','eyeSquintRight','eyeWideLeft','eyeWideRight','jawForward','jawLeft','jawRight','jawOpen','mouthClose','mouthFunnel','mouthPucker','mouthLeft','mouthRight','mouthSmileLeft','mouthSmileRight','mouthFrownLeft','mouthFrownRight','mouthDimpleLeft','mouthDimpleRight','mouthStretchLeft','mouthStretchRight','mouthRollLower','mouthRollUpper','mouthShrugLower','mouthShrugUpper','mouthPressLeft','mouthPressRight','mouthLowerDownLeft','mouthLowerDownRight','mouthUpperUpLeft','mouthUpperUpRight','browDownLeft','browDownRight','browInnerUp','browOuterUpLeft','browOuterUpRight','cheekPuff','cheekSquintLeft','cheekSquintRight','noseSneerLeft','noseSneerRight','tongueOut',]);+// Above this many morphs the panel stops being scannable and earns a filter.+// Parametric bases blow past it; a 52-blendshape RPM avatar never does, so its+// panel stays exactly as it was.+const FILTER_THRESHOLD = 80;+/* ────────────────────────────────────────────────────────────────────────── ** Blend wheel presets — 6 face archetypes placed on a 2-D [-1..1] plane.*@@ -309,6 +348,13 @@ export function renderSculptPanel({ container, root, working, onDirty, onRigChan</label>` : ''}<button class="ae-btn ae-sculpt-reset" type="button" id="ae-sculpt-reset">Reset all</button></div>+ ${all.length > FILTER_THRESHOLD ? `+ <div class="ae-sculpt-filter">+ <input type="search" id="ae-sculpt-filter-input" autocomplete="off"+ placeholder="Filter ${all.length} sliders (nose, jaw, calf...)"+ aria-label="Filter sculpt sliders">+ <span class="ae-sculpt-filter-count" id="ae-sculpt-filter-count" role="status" aria-live="polite"></span>+ </div>` : ''}<p class="ae-sculpt-note">${all.length? `Drag the wheel puck to blend face types. Use sliders for fine control.@@ -327,6 +373,7 @@ export function renderSculptPanel({ container, root, working, onDirty, onRigChanensureProportionCss();wireSliders(container, root, working, onDirty);+ wireFilter(container);if (all.length) wireBlendWheel(container, root, working, available, onDirty);wireProportionsGroup({ container, root, working, boneMap, onDirty, onRigChanged, rerender });@@ -380,6 +427,55 @@ function ensureProportionCss() {.ae-prop-row { grid-template-columns: minmax(0, 1.3fr) minmax(0, 2fr) 52px; }.ae-prop-row .ae-sculpt-value { color: var(--text-2, var(--text-3)); }.ae-prop-rows #ae-prop-reset { align-self: flex-start; margin-top: 10px; }++ /* Filter + edited badges. These ship with the module rather than with+ either page's inline <style> because both surfaces render the same+ panel and a copy-pasted rule is a rule that drifts. */+ .ae-sculpt-filter {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 0 0 10px;+ }+ .ae-sculpt-filter input[type='search'] {+ flex: 1 1 auto;+ min-width: 0;+ padding: 8px 10px;+ font: inherit;+ font-size: 12px;+ color: var(--text);+ background: var(--panel);+ border: 1px solid var(--border-2);+ border-radius: 8px;+ transition: border-color 0.12s, box-shadow 0.12s;+ }+ .ae-sculpt-filter input[type='search']:hover { border-color: var(--text-3); }+ .ae-sculpt-filter input[type='search']:focus-visible {+ outline: none;+ border-color: var(--accent);+ box-shadow: 0 0 0 2px var(--accent-dim, rgba(255, 255, 255, 0.14));+ }+ .ae-sculpt-filter-count {+ font-size: 10px;+ color: var(--text-3);+ white-space: nowrap;+ }+ /* .ae-sculpt-row sets display:grid, which outranks the UA [hidden] rule,+ so filtering needs its own hide. Same for the group wrapper. */+ .ae-sculpt-row[hidden],+ .ae-sculpt-group[hidden] { display: none; }+ /* Let the group title claim the free space so the badges sit together on+ the right whether or not the edited pill is showing. */+ .ae-sculpt-group summary > span:first-child { margin-right: auto; }+ .ae-sculpt-group summary .ae-sculpt-count { margin-left: 6px; }+ .ae-sculpt-edited {+ font-size: 10px;+ font-weight: 600;+ color: var(--accent-ink, #000);+ background: var(--accent);+ padding: 2px 7px;+ border-radius: 999px;+ }`;document.head.appendChild(style);}@@ -566,6 +662,7 @@ function wireSliders(container, root, working, onDirty) {writeMorph(working, pairName, w);applyMorphsToRoot(root, { [pairName]: w });}+ refreshEditedBadge(input);onDirty?.();};input.addEventListener('input', onChange);@@ -582,6 +679,88 @@ function writeMorph(working, name, w) {* Group rendering — mirror-lock collapses L/R pairs to a single slider* ────────────────────────────────────────────────────────────────────────── */+/**+ * Live filter over every slider row. Groups whose rows all fall away are hidden+ * entirely and matching groups spring open, so a query lands the user on the+ * control instead of on a list of closed folders. Clearing the box restores the+ * group open/closed state exactly as it was before the first keystroke.+ */+function wireFilter(container) {+ const input = container.querySelector('#ae-sculpt-filter-input');+ if (!input) return;+ const countEl = container.querySelector('#ae-sculpt-filter-count');+ const groups = [...container.querySelectorAll('details.ae-sculpt-group')];+ const rows = [...container.querySelectorAll('.ae-sculpt-row[data-search]')];+ const total = rows.length;+ let restoreOpen = null;++ const apply = () => {+ const q = input.value.trim().toLowerCase();+ if (!q) {+ for (const row of rows) row.hidden = false;+ groups.forEach((g, i) => {+ g.hidden = false;+ if (restoreOpen) g.open = restoreOpen[i];+ });+ restoreOpen = null;+ if (countEl) countEl.textContent = '';+ return;+ }+ if (!restoreOpen) restoreOpen = groups.map((g) => g.open);++ const terms = q.split(/\s+/);+ let shown = 0;+ for (const row of rows) {+ const hay = row.dataset.search;+ const hit = terms.every((t) => hay.includes(t));+ row.hidden = !hit;+ if (hit) shown++;+ }+ for (const g of groups) {+ const hit = !!g.querySelector('.ae-sculpt-row[data-search]:not([hidden])');+ g.hidden = !hit;+ if (hit) g.open = true;+ }+ if (countEl) {+ countEl.textContent = shown+ ? `${shown} of ${total}`+ : 'No slider matches that';+ }+ };++ input.addEventListener('input', apply);+ input.addEventListener('keydown', (e) => {+ if (e.key !== 'Escape' || !input.value) return;+ e.stopPropagation();+ input.value = '';+ apply();+ });+}++/**+ * "3 edited" pill on a collapsed group's summary. With hundreds of sliders the+ * panel is mostly closed, and without this the user has no way to tell which+ * closed groups they have already touched.+ */+function editedBadge(names, morphs) {+ const n = names.reduce((c, name) => c + (morphs[name] ? 1 : 0), 0);+ return `<span class="ae-sculpt-edited" data-edited="${n}"${n ? '' : ' hidden'}>${n} edited</span>`;+}++/** Recount the badge on the group owning `input` after a slider moves. */+function refreshEditedBadge(input) {+ const group = input.closest('details.ae-sculpt-group');+ const badge = group?.querySelector('.ae-sculpt-edited');+ if (!badge) return;+ let n = 0;+ group.querySelectorAll('input[type="range"][data-morph]').forEach((el) => {+ if (Number(el.value) !== 0) n++;+ });+ badge.dataset.edited = String(n);+ badge.textContent = `${n} edited`;+ badge.hidden = n === 0;+}+function renderGroup(g, morphs) {if (_mirrorLocked) {const visible = [];@@ -606,6 +785,7 @@ function renderGroup(g, morphs) {<details class="ae-sculpt-group" ${g.collapsed ? '' : 'open'}><summary><span>${escHtml(g.label)}</span>+ ${editedBadge(visible.map((v) => v.name), morphs)}<span class="ae-sculpt-count">${visible.length}</span></summary><div class="ae-sculpt-rows">@@ -618,6 +798,7 @@ function renderGroup(g, morphs) {<details class="ae-sculpt-group" ${g.collapsed ? '' : 'open'}><summary><span>${escHtml(g.label)}</span>+ ${editedBadge(g.morphs, morphs)}<span class="ae-sculpt-count">${g.morphs.length}</span></summary><div class="ae-sculpt-rows">@@ -805,8 +986,11 @@ function sliderRow(name, value, displayLabel, pairName) {const label = humanize(labelSource);const meta = ARKIT52.has(name) ? 'ARKit' : isVisemeName(name) ? 'Viseme' : '';const pairAttr = pairName ? ` data-pair="${escAttr(pairName)}"` : '';+ // data-search carries both the human label and the raw morph name so the+ // filter finds "cupids bow" and "mouthCupidsBowWider" with one query.+ const search = `${label} ${name}`.toLowerCase();return `- <div class="ae-sculpt-row">+ <div class="ae-sculpt-row" data-search="${escAttr(search)}"><div class="ae-sculpt-label"><span class="ae-sculpt-name" title="${escAttr(name)}">${escHtml(label)}</span>${meta ? `<span class="ae-sculpt-meta">${meta}</span>` : ''}diff --git a/src/avatar-studio-utils.js b/src/avatar-studio-utils.jsindex 922f37ab4..fcc92f6b7 100644--- a/src/avatar-studio-utils.js+++ b/src/avatar-studio-utils.js@@ -8,12 +8,11 @@ import { normalizeProportions } from './avatar-proportions.js';export const DRAFT_KEY = 'avatar-studio-draft';export const DRAFT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days-// `outfit` (a baked preset id) and `garments` (additive catalog wearables, see-// specs/GARMENT_MANIFEST.md) are part of the stored appearance record but the-// Studio has no UI for either (the wardrobe lives in the avatar editor). They-// are still carried through hydrate/collapse/clone verbatim: a PATCH replaces-// `appearance` wholesale, so dropping them here would silently undress any-// avatar opened in Studio's edit mode and saved.+// `garments` (additive catalog wearables, see specs/GARMENT_MANIFEST.md) are+// driven by the Studio's Wardrobe tab; `outfit` (a baked preset id) still has+// no UI anywhere. Both are carried through hydrate/collapse/clone verbatim: a+// PATCH replaces `appearance` wholesale, so dropping either here would silently+// undress an avatar opened in Studio's edit mode and saved./** Copy the garment list, isolating each {slot, id} entry from the source. */function copyGarments(list) {diff --git a/src/avatar-studio.js b/src/avatar-studio.jsindex fb638fc6d..2e878c4d3 100644--- a/src/avatar-studio.js+++ b/src/avatar-studio.js@@ -29,6 +29,11 @@ import {PROPORTION_PARAMS,} from './avatar-proportions.js';import { canonicalBoneNodesFromObject } from './animation-retarget.js';+import { renderWardrobePanel } from './avatar-wardrobe.js';+import { GarmentCloset, renderClosetSection, SLOT_LABEL_ONE } from './garment-closet.js';+import { renderRigPanel } from './avatar-rig.js';+import { createWalkPanel } from './avatar-walk-panel.js';+import { playAs } from './game/play-handoff.js';import { saveRemoteGlbToAccount, apiFetch } from './account.js';import { captureWizardReturn, returnToWizard } from './shared/wizard-return.js';@@ -97,6 +102,19 @@ let editAvatarId = null; // non-null when in edit mode (?edit=ID)let history = [];let historyIndex = -1;+// Additive-wardrobe controller: catalog garments skinned onto this avatar's+// skeleton at runtime (specs/GARMENT_MANIFEST.md). Created once the scene root+// exists, in both create and edit mode -- adding a garment needs a rig, not a+// saved record.+let closet = null;+// Walk-tab controller (src/avatar-walk-panel.js). Owns a second AnimationManager+// on the same rig, so proportion edits have to re-measure it too.+let walkPanel = null;+// The avatar loaded in edit mode, kept for the panels that need the record+// itself (rig status, the /walk draft handoff, "Play as this").+let editAvatar = null;+let idleDispose = null;+let previewedId = null;let previewToken = 0;let opQueue = Promise.resolve();@@ -184,15 +202,26 @@ function beginBusy(label) {};}+// `editOnly` tabs need a saved avatar record behind them: rigging POSTs the+// avatar's id to the regenerate backend, so there is nothing to rig from a+// draft. The Walk tab renders in both modes (locomotion needs only the live+// rig); its handoff into /walk is what degrades, inside the panel.const TABS = [{ id: 'color', label: 'Color', kinds: [], emoji: '🎨', color: true },+ { id: 'wardrobe', label: 'Wardrobe', kinds: [], emoji: '👕', wardrobe: true },{ id: 'hat', label: 'Hats', kinds: ['hat'], emoji: '🎩', single: true },{ id: 'glasses', label: 'Glasses', kinds: ['glasses'], emoji: '🕶️', single: true },{ id: 'earrings', label: 'Earrings', kinds: ['earrings'], emoji: '💎', single: false },{ id: 'sculpt', label: 'Sculpt', kinds: [], emoji: '✨', single: true, sculpt: true },{ id: 'animate', label: 'Animate', kinds: [], emoji: '🎬', animate: true },+ { id: 'walk', label: 'Walk', kinds: [], emoji: '🚶', walk: true },+ { id: 'rig', label: 'Rig', kinds: [], emoji: '🦴', rig: true, editOnly: true },];+function visibleTabs() {+ return TABS.filter((t) => !t.editOnly || editAvatar);+}+const KIND_EMOJI = { hat: '🎩', glasses: '🕶️', earrings: '💎' };const KIND_LABEL = { hat: 'Hat', glasses: 'Glasses', earrings: 'Earrings' };let activeTab = 'color';@@ -281,7 +310,6 @@ async function init() {const params = new URLSearchParams(location.search);editAvatarId = parseEditId(params);- let editAvatar = null;if (editAvatarId) {try {editAvatar = await fetchEditAvatar(editAvatarId);@@ -329,9 +357,9 @@ async function init() {bindHeader();bindKeyboard();- // The accessory catalog powers three of six tabs. A catalog outage degrades- // those tabs to a retryable error; it must not take down colors, sculpt,- // animate, or save, all of which need nothing from it.+ // The accessory catalog powers three of the accessory tabs. A catalog outage+ // degrades those tabs to a retryable error; it must not take down colors,+ // wardrobe, sculpt, animate, walk or save, none of which need it.const presetsPromise = loadPresets();await scenePromise;@@ -340,10 +368,48 @@ async function init() {applyAllColors();applyAllLayers();}+ await applyEquipHandoff(params);renderActivePanel();updateDirtyState();}+// Gallery "Equip" handoff: /avatar-studio?equip-glb=<url>&equip-kind=hat pre-+// applies an accessory GLB that is not in the presets catalog and dirties the+// state so Save lights up. Same contract the avatar editor honours, so a+// gallery tile can hand off to either editor.+const EQUIP_KINDS = ['hat', 'glasses', 'earrings'];++async function applyEquipHandoff(params) {+ const glbUrl = params.get('equip-glb') || '';+ if (!glbUrl || !accessoryManager) return;+ const kind = EQUIP_KINDS.includes(params.get('equip-kind') || '')+ ? params.get('equip-kind')+ : 'hat';+ const name = params.get('equip-name') || 'Gallery accessory';+ const preset = {+ id: `gallery:${btoa(glbUrl).replace(/[^a-z0-9]/gi, '').slice(0, 32)}`,+ kind,+ name,+ glbUrl,+ attachBone: params.get('equip-bone') || 'Head',+ };+ const { ok } = await runQueued(() => accessoryManager.applyPreset(preset));+ if (!ok) {+ setStatus('err', `Could not load "${name}". Everything else is ready.`);+ return;+ }+ if (!workingAppearance.accessories.includes(preset.id)) {+ workingAppearance.accessories = [...workingAppearance.accessories, preset.id];+ }+ // The synthetic preset is not in the catalog, so register it for the chip+ // bar and the tile-selected checks that read presetsById.+ presetsById.set(preset.id, preset);+ pushHistory();+ renderChips();+ updateDirtyState();+ setStatus('ok', `"${name}" added. Save to keep it on your avatar.`);+}+async function fetchEditAvatar(id) {const res = await apiFetch(`/api/avatars/${encodeURIComponent(id)}`);if (!res.ok) {@@ -492,6 +558,13 @@ async function applyHistoryState(state) {if (accessoryManager) {await runQueued(() => accessoryManager.hydrateFromAppearance(target));}+ // Catalog garments live on the rig, not in the appearance-driven accessory+ // manager, so undo/redo has to re-dress the closet explicitly or a stepped-+ // over garment stays on the body while the record says it is off.+ if (closet && token === historyToken) {+ closet.clear();+ await closet.hydrate(target.garments);+ }done();if (token !== historyToken) return;@@ -608,6 +681,9 @@ function applyProportions() {if (!scene?.root) return;applyProportionsToRoot(scene.root, workingAppearance.proportions, { boneMap: boneNodes });scene.getEmoteController()?.remeasureRig?.();+ // The walk preview owns a second AnimationManager on the same rig, so it has+ // its own stale hip scale to fix.+ walkPanel?.remeasureProportions();}// ── Boot scene ────────────────────────────────────────────────────────@@ -645,9 +721,34 @@ async function bootScene(glbUrl, editAvatar) {idle = new IdleAnimation({getRoot: () => scene.root,- seed: 'avatar-studio',+ seed: editAvatar?.id || 'avatar-studio',+ });+ // Held rather than discarded: the Walk tab has to silence this layer+ // while a retargeted clip owns the skeleton, or the two fight per frame.+ idleDispose = scene.addOnTick((dt) => idle.update(dt));++ // Additive wardrobe. Unknown or retired garments degrade to "not worn"+ // inside hydrate rather than failing the whole boot.+ closet = new GarmentCloset({+ getRoot: () => scene?.root || null,+ getWorking: () => workingAppearance,+ // The parametric base ships a baked UV region mask, giving worn+ // garments pixel-exact skin occlusion. Other bodies use bone-cull.+ regionMaskUrl: glbUrl.includes('parametric-base')+ ? '/avatars/parametric-base.regions.png'+ : null,+ onDirty: () => {+ pushHistory();+ updateDirtyState();+ scheduleDraftSave();+ },+ onChanged: () => renderChips(),});- scene.addOnTick((dt) => idle.update(dt));+ // Racks render as soon as the closet exists: browsing the catalog must+ // not wait behind re-downloading a saved outfit (hydrate below marks+ // tiles worn as each piece lands, via the onChanged re-render).+ if (activeTab === 'wardrobe') renderActivePanel();+ await closet.hydrate(workingAppearance.garments);// Bring the rig to life: load the clip library and settle the avatar into// a looping idle so it leaves its bind T-pose. The clip drives the whole@@ -672,6 +773,66 @@ async function bootScene(glbUrl, editAvatar) {}}+// ── Walk preview ─────────────────────────────────────────────────────++// Same control the avatar editor mounts (src/avatar-walk-panel.js). In edit+// mode the "Open in Walk page" handoff stashes the *unsaved* look as a draft so+// the walk page renders the stage, not the last save. In create mode there is+// no avatar record to presign a base GLB from, so the panel says so instead of+// offering a button that would 400.+function getWalkPanel() {+ if (walkPanel) return walkPanel;+ if (!scene?.root) return null;+ walkPanel = createWalkPanel({+ getScene: () => scene,+ getStageEl: () => $('as-stage'),+ buttonClass: 'as-btn',+ emptyClass: 'as-empty',+ pauseAmbient: () => {+ if (idleDispose) {+ idleDispose();+ idleDispose = null;+ }+ },+ resumeAmbient: () => {+ if (idle && scene && !idleDispose) {+ idleDispose = scene.addOnTick((dt) => idle.update(dt));+ }+ },+ openWalkUrl: editAvatar ? buildWalkDraftUrl : null,+ saveHint: 'Save this avatar to open it in the full Walk page.',+ });+ return walkPanel;+}++function renderWalkPanel(panel) {+ const p = getWalkPanel();+ if (!p) {+ panel.innerHTML = `<div class="as-empty">Waiting for avatar to load...</div>`;+ return;+ }+ p.render(panel);+}++async function buildWalkDraftUrl(env) {+ const draftId = (crypto.randomUUID?.() || `${Date.now()}-${Math.random()}`)+ .replace(/[^a-z0-9]/gi, '')+ .slice(0, 40);+ const r = await apiFetch(`/api/avatars/draft/${encodeURIComponent(draftId)}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ avatar_id: editAvatar.id,+ appearance: collapseAppearance(workingAppearance),+ }),+ });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || `Could not save draft (${r.status})`);+ }+ return `/walk?avatar=${encodeURIComponent(draftId)}&preview=true&env=${encodeURIComponent(env)}`;+}+// ── Animate — live rig playback ──────────────────────────────────────/**@@ -776,7 +937,7 @@ async function retryPresets() {function renderTabs() {const el = $('as-tabs');- el.innerHTML = TABS.map((t) => {+ el.innerHTML = visibleTabs().map((t) => {const active = t.id === activeTab;// The icon carries the tab on narrow viewports, where the word label is// hidden. `aria-label` is unconditional so the button keeps its name in@@ -828,15 +989,80 @@ function renderActivePanel() {// A re-render replaces the swatch DOM the popover is anchored to; close it// first so it never points at a detached node.closeActivePopover();- const tab = TABS.find((t) => t.id === activeTab);+ const tabs = visibleTabs();+ let tab = tabs.find((t) => t.id === activeTab);+ if (!tab) {+ tab = tabs[0];+ activeTab = tab.id;+ }const panel = $('as-panel');panel.setAttribute('aria-labelledby', `as-tab-${activeTab}`);+ // Leaving the Walk tab tears locomotion down and restores the static stage.+ // Idempotent, so it is safe on every render regardless of the source tab.+ if (activeTab !== 'walk') walkPanel?.exit();+if (tab.color) {renderColorPanel(panel);return;}+ if (tab.walk) {+ renderWalkPanel(panel);+ return;+ }++ // Wardrobe: recolour and show/hide the avatar's own baked garment layers+ // (src/avatar-wardrobe.js resolves them on arbitrary GLBs by mesh/material+ // shape, not a hardcoded name list), plus the closet of additive catalog+ // garments skinned onto the live skeleton with occlusion masking.+ if (tab.wardrobe) {+ if (!scene?.root) {+ panel.innerHTML = `<div class="as-empty">Waiting for avatar to load...</div>`;+ return;+ }+ renderWardrobePanel({+ container: panel,+ root: scene.root,+ working: workingAppearance,+ applyLayers: (layers) => accessoryManager?.applyLayers(layers),+ onDirty: () => {+ pushHistory();+ renderChips();+ updateDirtyState();+ scheduleDraftSave();+ },+ });+ // The closet renders beneath the layer cards. It exists even for models+ // with no built-in layers: being able to ADD a garment is exactly what a+ // layerless avatar needs.+ const closetMount = document.createElement('div');+ closetMount.className = 'as-closet-mount';+ panel.appendChild(closetMount);+ if (closet) {+ renderClosetSection({ container: closetMount, closet });+ } else {+ closetMount.innerHTML = '<div class="gc-loading">Closet opens when the avatar finishes loading...</div>';+ }+ return;+ }++ // Rig: rig status plus one-click auto-rig. Non-destructive (it mints a new+ // sibling avatar), so on success we hand the owner into that new avatar's+ // Studio session rather than silently swapping the model under them.+ if (tab.rig) {+ renderRigPanel({+ container: panel,+ avatar: editAvatar,+ buttonClass: 'as-btn',+ onRigged: (newAvatar) => {+ if (!newAvatar?.id) return;+ location.href = `/avatar-studio?edit=${encodeURIComponent(newAvatar.id)}`;+ },+ });+ return;+ }+if (tab.sculpt) {if (!scene?.root) {panel.innerHTML = `<div class="as-empty">Waiting for avatar to load…</div>`;@@ -854,7 +1080,10 @@ function renderActivePanel() {},// Debounced by the panel: rebuilding every bound action on each// slider frame would stutter the drag.- onRigChanged: () => scene?.getEmoteController()?.remeasureRig?.(),+ onRigChanged: () => {+ scene?.getEmoteController()?.remeasureRig?.();+ walkPanel?.remeasureProportions();+ },});return;}@@ -1464,8 +1693,28 @@ function renderChips() {</span>`);}+ // Worn catalog garments. Read from the closet rather than+ // `workingAppearance.garments` so a chip only ever names a piece that is+ // actually on the rig (hydrate drops retired ids).+ for (const [slot, entry] of closet?.attached() || []) {+ const name = entry?.manifest?.name;+ if (!name) continue;+ parts.push(`+ <span class="as-chip" data-garment="${esc(slot)}">+ <span class="as-chip-kind">${esc(SLOT_LABEL_ONE[slot] || slot)}</span>+ <span>${esc(name)}</span>+ <button type="button" aria-label="Take off ${esc(name)}" data-takeoff="${esc(slot)}">×</button>+ </span>`);+ }+el.innerHTML = parts.join('');+ // detach() emits onDirty + onChanged, which re-runs this render and refreshes+ // the closet racks through their own subscription, so nothing else to do here.+ el.querySelectorAll('button[data-takeoff]').forEach((btn) => {+ btn.addEventListener('click', () => closet?.detach(btn.dataset.takeoff));+ });+el.querySelectorAll('button[data-remove]').forEach((btn) => {btn.addEventListener('click', () => removeCommitted(btn.dataset.remove));});@@ -1667,6 +1916,7 @@ async function applyAccessory(tab, presetId) {function bindHeader() {$('as-save').addEventListener('click', () => saveAvatar());$('as-reset').addEventListener('click', () => resetAll());+ bindPlayAs();// A renamed avatar is an unsaved change too, so keep the dirty marker honest.$('as-name')?.addEventListener('input', () => updateDirtyState());$('as-randomize')?.addEventListener('click', () => randomizeAppearance());@@ -1674,6 +1924,36 @@ function bindHeader() {$('as-redo')?.addEventListener('click', () => redoAppearance());}+// "Play as this": drop straight into /play wearing the avatar on the stage.+// Only offered in edit mode, where there is a saved record for /play to load;+// a create-mode draft has nothing to hand over until Save mints one. Unsaved+// edits are committed first, so /play never renders a stale look.+function bindPlayAs() {+ const btn = $('as-play');+ if (!btn) return;+ if (!editAvatar) return;+ btn.hidden = false;+ btn.addEventListener('click', async () => {+ btn.disabled = true;+ try {+ if (isDirtyNow()) {+ // The PATCH directly, not saveAvatar(): the full save path ends in a+ // success toast and a redirect to the avatar page, which would race+ // the handoff into /play.+ setStatus('spin', 'Saving your look before you play...');+ await patchEditedAvatar(editAvatarId, currentName(), collapseAppearance(workingAppearance));+ savedAppearance = cloneAppearance(workingAppearance);+ updateDirtyState();+ }+ setStatus('spin', 'Entering /play...');+ await playAs({ id: editAvatar.id, name: currentName(), dest: '/play' });+ } catch (err) {+ setStatus('err', err.message);+ btn.disabled = false;+ }+ });+}+function bindKeyboard() {document.addEventListener('keydown', (e) => {const mod = e.metaKey || e.ctrlKey;@@ -1692,13 +1972,14 @@ async function resetAll() {if (accessoryManager) {for (const id of wasIds) accessoryManager.removePreset(id);}- // Reset clears what Studio controls. The wardrobe it cannot show (baked- // outfit preset, catalog garments) is not Studio's to throw away.+ // Reset clears what Studio controls, which now includes the closet. The+ // baked `outfit` preset id has no Studio UI, so it is not Studio's to+ // throw away and rides through untouched.workingAppearance = {...hydrateAppearance(null),outfit: workingAppearance.outfit ?? null,- garments: (workingAppearance.garments || []).map((g) => ({ ...g })),};+ closet?.clear();if (scene?.root) {applyMorphsToRoot(scene.root, {});applyProportions();@@ -1859,7 +2140,12 @@ async function saveAvatar() {// This captures all colours, morphs, and accessories already applied// to the Three.js scene — no server-side bake needed.updateSaveOverlay('Exporting model...', 'Capturing colours and accessories');- const rawGlbBlob = await exportSceneGlb();+ // Catalog garments are re-baked from the appearance record PATCHed below,+ // so the uploaded base must not already be wearing them (see+ // GarmentCloset#withGarmentsOff). The closet puts them straight back.+ const rawGlbBlob = closet+ ? await closet.withGarmentsOff(() => exportSceneGlb())+ : await exportSceneGlb();updateProgress(15);// ── Step 1b: Compress + validate before upload ──────────────@@ -1965,11 +2251,11 @@ async function patchEditedAvatar(avatarId, name, appearance) {// toast, redirect.async function finishSave(avatar) {// A Studio snapshot only represents the avatar faithfully when Studio drew- // everything it is wearing. Wardrobe garments and baked outfit presets are- // carried through the appearance record but have no Studio UI and are not in- // the live scene, so overwriting the thumbnail here would show the avatar- // undressed. Leave the existing thumbnail alone in that case.- const wearsUnrenderedLayers = !!(workingAppearance.outfit || workingAppearance.garments?.length);+ // everything it is wearing. Closet garments now ARE on the live rig, so they+ // photograph correctly; a baked `outfit` preset id still has no Studio UI and+ // is not in the scene, so overwriting the thumbnail while one is set would+ // show the avatar undressed. Leave the existing thumbnail alone in that case.+ const wearsUnrenderedLayers = !!workingAppearance.outfit;if (!wearsUnrenderedLayers) {updateSaveOverlay('Capturing thumbnail...');try {diff --git a/src/avatar-walk-panel.js b/src/avatar-walk-panel.jsnew file mode 100644index 000000000..1181c89a9--- /dev/null+++ b/src/avatar-walk-panel.js@@ -0,0 +1,213 @@+/**+ * Walk-preview panel, shared by /avatars/:id/edit ("Walk" tab) and the Avatar+ * Studio ("Walk" tab).+ *+ * The panel is two things at once:+ * 1. An in-stage locomotion preview. `AvatarWalkPreview` takes over the+ * editor's existing TalkScene, so every sculpt, colour, garment and+ * accessory edit shows up in motion without a reload.+ * 2. A handoff into the full /walk page. That leg needs a saved avatar: the+ * draft endpoint resolves the avatar's private base GLB server-side and+ * presigns it (see api/avatars/draft/[id].js), which it can only do for a+ * record the caller owns. An unsaved Studio draft has no such record, so+ * the button is replaced by an honest "save first" line rather than a+ * control that would 400.+ *+ * The module owns its own CSS so neither host page has to declare `.ae-walk-*`.+ */++import { AvatarWalkPreview } from './avatar-edit-walk.js';+import { log } from './shared/log.js';++const KEYS = ['W', 'A', 'S', 'D'];++function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/**+ * Create a walk-preview controller bound to one editor's scene.+ *+ * @param {Object} options+ * @param {() => Object|null} options.getScene - the live TalkScene (null before mount).+ * @param {() => HTMLElement|null} options.getStageEl - the 3D stage container.+ * @param {() => void} options.pauseAmbient - stop the editor's procedural idle layer.+ * @param {() => void} options.resumeAmbient - restart it on exit.+ * @param {string} [options.buttonClass] - host page's button class for the handoff CTA.+ * @param {string} [options.emptyClass] - host page's "waiting for the avatar" class.+ * @param {() => Promise<string>} [options.openWalkUrl] - resolve the /walk URL to+ * open, given the currently selected environment. Omit it (or return null) and+ * the handoff CTA is replaced by `saveHint`.+ * @param {string} [options.saveHint] - what to say when the handoff is unavailable.+ */+export function createWalkPanel({+ getScene,+ getStageEl,+ pauseAmbient,+ resumeAmbient,+ buttonClass = 'ae-btn',+ emptyClass = 'ae-empty',+ openWalkUrl = null,+ saveHint = '',+}) {+ let preview = null;+ let statusEl = null;++ function getPreview() {+ if (preview) return preview;+ const scene = getScene();+ if (!scene?.root) return null;+ preview = new AvatarWalkPreview({+ scene,+ stageEl: getStageEl(),+ pauseAmbient,+ resumeAmbient,+ });+ preview.onStatus((msg) => {+ if (statusEl) statusEl.textContent = msg || '';+ });+ return preview;+ }++ function enter() {+ const p = getPreview();+ if (!p || p.active) return;+ p.enter().catch((err) => {+ log.warn('[walk-panel] preview enter failed:', err?.message);+ if (statusEl) statusEl.textContent = `Could not start walk: ${err.message}`;+ });+ }++ function exit() {+ if (preview?.active) preview.exit();+ }++ function render(panel) {+ injectCss();+ if (!getScene()?.root) {+ panel.innerHTML = `<div class="${esc(emptyClass)}">Waiting for avatar to load...</div>`;+ return;+ }+ // Re-rendering would drop the chosen environment, and renderActivePanel+ // re-fires while the Walk tab stays active (a save, an undo). Re-entering+ // locomotion is idempotent, so that is all this branch has to do.+ if (panel.querySelector('.ae-walk')) {+ enter();+ return;+ }++ const kbd = KEYS.map((k) => `<kbd>${k}</kbd>`).join('');+ const cta = openWalkUrl+ ? `<button class="${esc(buttonClass)} primary ae-walk-open" type="button">Open in Walk page →</button>`+ : `<p class="ae-walk-note ae-walk-hint">${esc(saveHint)}</p>`;++ panel.innerHTML = `+ <div class="ae-walk">+ <p class="ae-walk-lede">+ See your avatar in motion. It auto-walks a circle around the stage,+ and you can take over any time with ${kbd} or the arrow keys.+ Every sculpt, outfit, and accessory edit shows up here live.+ </p>++ <label class="ae-walk-field">+ <span class="ae-walk-field-label">Environment</span>+ <select class="ae-walk-select" aria-label="Preview environment">+ <option value="void">Void</option>+ </select>+ </label>++ ${cta}+ <p class="ae-walk-note ae-walk-status" role="status" aria-live="polite"></p>+ </div>+ `;++ statusEl = panel.querySelector('.ae-walk-status');+ const envSel = panel.querySelector('.ae-walk-select');+ envSel.addEventListener('change', () => getPreview()?.setEnvironment(envSel.value));+ panel.querySelector('.ae-walk-open')?.addEventListener('click', (e) => {+ openInWalkPage(e.currentTarget, envSel.value);+ });++ enter();++ // Backfill the real environment list once the manifest resolves. Until+ // then the select offers the one environment the runtime always has.+ const p = getPreview();+ p?.listEnvironments().then((envs) => {+ if (!envs || envs.length <= 1) return;+ const current = p.envName || 'void';+ envSel.innerHTML = envs+ .map(+ (e) =>+ `<option value="${esc(e.name)}"${e.name === current ? ' selected' : ''}>${esc(e.label)}</option>`,+ )+ .join('');+ });+ }++ async function openInWalkPage(btn, env) {+ if (!openWalkUrl) return;+ btn.disabled = true;+ if (statusEl) statusEl.textContent = 'Preparing preview...';+ try {+ const url = await openWalkUrl(env);+ if (!url) throw new Error('Could not build the preview link.');+ window.open(url, '_blank', 'noopener');+ if (statusEl) statusEl.textContent = 'Opened in a new tab.';+ } catch (err) {+ if (statusEl) statusEl.textContent = err.message;+ } finally {+ btn.disabled = false;+ }+ }++ return {+ render,+ enter,+ exit,+ get active() {+ return !!preview?.active;+ },+ /** Re-measure the clip stack after a proportion edit moved the hips. */+ remeasureProportions() {+ preview?.remeasureProportions();+ },+ };+}++/* ── styles ──────────────────────────────────────────────────────────────── */++let cssInjected = false;+function injectCss() {+ if (cssInjected || typeof document === 'undefined') return;+ cssInjected = true;+ const style = document.createElement('style');+ style.id = 'ae-walk-css';+ style.textContent = `+ .ae-walk { display: flex; flex-direction: column; gap: 16px; padding: 4px 2px; }+ .ae-walk-lede { margin: 0; font-size: 13px; line-height: 1.6; color: var(--text-2, #a1a1aa); }+ .ae-walk-lede kbd {+ display: inline-block; min-width: 18px; padding: 1px 5px; margin: 0 1px;+ font-family: ui-monospace, 'SF Mono', monospace; font-size: 11px; text-align: center;+ color: var(--text, #fafafa); background: var(--panel-2, #161616);+ border: 1px solid var(--border-2, #2a2a2a); border-bottom-width: 2px; border-radius: 5px;+ }+ .ae-walk-field { display: flex; flex-direction: column; gap: 6px; }+ .ae-walk-field-label {+ font-size: 11px; text-transform: uppercase; letter-spacing: 0.07em; color: var(--text-3, #71717a);+ }+ .ae-walk-select {+ width: 100%; background: var(--panel-2, #161616); border: 1px solid var(--border-2, #2a2a2a);+ border-radius: 8px; color: var(--text, #fafafa); padding: 9px 12px; font-size: 13px;+ font-family: inherit; outline: none; cursor: pointer; transition: border-color 0.15s;+ }+ .ae-walk-select:focus-visible { border-color: var(--accent, #fafafa); }+ .ae-walk-open { align-self: flex-start; }+ .ae-walk-note { margin: 0; font-size: 12px; line-height: 1.5; color: var(--text-3, #71717a); min-height: 16px; }+ .ae-walk-hint { color: var(--text-2, #a1a1aa); }+ `;+ document.head.appendChild(style);+}diff --git a/src/garment-closet.js b/src/garment-closet.jsindex 904cac046..722830ae1 100644--- a/src/garment-closet.js+++ b/src/garment-closet.js@@ -27,11 +27,18 @@ import { clampOccludes } from './garment-taxonomy.js';import { loadCatalog, bySlot, verifyModelBytes } from './garment-catalog.js';import { log } from './shared/log.js';+// Plural rack headings. `SLOT_LABEL_ONE` is the singular form a chip or a+// one-item summary needs, so callers do not have to de-pluralize by hand.const SLOT_LABELS = {top: 'Tops', bottom: 'Bottoms', footwear: 'Footwear', outerwear: 'Outerwear',hair: 'Hair', headwear: 'Headwear', glasses: 'Glasses', accessory: 'Accessories',};+export const SLOT_LABEL_ONE = Object.freeze({+ top: 'Top', bottom: 'Bottom', footwear: 'Shoes', outerwear: 'Outerwear',+ hair: 'Hair', headwear: 'Headwear', glasses: 'Glasses', accessory: 'Accessory',+});+/*** Controller for one avatar's attached garments. Owns the scene-side state;* the persisted state is the `working.garments` array of `{slot, id}` refs.@@ -218,6 +225,34 @@ export class GarmentCloset {return { missing };}+ /**+ * Run `fn` with every worn garment temporarily off the rig and the skin+ * occlusion they impose lifted, then put them back exactly as they were.+ *+ * Avatar Studio's create-mode save exports the live scene as the new+ * avatar's BASE model and PATCHes the appearance record alongside it. The+ * server bake replays `appearance.garments` onto that base+ * (api/_lib/bake-garments.js), so exporting an already-dressed body would+ * apply every garment twice. Detaching is scene-side only: `working.garments`+ * is untouched, because it is exactly what the bake needs to replay.+ *+ * Re-attach reads the GLB bytes back from this closet's cache, so putting+ * the outfit back costs a parse, not a download.+ */+ async withGarmentsOff(fn) {+ const worn = [...this._attached.values()].map(({ manifest }) => manifest);+ if (!worn.length) return fn();+ await this._enqueue(async () => {+ for (const slot of [...this._attached.keys()]) this._detachNow(slot);+ this._reoccludeAll();+ });+ try {+ return await fn();+ } finally {+ for (const manifest of worn) await this.attach(manifest);+ }+ }+/** Detach everything (model swap teardown). Scene-side only. */clear() {for (const slot of [...this._attached.keys()]) this._detachNow(slot);diff --git a/tests/bake-proportions.test.js b/tests/bake-proportions.test.jsnew file mode 100644index 000000000..00427ac6a--- /dev/null+++ b/tests/bake-proportions.test.js@@ -0,0 +1,212 @@+/**+ * Server-side proportions baker — api/_lib/bake-proportions.js.+ *+ * The contract this file exists to protect is PARITY. Two code paths write a+ * user's build into a GLB and they must agree exactly:+ *+ * Avatar Studio exports the live three.js scene, so applyProportionsToRoot()+ * in src/avatar-proportions.js is what lands in the file.+ * /avatars/:id/edit PATCHes `appearance.proportions` and lets the server+ * render from the pristine base, so applyProportions() in+ * api/_lib/bake-proportions.js is what lands in the file.+ *+ * Both call the same dependency-free solver. These tests prove the two+ * adapters around it produce identical bone locals on the real parametric base,+ * that the feet stay on the floor after a leg-length edit, and that a+ * proportions-only appearance is recognised as bakeable at all (it was not, and+ * that is the bug this module closes).+ */++import { describe, it, expect, beforeAll } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { NodeIO } from '@gltf-transform/core';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { Vector3 } from 'three';++import { applyProportions, hasProportions } from '../api/_lib/bake-proportions.js';+import { isBakeable } from '../api/_lib/bake.js';+import {+ applyProportionsToRoot,+ PROPORTION_BONES,+} from '../src/avatar-proportions.js';+import { canonicalBoneNodesFromObject } from '../src/animation-retarget.js';++const GLB_PATH = resolve(process.cwd(), 'public/avatars/parametric-base.glb');+const glbBytes = readFileSync(GLB_PATH);++// A build that exercises every operation class: stature, plain offset, lateral+// offset, and joint scale.+const BUILD = {+ height: 1.08,+ legLength: 1.12,+ armLength: 0.94,+ shoulderWidth: 1.1,+ headSize: 1.06,+};++function loadThree() {+ const loader = new GLTFLoader();+ return new Promise((res, rej) => {+ loader.parse(+ glbBytes.buffer.slice(glbBytes.byteOffset, glbBytes.byteOffset + glbBytes.byteLength),+ '',+ res,+ rej,+ );+ });+}++/** canonical bone → { position, scale } read off a baked gltf-transform doc. */+async function bakeLocals(proportions) {+ const doc = await new NodeIO().readBinary(new Uint8Array(glbBytes));+ const result = applyProportions(doc, proportions);+ const { canonicalizeBoneName } = await import('../src/glb-canonicalize.js');+ const locals = new Map();+ let armatureScale = null;+ const skin = doc.getRoot().listSkins()[0];+ for (const joint of skin.listJoints()) {+ const canonical = canonicalizeBoneName(joint.getName() || '');+ if (!canonical || !PROPORTION_BONES.includes(canonical) || locals.has(canonical)) continue;+ locals.set(canonical, { position: joint.getTranslation(), scale: joint.getScale() });+ if (canonical === 'Hips') armatureScale = joint.getParentNode()?.getScale() ?? null;+ }+ return { result, locals, armatureScale };+}++describe('bake-proportions: parity with the runtime path', () => {+ let clientLocals;+ let clientArmatureScale;++ beforeAll(async () => {+ const { scene } = await loadThree();+ const boneMap = canonicalBoneNodesFromObject(scene);+ const applied = applyProportionsToRoot(scene, BUILD, { boneMap });+ expect(applied).not.toBeNull();+ clientLocals = new Map();+ for (const canonical of PROPORTION_BONES) {+ const node = boneMap.get(canonical);+ if (!node) continue;+ clientLocals.set(canonical, {+ position: node.position.toArray(),+ scale: node.scale.toArray(),+ });+ }+ clientArmatureScale = boneMap.get('Hips').parent.scale.toArray();+ });++ it('writes the same bone locals as the browser sculpt path', async () => {+ const { locals, armatureScale } = await bakeLocals(BUILD);+ expect(locals.size).toBeGreaterThan(0);+ for (const [canonical, server] of locals) {+ const client = clientLocals.get(canonical);+ expect(client, canonical).toBeTruthy();+ for (let i = 0; i < 3; i++) {+ expect(server.position[i], `${canonical}.position[${i}]`).toBeCloseTo(client.position[i], 6);+ expect(server.scale[i], `${canonical}.scale[${i}]`).toBeCloseTo(client.scale[i], 6);+ }+ }+ for (let i = 0; i < 3; i++) {+ expect(armatureScale[i]).toBeCloseTo(clientArmatureScale[i], 6);+ }+ });++ it('reports which parameters it applied and moves the bones they name', async () => {+ const { result, locals } = await bakeLocals(BUILD);+ expect(result.missing).toEqual([]);+ expect(result.applied.sort()).toEqual(Object.keys(BUILD).sort());+ expect(result.stature).toBeCloseTo(BUILD.height, 6);+ // headSize is a scale op, legLength an offset op: both must be visible.+ expect(locals.get('Head').scale[0]).toBeCloseTo(BUILD.headSize, 6);+ expect(Math.abs(locals.get('LeftLeg').position[1])).toBeGreaterThan(0);+ });+});++describe('bake-proportions: ground contact and rig tolerance', () => {+ it('keeps the feet on the floor after a leg-length edit', async () => {+ const proportions = { legLength: 1.15 };+ const doc = await new NodeIO().readBinary(new Uint8Array(glbBytes));+ const { canonicalizeBoneName } = await import('../src/glb-canonicalize.js');++ const skin = doc.getRoot().listSkins()[0];+ const byCanonical = new Map();+ for (const joint of skin.listJoints()) {+ const canonical = canonicalizeBoneName(joint.getName() || '');+ if (canonical && !byCanonical.has(canonical)) byCanonical.set(canonical, joint);+ }+ // World Y of a joint, walking translations up the graph. Every joint in+ // this rig has identity rotation and unit scale at rest, which is what+ // makes the plain sum correct here.+ const worldY = (node) => {+ let y = 0;+ for (let n = node; n; n = n.getParentNode()) y += n.getTranslation()[1];+ return y;+ };+ const toe = byCanonical.get('LeftToeBase');+ expect(toe).toBeTruthy();+ const before = worldY(toe);++ applyProportions(doc, proportions);+ const after = worldY(toe);+ expect(after).toBeCloseTo(before, 6);+ });++ it('drops parameters a rig has no bones for instead of throwing', async () => {+ const doc = await new NodeIO().readBinary(new Uint8Array(glbBytes));+ // Strip the skin so nothing resolves: the baker must degrade, not die.+ for (const s of doc.getRoot().listSkins()) s.dispose();+ const result = applyProportions(doc, BUILD);+ expect(result.applied).toEqual([]);+ expect(result.missing.sort()).toEqual(Object.keys(BUILD).sort());+ });++ it('is a no-op for an empty or neutral record', async () => {+ const { result } = await bakeLocals({});+ expect(result.applied).toEqual([]);+ const neutral = await bakeLocals({ height: 1, legLength: 1 });+ expect(neutral.result.applied).toEqual([]);+ });+});++describe('bake-proportions: bakeability', () => {+ it('treats a proportions-only appearance as bakeable', () => {+ expect(hasProportions({ proportions: { height: 1.1 } })).toBe(true);+ expect(hasProportions({ proportions: { height: 1 } })).toBe(false);+ expect(hasProportions(null)).toBe(false);+ expect(isBakeable({ proportions: { height: 1.1 } })).toBe(true);+ expect(isBakeable({ proportions: {} })).toBe(false);+ expect(isBakeable(null)).toBe(false);+ });+});++describe('bake-proportions: end-to-end through bakeAppearance', () => {+ it('renders a taller body into the served GLB', async () => {+ const { bakeAppearance } = await import('../api/_lib/bake.js');+ const bytes = await bakeAppearance(glbBytes, { proportions: { height: 1.1 } });+ expect(bytes.byteLength).toBeGreaterThan(0);++ const { MeshoptDecoder } = await import('meshoptimizer');+ await MeshoptDecoder.ready;+ const { scene } = await new Promise((res, rej) => {+ new GLTFLoader().setMeshoptDecoder(MeshoptDecoder).parse(+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),+ '',+ res,+ rej,+ );+ });+ scene.updateMatrixWorld(true);+ const boneMap = canonicalBoneNodesFromObject(scene);+ const head = boneMap.get('Head');+ expect(head).toBeTruthy();+ const baked = new Vector3();+ head.getWorldPosition(baked);++ const { scene: plain } = await loadThree();+ plain.updateMatrixWorld(true);+ const plainHead = new Vector3();+ canonicalBoneNodesFromObject(plain).get('Head').getWorldPosition(plainHead);++ expect(baked.y / plainHead.y).toBeCloseTo(1.1, 2);+ });+});