Skip to content

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

feat: enhance avatar customization with garment catalog integration and vocabulary features

nirholas75160b52d995
diff --git a/api/_lib/migrations/20260725120000_sniper_postmortem_fixes.sql b/api/_lib/migrations/20260725120000_sniper_postmortem_fixes.sql
new file mode 100644
index 000000000..203923add
--- /dev/null
+++ b/api/_lib/migrations/20260725120000_sniper_postmortem_fixes.sql
@@ -0,0 +1,40 @@
+-- Post-postmortem fixes, from the published fleet audit
+-- (three.ws/blog/autonomous-trading-experiment) and its follow-up verification.
+--
+-- Three findings, three fields:
+--
+-- 1. "Model overconfidence is real and measurable. Judge verdicts at 0.7
+-- confidence were the best band; 0.9-plus verdicts went winless."
+-- -> llm_max_confidence: an optional CEILING next to the existing floor. A
+-- verdict at or above it is treated as a miscalibrated screamer and skipped.
+-- NULL = no ceiling (unchanged behavior).
+--
+-- 2. "The failover chain answering most calls muddied the model-vs-model
+-- comparison." The named-model arms were mostly piloted by fallback models.
+-- -> llm_strict_model: when true, a verdict whose answering model was a
+-- fallback (model tag 'fallback:*') may be RECORDED for calibration but can
+-- never fund a buy. The arm pauses rather than pollutes its own experiment.
+--
+-- 3. "Dead coins stop squatting on concurrency slots for half an hour." A coin
+-- with zero trades is priced by a bonding curve that never moves; the only
+-- exit that ever fired on those was the timeout.
+-- -> stale_since on the position: the moment its re-quoted value stopped
+-- changing while underwater. The position loop exits 'liquidity_decay' once
+-- the clock exceeds the fleet threshold, freeing the slot in minutes.
+--
+-- Additive and idempotent, safe to re-run.
+
+ALTER TABLE agent_sniper_strategies
+ ADD COLUMN IF NOT EXISTS llm_max_confidence NUMERIC,
+ ADD COLUMN IF NOT EXISTS llm_strict_model BOOLEAN NOT NULL DEFAULT false;
+
+COMMENT ON COLUMN agent_sniper_strategies.llm_max_confidence IS
+ 'Optional confidence CEILING for LLM verdicts. A buy verdict at/above this is skipped as miscalibrated overconfidence (the 0.9+ band went winless in the July 2026 audit). NULL = no ceiling.';
+COMMENT ON COLUMN agent_sniper_strategies.llm_strict_model IS
+ 'When true, a verdict answered by a fallback model (not the arm''s named model) is recorded but can never fund a buy. Keeps the model-vs-model experiment clean.';
+
+ALTER TABLE agent_sniper_positions
+ ADD COLUMN IF NOT EXISTS stale_since TIMESTAMPTZ;
+
+COMMENT ON COLUMN agent_sniper_positions.stale_since IS
+ 'When the position''s re-quoted value stopped changing while underwater (no trades are moving the curve). Cleared on any movement; liquidity_decay exits fire off this clock.';
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 175926109..17527bab3 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -28,6 +28,24 @@ export const avatarAppearance = z
// hex validity is enforced in validateAppearance() (accessories.js).
colors: z.record(z.string().regex(/^#[0-9a-fA-F]{6}$/)).optional(),
hidden: z.array(z.string().min(1).max(32)).max(8).optional(),
+ // Additive catalog garments ({slot, id} refs into the garment catalog —
+ // specs/GARMENT_MANIFEST.md). Slot list mirrors GARMENT_SLOTS in
+ // src/avatar-garment.js; existence against the live catalog is checked
+ // at bake time so a retired garment degrades to "not worn", not a 400.
+ garments: z
+ .array(
+ z
+ .object({
+ slot: z.enum([
+ 'top', 'bottom', 'footwear', 'outerwear',
+ 'hair', 'headwear', 'glasses', 'accessory',
+ ]),
+ id: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(64),
+ })
+ .strict(),
+ )
+ .max(8)
+ .optional(),
})
.strict()
.superRefine((val, ctx) => {
diff --git a/pages/sign-language.html b/pages/sign-language.html
index 07268b094..20113c985 100644
--- a/pages/sign-language.html
+++ b/pages/sign-language.html
@@ -107,6 +107,24 @@
.sl-cam-result[data-state='ok'] { border-color: rgba(56,211,159,.5); }
.sl-cam-hint { font-size: 13px; color: var(--ink-dim); line-height: 1.5; }
+ /* Vocabulary */
+ .sl-vocab { margin-top: clamp(48px, 6vw, 76px); }
+ .sl-vocab h2 { font-size: clamp(22px, 2.4vw, 30px); letter-spacing: -.02em; margin: 0 0 10px; }
+ .sl-vocab > p { color: var(--ink-dim); font-size: 15px; line-height: 1.65; max-width: 70ch; margin: 0 0 20px; }
+ .sl-vocab-chips { display: flex; flex-wrap: wrap; gap: 8px; }
+ .sl-vocab-chip {
+ display: inline-flex; align-items: center; gap: 7px;
+ border: 1px solid var(--stroke); border-radius: 999px;
+ background: var(--surface-2); color: var(--ink-dim);
+ padding: 7px 14px; font-size: 13px; font-weight: 600; letter-spacing: .01em;
+ cursor: pointer; transition: color .16s ease, border-color .16s ease, transform .16s ease, background .16s ease;
+ }
+ .sl-vocab-chip::before { content: '🤟'; font-size: 12px; opacity: .65; }
+ .sl-vocab-chip:hover { color: var(--ink); border-color: rgba(167,139,250,.6); transform: translateY(-1px); }
+ .sl-vocab-chip:focus-visible { outline: 2px solid rgba(167,139,250,.9); outline-offset: 2px; }
+ .sl-vocab-chip[aria-pressed='true'] { color: var(--ink); background: rgba(167,139,250,.16); border-color: rgba(167,139,250,.7); }
+ @media (prefers-reduced-motion: reduce) { .sl-vocab-chip:hover { transform: none; } }
+
/* Honest scope note */
.sl-note { margin-top: clamp(36px, 5vw, 56px); border-left: 2px solid rgba(167,139,250,.5); padding: 4px 0 4px 18px; color: var(--ink-dim); font-size: 14px; line-height: 1.65; max-width: 72ch; }
@@ -199,6 +217,17 @@
</article>
</section>
+ <section class="sl-vocab" id="sl-vocab" aria-label="Words the avatar signs rather than spells">
+ <h2>It signs these — it doesn’t spell them</h2>
+ <p>
+ A signer spells names and loanwords and <em>signs</em> everything else. These
+ words have real signs in the avatar’s vocabulary: a handshape, a place on the
+ body, and a movement, on one or both hands. Pick one to watch it. Everything
+ else in a sentence still fingerspells.
+ </p>
+ <div class="sl-vocab-chips" id="sl-vocab-chips" role="list"></div>
+ </section>
+
<section class="sl-webcam" id="sl-webcam" aria-label="Webcam sign recognition demo">
<h2>Sign to us — we’ll read it</h2>
<p>
@@ -221,11 +250,11 @@
</section>
<p class="sl-note">
- Fingerspelling spells words letter by letter; it is not full grammatical ASL, which
- has its own grammar and facial-expression markers. Lexical signs come from recordings
- of real signers through our motion-capture pipeline, never synthesized guesses — which
- is why the sign dictionary grows deliberately. Read the
- <a href="/docs/sign-language">full breakdown</a>.
+ Honest scope: words with a sign are signed, everything else is fingerspelled letter
+ by letter. Signs are strung together in English word order, which is signed English,
+ not ASL grammar — real ASL reorders sentences, inflects verbs through space, and
+ carries grammar on the face. The vocabulary above is a starting set and is meant to
+ grow. Read the <a href="/docs/sign-language">full breakdown</a>.
</p>
</main>
diff --git a/scripts/.scratch/page-check.mjs b/scripts/.scratch/page-check.mjs
new file mode 100644
index 000000000..7c3194261
--- /dev/null
+++ b/scripts/.scratch/page-check.mjs
@@ -0,0 +1,28 @@
+// Load the real /sign-language page, let the hero sign, screenshot, report console errors.
+import { chromium } from 'playwright';
+
+const browser = await chromium.launch({
+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
+});
+const page = await browser.newPage({ viewport: { width: 1440, height: 950 } });
+const msgs = [];
+page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') msgs.push(`[${m.type()}] ${m.text()}`); });
+page.on('pageerror', (e) => msgs.push(`[pageerror] ${e}`));
+await page.goto('http://localhost:3000/sign-language', { waitUntil: 'load' });
+await page.waitForTimeout(9000);
+await page.screenshot({ path: '/tmp/claude-1000/-workspaces-three-ws/07298a69-ffef-4726-8a81-87336d28fc86/scratchpad/page-hero.png' });
+
+// Vocabulary chips rendered?
+const chips = await page.$$eval('.sl-vocab-chip', (els) => els.map((e) => e.textContent));
+console.log('vocab chips:', chips.length, chips.slice(0, 8).join(', '));
+
+// Type a mixed sentence and watch the status.
+await page.fill('#sl-spell-input', 'happy to meet you');
+await page.click('#sl-spell-btn');
+await page.waitForTimeout(2500);
+await page.screenshot({ path: '/tmp/claude-1000/-workspaces-three-ws/07298a69-ffef-4726-8a81-87336d28fc86/scratchpad/page-sign.png' });
+await page.waitForTimeout(6000);
+console.log('status:', await page.textContent('#sl-status'));
+
+console.log(msgs.length ? 'CONSOLE:\n' + msgs.join('\n') : 'no console errors/warnings');
+await browser.close();
diff --git a/src/avatar-edit.js b/src/avatar-edit.js
index 74ca103bd..1329ba122 100644
--- a/src/avatar-edit.js
+++ b/src/avatar-edit.js
@@ -24,6 +24,7 @@ import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';
import { IdleAnimation } from './idle-animation.js';
import { renderSculptPanel } from './avatar-sculpt.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 { apiFetch } from './api.js';
@@ -72,7 +73,10 @@ let walkPreview = null;
// the UI has committed (locally) and will save. We're dirty when they differ.
// `previewedId` is what's *temporarily* applied on hover, never persisted.
let currentAppearance = null;
-let workingAppearance = { outfit: null, accessories: [], morphs: {}, colors: {}, hidden: [] };
+let workingAppearance = { outfit: null, accessories: [], morphs: {}, colors: {}, hidden: [], garments: [] };
+// Additive-wardrobe controller (catalog garments skinned onto this avatar's
+// skeleton at runtime). Created once the scene root exists.
+let closet = null;
let previewedId = null;
// Monotonic token guards async preset loads from out-of-order arrivals when
@@ -225,6 +229,17 @@ async function bootScene() {
});
await accessoryManager.hydrateFromAppearance(currentAppearance);
+ // Additive wardrobe: re-attach saved catalog garments onto the live
+ // skeleton. Unknown/retired garments degrade to "not worn" inside
+ // hydrate rather than failing the whole boot.
+ closet = new GarmentCloset({
+ getRoot: () => scene?.root || null,
+ getWorking: () => workingAppearance,
+ onDirty: () => updateDirtyState(),
+ onChanged: () => renderChips(),
+ });
+ await closet.hydrate(currentAppearance.garments);
+
// Ambient idle layer — breathing, micro-saccades, blink, weight shift.
// Static preview here (no AgentProtocol); IdleAnimation's no-op stub
// covers the SPEAK / LOOK_AT subscriptions. Seeded by avatar id so two
@@ -345,6 +360,17 @@ function renderActivePanel() {
updateDirtyState();
},
});
+ // The closet (additive catalog garments) 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.id = 'ae-closet';
+ 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;
}
@@ -909,6 +935,10 @@ function bindHeader() {
}
workingAppearance = clone(currentAppearance);
if (accessoryManager) await accessoryManager.hydrateFromAppearance(workingAppearance);
+ if (closet) {
+ closet.clear();
+ await closet.hydrate(workingAppearance.garments);
+ }
});
renderChips();
renderActivePanel();
@@ -942,7 +972,7 @@ function setStatus(kind, text) {
// ── Helpers ────────────────────────────────────────────────────────────
function normalizeAppearance(a) {
- if (!a) return { outfit: null, accessories: [], morphs: {}, colors: {}, hidden: [] };
+ if (!a) return { outfit: null, accessories: [], morphs: {}, colors: {}, hidden: [], garments: [] };
return {
outfit: a.outfit || null,
accessories: Array.isArray(a.accessories) ? [...a.accessories] : [],
@@ -952,6 +982,10 @@ function normalizeAppearance(a) {
// it, so editing accessories never silently strips a studio look.
colors: a.colors && typeof a.colors === 'object' ? { ...a.colors } : {},
hidden: Array.isArray(a.hidden) ? [...a.hidden] : [],
+ // Additive catalog garments worn by this avatar ({slot, id} refs).
+ garments: Array.isArray(a.garments)
+ ? a.garments.filter((g) => g && g.slot && g.id).map((g) => ({ slot: g.slot, id: g.id }))
+ : [],
};
}
@@ -964,6 +998,7 @@ function collapseAppearance(a) {
if (a.morphs && Object.keys(a.morphs).length) out.morphs = { ...a.morphs };
if (a.colors && Object.keys(a.colors).length) out.colors = { ...a.colors };
if (a.hidden?.length) out.hidden = [...a.hidden];
+ if (a.garments?.length) out.garments = a.garments.map((g) => ({ slot: g.slot, id: g.id }));
return Object.keys(out).length ? out : null;
}
@@ -989,5 +1024,9 @@ function appearanceEquals(a, b) {
const hb = new Set(b?.hidden || []);
if (ha.size !== hb.size) return false;
for (const v of ha) if (!hb.has(v)) return false;
+ const ga = new Set((a?.garments || []).map((g) => `${g.slot}/${g.id}`));
+ const gb = new Set((b?.garments || []).map((g) => `${g.slot}/${g.id}`));
+ if (ga.size !== gb.size) return false;
+ for (const v of ga) if (!gb.has(v)) return false;
return true;
}
diff --git a/src/garment-closet.js b/src/garment-closet.js
index 4f11e3591..1ec7ebeed 100644
--- a/src/garment-closet.js
+++ b/src/garment-closet.js
@@ -38,15 +38,16 @@ const SLOT_LABELS = {
export class GarmentCloset {
/**
* @param {object} opts
- * @param {() => object|null} opts.getRoot live avatar scene root
- * @param {object} opts.working workingAppearance (mutated: .garments)
+ * @param {() => object|null} opts.getRoot live avatar scene root
+ * @param {() => object} opts.getWorking workingAppearance accessor — a
+ * getter (not a reference) because the editor REASSIGNS the working
+ * object on load/save/reset; a captured reference would go stale.
* @param {() => void} [opts.onDirty]
- * @param {() => void} [opts.onChanged] re-render hook (state text, chips)
+ * @param {() => void} [opts.onChanged] re-render hook (state text, chips)
*/
- constructor({ getRoot, working, onDirty, onChanged }) {
+ constructor({ getRoot, getWorking, onDirty, onChanged }) {
this.getRoot = getRoot;
- this.working = working;
- this.working.garments = Array.isArray(working.garments) ? working.garments : [];
+ this.getWorking = getWorking;
this.onDirty = onDirty || (() => {});
this.onChanged = onChanged || (() => {});
// slot → { manifest, result } for what is live in the scene right now
@@ -169,7 +170,9 @@ export class GarmentCloset {
}
_syncWorking() {
- this.working.garments = [...this._attached.values()].map(({ manifest }) => ({
+ const working = this.getWorking?.();
+ if (!working) return;
+ working.garments = [...this._attached.values()].map(({ manifest }) => ({
slot: manifest.slot,
id: manifest.id,
}));
diff --git a/src/sign-language-page.js b/src/sign-language-page.js
index 9aacba063..0f78203ad 100644
--- a/src/sign-language-page.js
+++ b/src/sign-language-page.js
@@ -11,13 +11,15 @@
import { PoseStage } from './avatar-pose.js';
import { SignSpeaker } from './sign-speech.js';
import { normalizeWord } from './fingerspelling.js';
+import { SIGNS, signGloss } from './sign-dictionary.js';
import { log } from './shared/log.js';
const HERO_AVATAR = '/avatars/cz.glb';
// Phrases the hero cycles through so a first-time visitor immediately sees the
-// avatar signing real content, not a static pose.
-const DEMO_PHRASES = ['HELLO', 'WELCOME TO THREE WS', 'ASK ME ANYTHING', 'NICE TO MEET YOU'];
+// avatar signing real content, not a static pose. Each mixes lexical signs with
+// fingerspelling, which is what the feature actually does.
+const DEMO_PHRASES = ['HELLO', 'HAPPY TO MEET YOU', 'WELCOME TO THREE WS', 'THANK YOU YALL'];
const $ = (sel, root = document) => root.querySelector(sel);
@@ -72,6 +74,16 @@ async function boot() {
// ── Spell-anything input ──────────────────────────────────────────────────
const spellInput = $('#sl-spell-input');
const spellBtn = $('#sl-spell-btn');
+
+ // Tell the visitor which words were SIGNED and which were spelled — the
+ // distinction is the whole point of having a dictionary.
+ const describeResult = ({ signed, spelled }) => {
+ const parts = [];
+ if (signed?.length) parts.push(`signed ${signed.map((w) => w.toLowerCase()).join(', ')}`);
+ if (spelled?.length) parts.push(`spelled ${spelled.map((w) => w.toLowerCase()).join(', ')}`);
+ return parts.length ? parts.join(' · ') : 'Type anything and watch the avatar sign it.';
+ };
+
const spellIt = async () => {
if (!speaker) return;
const raw = spellInput.value.trim();
@@ -84,8 +96,8 @@ async function boot() {
heroActive = false;
setStatus(`Signing: “${norm.toLowerCase()}”`);
try {
- await speaker.speak(raw);
- setStatus('Type anything and watch the avatar sign it.');
+ const result = await speaker.speak(raw);
+ if (!result.superseded) setStatus(describeResult(result));
} catch (e) {
setStatus(e?.message || 'Could not sign that.');
}
@@ -105,6 +117,40 @@ async function boot() {
});
});
+ // ── Vocabulary: every word with a real sign, playable ─────────────────────
+ const vocabHost = $('#sl-vocab-chips');
+ if (vocabHost) {
+ const words = Object.keys(SIGNS).sort();
+ let active = null;
+ for (const word of words) {
+ const chip = document.createElement('button');
+ chip.type = 'button';
+ chip.className = 'sl-vocab-chip';
+ chip.setAttribute('role', 'listitem');
+ chip.setAttribute('aria-pressed', 'false');
+ chip.textContent = word.toLowerCase();
+ const gloss = signGloss(word);
+ if (gloss) chip.title = gloss;
+ chip.addEventListener('click', async () => {
+ if (!speaker) return;
+ stopHero();
+ heroActive = false;
+ active?.setAttribute('aria-pressed', 'false');
+ active = chip;
+ chip.setAttribute('aria-pressed', 'true');
+ setStatus(gloss ? `${word.toLowerCase()} — ${gloss}` : `Signing “${word.toLowerCase()}”`);
+ try {
+ const result = await speaker.speak(word);
+ if (!result.superseded) chip.setAttribute('aria-pressed', 'false');
+ } catch {
+ chip.setAttribute('aria-pressed', 'false');
+ setStatus('Could not sign that.');
+ }
+ });
+ vocabHost.appendChild(chip);
+ }
+ }
+
// ── Webcam sign-in demo ───────────────────────────────────────────────────
wireWebcamDemo(setStatus);
}
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
index 61d3b45a2..e13c9d0ed 100644
--- a/workers/agent-sniper/index.js
+++ b/workers/agent-sniper/index.js
@@ -263,9 +263,12 @@ async function main() {
};
judgeLaunch(judgeMint, strat).then((verdict) => {
if (!verdict) return;
- const minConf = Number(strat.llm_min_confidence ?? 0.6);
- if (!verdict.buy || verdict.confidence < minConf) {
- log.info('llm judge pass', { agent: strat.agent_id, mint: rec.mint, model: verdict.model, buy: verdict.buy, confidence: verdict.confidence });
+ // Floor + overconfidence ceiling + named-model strictness in one
+ // gate (llmVerdictGate). The verdict is already recorded either
+ // way; only the money is gated here.
+ const gate = llmVerdictGate(verdict, strat);
+ if (!gate.pass) {
+ log.info('llm judge pass', { agent: strat.agent_id, mint: rec.mint, model: verdict.model, buy: verdict.buy, confidence: verdict.confidence, gate: gate.reason });
return;
}
log.info('llm judge buy', { agent: strat.agent_id, mint: rec.mint, model: verdict.model, confidence: verdict.confidence, thesis: verdict.thesis });
diff --git a/workers/agent-sniper/llm-judge.js b/workers/agent-sniper/llm-judge.js
index 7dfa64d2b..8ef16e6a4 100644
--- a/workers/agent-sniper/llm-judge.js
+++ b/workers/agent-sniper/llm-judge.js
@@ -236,6 +236,36 @@ export async function judgeLaunch(mint, strat) {
return promise;
}
+/**
+ * Decide whether a verdict may FUND A BUY for this strategy. The verdict itself
+ * is always recorded (skips teach calibration); this gate only controls money.
+ * Pure, exported for tests. Returns { pass, reason }.
+ *
+ * Three checks, each from the July 2026 fleet audit:
+ * floor — the classic llm_min_confidence bar (default 0.6).
+ * ceiling — llm_max_confidence. The audit's calibration table showed the
+ * 0.7 band was the best performer and 0.9+ verdicts went
+ * WINLESS: a screaming-confident model is a miscalibrated one,
+ * and the gate now treats it that way instead of rewarding it.
+ * strict model— llm_strict_model. During the audit window the failover chain
+ * answered most named-model calls, which muddied the
+ * model-vs-model comparison. A strict arm refuses to trade on a
+ * fallback's judgment: better a paused experiment than a
+ * polluted one.
+ */
+export function llmVerdictGate(verdict, strat) {
+ if (!verdict || verdict.buy !== true) return { pass: false, reason: 'no_buy' };
+ const conf = Number(verdict.confidence);
+ const floor = Number(strat?.llm_min_confidence ?? 0.6);
+ if (!Number.isFinite(conf) || conf < floor) return { pass: false, reason: 'below_floor' };
+ const ceiling = strat?.llm_max_confidence != null ? Number(strat.llm_max_confidence) : null;
+ if (ceiling != null && Number.isFinite(ceiling) && conf >= ceiling) return { pass: false, reason: 'overconfident' };
+ if (strat?.llm_strict_model === true && String(verdict.model || '').startsWith('fallback:')) {
+ return { pass: false, reason: 'fallback_model' };
+ }
+ return { pass: true, reason: 'ok' };
+}
+
/** Test seam: reset shared state. */
export function _resetLlmJudge() {
_verdicts.clear();
diff --git a/workers/garment-forge/canonical_bones.py b/workers/garment-forge/canonical_bones.py
new file mode 100644
index 000000000..aaa5722dc
--- /dev/null
+++ b/workers/garment-forge/canonical_bones.py
@@ -0,0 +1,98 @@
+"""
+Python mirror of the three.ws canonical humanoid bone contract.
+
+CANONICAL_BONES / REGION_BONES / BODY_REGIONS / GARMENT_SLOTS are copied
+verbatim from their JS sources of truth:
+
+ - CANONICAL_BONES src/glb-canonicalize.js
+ - REGION_BONES / BODY_REGIONS src/avatar-garment.js
+ - GARMENT_SLOTS src/avatar-garment.js
+ - MIN_BIND_COVERAGE src/avatar-garment.js
+
+canonicalize_bone_name() is deliberately a SUBSET of the JS canonicalizer:
+this worker controls its whole pipeline, and the only skeleton that ever
+reaches validation here is the one model-rig emits (Mixamo names, optionally
+behind a `mixamorig:`/`mixamorigN:` namespace) or names that are already
+canonical. Porting the full multi-vendor alias table would duplicate logic
+the runtime already owns without ever being exercised.
+"""
+
+from __future__ import annotations
+
+import re
+
+CANONICAL_BONES = (
+ "Hips", "Spine", "Spine1", "Spine2", "Neck", "Head",
+ "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand",
+ "LeftHandIndex1", "LeftHandIndex2", "LeftHandIndex3",
+ "LeftHandMiddle1", "LeftHandMiddle2", "LeftHandMiddle3",
+ "LeftHandPinky1", "LeftHandPinky2", "LeftHandPinky3",
+ "LeftHandRing1", "LeftHandRing2", "LeftHandRing3",
+ "LeftHandThumb1", "LeftHandThumb2", "LeftHandThumb3",
+ "RightShoulder", "RightArm", "RightForeArm", "RightHand",
+ "RightHandIndex1", "RightHandIndex2", "RightHandIndex3",
+ "RightHandMiddle1", "RightHandMiddle2", "RightHandMiddle3",
+ "RightHandPinky1", "RightHandPinky2", "RightHandPinky3",
+ "RightHandRing1", "RightHandRing2", "RightHandRing3",
+ "RightHandThumb1", "RightHandThumb2", "RightHandThumb3",
+ "LeftUpLeg", "LeftLeg", "LeftFoot", "LeftToeBase",
+ "RightUpLeg", "RightLeg", "RightFoot", "RightToeBase",
+)
+
+_CANONICAL_LOOKUP = {name.lower(): name for name in CANONICAL_BONES}
+
+BODY_REGIONS = (
+ "torso", "upperArms", "lowerArms", "hands",
+ "hips", "upperLegs", "lowerLegs", "feet", "neck", "scalp",
+)
+
+REGION_BONES = {
+ "torso": ("Spine", "Spine1", "Spine2"),
+ "upperArms": ("LeftArm", "RightArm"),
+ "lowerArms": ("LeftForeArm", "RightForeArm"),
+ "hands": ("LeftHand", "RightHand"),
+ "hips": ("Hips",),
+ "upperLegs": ("LeftUpLeg", "RightUpLeg"),
+ "lowerLegs": ("LeftLeg", "RightLeg"),
+ "feet": ("LeftFoot", "RightFoot", "LeftToeBase", "RightToeBase"),
+ "neck": ("Neck",),
+ "scalp": ("Head",),
+}
+
+# Finger joints roll up into the hand for region accounting: a glove garment
+# weighted to LeftHandIndex2 covers the "hands" region even though that joint
+# is not listed in REGION_BONES (the runtime's mask is per-major-joint).
+_BONE_TO_REGION = {}
+for _region, _bones in REGION_BONES.items():
+ for _b in _bones:
+ _BONE_TO_REGION[_b] = _region
+for _b in CANONICAL_BONES:
+ if _b not in _BONE_TO_REGION and ("Hand" in _b):
+ _BONE_TO_REGION[_b] = "hands"
+
+GARMENT_SLOTS = (
+ "top", "bottom", "footwear", "outerwear",
+ "hair", "headwear", "glasses", "accessory",
+)
+
+MIN_BIND_COVERAGE = 0.6
+
+_NAMESPACE_RE = re.compile(r"^.*:") # `mixamorig:LeftArm` → `LeftArm`
+_MIXAMO_GLUED_RE = re.compile(r"^mixamorig\d*", re.IGNORECASE)
+_SEPARATORS_RE = re.compile(r"[-_.\s]+")
+
+
+def canonicalize_bone_name(name: str | None) -> str | None:
+ """Reduce a Mixamo/canonical bone name to its canonical three.ws form,
+ or None when it is not a recognised humanoid bone."""
+ if not name or not isinstance(name, str):
+ return None
+ stripped = _NAMESPACE_RE.sub("", name)
+ stripped = _MIXAMO_GLUED_RE.sub("", stripped)
+ key = _SEPARATORS_RE.sub("", stripped).lower()
+ return _CANONICAL_LOOKUP.get(key)
+
+
+def region_of_bone(canonical_name: str) -> str | None:
+ """Body region a canonical bone belongs to, fingers rolled into hands."""
+ return _BONE_TO_REGION.get(canonical_name)