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(rig): rig doctor, GLB inspect, seed mesh gate, and avatar capabilities
nirholasa6634ee36392
diff --git a/api/3d/inspect.js b/api/3d/inspect.jsindex 91b589f35..404e66fd1 100644--- a/api/3d/inspect.js+++ b/api/3d/inspect.js@@ -17,7 +17,12 @@// Output:// { url, valid, stats:{ vertices, triangles, materials, textures, animations,// extensions[], … }, sizeBytes, recommendations:[{ severity, issue, fix }],-// validation:{…}, ts }+// validation:{ valid, numErrors, numWarnings, …,+// issues:[{ code, message, severity, pointer? }] }, ts }+//+// `validation.issues` carries the actual glTF-Validator findings (capped at 10;+// the counts beside it are the true totals). Without them a caller that gates on+// `valid` knows only that an asset failed, never why.//// Reuses the same inspection core the paid /api/x402/model-check route uses// (api/_lib/model-inspect.js → src/gltf-inspect.js) plus the official Khronos@@ -104,12 +109,43 @@ export function buildRecommendations(info) {.sort((a, b) => (SEVERITY_RANK[a.severity] ?? 3) - (SEVERITY_RANK[b.severity] ?? 3));}+// The validator reports severity as an integer; callers want a word they can+// branch on without memorizing the enum.+const VALIDATOR_SEVERITY = ['error', 'warning', 'info', 'hint'];++// How many individual issues ride along in the response. The validator itself is+// capped at 100 below; a caller needs the first handful to act, not a wall of+// repeats of the same code, and the counts above already carry the true totals.+const MAX_REPORTED_ISSUES = 10;++// Reshape the validator's raw message list into the wire contract: what is wrong,+// where, and how severe. Exported so the shape is pinned in tests without running+// the validator over real bytes.+export function shapeIssues(messages) {+ if (!Array.isArray(messages)) return [];+ return messages.slice(0, MAX_REPORTED_ISSUES).map((m) => ({+ code: typeof m?.code === 'string' ? m.code : 'UNKNOWN',+ message: typeof m?.message === 'string' ? m.message : '',+ severity: VALIDATOR_SEVERITY[m?.severity] || 'error',+ // The JSON pointer into the asset (e.g. /images/0/bufferView). Absent on+ // whole-file issues, so it is omitted rather than sent as an empty string.+ ...(typeof m?.pointer === 'string' && m.pointer ? { pointer: m.pointer } : {}),+ }));+}+// Run the Khronos glTF-Validator for the authoritative spec-compliance verdict.// External resources (a .gltf's side-car .bin/textures) are NOT fetched — GLBs// are self-contained, and fetching arbitrary side files would reopen the SSRF// surface fetch-model.js closes. A validator failure never fails the whole call:// inspectModel already proved the bytes parse, so we degrade to valid:true with a-// note rather than 500. Returns { valid, ...counts } or null when unavailable.+// note rather than 500. Returns { valid, ...counts, issues[] } or null when+// unavailable.+//+// The `issues` array is the difference between a usable verdict and an unusable+// one. Counts alone tell a caller that the asset failed and nothing about why:+// a CI gate keyed on `valid` can only print "1 error" and stop. Carrying the+// codes and pointers means the same gate can say IMAGE_MIME_TYPE_INVALID at+// /images/0/bufferView, which is a fix, not a mystery.async function runValidator(bytes, filename) {try {const report = await validateBytes(bytes, {@@ -126,6 +162,8 @@ async function runValidator(bytes, filename) {numWarnings: issues.numWarnings ?? 0,numInfos: issues.numInfos ?? 0,numHints: issues.numHints ?? 0,+ issues: shapeIssues(issues.messages),+ truncated: Boolean(issues.truncated),};} catch {return null;diff --git a/api/_lib/avatar-capabilities.js b/api/_lib/avatar-capabilities.jsnew file mode 100644index 000000000..1a9da6dc8--- /dev/null+++ b/api/_lib/avatar-capabilities.js@@ -0,0 +1,282 @@+// What can this avatar actually do?+//+// Every render, pose, expression, and lipsync call on three.ws succeeds or+// degrades based on facts that live inside the GLB: which morph targets it+// carries, whether its bone names map onto the canonical humanoid skeleton the+// pre-baked clip library addresses, and how heavy the geometry is. Until now+// those facts were only discoverable by trying: you sent an expression, got a+// picture back, and had to eyeball whether the smile landed.+//+// This module answers the question up front. It reads ONLY the glTF JSON chunk+// (a ranged read of the head of the file, never the mesh binary), then runs the+// exact same two mappers the runtime uses:+//+// • src/runtime/arkit52.js morph name → canonical ARKit-52 shape+// • src/glb-canonicalize.js bone name → canonical humanoid bone+//+// Because it is the same mapping, the report is not an estimate. A morph this+// module reports as supported is a morph the renderer will drive, and a rig it+// reports as animatable is one src/animation-retarget.js will retarget onto+// (its MIN_COVERAGE gate is applied here by name).+//+// Consumed by GET /api/avatar/capabilities and the /render-lab composer, which+// disables controls an avatar cannot honor instead of letting you request them+// and wonder why nothing changed.++import { getObjectRange } from './r2.js';+import { resolvePublicHost, pinnedAgent, validatePublicUrl } from './ssrf.js';+import { inspectGlb, glbJsonChunkEnd } from './glb-inspect.js';+import { conformanceFromNames, ARKIT_52 } from '../../src/runtime/arkit52.js';+import { canonicalizeBoneName, CANONICAL_BONES } from '../../src/glb-canonicalize.js';+import { MIN_COVERAGE } from '../../src/animation-retarget.js';++// 256 KB covers the JSON chunk of essentially every real avatar in one read.+// Same first-pass budget as rig-inspect.js, for the same reason.+const INITIAL_PREFIX = 256 * 1024;+// A JSON chunk past this is pathological; report "unknown" rather than pull+// megabytes hunting for names.+const MAX_PREFIX = 8 * 1024 * 1024;+// A third-party host gets one short window to answer; the JSON chunk is the+// head of the file, so a healthy server returns it immediately.+const EXTERNAL_TIMEOUT_MS = 12_000;++// Expression control needs a mouth AND a brow to read as an expression at all;+// a rig with only visemes can lipsync but cannot emote.+const EXPRESSION_MIN_SHAPES = 4;++// Bones the retargeter must have to drive a full-body clip. Fingers are graded+// separately: a rig can walk convincingly with no finger joints at all, so+// missing hands lower the grade without disqualifying the rig.+const CORE_BONES = Object.freeze([+ 'Hips', 'Spine', 'Neck', 'Head',+ 'LeftArm', 'LeftForeArm', 'RightArm', 'RightForeArm',+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot',+ 'RightUpLeg', 'RightLeg', 'RightFoot',+]);++const FINGER_BONES = CANONICAL_BONES.filter((b) => /Hand(Index|Middle|Pinky|Ring|Thumb)\d$/.test(b));++// Generator strings are the most reliable pipeline tell, but plenty of rigs+// arrive with a generic one; bone spelling is the fallback signal.+const RIG_SIGNATURES = Object.freeze([+ { id: 'mixamo', label: 'Mixamo', test: (b) => b.some((n) => /^mixamorig/i.test(n)) },+ { id: 'vrm', label: 'VRM / VRoid', test: (b) => b.some((n) => /^J_Bip_/i.test(n)) },+ { id: 'unreal', label: 'Unreal mannequin', test: (b) => b.some((n) => /^(upperarm|thigh|calf|clavicle)_[lr]$/i.test(n)) },+ { id: 'rigify', label: 'Blender Rigify', test: (b) => b.some((n) => /^(DEF|ORG|MCH)-/i.test(n)) },+ { id: 'daz', label: 'Daz / Genesis', test: (b) => b.some((n) => /^(lShldr|rShldr|lForeArm|abdomen)$/i.test(n)) },+ { id: 'smpl', label: 'SMPL / SMPL-X', test: (b) => b.some((n) => /^(left|right)_(hip|knee|ankle|elbow|wrist)$/i.test(n)) },+ { id: 'secondlife', label: 'Second Life', test: (b) => b.some((n) => /^m(Pelvis|Torso|Chest)$/i.test(n)) },+ { id: 'blender-side', label: 'Blender .L/.R', test: (b) => b.some((n) => /\.(L|R)$/.test(n)) },+ { id: 'canonical', label: 'three.ws canonical', test: (b) => b.includes('Hips') && b.includes('LeftForeArm') },+]);++async function readGlbPrefix(storageKey, length) {+ if (/^https?:\/\//i.test(storageKey)) {+ const r = await fetch(storageKey, { headers: { Range: `bytes=0-${length - 1}` } });+ if (!r.ok) throw new Error(`http ${r.status}`);+ return Buffer.from(await r.arrayBuffer());+ }+ return getObjectRange(storageKey, length);+}++// Ranged read of a URL nobody on this platform controls. The host is resolved+// and pinned before the request so a redirect or a DNS rebind cannot walk the+// fetch onto a private address, and the Range header caps what a hostile server+// can make us buffer.+async function readUntrustedGlbPrefix(rawUrl, length) {+ const url = validatePublicUrl(rawUrl);+ const addrs = await resolvePublicHost(url.hostname);+ const agent = pinnedAgent(url.hostname, addrs);+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), EXTERNAL_TIMEOUT_MS);+ try {+ const r = await fetch(url, {+ redirect: 'error',+ signal: controller.signal,+ dispatcher: agent,+ headers: {+ Range: `bytes=0-${length - 1}`,+ 'user-agent': 'three-ws-capabilities/1.0 (+https://three.ws/render-lab)',+ },+ });+ if (!r.ok) throw new Error(`http ${r.status}`);+ const buf = Buffer.from(await r.arrayBuffer());+ // A server that ignores Range answers 200 with the whole file; truncate+ // rather than hold an arbitrarily large body in memory.+ return buf.length > length ? buf.subarray(0, length) : buf;+ } finally {+ clearTimeout(timer);+ await agent.close().catch(() => {});+ }+}++async function inspectPrefix(storageKey, { untrusted = false } = {}) {+ const read = untrusted ? readUntrustedGlbPrefix : readGlbPrefix;+ let buf = await read(storageKey, INITIAL_PREFIX);+ let info = inspectGlb(buf, { allowPartial: true });+ if (!info) {+ const need = glbJsonChunkEnd(buf);+ if (need > buf.length && need <= MAX_PREFIX) {+ buf = await read(storageKey, need);+ info = inspectGlb(buf, { allowPartial: true });+ }+ }+ return info;+}++function detectRig(boneNames, generator) {+ for (const sig of RIG_SIGNATURES) {+ if (sig.test(boneNames)) return { id: sig.id, label: sig.label };+ }+ if (generator && /avaturn/i.test(generator)) return { id: 'avaturn', label: 'Avaturn' };+ if (generator && /ready ?player ?me/i.test(generator)) return { id: 'rpm', label: 'Ready Player Me' };+ return { id: 'unknown', label: boneNames.length ? 'Unrecognized humanoid' : 'No skeleton' };+}++function gradeSkeleton(boneNames) {+ const mapped = new Map();+ const unmapped = [];+ for (const raw of boneNames) {+ const canonical = canonicalizeBoneName(raw);+ if (canonical && !mapped.has(canonical)) mapped.set(canonical, raw);+ else if (!canonical) unmapped.push(raw);+ }+ const mappedNames = CANONICAL_BONES.filter((b) => mapped.has(b));+ const coverage = mappedNames.length / CANONICAL_BONES.length;+ const coreMissing = CORE_BONES.filter((b) => !mapped.has(b));+ const fingersMapped = FINGER_BONES.filter((b) => mapped.has(b)).length;+ return {+ coverage,+ mapped: mappedNames,+ missing: CANONICAL_BONES.filter((b) => !mapped.has(b)),+ unmapped,+ coreMissing,+ fingerCoverage: FINGER_BONES.length ? fingersMapped / FINGER_BONES.length : 0,+ // The retargeter's own gate, applied by name so this answer and the+ // runtime's answer cannot drift apart.+ retargetable: coverage >= MIN_COVERAGE && coreMissing.length === 0,+ };+}++/**+ * Human-readable reason a capability is or is not available. The UI shows this+ * verbatim, so it has to explain the fix, not just the fact.+ */+function poseVerdict(skeleton, isRigged) {+ if (!isRigged) {+ return {+ supported: false,+ reason: 'This model has no skeleton, so poses and animation clips cannot drive it. Rig it first (POST /api/rig) and every pose preset becomes available.',+ };+ }+ if (skeleton.retargetable) {+ return {+ supported: true,+ reason: `${skeleton.mapped.length} of ${CANONICAL_BONES.length} canonical bones mapped; every pose preset and animation clip retargets onto this rig.`,+ };+ }+ if (skeleton.coreMissing.length) {+ return {+ supported: false,+ reason: `Core bones did not map (${skeleton.coreMissing.slice(0, 6).join(', ')}). Renders fall back to the default rig rather than showing a broken pose.`,+ };+ }+ return {+ supported: false,+ reason: `Only ${Math.round(skeleton.coverage * 100)}% of the canonical skeleton mapped, below the ${Math.round(MIN_COVERAGE * 100)}% retarget floor. Renders fall back to the default rig.`,+ };+}++function expressionVerdict(morphs) {+ if (!morphs.implemented.length && !morphs.visemes.length) {+ return {+ supported: false,+ reason: 'No ARKit-52 morph targets on this model, so the expression parameter has nothing to drive. The render still succeeds and reports x-render-expression: none.',+ };+ }+ if (morphs.implemented.length < EXPRESSION_MIN_SHAPES) {+ return {+ supported: false,+ partial: true,+ reason: `Only ${morphs.implemented.length} ARKit shape(s) present (${morphs.implemented.join(', ')}). Requests naming anything else come back as x-render-expression: partial.`,+ };+ }+ return {+ supported: true,+ reason: `${morphs.implemented.length} of ${ARKIT_52.length} ARKit-52 shapes present. Anything outside that set reports back in x-render-expression-missing.`,+ };+}++function lipsyncVerdict(morphs) {+ const jaw = morphs.implemented.includes('jawOpen');+ if (morphs.visemes.length >= 8) {+ return { supported: true, reason: `${morphs.visemes.length} viseme shapes present: phoneme-accurate lipsync.` };+ }+ if (jaw) {+ return { supported: true, degraded: true, reason: 'No viseme set, but jawOpen is present: lipsync falls back to amplitude-driven jaw motion.' };+ }+ return { supported: false, reason: 'Neither visemes nor jawOpen are present, so speech cannot move this face. Voice still plays; the mouth stays still.' };+}++/**+ * Full capability report for a GLB.+ *+ * @param {string} storageKey — R2 object key or absolute URL+ * @param {object} [opts]+ * @param {boolean} [opts.untrusted=false] — the URL came from a caller, so+ * resolve and pin the host before fetching (SSRF guard).+ * @returns {Promise<null | object>} null when the object is not a parseable GLB+ */+export async function inspectGlbCapabilities(storageKey, opts = {}) {+ if (!storageKey) return null;+ const info = await inspectPrefix(storageKey, opts);+ if (!info) return null;++ const morphs = conformanceFromNames(info.morphTargetNames);+ const skeleton = gradeSkeleton(info.boneNames);+ const rig = detectRig(info.boneNames, info.generator);++ const pose = poseVerdict(skeleton, info.isRigged);+ const expression = expressionVerdict(morphs);+ const lipsync = lipsyncVerdict(morphs);++ return {+ rig: {+ detected: rig.id,+ label: rig.label,+ generator: info.generator,+ isRigged: info.isRigged,+ boneCount: info.boneNames.length,+ skinCount: info.skinCount,+ canonicalCoverage: Number(skeleton.coverage.toFixed(4)),+ fingerCoverage: Number(skeleton.fingerCoverage.toFixed(4)),+ mappedBones: skeleton.mapped,+ unmappedBones: skeleton.unmapped.slice(0, 64),+ bakedAnimations: info.animationNames,+ },+ morphs: {+ total: info.morphTargetNames.length || info.morphTargetSlots,+ named: info.morphTargetNames.length,+ arkitCoverage: Number(morphs.coverage.toFixed(4)),+ supported: morphs.implemented,+ missing: morphs.missing,+ visemes: morphs.visemes,+ // Shapes the model carries that are not part of the ARKit set:+ // custom sliders (body shape, hair, accessories) a caller may still+ // want to know exist even though the expression parameter ignores them.+ custom: morphs.unmapped.slice(0, 64),+ },+ geometry: {+ triangles: info.triangleCount,+ vertices: info.vertexCount,+ meshes: info.meshCount,+ primitives: info.primitiveCount,+ materials: info.materialCount,+ textures: info.textureCount,+ extensions: info.extensionsUsed,+ },+ can: { pose, expression, lipsync },+ };+}++export { CORE_BONES, EXPRESSION_MIN_SHAPES };diff --git a/api/_lib/glb-inspect.js b/api/_lib/glb-inspect.jsindex 83543a3ab..00d6e0351 100644--- a/api/_lib/glb-inspect.js+++ b/api/_lib/glb-inspect.js@@ -35,6 +35,15 @@ const CHUNK_BIN = 0x004E4942; // 'BIN\0' little-endian* extensionsUsed: string[],* hasBinChunk: boolean,* binChunkBytes: number,+ * morphTargetNames: string[],+ * morphTargetSlots: number,+ * boneNames: string[],+ * animationNames: string[],+ * primitiveCount: number,+ * triangleCount: number,+ * vertexCount: number,+ * materialCount: number,+ * textureCount: number,* }}*/export function inspectGlb(buf, { allowPartial = false } = {}) {@@ -116,6 +125,86 @@ export function inspectGlb(buf, { allowPartial = false } = {}) {extensionsUsed,hasBinChunk,binChunkBytes,+ ...describeAssetSurface(gltf, { skins, nodes, meshes, animations }),+ };+}++/**+ * The named, countable surface of a glTF asset: which morph targets and bones+ * it exposes, and how heavy the geometry is. Everything here is read from the+ * JSON chunk alone, so it costs nothing beyond the prefix already fetched.+ *+ * Morph target names live in `extras.targetNames` by convention (the glTF spec+ * has no first-class place for them). Blender, three.js, Ready Player Me and+ * Avaturn all write them on the mesh; some pipelines write them per-primitive+ * instead, so both are read and merged in declaration order.+ */+function describeAssetSurface(gltf, { skins, nodes, meshes, animations }) {+ const accessors = Array.isArray(gltf.accessors) ? gltf.accessors : [];+ const materials = Array.isArray(gltf.materials) ? gltf.materials : [];+ const textures = Array.isArray(gltf.textures) ? gltf.textures : [];++ const morphTargetNames = [];+ const seenMorph = new Set();+ const pushMorph = (list) => {+ if (!Array.isArray(list)) return;+ for (const name of list) {+ if (typeof name !== 'string' || seenMorph.has(name)) continue;+ seenMorph.add(name);+ morphTargetNames.push(name);+ }+ };++ let primitiveCount = 0;+ let triangleCount = 0;+ let vertexCount = 0;+ let morphSlotCount = 0;+ for (const mesh of meshes) {+ pushMorph(mesh?.extras?.targetNames);+ const primitives = Array.isArray(mesh?.primitives) ? mesh.primitives : [];+ for (const prim of primitives) {+ primitiveCount += 1;+ pushMorph(prim?.extras?.targetNames);+ if (Array.isArray(prim?.targets)) morphSlotCount = Math.max(morphSlotCount, prim.targets.length);+ const position = accessors[prim?.attributes?.POSITION];+ if (position?.count > 0) vertexCount += position.count;+ // mode 4 is TRIANGLES and is also the spec default when omitted.+ const mode = prim?.mode ?? 4;+ if (mode !== 4) continue;+ const indices = accessors[prim?.indices];+ const indexed = indices?.count > 0 ? indices.count : position?.count;+ if (indexed > 0) triangleCount += Math.floor(indexed / 3);+ }+ }++ const boneNames = [];+ const seenBone = new Set();+ for (const skin of skins) {+ const joints = Array.isArray(skin?.joints) ? skin.joints : [];+ for (const index of joints) {+ const name = nodes[index]?.name;+ if (typeof name !== 'string' || seenBone.has(name)) continue;+ seenBone.add(name);+ boneNames.push(name);+ }+ }++ const animationNames = animations+ .map((a) => (typeof a?.name === 'string' ? a.name : null))+ .filter(Boolean);++ return {+ morphTargetNames,+ // A mesh can carry morph targets with no names attached; the slot count+ // keeps "this model can morph" true even when nothing can address them.+ morphTargetSlots: morphSlotCount,+ boneNames,+ animationNames,+ primitiveCount,+ triangleCount,+ vertexCount,+ materialCount: materials.length,+ textureCount: textures.length,};}@@ -173,7 +262,11 @@ function bufToDataView(buf) {}function bufSlice(buf, start, end) {- if (Buffer.isBuffer?.(buf)) return buf.subarray(start, end);+ // `typeof` guard, not `Buffer?.isBuffer`: a browser has no `Buffer` binding+ // at all, and reading an undeclared identifier throws a ReferenceError that+ // optional chaining cannot catch. This module is reachable from the browser+ // via seed-mesh-gate.js (the /inspect page).+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer?.(buf)) return buf.subarray(start, end);if (ArrayBuffer.isView(buf)) {return new Uint8Array(buf.buffer, buf.byteOffset + start, end - start);}diff --git a/api/_lib/seed-mesh-gate.js b/api/_lib/seed-mesh-gate.jsnew file mode 100644index 000000000..66bae16fc--- /dev/null+++ b/api/_lib/seed-mesh-gate.js@@ -0,0 +1,289 @@+// @ts-check+// The catalog bar: stage 1 of the seed quality gate, and the ONLY part of it+// that is safe to run in a browser.+//+// Why this module exists separately from seed-quality.js+// -----------------------------------------------------+// seed-quality.js is the full two-stage gate, and it statically imports Vertex+// Gemini, the headless renderer and the R2 client. None of that can load in a+// browser. But stage 1 — the deterministic structural gate — reads nothing but+// the glTF JSON chunk, so it can run anywhere: the seeding cron, the tests, and+// the public inspector at /inspect.+//+// Splitting it out is what lets the inspector make its central promise: the+// verdict a creator sees in their own browser is produced by the SAME code that+// decides whether a platform-generated asset reaches the public catalog. Not a+// re-implementation, not an approximation of the rules, the module itself. A+// threshold change lands in both places at once because there is only one place.+//+// Two hard constraints on everything in this file, enforced mechanically by+// `npm run check:browser-graph` (it walks the real bundler graph from the HTML+// entries and fails the build the moment a `node:` built-in becomes reachable):+//+// 1. No Node built-ins, transitively. glb-quality.js and glb-inspect.js are+// both clean, which is why the split stops here.+// 2. No bare `process` / `Buffer` identifier reads. A browser has neither, and+// optional chaining does NOT save you: `process?.env` still throws a+// ReferenceError when `process` was never declared. Read them through the+// guarded helpers below.++import { scoreGlbQuality } from './glb-quality.js';+import { inspectGlb } from './glb-inspect.js';++// Bumped whenever a threshold changes, and stored on every verdict — an accept+// rate is only comparable within one gate version.+export const SEED_GATE_VERSION = 1;++// `typeof` is the only safe way to reach an identifier that may not exist.+function envRaw(name) {+ if (typeof process === 'undefined') return null;+ return process?.env?.[name] ?? null;+}++function numEnv(name, fallback) {+ const raw = envRaw(name);+ const n = raw == null || raw === '' ? NaN : Number(raw);+ return Number.isFinite(n) && n >= 0 ? n : fallback;+}++// Catalog bounds, on top of the forge-wide QUALITY_THRESHOLDS. Deliberately+// stricter than the interactive flow: a user who generates a coarse mesh chose+// to, a catalog entry nobody asked for has to earn its slot.+export const SEED_MESH_BOUNDS = Object.freeze({+ minVertices: numEnv('SEED_GATE_MIN_VERTICES', 1_500),+ maxVertices: numEnv('SEED_GATE_MAX_VERTICES', 1_500_000),+ minBytes: numEnv('SEED_GATE_MIN_BYTES', 20_000),+ // A rigged avatar with blendshapes legitimately runs tens of MB; the ceiling+ // only catches runaway output that would break the viewer's fetch budget.+ maxBytes: numEnv('SEED_GATE_MAX_BYTES', 80 * 1024 * 1024),+ requireTexture: (envRaw('SEED_GATE_REQUIRE_TEXTURE') ?? '1') !== '0',+});++/**+ * Deterministic structural gate over the GLB bytes.+ * @param {Uint8Array|ArrayBuffer|DataView} buf+ * @param {{ category?: string }} [opts]+ */+export function gateMesh(buf, { category = 'avatar' } = {}) {+ const quality = scoreGlbQuality(buf);+ const inspected = inspectGlb(buf);+ const reasons = [];+ const b = SEED_MESH_BOUNDS;++ if (!quality.valid) {+ return {+ pass: false,+ reasons: ['not_valid_glb'],+ quality,+ rigged: false,+ metrics: quality.metrics,+ };+ }+ if (quality.flag === 'degenerate') reasons.push(...quality.reasons);++ const m = quality.metrics;+ if (m.vertexCount < b.minVertices) reasons.push('vertices_below_floor');+ if (m.vertexCount > b.maxVertices) reasons.push('vertices_above_ceiling');+ if (m.sizeBytes < b.minBytes) reasons.push('file_too_small');+ if (m.sizeBytes > b.maxBytes) reasons.push('file_too_large');+ if (b.requireTexture && !m.hasTextures) reasons.push('no_textures');+ // A collapsed bounding box passes triangle counts but renders as a speck.+ if (!(m.bboxDiagonal > 0)) reasons.push('zero_volume');+ // Props may be a loose collection of parts; a catalog avatar that arrives as+ // a dozen disconnected meshes is a scene, not a character.+ if (category === 'avatar' && m.meshCount > 8) reasons.push('too_many_meshes_for_a_character');++ return {+ pass: reasons.length === 0,+ reasons,+ quality,+ rigged: Boolean(inspected?.isRigged),+ jointCount: inspected?.skeletonJointCount ?? 0,+ metrics: m,+ };+}++// ── The explain layer ────────────────────────────────────────────────────────+//+// gateMesh() returns a decision. A decision is all the cron needs, but it is+// useless to a person: `['vertices_below_floor', 'no_textures']` tells a creator+// their model was rejected without telling them what to do about it.+//+// This turns the same verdict into the checks that produced it — what was+// measured, what the bound was, why the bound exists, and the concrete next+// action. It lives beside the gate rather than in the page so the guidance+// cannot drift from the rule it describes, and so a reason code can never ship+// without an explanation (tests/seed-mesh-gate.test.js asserts exactly that).++/** Every reason code gateMesh can emit, with the guidance a creator needs. */+export const MESH_GATE_RULES = Object.freeze({+ not_valid_glb: {+ label: 'Readable glTF 2.0',+ why: 'The file is not a binary glTF. Nothing downstream can open it, so no other check can even run.',+ fix: 'Re-export as .glb (binary glTF 2.0). A .gltf + .bin pair, a .fbx or a .obj renamed to .glb will all land here.',+ },+ degenerate_triangles: {+ label: 'Renderable surface',+ why: 'There is almost no triangle geometry. This renders as nothing at all.',+ fix: 'The generation failed rather than produced a coarse result. Regenerate rather than trying to repair it.',+ },+ zero_volume: {+ label: 'Non-collapsed bounds',+ why: 'The bounding box has no extent, so the mesh draws as a single speck no matter how the camera is framed. It passes triangle counts, which is exactly why it needs its own check.',+ fix: 'Usually a failed generation. Regenerate; if it persists, check the exporter is not writing a zeroed transform.',+ },+ vertices_below_floor: {+ label: 'Geometry density',+ why: 'Too coarse to read as the thing it claims to be once it is on a storefront card next to denser models.',+ fix: 'Regenerate at a higher detail setting, or subdivide and re-bake. Raising the vertex count without adding real detail will not help how it looks.',+ },+ vertices_above_ceiling: {+ label: 'Geometry density',+ why: 'Runaway output. It will stall the viewer on lower-end devices and mobile.',+ fix: 'Decimate the mesh. Above roughly a million vertices there is essentially always a lossless-looking reduction available.',+ },+ file_too_small: {+ label: 'File weight',+ why: 'Structurally empty. A real textured model does not fit in this many bytes.',+ fix: 'Check the export actually embedded its buffers and textures rather than referencing external files.',+ },+ file_too_large: {+ label: 'File weight',+ why: 'Beyond the viewer fetch budget. Visitors on a slow connection will abandon before it appears.',+ fix: 'Compress textures (KTX2/Basis) and apply Draco or meshopt geometry compression. This usually cuts the file by an order of magnitude with no visible loss.',+ },+ no_textures: {+ label: 'Surface texture',+ why: 'Untextured geometry reads as flat grey clay. This bound is stricter than the interactive forge on purpose: a catalog entry is the platform vouching for itself.',+ fix: 'Bake and embed at least a base-colour map before publishing.',+ },+ too_many_meshes_for_a_character: {+ label: 'Single assembled character',+ why: 'A character arriving as a dozen disconnected meshes is a scene, not a character, and it will not rig or animate as one body.',+ fix: 'Join the parts into one mesh, or switch the category to Prop, where loose parts are legitimate and this check does not apply.',+ },+});++const fmtInt = (n) => Number(n || 0).toLocaleString('en-US');++function fmtBytes(n) {+ const b = Number(n || 0);+ if (b >= 1024 * 1024) return `${(b / 1024 / 1024).toFixed(1)} MB`;+ if (b >= 1024) return `${Math.round(b / 1024)} KB`;+ return `${fmtInt(b)} bytes`;+}++/**+ * Expand a gateMesh() verdict into the ordered checks that produced it.+ *+ * Every check reports whether it ran and what it measured, so a passing model+ * is as informative as a failing one: "3,273 vertices, floor is 1,500" tells a+ * creator how much headroom they have, where a bare `pass: true` tells them+ * nothing.+ *+ * @param {ReturnType<typeof gateMesh>} verdict+ * @param {{ category?: string }} [opts]+ */+export function explainMeshGate(verdict, { category = 'avatar' } = {}) {+ const b = SEED_MESH_BOUNDS;+ const m = verdict?.metrics || {};+ const reasons = Array.isArray(verdict?.reasons) ? verdict.reasons : [];+ const failed = new Set(reasons);+ const rule = (id) => MESH_GATE_RULES[id] || { label: id, why: '', fix: '' };++ // The file never parsed, so no measurement below it is meaningful. Reporting+ // the other checks as "passed" here would be a lie by omission.+ if (failed.has('not_valid_glb')) {+ return {+ gateVersion: SEED_GATE_VERSION,+ category,+ pass: false,+ headline: 'Not a readable .glb',+ summary: 'The file could not be parsed as binary glTF 2.0, so none of the other checks could run.',+ checks: [{ id: 'not_valid_glb', status: 'fail', actual: 'unreadable', bound: 'binary glTF 2.0', ...rule('not_valid_glb') }],+ metrics: m,+ };+ }++ const checks = [+ {+ id: 'vertices_below_floor',+ status: failed.has('vertices_below_floor') ? 'fail' : 'pass',+ actual: `${fmtInt(m.vertexCount)} vertices`,+ bound: `at least ${fmtInt(b.minVertices)}`,+ ...rule('vertices_below_floor'),+ },+ {+ id: 'vertices_above_ceiling',+ status: failed.has('vertices_above_ceiling') ? 'fail' : 'pass',+ actual: `${fmtInt(m.vertexCount)} vertices`,+ bound: `at most ${fmtInt(b.maxVertices)}`,+ ...rule('vertices_above_ceiling'),+ },+ {+ id: 'file_too_small',+ status: failed.has('file_too_small') ? 'fail' : 'pass',+ actual: fmtBytes(m.sizeBytes),+ bound: `at least ${fmtBytes(b.minBytes)}`,+ ...rule('file_too_small'),+ },+ {+ id: 'file_too_large',+ status: failed.has('file_too_large') ? 'fail' : 'pass',+ actual: fmtBytes(m.sizeBytes),+ bound: `at most ${fmtBytes(b.maxBytes)}`,+ ...rule('file_too_large'),+ },+ {+ id: 'no_textures',+ status: !b.requireTexture ? 'skipped' : failed.has('no_textures') ? 'fail' : 'pass',+ actual: m.hasTextures ? `${fmtInt(m.textureCount)} texture${m.textureCount === 1 ? '' : 's'}` : 'none',+ bound: b.requireTexture ? 'at least 1' : 'not enforced',+ ...rule('no_textures'),+ },+ {+ id: 'zero_volume',+ status: failed.has('zero_volume') ? 'fail' : 'pass',+ actual: `${Number(m.bboxDiagonal || 0).toFixed(3)} diagonal`,+ bound: 'greater than 0',+ ...rule('zero_volume'),+ },+ {+ id: 'too_many_meshes_for_a_character',+ // Props may legitimately be a loose collection of parts, so the rule+ // genuinely does not apply rather than silently passing.+ status:+ category !== 'avatar'+ ? 'skipped'+ : failed.has('too_many_meshes_for_a_character')+ ? 'fail'+ : 'pass',+ actual: `${fmtInt(m.meshCount)} mesh${m.meshCount === 1 ? '' : 'es'}`,+ bound: category === 'avatar' ? 'at most 8' : 'props exempt',+ ...rule('too_many_meshes_for_a_character'),+ },+ ];++ // Degenerate-geometry reasons come from the shared forge scorer rather than+ // from a catalog bound, so they are appended as they arrive instead of being+ // enumerated above. Anything already rendered as a check is not repeated.+ for (const id of reasons) {+ if (checks.some((c) => c.id === id)) continue;+ checks.push({ id, status: 'fail', actual: 'failed', bound: 'forge quality scorer', ...rule(id) });+ }++ const failures = checks.filter((c) => c.status === 'fail');+ return {+ gateVersion: SEED_GATE_VERSION,+ category,+ pass: Boolean(verdict?.pass),+ headline: verdict?.pass+ ? 'Clears the catalog bar'+ : `${failures.length} check${failures.length === 1 ? '' : 's'} short of the catalog bar`,+ summary: verdict?.pass+ ? 'This model passes every structural check the platform applies to its own catalog entries.'+ : failures.map((c) => c.label).join(' · '),+ checks,+ metrics: m,+ };+}diff --git a/api/_lib/seed-quality.js b/api/_lib/seed-quality.jsindex 03f645747..70b8ca213 100644--- a/api/_lib/seed-quality.js+++ b/api/_lib/seed-quality.js@@ -29,15 +29,25 @@// with a JSON sidecar carrying the full verdict, so prompt and threshold tuning// works off real failures instead of guesses.-import { scoreGlbQuality } from './glb-quality.js';-import { inspectGlb } from './glb-inspect.js';import { judgeOnce, JUDGE_MODEL, RENDER_BACKGROUND } from './quality-bench.js';import { vertexGeminiAvailable, vertexGeminiChatUrl, vertexGeminiHeaders } from './vertex-gemini.js';import { copyObject, putObject } from './r2.js';-// Bumped whenever a threshold or judge prompt changes, and stored on every-// verdict — an accept rate is only comparable within one gate version.-export const SEED_GATE_VERSION = 1;+// Stage 1 lives in its own module because it is the only part of this gate that+// can run in a browser: it touches nothing but the glTF JSON chunk, where this+// file statically imports Vertex, the headless renderer and the R2 client.+// The public inspector at /inspect imports that module directly, so the verdict+// a creator sees is produced by this exact code rather than a re-implementation+// of the rules. Re-exported here so existing server callers are unaffected.+import {+ SEED_GATE_VERSION,+ SEED_MESH_BOUNDS,+ gateMesh,+ explainMeshGate,+ MESH_GATE_RULES,+} from './seed-mesh-gate.js';++export { SEED_GATE_VERSION, SEED_MESH_BOUNDS, gateMesh, explainMeshGate, MESH_GATE_RULES };function numEnv(name, fallback) {const raw = typeof process !== 'undefined' ? process.env?.[name] : null;@@ -45,19 +55,6 @@ function numEnv(name, fallback) {return Number.isFinite(n) && n >= 0 ? n : fallback;}-// Catalog bounds, on top of the forge-wide QUALITY_THRESHOLDS. Deliberately-// stricter than the interactive flow: a user who generates a coarse mesh chose-// to, a catalog entry nobody asked for has to earn its slot.-export const SEED_MESH_BOUNDS = Object.freeze({- minVertices: numEnv('SEED_GATE_MIN_VERTICES', 1_500),- maxVertices: numEnv('SEED_GATE_MAX_VERTICES', 1_500_000),- minBytes: numEnv('SEED_GATE_MIN_BYTES', 20_000),- // A rigged avatar with blendshapes legitimately runs tens of MB; the ceiling- // only catches runaway output that would break the viewer's fetch budget.- maxBytes: numEnv('SEED_GATE_MAX_BYTES', 80 * 1024 * 1024),- requireTexture: (process?.env?.SEED_GATE_REQUIRE_TEXTURE ?? '1') !== '0',-});-// Vision thresholds, 1-10 on the shared realism-bench scale.export const SEED_JUDGE_THRESHOLDS = Object.freeze({minGeometryIntegrity: numEnv('SEED_GATE_MIN_GEOMETRY', 5),@@ -65,52 +62,6 @@ export const SEED_JUDGE_THRESHOLDS = Object.freeze({minMean: numEnv('SEED_GATE_MIN_MEAN', 4.5),});-// ── Stage 1: mesh sanity ─────────────────────────────────────────────────────--/**- * Deterministic structural gate over the GLB bytes.- * @param {Buffer|Uint8Array} buf- * @param {{ category?: string }} [opts]- */-export function gateMesh(buf, { category = 'avatar' } = {}) {- const quality = scoreGlbQuality(buf);- const inspected = inspectGlb(buf);- const reasons = [];- const b = SEED_MESH_BOUNDS;-- if (!quality.valid) {- return {- pass: false,- reasons: ['not_valid_glb'],- quality,- rigged: false,- metrics: quality.metrics,- };- }- if (quality.flag === 'degenerate') reasons.push(...quality.reasons);-- const m = quality.metrics;- if (m.vertexCount < b.minVertices) reasons.push('vertices_below_floor');- if (m.vertexCount > b.maxVertices) reasons.push('vertices_above_ceiling');- if (m.sizeBytes < b.minBytes) reasons.push('file_too_small');- if (m.sizeBytes > b.maxBytes) reasons.push('file_too_large');- if (b.requireTexture && !m.hasTextures) reasons.push('no_textures');- // A collapsed bounding box passes triangle counts but renders as a speck.- if (!(m.bboxDiagonal > 0)) reasons.push('zero_volume');- // Props may be a loose collection of parts; a catalog avatar that arrives as- // a dozen disconnected meshes is a scene, not a character.- if (category === 'avatar' && m.meshCount > 8) reasons.push('too_many_meshes_for_a_character');-- return {- pass: reasons.length === 0,- reasons,- quality,- rigged: Boolean(inspected?.isRigged),- jointCount: inspected?.skeletonJointCount ?? 0,- metrics: m,- };-}-// ── Stage 2: vision judge ────────────────────────────────────────────────────// Catalog-specific question the realism bench does not ask: can this asset bediff --git a/api/avatar/capabilities.js b/api/avatar/capabilities.jsnew file mode 100644index 000000000..ae7eb367a--- /dev/null+++ b/api/avatar/capabilities.js@@ -0,0 +1,186 @@+// GET /api/avatar/capabilities — what a 3D avatar can actually do, before you render it.+//+// Every other avatar API in this stack answers "here is a picture". This one+// answers "here is what this model will and will not honor, and why". It reads+// the glTF JSON chunk of a GLB (a ranged read of the head of the file, never the+// mesh binary) and reports:+//+// • which ARKit-52 morph targets are present, so an `expression` request can+// be built from shapes that exist instead of shapes that were hoped for+// • whether the skeleton maps onto the canonical humanoid bone set the+// pre-baked clip library addresses, so `pose` and animation are knowable+// up front rather than discovered as a T-pose+// • geometry weight (triangles, textures, extensions) for budget decisions+// • a plain-language verdict per capability that names the fix when the+// answer is no+//+// Query parameters (exactly one of avatar/url is required):+// avatar — three.ws avatar UUID (public or unlisted)+// url — any publicly reachable .glb URL, SSRF-guarded and range-capped+//+// Called with neither, it returns its own schema, so the endpoint is+// self-documenting from a browser address bar.+//+// The capability mapping is the same code the renderer and the retargeter run+// (src/runtime/arkit52.js, src/glb-canonicalize.js, src/animation-retarget.js),+// so this is a report of what will happen, not an estimate of it. Drives the+// /render-lab composer, which disables controls a model cannot honor.++import { cors, error, json, wrap, rateLimited } from '../_lib/http.js';+import { getAvatar } from '../_lib/avatars.js';+import { inspectGlbCapabilities } from '../_lib/avatar-capabilities.js';+import { ARKIT_52, ARKIT_VISEMES } from '../../src/runtime/arkit52.js';+import { CANONICAL_BONES } from '../../src/glb-canonicalize.js';++export const maxDuration = 20;++const RATE_LIMIT_WINDOW_MS = 10 * 60 * 1000;+const RATE_LIMIT_MAX = 120;+const rateMap = new Map();++// Inspection is deterministic for a given (model, version) pair, and the+// composer re-asks on every avatar switch. Cache the answer in-process so a+// browsing session costs one ranged read per avatar, not one per interaction.+const CACHE_TTL_MS = 10 * 60 * 1000;+const CACHE_MAX = 500;+const cache = new Map();++function rateCheck(ip) {+ const now = Date.now();+ if (!ip) return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX, reset: now + RATE_LIMIT_WINDOW_MS };+ const arr = (rateMap.get(ip) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS);+ if (arr.length >= RATE_LIMIT_MAX) {+ rateMap.set(ip, arr);+ return { success: false, limit: RATE_LIMIT_MAX, remaining: 0, reset: arr[0] + RATE_LIMIT_WINDOW_MS };+ }+ arr.push(now);+ rateMap.set(ip, arr);+ if (rateMap.size > 10000) {+ for (const [k, v] of rateMap) {+ if (v.every((t) => now - t >= RATE_LIMIT_WINDOW_MS)) rateMap.delete(k);+ }+ }+ return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };+}++function cacheGet(key) {+ const hit = cache.get(key);+ if (!hit) return null;+ if (Date.now() - hit.at > CACHE_TTL_MS) {+ cache.delete(key);+ return null;+ }+ return hit.value;+}++function cacheSet(key, value) {+ if (cache.size >= CACHE_MAX) {+ const oldest = cache.keys().next().value;+ if (oldest !== undefined) cache.delete(oldest);+ }+ cache.set(key, { at: Date.now(), value });+}++function schema() {+ return {+ endpoint: 'GET /api/avatar/capabilities',+ description:+ 'Report what a GLB avatar can actually do (expressions, poses, lipsync) before you render it. Reads only the glTF JSON chunk, so it is fast even on large models.',+ parameters: {+ avatar: { type: 'uuid', description: 'three.ws avatar ID (public or unlisted)' },+ url: { type: 'url', description: 'Any publicly reachable .glb URL. One of avatar or url is required.' },+ },+ returns: {+ rig: 'Detected authoring pipeline, bone count, canonical-skeleton coverage, baked clip names',+ morphs: 'ARKit-52 shapes present and missing, viseme set, non-ARKit custom shapes',+ geometry: 'Triangles, vertices, meshes, materials, textures, glTF extensions in use',+ can: 'Per-capability verdict (pose, expression, lipsync) with a plain-language reason',+ },+ reference: {+ arkit52: ARKIT_52,+ visemes: ARKIT_VISEMES,+ canonicalBones: CANONICAL_BONES,+ },+ examples: [+ '/api/avatar/capabilities?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209',+ '/api/avatar/capabilities?url=https://three.ws/avatars/selfie-girl.glb',+ ],+ playground: 'https://three.ws/render-lab',+ };+}++export default wrap(async function handler(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ if (req.method !== 'GET') {+ res.setHeader('allow', 'GET, OPTIONS');+ return error(res, 405, 'method_not_allowed', 'Use GET');+ }++ const ip = (req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket?.remoteAddress;+ const rl = rateCheck(ip);+ if (!rl.success) {+ return rateLimited(res, rl, `Limit: ${RATE_LIMIT_MAX} inspections per ${RATE_LIMIT_WINDOW_MS / 60000}m`);+ }++ const q = new URL(req.url, 'http://x').searchParams;+ const avatarId = q.get('avatar');+ const rawUrl = q.get('url');++ if (!avatarId && !rawUrl) {+ return json(res, 200, schema(), { 'cache-control': 'public, max-age=86400' });+ }++ let source;+ let cacheKey;+ let subject = null;++ if (avatarId) {+ const avatar = await getAvatar({ id: avatarId });+ if (!avatar) return error(res, 404, 'not_found', 'Avatar not found or is private');+ if (!avatar.model_url) {+ return error(res, 403, 'private', 'Avatar is private: only public or unlisted avatars can be inspected');+ }+ source = avatar.model_url;+ // updated_at in the key means an edited avatar re-inspects instead of+ // serving a stale verdict about the model it used to be.+ cacheKey = `a:${avatar.id}:${avatar.updated_at || ''}`;+ subject = { kind: 'avatar', id: avatar.id, name: avatar.name || null, slug: avatar.slug || null };+ } else {+ if (!/^https?:\/\//i.test(rawUrl)) {+ return error(res, 400, 'invalid_url', 'url must be an absolute http(s) URL to a .glb file');+ }+ source = rawUrl;+ cacheKey = `u:${rawUrl}`;+ subject = { kind: 'url', url: rawUrl };+ }++ const cached = cacheGet(cacheKey);+ if (cached) {+ res.setHeader('x-capabilities-cache', 'hit');+ return json(res, 200, { ...cached, subject }, { 'cache-control': 'public, max-age=300, s-maxage=3600' });+ }++ let report;+ try {+ report = await inspectGlbCapabilities(source, { untrusted: Boolean(rawUrl) });+ } catch (err) {+ // A caller-supplied URL failing is a fact about their input, not a fault+ // on this side, so it comes back as a 400 they can act on.+ const isCallerUrl = Boolean(rawUrl);+ return error(+ res,+ isCallerUrl ? 400 : 502,+ 'fetch_failed',+ `Could not read the model: ${err?.message || 'unknown error'}`,+ );+ }++ if (!report) {+ return error(res, 422, 'not_a_glb', 'That file is not a parseable binary glTF 2.0 (.glb). Only GLB is supported; .gltf + external buffers is not.');+ }++ cacheSet(cacheKey, report);+ res.setHeader('x-capabilities-cache', 'miss');+ return json(res, 200, { ...report, subject }, { 'cache-control': 'public, max-age=300, s-maxage=3600' });+});diff --git a/docs/rig-doctor.md b/docs/rig-doctor.mdnew file mode 100644index 000000000..33e1c06c8--- /dev/null+++ b/docs/rig-doctor.md@@ -0,0 +1,223 @@+# Rig Doctor++**[Rig Doctor](https://three.ws/rig-doctor) tells you whether a `.glb` will actually animate on three.ws, before you upload it anywhere.**++Drop a file and you get four things in about a second: a verdict, a limb-by-limb coverage score, a live preview of your own rig performing the real clip library, and (when the bone names need it) a repaired copy of the file to download.++Everything runs in your browser. The file is read with `FileReader` and analysed on your machine; no bytes are posted to any server. You can disconnect your network and the diagnosis still works.++**On this page:** [The problem](#the-problem-a-rig-that-loads-but-never-moves) · [Reading the verdict](#reading-the-verdict) · [Coverage](#coverage-which-limbs-will-move) · [The repair](#the-repair) · [Generated output](#generated-output) · [Conventions](#recognised-rig-conventions) · [The canonical skeleton](#the-canonical-skeleton) · [Programmatic use](#programmatic-use)++Related: [Avatar CLI](./avatar-cli.md) turns the generated manifest into a validated, hash-anchored file. The [web component reference](./web-component.md) covers the `<agent-3d>` element the embed tab emits. [Asset pipeline](./3d-asset-pipeline.md) covers FBX and GLB conversion upstream of all of this.++---++## The problem: a rig that loads but never moves++Every animation clip on three.ws is authored against one skeleton and stores its motion as tracks addressed **by bone name**: `Hips.quaternion`, `LeftForeArm.quaternion`, `RightUpLeg.quaternion`, and so on across 52 joints.++When your rig names those same joints something else, the track addresses a bone that does not exist. Nothing errors. The GLB parses, the materials render, the animation mixer runs at 60fps, and the character stands in its authored bind pose forever.++That failure is invisible from the outside, which is what makes it expensive. A creator exports from Unreal, uploads, sees a T-pose, and has no way to learn that the only problem was `upperarm_l` instead of `LeftArm`.++Rig Doctor moves that answer to the front of the process and makes it local.++---++## Reading the verdict++The banner at the top of the report is one of three levels. It mirrors the runtime gate exactly (`AnimationManager.supportsCanonicalClips()`), so what it says is what the platform will do.++### Ready++Every limb group resolved. Retargeted clips drive the whole character: torso, arms, hands, and legs.++The notes below the headline still carry useful detail, most often about lip-sync. A rig can be fully drivable and still lack the blendshapes that let it speak.++### Partial++The rig animates, but at least one limb group did not map and will stay at its bind pose while everything else moves.++This is the most common result, and the most common shape of it is **legs**. A halfbody avatar or a rig using a non-standard leg naming convention produces a character that glides across the floor with frozen knees during a walk cycle. The verdict names exactly which joints are missing.++### Will not animate++One of two things is true:++- **No skinned mesh.** There is no skin binding a mesh to a skeleton, so no clip can deform anything. The model renders as a static prop and every animation affordance is hidden. Fix it by re-exporting with skinning enabled, or by running the mesh through the auto-rigger (`POST /api/forge?action=rig` with a `glb_url`).+- **Under the joint floor.** Fewer than **8** joints mapped to the canonical set. Below that threshold a retargeted clip moves a limb or two on an otherwise frozen statue, which reads worse than not animating at all, so the platform substitutes the default rig instead.++---++## Coverage: which limbs will move++A single percentage is not actionable. "62% covered" does not tell a creator what to fix. Rig Doctor scores four groups independently, each with its own set of **key joints** whose absence is visible in motion:++| Group | Key joints | What breaks without them |+|---|---|---|+| Torso | `Hips` | Root motion and sway. Everything else hangs off this anchor. |+| Arms | `LeftArm`, `LeftForeArm`, `RightArm`, `RightForeArm` | Waves, claps, and gestures. The arms stay out at the bind pose. |+| Hands | `LeftHandIndex1`, `RightHandIndex1` | Sign language and detailed emotes. Walk cycles survive without fingers. |+| Legs | `LeftUpLeg`, `LeftLeg`, `RightUpLeg`, `RightLeg` | Walk and run cycles. The avatar slides instead of stepping. |++A group is marked **Will animate** only when every key joint mapped. The bar shows total coverage for that group including the non-key joints, so a rig with `LeftArm` but no `LeftShoulder` reads as drivable with an incomplete bar, which is exactly right: it moves, slightly less expressively.++Use the clip buttons under the live preview to see this directly. Each clip is labelled with the group it exercises, and a clip whose group is unmapped is tinted so you know before pressing it that the point is to watch something *not* move.++---++## The repair++When your joint names are recognisable but non-canonical (a Mixamo rig, an Unreal mannequin, a VRoid export), Rig Doctor offers **Download the repaired GLB**.++The repair runs [`canonicalizeGLBBones`](https://github.com/nirholas/three.ws/blob/main/src/glb-canonicalize.js) in your browser, the same function the upload path uses server-side. It:++- rewrites the names of nodes referenced from `skins[].joints[]` to their canonical form+- folds a non-identity armature orientation when one is present, reverting the fold if it would have moved the mesh+- copies the binary chunk through byte for byte++It does **not** touch geometry, materials, textures, morph targets, or animations. The output is a valid glTF 2.0 binary with the same visual result and a skeleton the clip library can address.++The button only appears when a repair would change something. A rig that is already canonical gets no button, because handing back a byte-identical file would be a lie about having helped.++> The live preview shows the **original** file, not the repaired one. Retargeting canonicalizes names in memory anyway, so a Mixamo rig performs correctly in the preview without downloading anything. Downloading matters for tools that are not three.ws: Blender, Unity, your own three.js scene.++---++## Generated output++The **Ship it** panel writes three artefacts from the file you dropped.++**Manifest** is a [schema v1](https://github.com/nirholas/three.ws/blob/main/packages/avatar-schema/schema/avatar.v1.json) avatar manifest with everything the file could tell us already filled in: triangle count, joint counts, morph-target count, lip-sync capability, and the correct `skeleton` enum value for your detected convention. You supply `id`, `name`, `owner`, and the public `mesh.uri`, none of which a local file can know.++**Embed** is the `<agent-3d>` loader and element, ready to paste into any page.++**CLI** is the [`@three-ws/avatar-cli`](./avatar-cli.md) invocation that produces the same manifest with a real `sha256` over the mesh bytes, plus the validate call. Run it when you are ready to anchor the manifest for real:++```bash+npx @three-ws/avatar-cli init \+ --name "Michelle" \+ --mesh ./michelle.glb \+ --mesh-uri https://your-host.example/michelle.glb \+ --owner YOUR_SOLANA_ADDRESS \+ --out michelle.avatar.json++npx @three-ws/avatar-cli validate michelle.avatar.json+```++---++## Recognised rig conventions++The convention detector reports which authoring tool your skeleton came from and what evidence it used. Detection is ordered most-specific first, so Ready Player Me is distinguished from plain Mixamo (they share bone names and differ only in their `Wolf3D_*` mesh nodes).++| Convention | Detected by | Manifest `skeleton` |+|---|---|---|+| Ready Player Me | `Wolf3D_*` mesh nodes over a Mixamo skeleton | `rpm` |+| Mixamo | `mixamorig:` joint prefix | `mixamo` |+| VRM / VRoid | `J_Bip_*` humanoid joint names | `vrm-humanoid` |+| Reallusion Character Creator | `CC_Base_*` joint prefix | `custom` |+| Unreal Engine mannequin | `pelvis`, `thigh_l`, `clavicle_l` | `custom` |+| 3ds Max Biped | `Bip01` / `Bip001` prefix | `custom` |+| Blender Rigify | `DEF-` / `ORG-` / `MCH-` bone layers | `custom` |+| Autodesk HumanIK / MotionBuilder | character-namespaced joints (`Character1:Hips`) | `custom` |+| Daz Genesis | `lShldr`, `abdomen`, `lThigh` | `custom` |+| MakeHuman / Blender side-suffix | `.L` / `.R` suffixes | `custom` |+| Avaturn / three.ws canonical | joint names already match exactly | `avaturn` |++An unrecognised rig is not automatically a failing rig. The canonicalizer strips vendor prefixes and normalises separators before it looks anything up, so a rig with no fingerprint can still map every joint. Detection tells you *where the file came from*; coverage tells you *whether it works*.++### When your rig is not recognised++The **Unrecognised joints** panel lists every joint name the canonicalizer could not resolve. If those names belong to a standard rig, they are precisely what belongs in [`src/glb-canonicalize.js`](https://github.com/nirholas/three.ws/blob/main/src/glb-canonicalize.js). Open an issue with the list and every future upload of that rig animates for everyone, not just for you.++---++## The canonical skeleton++52 joints. Torso and head:++```+Hips Spine Spine1 Spine2 Neck Head+```++Each arm (mirrored `Left` / `Right`):++```+LeftShoulder LeftArm LeftForeArm LeftHand+```++Each hand, three joints per finger (mirrored):++```+LeftHandThumb1..3 LeftHandIndex1..3 LeftHandMiddle1..3+LeftHandRing1..3 LeftHandPinky1..3+```++Each leg (mirrored):++```+LeftUpLeg LeftLeg LeftFoot LeftToeBase+```++This is the Avaturn reference rig, the same skeleton every clip in `/public/animations/clips/` is authored against. Rename your joints to match and no retargeting is needed at all.++---++## Programmatic use++The analysis is a pure function of the GLB bytes, exported from `src/rig-report.js`. It has no DOM, WebGL, or network dependency, so it runs in Node as well as in the browser:++```js+import { readFileSync } from 'node:fs';+import { analyzeGlb } from './src/rig-report.js';++const buf = readFileSync('./michelle.glb');+const report = analyzeGlb(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength), {+ fileName: 'michelle.glb',+});++console.log(report.verdict.level); // 'pass' | 'warn' | 'fail'+console.log(report.verdict.headline); // one sentence you can print+console.log(report.skeleton.convention); // { id: 'mixamo', label: 'Mixamo', … }+console.log(report.skeleton.mapped); // 52+console.log(report.skeleton.unmapped); // joint names with no canonical form++for (const g of report.skeleton.groups) {+ if (!g.driven) console.log(`${g.label} frozen, missing ${g.missingKey.join(', ')}`);+}+```++That makes it usable as a CI gate. Exit non-zero when a rig regresses and a broken avatar never reaches production:++```js+if (report.verdict.level === 'fail') {+ console.error(report.verdict.headline);+ process.exit(1);+}+```++### Exported API++| Export | Returns |+|---|---|+| `analyzeGlb(buffer, { fileName })` | the full report. Throws only when the bytes are not a readable glTF 2.0 binary. |+| `readGlbJson(buffer)` | `{ json, jsonBytes, binBytes }` for inspecting the raw glTF document. |+| `manifestFromReport(report, identity)` | a schema-v1 avatar manifest. `identity` supplies `id`, `name`, `meshUri`, `owner`, `createdAt`, and optionally `sha256`. |+| `formatBytes(n)` | a human-readable size string. |+| `MIN_CANONICAL_BONES` | `8`, the drivability floor. |+| `CANONICAL_TOTAL` | `52`, the size of the canonical set. |+| `LIMB_GROUPS` | the group definitions, including each group's key joints. |++---++## Sharing a result++Every sample rig is linkable, which is how the failure states in this document can be checked against a live page rather than taken on faith:++- [A Mixamo rig that fully animates](https://three.ws/rig-doctor?sample=/avatars/michelle.glb)+- [A halfbody avatar with frozen legs](https://three.ws/rig-doctor?sample=/avatars/realistic-halfbody.glb)+- [A skinned but non-humanoid rig](https://three.ws/rig-doctor?sample=/avatars/fox.glb)+- [A static mesh with no skeleton](https://three.ws/rig-doctor?sample=/avatars/mannequin.glb)++Your own file cannot be shared this way, because it never leaves your machine.diff --git a/pages/inspect.html b/pages/inspect.htmlnew file mode 100644index 000000000..d937f6fd3--- /dev/null+++ b/pages/inspect.html@@ -0,0 +1,301 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Model Inspector · Does your model clear the catalog bar? · three.ws</title>+ <meta name="description" content="Run the exact quality gate three.ws applies to its own catalog against any .glb, in your browser. Nothing is uploaded. Instant per-rule verdict with the fix for every failure." />+ <link rel="canonical" href="https://three.ws/inspect" />+ <meta property="og:title" content="Model Inspector · three.ws" />+ <meta property="og:description" content="Run the exact quality gate three.ws applies to its own catalog against any .glb, in your browser. Nothing is uploaded." />+ <meta property="og:url" content="https://three.ws/inspect" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <style>+ :root {+ --ins-pass: #2fbf71;+ --ins-fail: #f87171;+ --ins-line: rgba(255, 255, 255, 0.09);+ --ins-panel: rgba(255, 255, 255, 0.032);+ --ins-ink-2: rgba(255, 255, 255, 0.58);+ --ins-ink-3: rgba(255, 255, 255, 0.38);+ }+ [data-theme='light'] {+ --ins-line: rgba(0, 0, 0, 0.11);+ --ins-panel: rgba(0, 0, 0, 0.025);+ --ins-ink-2: rgba(0, 0, 0, 0.62);+ --ins-ink-3: rgba(0, 0, 0, 0.45);+ }++ .ins-wrap { max-width: 1240px; margin: 0 auto; padding: clamp(1.5rem, 4vw, 3.25rem) 1.25rem 5rem; }++ .ins-hero { max-width: 62ch; margin-bottom: 2rem; }+ .ins-eyebrow {+ display: inline-flex; align-items: center; gap: 0.5rem;+ font-size: 11px; font-weight: 700; letter-spacing: 0.09em; text-transform: uppercase;+ color: var(--ins-ink-3); margin: 0 0 0.85rem;+ }+ .ins-eyebrow::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--ins-pass); box-shadow: 0 0 10px var(--ins-pass); }+ .ins-title { font-size: clamp(1.75rem, 4.4vw, 2.6rem); font-weight: 800; letter-spacing: -0.032em; line-height: 1.08; margin: 0 0 0.85rem; }+ .ins-lede { font-size: clamp(14px, 1.6vw, 16px); line-height: 1.62; color: var(--ins-ink-2); margin: 0; }+ .ins-lede strong { color: inherit; font-weight: 650; }++ /* Input */+ .ins-intake { display: grid; grid-template-columns: 1.15fr 1fr; gap: 1rem; margin-bottom: 1rem; }+ @media (max-width: 780px) { .ins-intake { grid-template-columns: 1fr; } }++ .ins-drop {+ position: relative; border: 1.5px dashed var(--ins-line); border-radius: 16px;+ background: var(--ins-panel); padding: 1.6rem 1.4rem; text-align: center;+ transition: border-color 0.18s ease, background 0.18s ease, transform 0.18s ease;+ }+ .ins-drop.is-over { border-color: var(--ins-pass); background: rgba(47, 191, 113, 0.09); transform: scale(1.008); }+ .ins-drop-title { font-size: 14.5px; font-weight: 650; margin: 0 0 0.3rem; }+ .ins-drop-sub { font-size: 12.5px; color: var(--ins-ink-3); margin: 0 0 0.95rem; }++ .ins-btn {+ font: inherit; font-size: 13px; font-weight: 600; padding: 9px 16px; border-radius: 10px;+ border: 1px solid var(--ins-line); background: rgba(255, 255, 255, 0.06); color: inherit;+ cursor: pointer; transition: background 0.16s ease, border-color 0.16s ease, transform 0.12s ease;+ }+ .ins-btn:hover { background: rgba(255, 255, 255, 0.11); border-color: rgba(255, 255, 255, 0.2); }+ .ins-btn:active { transform: translateY(1px); }+ .ins-btn:focus-visible, .ins-preset:focus-visible, .ins-seg button:focus-visible, .ins-url-row input:focus-visible, .ins-check summary:focus-visible {+ outline: 2px solid var(--ins-pass); outline-offset: 2px;+ }++ .ins-side { display: flex; flex-direction: column; gap: 0.85rem; }+ .ins-url-row { display: flex; gap: 0.5rem; }+ .ins-url-row input {+ flex: 1; min-width: 0; font: inherit; font-size: 13px; padding: 9px 13px; border-radius: 10px;+ border: 1px solid var(--ins-line); background: var(--ins-panel); color: inherit;+ }+ .ins-url-row input::placeholder { color: var(--ins-ink-3); }++ .ins-presets { display: flex; flex-wrap: wrap; gap: 0.45rem; }+ .ins-preset {+ font: inherit; text-align: left; padding: 7px 12px; border-radius: 10px; cursor: pointer;+ border: 1px solid var(--ins-line); background: var(--ins-panel); color: inherit;+ display: flex; flex-direction: column; gap: 1px;+ transition: background 0.16s ease, border-color 0.16s ease, transform 0.12s ease;+ }+ .ins-preset:hover { background: rgba(255, 255, 255, 0.09); border-color: rgba(255, 255, 255, 0.2); transform: translateY(-1px); }+ .ins-preset:active { transform: translateY(0); }+ .ins-preset-name { font-size: 12.5px; font-weight: 650; }+ .ins-preset-note { font-size: 10.5px; color: var(--ins-ink-3); }++ .ins-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; margin-bottom: 1.5rem; }+ .ins-seg { display: inline-flex; padding: 3px; border-radius: 11px; border: 1px solid var(--ins-line); background: var(--ins-panel); }+ .ins-seg button {+ font: inherit; font-size: 12.5px; font-weight: 600; padding: 6px 14px; border-radius: 8px;+ border: 0; background: transparent; color: var(--ins-ink-2); cursor: pointer; transition: background 0.16s ease, color 0.16s ease;+ }+ .ins-seg button[aria-pressed='true'] { background: rgba(255, 255, 255, 0.13); color: inherit; }+ .ins-seg button:hover[aria-pressed='false'] { color: inherit; }+ .ins-meta { font-size: 11.5px; color: var(--ins-ink-3); font-variant-numeric: tabular-nums; }+ .ins-filename { font-size: 12.5px; font-weight: 600; padding: 4px 10px; border-radius: 7px; background: rgba(255, 255, 255, 0.07); }++ /* Layout */+ .ins-main { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr); gap: 1.5rem; align-items: start; }+ @media (max-width: 940px) { .ins-main { grid-template-columns: 1fr; } }++ .ins-stage {+ position: relative; border-radius: 18px; border: 1px solid var(--ins-line);+ background: radial-gradient(120% 90% at 50% 0%, rgba(124, 92, 255, 0.11), transparent 62%), var(--ins-panel);+ aspect-ratio: 1 / 1; overflow: hidden; position: sticky; top: 1.25rem;+ }+ @media (max-width: 940px) { .ins-stage { position: static; aspect-ratio: 4 / 3; } }+ #ins-canvas { width: 100%; height: 100%; display: block; opacity: 0; transition: opacity 0.5s ease; }+ .ins-stage.has-model #ins-canvas { opacity: 1; }+ .ins-stage-empty {+ position: absolute; inset: 0; display: grid; place-content: center; gap: 0.4rem; text-align: center;+ padding: 2rem; color: var(--ins-ink-3); font-size: 13px; pointer-events: none; transition: opacity 0.3s ease;+ }+ .ins-stage.has-model .ins-stage-empty { opacity: 0; }+ .ins-stage-empty svg { margin: 0 auto 0.5rem; opacity: 0.5; }+ .ins-hint {+ position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%);+ font-size: 11px; color: var(--ins-ink-3); background: rgba(0, 0, 0, 0.4);+ padding: 4px 11px; border-radius: 999px; backdrop-filter: blur(8px); pointer-events: none;+ }+ .ins-viewer-note {+ position: absolute; left: 12px; right: 12px; bottom: 12px; font-size: 11.5px; line-height: 1.45;+ padding: 9px 12px; border-radius: 10px; background: rgba(248, 113, 113, 0.12);+ border: 1px solid rgba(248, 113, 113, 0.28); color: inherit;+ }++ .ins-busy {+ position: absolute; inset: 0; display: grid; place-content: center; gap: 0.6rem; justify-items: center;+ background: rgba(0, 0, 0, 0.35); backdrop-filter: blur(3px); z-index: 3; font-size: 12.5px; color: var(--ins-ink-2);+ }+ .ins-spinner { width: 26px; height: 26px; border-radius: 50%; border: 2px solid var(--ins-line); border-top-color: var(--ins-pass); animation: ins-spin 0.75s linear infinite; }+ @keyframes ins-spin { to { transform: rotate(360deg); } }+ @media (prefers-reduced-motion: reduce) { .ins-spinner { animation-duration: 2.4s; } }++ /* Verdict */+ .ins-panel { border-radius: 18px; border: 1px solid var(--ins-line); background: var(--ins-panel); padding: 1.4rem; }+ .ins-placeholder h2 { font-size: 15px; font-weight: 700; margin: 0 0 0.5rem; }+ .ins-placeholder p { font-size: 13px; line-height: 1.6; color: var(--ins-ink-2); margin: 0 0 0.9rem; }+ .ins-placeholder ol { margin: 0; padding-left: 1.15rem; font-size: 13px; line-height: 1.75; color: var(--ins-ink-2); }+ .ins-placeholder li::marker { color: var(--ins-ink-3); font-variant-numeric: tabular-nums; }++ .ins-error { border-radius: 14px; border: 1px solid rgba(248, 113, 113, 0.3); background: rgba(248, 113, 113, 0.08); padding: 1.1rem 1.25rem; font-size: 13px; line-height: 1.6; }++ .ins-verdict-head { display: flex; align-items: center; gap: 0.7rem; flex-wrap: wrap; margin-bottom: 0.9rem; }+ .ins-badge { font-size: 11.5px; font-weight: 750; letter-spacing: 0.04em; text-transform: uppercase; padding: 5px 12px; border-radius: 999px; }+ .ins-badge.is-pass { background: rgba(47, 191, 113, 0.16); color: var(--ins-pass); border: 1px solid rgba(47, 191, 113, 0.34); }+ .ins-badge.is-fail { background: rgba(248, 113, 113, 0.14); color: var(--ins-fail); border: 1px solid rgba(248, 113, 113, 0.32); }+ .ins-headline { font-size: 17px; font-weight: 750; letter-spacing: -0.018em; margin: 0; }+ .ins-summary { font-size: 13px; line-height: 1.58; color: var(--ins-ink-2); margin: 0 0 0.85rem; }++ .ins-rig { font-size: 12px; font-weight: 600; padding: 7px 12px; border-radius: 10px; margin-bottom: 1.1rem; }+ .ins-rig.is-rigged { background: rgba(47, 191, 113, 0.1); color: var(--ins-pass); }+ .ins-rig.is-unrigged { background: rgba(255, 255, 255, 0.06); color: var(--ins-ink-2); }++ .ins-checks { display: flex; flex-direction: column; gap: 0.4rem; }+ .ins-check { border-radius: 12px; border: 1px solid var(--ins-line); background: rgba(255, 255, 255, 0.02); overflow: hidden; }+ .ins-check.is-fail { border-color: rgba(248, 113, 113, 0.3); background: rgba(248, 113, 113, 0.05); }+ .ins-check.is-skipped { opacity: 0.6; }+ .ins-check summary {+ display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; gap: 0.6rem; align-items: baseline;+ padding: 0.7rem 0.9rem; cursor: pointer; list-style: none; font-size: 13px;+ transition: background 0.15s ease;+ }+ .ins-check summary::-webkit-details-marker { display: none; }+ .ins-check summary:hover { background: rgba(255, 255, 255, 0.035); }+ .ins-check-icon { font-weight: 800; font-size: 12px; }+ .ins-check.is-pass .ins-check-icon { color: var(--ins-pass); }+ .ins-check.is-fail .ins-check-icon { color: var(--ins-fail); }+ .ins-check.is-skipped .ins-check-icon { color: var(--ins-ink-3); }+ .ins-check-label { font-weight: 620; }+ .ins-check-actual { font-size: 12px; font-variant-numeric: tabular-nums; color: var(--ins-ink-2); text-align: right; }+ .ins-check-bound { grid-column: 2 / -1; font-size: 11px; color: var(--ins-ink-3); font-variant-numeric: tabular-nums; }+ .ins-check-body { padding: 0 0.9rem 0.85rem 1.95rem; }+ .ins-check-why { font-size: 12.5px; line-height: 1.6; color: var(--ins-ink-2); margin: 0; }+ .ins-check-fix { font-size: 12.5px; line-height: 1.6; margin: 0.55rem 0 0; padding: 0.6rem 0.8rem; border-radius: 9px; background: rgba(255, 255, 255, 0.045); }+ .ins-check-fix span { display: block; font-size: 10px; font-weight: 750; letter-spacing: 0.09em; text-transform: uppercase; color: var(--ins-ink-3); margin-bottom: 0.25rem; }++ .ins-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 1.15rem; padding-top: 1.15rem; border-top: 1px solid var(--ins-line); }++ /* Explainer */+ .ins-notes { margin-top: 3rem; display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; }+ .ins-note { border-radius: 14px; border: 1px solid var(--ins-line); background: var(--ins-panel); padding: 1.1rem 1.2rem; }+ .ins-note h3 { font-size: 13px; font-weight: 700; margin: 0 0 0.45rem; }+ .ins-note p { font-size: 12.5px; line-height: 1.62; color: var(--ins-ink-2); margin: 0; }+ .ins-note a { color: inherit; text-decoration: underline; text-underline-offset: 2px; text-decoration-color: var(--ins-ink-3); }+ .ins-note a:hover { text-decoration-color: currentColor; }++ .ins-sr { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }+ </style>+</head>+<body>+ <div class="ins-wrap">+ <header class="ins-hero">+ <p class="ins-eyebrow">Catalog bar · <span id="ins-gate-version">gate</span></p>+ <h1 class="ins-title">Would your model make it into the catalog?</h1>+ <p class="ins-lede">+ This runs the <strong>exact quality gate</strong> three.ws applies to its own catalog entries against any+ <code>.glb</code> you give it. Same module, same thresholds, same decision.+ It runs entirely in your browser: <strong>nothing is uploaded</strong>, and the verdict is instant.+ </p>+ </header>++ <div class="ins-intake">+ <div class="ins-drop" id="ins-drop">+ <p class="ins-drop-title">Drop a .glb here</p>+ <p class="ins-drop-sub">It never leaves your machine.</p>+ <button type="button" class="ins-btn" id="ins-browse">Choose a file</button>+ <input type="file" id="ins-file" accept=".glb,model/gltf-binary" hidden />+ </div>++ <div class="ins-side">+ <form class="ins-url-row" id="ins-url-form">+ <input type="url" id="ins-url" placeholder="…or paste a .glb URL" aria-label="Model URL" />+ <button type="submit" class="ins-btn">Inspect</button>+ </form>+ <div>+ <p class="ins-meta" style="margin: 0 0 0.45rem;">Try one of these real models from our library:</p>+ <div class="ins-presets" id="ins-presets"></div>+ </div>+ </div>+ </div>++ <div class="ins-toolbar">+ <div class="ins-seg" role="group" aria-label="Asset category">+ <button type="button" data-category="avatar" aria-pressed="true">Character</button>+ <button type="button" data-category="accessory" aria-pressed="false">Prop</button>+ </div>+ <span class="ins-meta">Props skip the character-only checks.</span>+ <span class="ins-filename" id="ins-filename" hidden></span>+ </div>++ <div class="ins-main">+ <div class="ins-stage" id="ins-stage">+ <canvas id="ins-canvas"></canvas>+ <div class="ins-stage-empty">+ <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true">+ <path d="M12 2 3 7v10l9 5 9-5V7z" /><path d="M3 7l9 5 9-5M12 12v10" />+ </svg>+ <span>Your model appears here</span>+ </div>+ <div class="ins-hint" id="ins-hint" hidden>Drag to orbit · scroll to zoom</div>+ <div class="ins-viewer-note" id="ins-viewer-note" hidden></div>+ <div class="ins-busy" id="ins-busy" hidden>+ <div class="ins-spinner"></div>+ <span id="ins-busy-label">Inspecting…</span>+ </div>+ </div>++ <div>+ <div class="ins-panel ins-placeholder" id="ins-placeholder">+ <h2>No model yet</h2>+ <p>Give the inspector a model and it reports every structural check the catalog applies, what it measured, and how to fix anything that failed.</p>+ <ol>+ <li>Drop a <code>.glb</code>, paste a URL, or pick a sample.</li>+ <li>Read the per-rule verdict. Failures open first.</li>+ <li>Switch to <strong>Prop</strong> if it is not a character.</li>+ </ol>+ </div>++ <div class="ins-error" id="ins-error" role="alert" hidden></div>++ <div class="ins-panel" id="ins-result" role="status" aria-live="polite" hidden>+ <div class="ins-verdict-head">+ <span class="ins-badge" id="ins-badge"></span>+ <h2 class="ins-headline" id="ins-headline"></h2>+ </div>+ <p class="ins-summary" id="ins-summary"></p>+ <div class="ins-rig" id="ins-rig"></div>+ <div class="ins-checks" id="ins-checks"></div>+ <div class="ins-actions">+ <button type="button" class="ins-btn" id="ins-copy-json">Copy verdict JSON</button>+ <button type="button" class="ins-btn" id="ins-share" hidden>Copy shareable link</button>+ <a class="ins-btn" href="/create" style="text-decoration: none;">Generate a new one</a>+ </div>+ </div>+ </div>+ </div>++ <section class="ins-notes">+ <div class="ins-note">+ <h3>Why the bar is strict</h3>+ <p>A creator who generates a coarse mesh chose to, and can regenerate. A visitor browsing the catalog chose nothing: every entry is the platform vouching for itself. One melted blob on the storefront costs more trust than ten rejected generations cost compute.</p>+ </div>+ <div class="ins-note">+ <h3>This is the real gate</h3>+ <p>The page imports the same module the seeding cron runs, so the rules here cannot drift from the rules in production. Read <a href="/docs/seed-quality">the full gate documentation</a> for the vision stage that runs after this one.</p>+ </div>+ <div class="ins-note">+ <h3>Structure, not taste</h3>+ <p>These checks measure whether a model is built well enough to publish: density, weight, texture, bounds, assembly. Whether it <em>looks</em> good is judged separately by a vision model on the catalog path.</p>+ </div>+ </section>+ </div>++ <script src="/nav.js"></script>+ <script type="module" src="/src/inspect-page.js"></script>+</body>+</html>diff --git a/pages/rig-doctor.html b/pages/rig-doctor.htmlnew file mode 100644index 000000000..603881557--- /dev/null+++ b/pages/rig-doctor.html@@ -0,0 +1,327 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot - no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Rig Doctor · Will your GLB animate? · three.ws</title>+ <meta+ name="description"+ content="Drop a .glb and find out in one second whether it will animate on three.ws. Rig Doctor names your skeleton convention, scores every limb group, repairs non-standard bone names in your browser, and hands the fixed file back. Nothing is uploaded."+ />+ <meta name="theme-color" content="#000000" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Rig Doctor · Will your GLB animate?" />+ <meta+ property="og:description"+ content="Drop a GLB. Get the verdict, the limb-by-limb coverage, and a repaired file with canonical bone names. Runs entirely in your browser."+ />+ <meta property="og:url" content="https://three.ws/rig-doctor" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Rig+Doctor&d=Drop+a+GLB+and+find+out+in+one+second+whether+it+will+animate.+Diagnose%2C+repair%2C+and+preview+in+your+browser.&p=%2Frig-doctor" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Rig Doctor · three.ws" />+ <meta name="twitter:description" content="Drop a GLB. Get the verdict, limb-by-limb coverage, and a repaired file. Nothing leaves your machine." />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Rig+Doctor&d=Drop+a+GLB+and+find+out+in+one+second+whether+it+will+animate.+Diagnose%2C+repair%2C+and+preview+in+your+browser.&p=%2Frig-doctor" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Rig Doctor - three.ws" />++ <link rel="canonical" href="https://three.ws/rig-doctor" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <link rel="stylesheet" href="/rig-doctor.css" />+ <script defer src="/footer-newsletter.js"></script>++ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Rig Doctor","description":"Diagnose and repair a GLB avatar skeleton in the browser. Names the rig convention, scores limb coverage against the three.ws canonical skeleton, rewrites non-standard bone names, and previews the result.","url":"https://three.ws/rig-doctor","applicationCategory":"DeveloperApplication","operatingSystem":"Any","browserRequirements":"Requires WebGL2","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Is my model uploaded anywhere?","acceptedAnswer":{"@type":"Answer","text":"No. Rig Doctor reads the file with the browser FileReader API and analyses it on your machine. No bytes are sent to any server, which is why it works with the network disconnected."}},{"@type":"Question","name":"Why does my avatar load but never move?","acceptedAnswer":{"@type":"Answer","text":"Animation clips address bones by name. If your rig names its joints something the canonical skeleton does not recognise, the clip plays against nothing and the character stands in its bind pose. Rig Doctor tells you exactly which joints failed to map and can rename them for you."}},{"@type":"Question","name":"What does the repaired file change?","acceptedAnswer":{"@type":"Answer","text":"Only the names of nodes referenced from skins[].joints[], plus an armature orientation fold when one is present. Geometry, materials, textures, and the binary chunk are copied through byte for byte."}}]}]}</script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>++ <main>+ <!-- Hero and the drop zone. The tool IS the hero: no scrolling to reach it. -->+ <section class="rd-hero" aria-labelledby="rd-hero-title">+ <div class="rd-hero-bg" aria-hidden="true">+ <div class="rd-orb a"></div>+ <div class="rd-orb b"></div>+ <div class="rd-grid"></div>+ </div>++ <div class="rd-hero-inner">+ <span class="rd-badge">+ <span class="rd-badge-dot" aria-hidden="true"></span>+ Runs entirely in your browser+ </span>+ <h1 class="rd-hero-title" id="rd-hero-title">+ Will your avatar actually move?+ </h1>+ <p class="rd-hero-sub">+ Animation clips address bones by name. A rig whose joints are called+ <code>Bip001 L UpperArm</code> loads perfectly, renders perfectly, and then+ stands frozen forever. Drop your <code>.glb</code> and know in one second,+ before you upload it anywhere.+ </p>++ <!-- Drop zone. Label wraps the input so click, keyboard, and drop all work. -->+ <div class="rd-drop-wrap">+ <label+ class="rd-drop"+ id="rd-drop"+ data-state="idle"+ data-tip="Or press D from anywhere on the page"+ >+ <input+ type="file"+ id="rd-file"+ accept=".glb,model/gltf-binary"+ class="rd-file-input"+ aria-describedby="rd-drop-hint"+ />+ <span class="rd-drop-icon" aria-hidden="true">+ <svg width="34" height="34" viewBox="0 0 24 24" fill="none">+ <path d="M12 15V3m0 0L8 7m4-4 4 4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M3 15v3a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3v-3" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>+ </svg>+ </span>+ <span class="rd-drop-title">Drop a .glb here</span>+ <span class="rd-drop-hint" id="rd-drop-hint">+ or click to choose a file. Nothing is uploaded.+ </span>+ </label>++ <div class="rd-samples">+ <span class="rd-samples-label">No file handy? Try one:</span>+ <div class="rd-samples-row" role="group" aria-label="Sample rigs">+ <button type="button" class="rd-sample" data-sample="/avatars/michelle.glb" data-sample-name="michelle.glb" data-tip="A Mixamo rig: every joint maps, full clip library plays">+ Mixamo rig+ </button>+ <button type="button" class="rd-sample" data-sample="/avatars/realistic-halfbody.glb" data-sample-name="realistic-halfbody.glb" data-tip="A halfbody avatar: hands rigged, legs missing entirely">+ Halfbody+ </button>+ <button type="button" class="rd-sample" data-sample="/avatars/fox.glb" data-sample-name="fox.glb" data-tip="A skinned but non-humanoid rig: nothing maps">+ Non-humanoid+ </button>+ <button type="button" class="rd-sample" data-sample="/avatars/mannequin.glb" data-sample-name="mannequin.glb" data-tip="A static mesh with no skeleton at all">+ No skeleton+ </button>+ </div>+ </div>+ </div>++ <ul class="rd-hero-facts">+ <li><strong>0 bytes</strong> leave your machine</li>+ <li><strong>52</strong> canonical joints scored</li>+ <li><strong>11</strong> rig conventions recognised</li>+ <li><strong>1</strong> click to download the repair</li>+ </ul>+ </div>+ </section>++ <!-- Everything below is written by src/rig-doctor-page.js once a file is read. -->+ <section class="rd-results" id="rd-results" hidden aria-live="polite" aria-labelledby="rd-results-title">+ <h2 class="rd-sr-only" id="rd-results-title">Diagnosis</h2>++ <!-- Verdict banner -->+ <div class="rd-verdict" id="rd-verdict" data-level="pass">+ <div class="rd-verdict-mark" id="rd-verdict-mark" aria-hidden="true"></div>+ <div class="rd-verdict-body">+ <p class="rd-verdict-file" id="rd-verdict-file"></p>+ <h3 class="rd-verdict-headline" id="rd-verdict-headline"></h3>+ <p class="rd-verdict-detail" id="rd-verdict-detail"></p>+ <ul class="rd-verdict-notes" id="rd-verdict-notes"></ul>+ </div>+ <div class="rd-verdict-actions" id="rd-verdict-actions"></div>+ </div>++ <div class="rd-columns">+ <!-- Left: live preview driven by the real clip library -->+ <div class="rd-col rd-col-stage">+ <div class="rd-panel rd-panel-stage">+ <div class="rd-panel-head">+ <h3 class="rd-panel-title">Live preview</h3>+ <span class="rd-panel-note" id="rd-stage-note">Loading the scene</span>+ </div>+ <div class="rd-stage" id="rd-stage" data-state="loading">+ <div class="rd-stage-status" id="rd-stage-status">+ <span class="rd-spinner" aria-hidden="true"></span>+ <span id="rd-stage-status-text">Building the scene</span>+ </div>+ </div>+ <div class="rd-clips" id="rd-clips" role="group" aria-label="Play a clip on this rig"></div>+ <p class="rd-stage-foot" id="rd-stage-foot">+ This is the same retargeting path the platform uses, running on your file.+ </p>+ </div>+ </div>++ <!-- Right: the diagnosis proper -->+ <div class="rd-col rd-col-report">+ <div class="rd-panel">+ <div class="rd-panel-head">+ <h3 class="rd-panel-title">Coverage</h3>+ <span class="rd-panel-note" id="rd-coverage-note"></span>+ </div>+ <div class="rd-groups" id="rd-groups"></div>+ </div>++ <div class="rd-panel">+ <div class="rd-panel-head">+ <h3 class="rd-panel-title">Inventory</h3>+ <span class="rd-panel-note" id="rd-inventory-note"></span>+ </div>+ <dl class="rd-stats" id="rd-stats"></dl>+ </div>++ <div class="rd-panel" id="rd-renames-panel" hidden>+ <div class="rd-panel-head">+ <h3 class="rd-panel-title">Bone rewrites</h3>+ <span class="rd-panel-note" id="rd-renames-note"></span>+ </div>+ <div class="rd-renames" id="rd-renames"></div>+ </div>++ <div class="rd-panel" id="rd-unmapped-panel" hidden>+ <div class="rd-panel-head">+ <h3 class="rd-panel-title">Unrecognised joints</h3>+ <span class="rd-panel-note">Not in any convention we know</span>+ </div>+ <div class="rd-chips" id="rd-unmapped"></div>+ <p class="rd-panel-foot">+ If these are a standard rig, they belong in the canonicalizer.+ <a href="https://github.com/nirholas/three.ws/blob/main/src/glb-canonicalize.js" rel="noopener">Open an issue with this list</a>+ and every future upload of that rig animates.+ </p>+ </div>++ <div class="rd-panel">+ <div class="rd-panel-head">+ <h3 class="rd-panel-title">Ship it</h3>+ <span class="rd-panel-note">Generated from this exact file</span>+ </div>+ <div class="rd-tabs" role="tablist" aria-label="Generated output">+ <button type="button" class="rd-tab" role="tab" id="rd-tab-manifest" aria-controls="rd-pane-manifest" aria-selected="true" data-pane="manifest">Manifest</button>+ <button type="button" class="rd-tab" role="tab" id="rd-tab-embed" aria-controls="rd-pane-embed" aria-selected="false" data-pane="embed">Embed</button>+ <button type="button" class="rd-tab" role="tab" id="rd-tab-cli" aria-controls="rd-pane-cli" aria-selected="false" data-pane="cli">CLI</button>+ </div>+ <div class="rd-pane" id="rd-pane-manifest" role="tabpanel" aria-labelledby="rd-tab-manifest">+ <pre class="rd-code"><code id="rd-out-manifest"></code></pre>+ <button type="button" class="rd-copy" data-copy-target="rd-out-manifest">Copy manifest</button>+ </div>+ <div class="rd-pane" id="rd-pane-embed" role="tabpanel" aria-labelledby="rd-tab-embed" hidden>+ <pre class="rd-code"><code id="rd-out-embed"></code></pre>+ <button type="button" class="rd-copy" data-copy-target="rd-out-embed">Copy embed</button>+ </div>+ <div class="rd-pane" id="rd-pane-cli" role="tabpanel" aria-labelledby="rd-tab-cli" hidden>+ <pre class="rd-code"><code id="rd-out-cli"></code></pre>+ <button type="button" class="rd-copy" data-copy-target="rd-out-cli">Copy commands</button>+ </div>+ <p class="rd-panel-foot">+ Replace the placeholder URI and owner, then+ <a href="/docs/avatar-cli">validate it with the CLI</a>.+ </p>+ </div>+ </div>+ </div>+ </section>++ <!-- Static explainer. Visible before any file is dropped, so the page still+ teaches something to a visitor who has nothing to test. -->+ <section class="rd-explain" aria-labelledby="rd-explain-title">+ <div class="rd-explain-inner">+ <h2 class="rd-explain-title" id="rd-explain-title">Why rigs go silent</h2>+ <div class="rd-explain-grid">+ <article class="rd-explain-card">+ <span class="rd-explain-num" aria-hidden="true">01</span>+ <h3>Clips address bones by name</h3>+ <p>+ Every clip in the three.ws library is authored against one canonical+ skeleton: <code>Hips</code>, <code>LeftForeArm</code>,+ <code>RightUpLeg</code>, 52 joints in total. A track that names+ <code>LeftForeArm</code> drives nothing on a rig that calls that joint+ <code>lowerarm_l</code>.+ </p>+ </article>+ <article class="rd-explain-card">+ <span class="rd-explain-num" aria-hidden="true">02</span>+ <h3>The failure is silent</h3>+ <p>+ Nothing errors. The GLB loads, the material renders, the mixer runs, and+ the character stands in its bind pose. Nobody tells you why, which is+ why this page exists and why it runs before you upload rather than after.+ </p>+ </article>+ <article class="rd-explain-card">+ <span class="rd-explain-num" aria-hidden="true">03</span>+ <h3>Most rigs are one rename away</h3>+ <p>+ Mixamo, Avaturn, Ready Player Me, Unreal, VRM, Daz, Rigify, Biped,+ HumanIK, Reallusion, and MakeHuman all name the same joints+ differently. The canonicalizer already knows every one of those+ dialects, and it can rewrite your file in place.+ </p>+ </article>+ <article class="rd-explain-card">+ <span class="rd-explain-num" aria-hidden="true">04</span>+ <h3>Partial rigs are the common case</h3>+ <p>+ A rig rarely fails outright. Far more often the torso and arms map and+ the legs do not, so the avatar glides across the floor with frozen+ knees. Scoring each limb group separately is the difference between+ "62% covered" and "your legs will not move".+ </p>+ </article>+ </div>++ <div class="rd-explain-next">+ <a class="rd-next-card" href="/animations">+ <h3 class="rd-next-title">The clip library</h3>+ <p class="rd-next-desc">Every motion your rig has to match, previewed. This is what the 52 joints are for.</p>+ <span class="rd-next-go" aria-hidden="true">Open+ <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>+ </span>+ </a>+ <a class="rd-next-card" href="/avatar-cli">+ <h3 class="rd-next-title">Avatar CLI</h3>+ <p class="rd-next-desc">Scaffold, hash, and validate the manifest from your shell or from CI.</p>+ <span class="rd-next-go" aria-hidden="true">Open+ <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>+ </span>+ </a>+ <a class="rd-next-card" href="/docs/rig-doctor">+ <h3 class="rd-next-title">Read the reference</h3>+ <p class="rd-next-desc">What each verdict means, the full canonical joint list, and how to fix each one.</p>+ <span class="rd-next-go" aria-hidden="true">Open+ <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>+ </span>+ </a>+ </div>+ </div>+ </section>+ </main>++ <footer class="h-footer-horizon" role="contentinfo" aria-label="Site footer">+ <div class="h-footer-glow-line" aria-hidden="true"></div>+ <div class="h-footer-floor" aria-hidden="true"></div>+ <div id="footer-content"></div>+ </footer>++ <script src="/nav.js" defer></script>+ <script type="module" src="/src/rig-doctor-page.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/public/rig-doctor.css b/public/rig-doctor.cssnew file mode 100644index 000000000..5400cfb6d--- /dev/null+++ b/public/rig-doctor.css@@ -0,0 +1,1149 @@+/* Rig Doctor (/rig-doctor)+ *+ * Built entirely on the tokens in /tokens.css, which is what makes the page+ * theme-aware for free: the light-theme block in tokens.css redefines every+ * surface, ink, and stroke value, and nothing here hardcodes a colour that+ * would survive that swap. The three verdict colours are the only exception,+ * and they are the token set's own --success / --warn / --danger.+ *+ * Class prefix `rd-` throughout, so this file can never collide with the+ * shared nav, footer, or mobile stylesheets loaded alongside it.+ */++/* ── Layout scale ───────────────────────────────────────────────────────── */++.rd-hero,+.rd-results,+.rd-explain {+ --rd-max: 1180px;+}++.rd-sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ border: 0;+}++/* ── Hero ───────────────────────────────────────────────────────────────── */++.rd-hero {+ position: relative;+ padding: clamp(var(--space-xl), 7vw, var(--space-2xl)) var(--space-lg) var(--space-xl);+ overflow: hidden;+ isolation: isolate;+}++.rd-hero-bg {+ position: absolute;+ inset: 0;+ z-index: -1;+ pointer-events: none;+}++.rd-orb {+ position: absolute;+ border-radius: 50%;+ filter: blur(90px);+ opacity: 0.5;+}++.rd-orb.a {+ width: 44vw;+ height: 44vw;+ max-width: 520px;+ max-height: 520px;+ top: -14%;+ left: -8%;+ background: radial-gradient(circle, rgba(74, 222, 128, 0.16), transparent 70%);+}++.rd-orb.b {+ width: 38vw;+ height: 38vw;+ max-width: 440px;+ max-height: 440px;+ top: 6%;+ right: -10%;+ background: radial-gradient(circle, rgba(139, 92, 246, 0.16), transparent 70%);+}++.rd-grid {+ position: absolute;+ inset: 0;+ background-image:+ linear-gradient(var(--hairline) 1px, transparent 1px),+ linear-gradient(90deg, var(--hairline) 1px, transparent 1px);+ background-size: 56px 56px;+ mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, #000 30%, transparent 78%);+ -webkit-mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, #000 30%, transparent 78%);+ opacity: 0.7;+}++.rd-hero-inner {+ max-width: var(--rd-max);+ margin: 0 auto;+ text-align: center;+}++.rd-badge {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+ padding: var(--space-2xs) var(--space-sm);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-pill);+ background: var(--surface-1);+ color: var(--ink-dim);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.04em;+ text-transform: uppercase;+}++.rd-badge-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--success);+ box-shadow: 0 0 0 3px rgba(74, 222, 128, 0.16);+}++.rd-hero-title {+ margin: var(--space-md) auto var(--space-sm);+ max-width: 16ch;+ font-family: var(--font-display);+ font-size: clamp(2rem, 6vw, var(--text-2xl));+ font-weight: var(--weight-bold);+ line-height: 1.08;+ letter-spacing: -0.03em;+ color: var(--ink-bright);+}++.rd-hero-sub {+ margin: 0 auto var(--space-lg);+ max-width: 60ch;+ font-size: var(--text-base);+ line-height: var(--leading-normal);+ color: var(--ink-dim);+}++.rd-hero-sub code,+.rd-explain-card code {+ padding: 0.1em 0.36em;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm);+ background: var(--surface-2);+ color: var(--ink);+ font-family: var(--font-mono);+ font-size: 0.86em;+}++/* ── Drop zone ──────────────────────────────────────────────────────────── */++.rd-drop-wrap {+ max-width: 640px;+ margin: 0 auto;+}++.rd-drop {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--space-2xs);+ padding: var(--space-xl) var(--space-lg);+ border: 1.5px dashed var(--stroke-strong);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ cursor: pointer;+ transition: border-color 0.18s ease, background 0.18s ease, transform 0.18s ease, box-shadow 0.18s ease;+}++.rd-drop:hover {+ border-color: var(--ink-faint);+ background: var(--surface-2);+}++.rd-drop:focus-within {+ outline: 2px solid var(--accent);+ outline-offset: 3px;+}++.rd-drop[data-state='dragging'] {+ border-style: solid;+ border-color: var(--success);+ background: rgba(74, 222, 128, 0.07);+ transform: scale(1.012);+ box-shadow: 0 0 0 6px rgba(74, 222, 128, 0.09);+}++.rd-drop[data-state='reading'] {+ border-style: solid;+ border-color: var(--stroke-strong);+ cursor: progress;+}++.rd-drop[data-state='loaded'] {+ border-style: solid;+ border-color: var(--stroke-strong);+ background: var(--surface-2);+}++.rd-file-input {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ opacity: 0;+ cursor: pointer;+}++.rd-drop-icon {+ color: var(--ink-faint);+ transition: color 0.18s ease, transform 0.18s ease;+}++.rd-drop:hover .rd-drop-icon,+.rd-drop[data-state='dragging'] .rd-drop-icon {+ color: var(--ink-bright);+ transform: translateY(-2px);+}++.rd-drop[data-state='reading'] .rd-drop-icon {+ animation: rd-pulse 1.1s ease-in-out infinite;+}++@keyframes rd-pulse {+ 0%, 100% { opacity: 0.35; }+ 50% { opacity: 1; }+}++.rd-drop-title {+ font-family: var(--font-display);+ font-size: var(--text-lg);+ font-weight: var(--weight-semibold);+ color: var(--ink-bright);+ overflow-wrap: anywhere;+}++.rd-drop-hint {+ font-size: var(--text-md);+ color: var(--ink-dim);+}++/* ── Sample rigs ────────────────────────────────────────────────────────── */++.rd-samples {+ margin-top: var(--space-md);+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: center;+ gap: var(--space-sm);+}++.rd-samples-label {+ font-size: var(--text-md);+ color: var(--ink-faint);+}++.rd-samples-row {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: var(--space-xs);+}++.rd-sample {+ padding: var(--space-2xs) var(--space-sm);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-pill);+ background: var(--surface-1);+ color: var(--ink);+ font-family: var(--font-body);+ font-size: var(--text-md);+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease, color 0.15s ease;+}++.rd-sample:hover {+ border-color: var(--stroke-strong);+ background: var(--surface-3);+ color: var(--ink-bright);+}++.rd-sample:active {+ transform: translateY(1px);+}++.rd-sample:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++/* ── Hero facts ─────────────────────────────────────────────────────────── */++.rd-hero-facts {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: center;+ gap: var(--space-sm) var(--space-lg);+ margin: var(--space-lg) 0 0;+ padding: 0;+ list-style: none;+ font-size: var(--text-md);+ color: var(--ink-faint);+}++.rd-hero-facts strong {+ color: var(--ink-bright);+ font-family: var(--font-mono);+ font-weight: var(--weight-semibold);+}++/* ── Results shell ──────────────────────────────────────────────────────── */++.rd-results {+ max-width: var(--rd-max);+ margin: 0 auto;+ padding: 0 var(--space-lg) var(--space-2xl);+ animation: rd-rise 0.36s cubic-bezier(0.22, 1, 0.36, 1) both;+}++@keyframes rd-rise {+ from { opacity: 0; transform: translateY(14px); }+ to { opacity: 1; transform: none; }+}++/* ── Verdict banner ─────────────────────────────────────────────────────── */++.rd-verdict {+ display: grid;+ grid-template-columns: auto 1fr auto;+ align-items: start;+ gap: var(--space-md);+ padding: var(--space-lg);+ border: 1px solid var(--rd-accent, var(--stroke));+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ margin-bottom: var(--space-lg);+}++.rd-verdict[data-level='pass'] { --rd-accent: rgba(74, 222, 128, 0.42); --rd-tint: var(--success); }+.rd-verdict[data-level='warn'] { --rd-accent: rgba(251, 191, 36, 0.42); --rd-tint: var(--warn); }+.rd-verdict[data-level='fail'] { --rd-accent: rgba(248, 113, 113, 0.42); --rd-tint: var(--danger); }++.rd-verdict-mark {+ display: grid;+ place-items: center;+ width: 40px;+ height: 40px;+ border-radius: 50%;+ background: color-mix(in srgb, var(--rd-tint) 16%, transparent);+ color: var(--rd-tint);+}++.rd-verdict-mark svg {+ width: 22px;+ height: 22px;+}++.rd-verdict-body {+ min-width: 0;+}++.rd-verdict-file {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-xs);+ margin: 0 0 var(--space-2xs);+ font-family: var(--font-mono);+ font-size: var(--text-md);+ color: var(--ink-faint);+ overflow-wrap: anywhere;+}++.rd-verdict-word {+ padding: 1px var(--space-xs);+ border: 1px solid var(--rd-accent);+ border-radius: var(--radius-pill);+ color: var(--rd-tint);+ font-size: var(--text-2xs);+ letter-spacing: 0.05em;+ text-transform: uppercase;+}++.rd-verdict-size {+ color: var(--ink-dim);+}++.rd-verdict-headline {+ margin: 0 0 var(--space-2xs);+ font-family: var(--font-display);+ font-size: var(--text-lg);+ font-weight: var(--weight-semibold);+ line-height: var(--leading-tight);+ color: var(--ink-bright);+}++.rd-verdict-detail {+ margin: 0;+ font-size: var(--text-ui);+ line-height: var(--leading-normal);+ color: var(--ink-dim);+}++.rd-verdict-notes {+ margin: var(--space-sm) 0 0;+ padding: 0;+ list-style: none;+ display: grid;+ gap: var(--space-2xs);+}++.rd-verdict-notes li {+ position: relative;+ padding-left: var(--space-md);+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--ink-dim);+}++.rd-verdict-notes li::before {+ content: '';+ position: absolute;+ left: 0;+ top: 0.55em;+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: var(--ink-faint);+}++.rd-verdict-notes .rd-note-fix {+ color: var(--ink);+}++.rd-verdict-notes .rd-note-fix::before {+ background: var(--rd-tint);+}++.rd-verdict-actions {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: var(--space-2xs);+}++.rd-action-primary {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+ padding: var(--space-sm) var(--space-md);+ border: 1px solid var(--rd-accent);+ border-radius: var(--radius-md);+ background: color-mix(in srgb, var(--rd-tint) 12%, transparent);+ color: var(--ink-bright);+ font-family: var(--font-body);+ font-size: var(--text-ui);+ font-weight: var(--weight-medium);+ white-space: nowrap;+ cursor: pointer;+ transition: background 0.15s ease, transform 0.12s ease;+}++.rd-action-primary:hover {+ background: color-mix(in srgb, var(--rd-tint) 20%, transparent);+}++.rd-action-primary:active {+ transform: translateY(1px);+}++.rd-action-primary:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.rd-action-primary.is-done {+ background: color-mix(in srgb, var(--success) 22%, transparent);+}++.rd-action-note {+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ color: var(--ink-faint);+}++/* ── Two-column body ────────────────────────────────────────────────────── */++.rd-columns {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);+ gap: var(--space-lg);+ align-items: start;+}++.rd-col {+ display: grid;+ gap: var(--space-lg);+ min-width: 0;+}++.rd-col-stage {+ position: sticky;+ top: calc(var(--header-h) + var(--space-md));+}++.rd-panel {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ padding: var(--space-md);+}++.rd-panel-head {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-xs);+ margin-bottom: var(--space-md);+}++.rd-panel-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-ui);+ font-weight: var(--weight-semibold);+ letter-spacing: -0.01em;+ color: var(--ink-bright);+}++.rd-panel-note {+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ color: var(--ink-faint);+ text-align: right;+}++.rd-panel-foot {+ margin: var(--space-sm) 0 0;+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--ink-faint);+}++.rd-panel-foot a {+ color: var(--ink);+ text-decoration: underline;+ text-underline-offset: 2px;+}++.rd-panel-foot a:hover {+ color: var(--ink-bright);+}++/* ── Live stage ─────────────────────────────────────────────────────────── */++.rd-panel-stage {+ padding-bottom: var(--space-md);+}++.rd-stage {+ position: relative;+ aspect-ratio: 3 / 4;+ width: 100%;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ background:+ radial-gradient(ellipse 70% 50% at 50% 100%, var(--surface-3), transparent 70%),+ var(--bg-0);+ overflow: hidden;+}++.rd-stage canvas {+ display: block;+ width: 100%;+ height: 100%;+}++.rd-stage-status {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--space-sm);+ padding: var(--space-lg);+ text-align: center;+ font-size: var(--text-md);+ color: var(--ink-dim);+ transition: opacity 0.3s ease;+}++.rd-stage[data-state='ready'] .rd-stage-status {+ opacity: 0;+ pointer-events: none;+}++.rd-spinner {+ width: 22px;+ height: 22px;+ border: 2px solid var(--stroke-strong);+ border-top-color: var(--ink-bright);+ border-radius: 50%;+ animation: rd-spin 0.8s linear infinite;+}++.rd-stage-status.is-static .rd-spinner {+ display: none;+}++@keyframes rd-spin {+ to { transform: rotate(360deg); }+}++.rd-clips {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-xs);+ margin-top: var(--space-sm);+}++.rd-clips:empty {+ margin-top: 0;+}++.rd-clip {+ padding: var(--space-2xs) var(--space-sm);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-pill);+ background: var(--surface-1);+ color: var(--ink-dim);+ font-family: var(--font-body);+ font-size: var(--text-md);+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease, color 0.15s ease;+}++.rd-clip:hover {+ border-color: var(--stroke-strong);+ color: var(--ink-bright);+}++.rd-clip:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.rd-clip.is-active {+ border-color: var(--stroke-strong);+ background: var(--surface-3);+ color: var(--ink-bright);+}++/* A clip whose limb group never mapped still plays, so it gets a warning tint+ * rather than a disabled state: watching the legs stay still is the proof. */+.rd-clip[data-frozen='true'] {+ border-color: rgba(251, 191, 36, 0.34);+ color: var(--warn);+}++.rd-stage-foot {+ margin: var(--space-sm) 0 0;+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--ink-faint);+}++/* ── Coverage groups ────────────────────────────────────────────────────── */++.rd-groups {+ display: grid;+ gap: var(--space-md);+}++.rd-group {+ display: grid;+ gap: var(--space-2xs);+ cursor: default;+}++.rd-group-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-xs);+}++.rd-group-label {+ font-size: var(--text-ui);+ font-weight: var(--weight-medium);+ color: var(--ink);+}++.rd-group-count {+ font-family: var(--font-mono);+ font-size: var(--text-md);+ color: var(--ink-faint);+}++.rd-group-bar {+ height: 6px;+ border-radius: var(--radius-pill);+ background: var(--surface-3);+ overflow: hidden;+}++.rd-group-fill {+ display: block;+ height: 100%;+ border-radius: inherit;+ background: var(--success);+ transform-origin: left;+ animation: rd-fill 0.5s cubic-bezier(0.22, 1, 0.36, 1) both;+}++@keyframes rd-fill {+ from { transform: scaleX(0); }+ to { transform: scaleX(1); }+}++.rd-group[data-driven='false'] .rd-group-fill {+ background: var(--warn);+}++.rd-group-state {+ margin: 0;+ font-size: var(--text-md);+ color: var(--ink-faint);+}++.rd-group[data-driven='false'] .rd-group-state {+ color: var(--warn);+}++/* ── Inventory ──────────────────────────────────────────────────────────── */++.rd-stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: var(--space-sm);+ margin: 0;+}++.rd-stat {+ padding: var(--space-sm);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-md);+ background: var(--surface-1);+ cursor: default;+ transition: border-color 0.15s ease;+}++.rd-stat:hover {+ border-color: var(--stroke-strong);+}++.rd-stat dt {+ font-size: var(--text-2xs);+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--ink-faint);+}++.rd-stat dd {+ margin: var(--space-3xs) 0 0;+ font-family: var(--font-mono);+ font-size: var(--text-ui);+ color: var(--ink-bright);+ overflow-wrap: anywhere;+}++/* ── Renames ────────────────────────────────────────────────────────────── */++.rd-renames {+ display: grid;+ gap: var(--space-2xs);+}++.rd-rename {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);+ align-items: center;+ gap: var(--space-xs);+ font-family: var(--font-mono);+ font-size: var(--text-md);+}++.rd-rename-from {+ color: var(--ink-faint);+ overflow-wrap: anywhere;+}++.rd-rename-arrow {+ color: var(--ink-faint);+}++.rd-rename-to {+ color: var(--success);+ overflow-wrap: anywhere;+}++/* ── Chips ──────────────────────────────────────────────────────────────── */++.rd-chips {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2xs);+}++.rd-chip {+ padding: 2px var(--space-xs);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm);+ background: var(--surface-2);+ color: var(--ink-dim);+ font-family: var(--font-mono);+ font-size: var(--text-md);+}++.rd-chip-more {+ color: var(--ink-faint);+ border-style: dashed;+}++/* ── Tabs and generated output ──────────────────────────────────────────── */++.rd-tabs {+ display: flex;+ gap: var(--space-3xs);+ padding: var(--space-3xs);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ background: var(--surface-1);+ margin-bottom: var(--space-sm);+}++.rd-tab {+ flex: 1;+ padding: var(--space-xs) var(--space-sm);+ border: 0;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--ink-dim);+ font-family: var(--font-body);+ font-size: var(--text-md);+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease;+}++.rd-tab:hover {+ color: var(--ink-bright);+}++.rd-tab:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: -2px;+}++.rd-tab[aria-selected='true'] {+ background: var(--surface-3);+ color: var(--ink-bright);+}++.rd-code {+ margin: 0;+ padding: var(--space-sm);+ max-height: 320px;+ overflow: auto;+ border: 1px solid var(--hairline);+ border-radius: var(--radius-md);+ background: var(--bg-0);+ font-family: var(--font-mono);+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--ink);+ white-space: pre;+ tab-size: 2;+}++.rd-copy {+ margin-top: var(--space-xs);+ padding: var(--space-2xs) var(--space-sm);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm);+ background: var(--surface-1);+ color: var(--ink-dim);+ font-family: var(--font-body);+ font-size: var(--text-md);+ cursor: pointer;+ transition: border-color 0.15s ease, color 0.15s ease;+}++.rd-copy:hover {+ border-color: var(--stroke-strong);+ color: var(--ink-bright);+}++.rd-copy:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.rd-copy.is-done {+ border-color: rgba(74, 222, 128, 0.4);+ color: var(--success);+}++/* ── Tooltip ────────────────────────────────────────────────────────────── */++.rd-tip {+ position: fixed;+ z-index: 9999;+ max-width: 280px;+ padding: var(--space-xs) var(--space-sm);+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-md);+ background: var(--bg-1);+ color: var(--ink);+ font-family: var(--font-body);+ font-size: var(--text-md);+ line-height: var(--leading-tight);+ box-shadow: var(--shadow-2);+ pointer-events: none;+ animation: rd-tip-in 0.13s ease both;+}++@keyframes rd-tip-in {+ from { opacity: 0; transform: translateY(3px); }+ to { opacity: 1; transform: none; }+}++/* ── Explainer ──────────────────────────────────────────────────────────── */++.rd-explain {+ border-top: 1px solid var(--hairline);+ padding: var(--space-2xl) var(--space-lg);+ background: var(--surface-1);+}++.rd-explain-inner {+ max-width: var(--rd-max);+ margin: 0 auto;+}++.rd-explain-title {+ margin: 0 0 var(--space-lg);+ font-family: var(--font-display);+ font-size: var(--text-xl);+ font-weight: var(--weight-bold);+ letter-spacing: -0.02em;+ color: var(--ink-bright);+}++.rd-explain-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: var(--space-md);+}++.rd-explain-card {+ position: relative;+ padding: var(--space-md);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--bg-0);+}++.rd-explain-num {+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ color: var(--ink-faint);+}++.rd-explain-card h3 {+ margin: var(--space-2xs) 0 var(--space-xs);+ font-family: var(--font-display);+ font-size: var(--text-ui);+ font-weight: var(--weight-semibold);+ color: var(--ink-bright);+}++.rd-explain-card p {+ margin: 0;+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--ink-dim);+}++/* ── Next cards ─────────────────────────────────────────────────────────── */++.rd-explain-next {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: var(--space-md);+ margin-top: var(--space-lg);+}++.rd-next-card {+ display: flex;+ flex-direction: column;+ gap: var(--space-2xs);+ padding: var(--space-md);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--bg-0);+ text-decoration: none;+ transition: border-color 0.15s ease, transform 0.15s ease;+}++.rd-next-card:hover {+ border-color: var(--stroke-strong);+ transform: translateY(-2px);+}++.rd-next-card:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.rd-next-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-ui);+ font-weight: var(--weight-semibold);+ color: var(--ink-bright);+}++.rd-next-desc {+ margin: 0;+ flex: 1;+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--ink-dim);+}++.rd-next-go {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2xs);+ margin-top: var(--space-xs);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--ink-faint);+ transition: color 0.15s ease, gap 0.15s ease;+}++.rd-next-card:hover .rd-next-go {+ color: var(--ink-bright);+ gap: var(--space-xs);+}++/* ── Responsive ─────────────────────────────────────────────────────────── */++@media (max-width: 940px) {+ .rd-columns {+ grid-template-columns: minmax(0, 1fr);+ }++ .rd-col-stage {+ position: static;+ }++ .rd-stage {+ aspect-ratio: 4 / 3;+ }+}++@media (max-width: 640px) {+ .rd-hero,+ .rd-explain {+ padding-left: var(--space-md);+ padding-right: var(--space-md);+ }++ .rd-results {+ padding-left: var(--space-md);+ padding-right: var(--space-md);+ }++ .rd-verdict {+ grid-template-columns: auto 1fr;+ row-gap: var(--space-sm);+ }++ .rd-verdict-actions {+ grid-column: 1 / -1;+ align-items: stretch;+ }++ .rd-action-primary {+ justify-content: center;+ }++ .rd-drop {+ padding: var(--space-lg) var(--space-md);+ }++ .rd-rename {+ grid-template-columns: minmax(0, 1fr);+ gap: 0;+ }++ .rd-rename-arrow {+ display: none;+ }++ .rd-rename-to::before {+ content: '\2192\00a0';+ color: var(--ink-faint);+ }+}++/* Honour the OS setting: kill every decorative motion, keep every state change+ * legible. The spinner becomes a static ring rather than disappearing, so a+ * loading state is still distinguishable from a finished one. */+@media (prefers-reduced-motion: reduce) {+ .rd-results,+ .rd-group-fill,+ .rd-tip {+ animation: none;+ }++ .rd-drop,+ .rd-next-card,+ .rd-action-primary {+ transition: none;+ }++ .rd-drop[data-state='dragging'] {+ transform: none;+ }++ .rd-next-card:hover {+ transform: none;+ }++ .rd-spinner {+ animation: none;+ border-top-color: var(--stroke-strong);+ }++ .rd-drop[data-state='reading'] .rd-drop-icon {+ animation: none;+ }+}diff --git a/src/avatar-pose.js b/src/avatar-pose.jsindex 36d81c0a7..3cd990f4c 100644--- a/src/avatar-pose.js+++ b/src/avatar-pose.js@@ -180,8 +180,14 @@ export class PoseStage {// It also centers on the model's true x/z, since a close camera amplifies// any off-origin authoring the full-body distance hides.const portrait = this.framing === 'portrait';- const cx = portrait ? center.x : 0;- const cz = portrait ? center.z : 0;+ // Center on the BODY, not on the bounding box. A raised arm moves the+ // box sideways, so framing from it swings the camera off the figure the+ // moment a pose plays (a signing hand pushed the avatar to the frame's+ // edge). The hips are the one landmark a pose does not move.+ const root = this.model.getObjectByName('Hips') || this.model.getObjectByName('mixamorig:Hips');+ const bodyCenter = root ? root.getWorldPosition(new Vector3()) : center;+ const cx = portrait ? bodyCenter.x : 0;+ const cz = portrait ? bodyCenter.z : 0;// Full framing must contain the whole figure: at fov 35 the visible span// is ~0.63*dist, so 1.75*height centered at 0.52*height leaves a few// percent of margin above the head and below the feet.diff --git a/src/inspect-page.js b/src/inspect-page.jsnew file mode 100644index 000000000..9aeec4b11--- /dev/null+++ b/src/inspect-page.js@@ -0,0 +1,451 @@+// The public catalog-bar inspector (/inspect).+//+// One promise holds this page together: the verdict shown here is produced by+// the SAME module that decides whether a platform-generated asset reaches the+// public catalog (api/_lib/seed-mesh-gate.js, stage 1 of the seed quality gate).+// Not a re-implementation of the rules, and not an API that might drift from+// them — the gate itself, imported and run on the visitor's own bytes.+//+// Two consequences, both deliberate:+//+// • Nothing is uploaded. The gate reads only the glTF JSON chunk, so it runs+// entirely in the browser. A creator can check an unreleased model without+// handing it to us, and the verdict is instant because there is no network+// round-trip in it at all.+// • A threshold change lands here and in the cron at the same time, because+// there is only one place to change it.+//+// three.js is imported lazily: the verdict is the product, and it must not wait+// on a renderer bundle. The gate runs and paints before the viewer boots.++import { gateMesh, explainMeshGate, SEED_GATE_VERSION } from '../api/_lib/seed-mesh-gate.js';++// Real models this site already serves, chosen because they demonstrate+// genuinely different verdicts rather than showcasing only passes. `mannequin`+// failing two rules and `default` (the platform's own fallback avatar) failing+// the mesh-count rule are honest results, and they teach the bar far faster+// than four passing models would.+const PRESETS = [+ { id: 'michelle', label: 'Michelle', url: '/avatars/michelle.glb', note: 'A clean pass' },+ { id: 'fox', label: 'Fox', url: '/avatars/fox.glb', note: 'Passes, barely' },+ { id: 'xbot', label: 'X Bot', url: '/avatars/xbot.glb', note: 'Untextured' },+ { id: 'mannequin', label: 'Mannequin', url: '/avatars/mannequin.glb', note: 'Fails two rules' },+];++const MAX_BYTES = 256 * 1024 * 1024;++const state = {+ category: 'avatar',+ bytes: null,+ name: '',+ sourceUrl: '',+ viewer: null,+ loadToken: 0,+};++const $ = (id) => document.getElementById(id);++// ── Viewer ───────────────────────────────────────────────────────────────────+//+// Deliberately small: one object, framed, lit, orbitable. It exists to let a+// person see WHAT the gate just judged, so anything that competes with the+// verdict for attention (grids, gizmos, animation) is left out.++class Viewer {+ constructor(canvas) {+ this.canvas = canvas;+ this.ready = false;+ this.disposed = false;+ this.current = null;+ this.raf = 0;+ }++ async boot() {+ if (this.ready) return;+ const [THREE, { OrbitControls }, { GLTFLoader }, { RoomEnvironment }] = await Promise.all([+ import('three'),+ import('three/addons/controls/OrbitControls.js'),+ import('three/addons/loaders/GLTFLoader.js'),+ import('three/addons/environments/RoomEnvironment.js'),+ ]);+ this.THREE = THREE;++ const renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ this.renderer = renderer;++ this.scene = new THREE.Scene();+ const pmrem = new THREE.PMREMGenerator(renderer);+ this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++ this.camera = new THREE.PerspectiveCamera(38, 1, 0.01, 1000);+ this.controls = new OrbitControls(this.camera, renderer.domElement);+ this.controls.enableDamping = true;+ this.controls.dampingFactor = 0.06;+ this.controls.enablePan = false;+ this.controls.minDistance = 0.4;+ this.controls.maxDistance = 40;++ const key = new THREE.DirectionalLight(0xffffff, 1.7);+ key.position.set(2.5, 4, 3);+ this.scene.add(key, new THREE.AmbientLight(0xffffff, 0.35));++ // Meshopt is used across this site's own library, so a viewer that cannot+ // decode it would fail on the presets it ships with.+ this.loader = new GLTFLoader();+ try {+ const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');+ this.loader.setMeshoptDecoder(MeshoptDecoder);+ } catch {+ // A model that needs meshopt will surface a load error of its own; the+ // gate verdict does not depend on decoding geometry, so this is not fatal.+ }++ this.resize();+ this.observer = new ResizeObserver(() => this.resize());+ this.observer.observe(this.canvas.parentElement);+ this.ready = true;+ this.tick();+ }++ resize() {+ if (!this.renderer) return;+ const host = this.canvas.parentElement;+ const w = Math.max(1, host.clientWidth);+ const h = Math.max(1, host.clientHeight);+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ }++ tick = () => {+ if (this.disposed) return;+ this.raf = requestAnimationFrame(this.tick);+ this.controls?.update();+ this.renderer?.render(this.scene, this.camera);+ };++ clear() {+ if (!this.current) return;+ this.scene.remove(this.current);+ this.current.traverse((n) => {+ if (n.isMesh) {+ n.geometry?.dispose?.();+ for (const m of [].concat(n.material || [])) {+ for (const k of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap']) m?.[k]?.dispose?.();+ m?.dispose?.();+ }+ }+ });+ this.current = null;+ }++ async show(bytes) {+ await this.boot();+ const THREE = this.THREE;+ // parse() wants a real ArrayBuffer of exactly this view's bytes.+ const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);+ const gltf = await new Promise((res, rej) => this.loader.parse(ab, '', res, rej));+ this.clear();+ const root = gltf.scene || gltf.scenes?.[0];+ if (!root) throw new Error('The file parsed but contains no scene to render.');+ this.scene.add(root);+ this.current = root;+ this.frame(root, THREE);+ }++ // Frame the object regardless of its authored scale or origin. Catalog+ // submissions arrive in metres, centimetres and arbitrary units, so a fixed+ // camera would put half of them off-screen.+ frame(root, THREE) {+ const box = new THREE.Box3().setFromObject(root);+ if (!box.isEmpty()) {+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ const radius = Math.max(size.length() / 2, 1e-4);+ const dist = (radius / Math.sin((this.camera.fov * Math.PI) / 360)) * 1.15;+ this.controls.target.copy(center);+ this.camera.position.set(center.x + dist * 0.42, center.y + size.y * 0.08, center.z + dist * 0.92);+ this.camera.near = Math.max(dist / 900, 0.001);+ this.camera.far = dist * 60;+ this.camera.updateProjectionMatrix();+ this.controls.minDistance = radius * 0.35;+ this.controls.maxDistance = dist * 7;+ this.controls.update();+ }+ }+}++// ── Verdict rendering ────────────────────────────────────────────────────────++const STATUS_META = {+ pass: { icon: '✓', label: 'Pass' },+ fail: { icon: '✕', label: 'Fail' },+ skipped: { icon: '–', label: 'Not applied' },+};++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++function renderVerdict(report, verdict) {+ const badge = $('ins-badge');+ badge.className = `ins-badge ${report.pass ? 'is-pass' : 'is-fail'}`;+ badge.textContent = report.pass ? 'Clears the bar' : 'Below the bar';++ $('ins-headline').textContent = report.headline;+ $('ins-summary').textContent = report.summary;++ // Rig state is not a gate rule (an unrigged prop is perfectly valid), but it+ // is the single most common surprise for someone who expected to animate the+ // model, so it is reported as information rather than as a pass/fail.+ const rig = $('ins-rig');+ rig.textContent = verdict.rigged+ ? `Rigged · ${verdict.jointCount} joints · ready to animate`+ : 'No skeleton · cannot be animated until it is rigged';+ rig.className = `ins-rig ${verdict.rigged ? 'is-rigged' : 'is-unrigged'}`;++ // Failures first: a person reading a rejection wants the reason, not a list+ // of the checks that were fine.+ const order = { fail: 0, pass: 1, skipped: 2 };+ const checks = [...report.checks].sort((a, b) => order[a.status] - order[b.status]);++ $('ins-checks').innerHTML = checks+ .map((c) => {+ const meta = STATUS_META[c.status] || STATUS_META.skipped;+ const detail =+ c.status === 'fail'+ ? `<p class="ins-check-why">${escapeHtml(c.why)}</p><p class="ins-check-fix"><span>How to fix</span>${escapeHtml(c.fix)}</p>`+ : `<p class="ins-check-why">${escapeHtml(c.why)}</p>`;+ return `<details class="ins-check is-${c.status}"${c.status === 'fail' ? ' open' : ''}>+ <summary>+ <span class="ins-check-icon" aria-hidden="true">${meta.icon}</span>+ <span class="ins-check-label">${escapeHtml(c.label)}</span>+ <span class="ins-check-actual">${escapeHtml(c.actual)}</span>+ <span class="ins-check-bound">${escapeHtml(c.bound)}</span>+ <span class="ins-sr">${meta.label}</span>+ </summary>+ <div class="ins-check-body">${detail}</div>+ </details>`;+ })+ .join('');++ $('ins-result').hidden = false;+ $('ins-placeholder').hidden = true;+ $('ins-error').hidden = true;+}++function showError(message) {+ $('ins-error').textContent = message;+ $('ins-error').hidden = false;+ $('ins-result').hidden = true;+ $('ins-placeholder').hidden = true;+ setBusy(false);+}++function setBusy(on, label = 'Inspecting…') {+ $('ins-busy').hidden = !on;+ $('ins-busy-label').textContent = label;+ $('ins-stage').classList.toggle('is-busy', on);+}++// ── The run ──────────────────────────────────────────────────────────────────++function runGate() {+ if (!state.bytes) return;+ const verdict = gateMesh(state.bytes, { category: state.category });+ const report = explainMeshGate(verdict, { category: state.category });+ state.lastReport = { ...report, rigged: verdict.rigged, jointCount: verdict.jointCount, source: state.name };+ renderVerdict(report, verdict);+ return verdict;+}++async function inspect(bytes, name, sourceUrl = '') {+ const token = ++state.loadToken;+ state.bytes = bytes;+ state.name = name;+ state.sourceUrl = sourceUrl;+ $('ins-filename').textContent = name;+ $('ins-filename').hidden = false;++ // The verdict paints first and the renderer follows. The gate is synchronous+ // and costs a few milliseconds; making a person wait for a WebGL bundle to+ // learn whether their model passed would be backwards.+ const verdict = runGate();+ setBusy(false);+ updateShareLink();++ if (!verdict?.quality?.valid) {+ state.viewer?.clear();+ return;+ }+ try {+ state.viewer ||= new Viewer($('ins-canvas'));+ await state.viewer.show(bytes);+ if (token !== state.loadToken) return;+ $('ins-stage').classList.add('has-model');+ $('ins-hint').hidden = false;+ } catch (err) {+ if (token !== state.loadToken) return;+ // The gate verdict is still valid and already on screen; only the preview+ // failed, so this is a note beside the viewer rather than a page error.+ $('ins-stage').classList.remove('has-model');+ $('ins-viewer-note').textContent = `Preview unavailable: ${err?.message || 'the renderer could not open this file'}. The verdict above is unaffected.`;+ $('ins-viewer-note').hidden = false;+ }+}++async function inspectFile(file) {+ if (file.size > MAX_BYTES) {+ showError(`That file is ${(file.size / 1024 / 1024).toFixed(0)} MB. The inspector reads up to 256 MB.`);+ return;+ }+ setBusy(true, 'Reading file…');+ try {+ const buf = await file.arrayBuffer();+ await inspect(new Uint8Array(buf), file.name);+ } catch (err) {+ showError(`Could not read that file: ${err?.message || 'unknown error'}`);+ }+}++async function inspectUrl(rawUrl) {+ let url;+ try {+ url = new URL(rawUrl, window.location.origin);+ } catch {+ showError('That does not look like a URL. Paste a direct link to a .glb file.');+ return;+ }+ if (!/^https?:$/.test(url.protocol)) {+ showError('Only http(s) URLs can be fetched. Drop the file instead.');+ return;+ }+ setBusy(true, 'Fetching model…');+ try {+ const res = await fetch(url.href);+ if (!res.ok) throw new Error(`the server returned ${res.status}`);+ const buf = await res.arrayBuffer();+ await inspect(new Uint8Array(buf), url.pathname.split('/').pop() || url.href, url.href);+ } catch (err) {+ // A cross-origin host without CORS headers is the overwhelmingly common+ // case here, and "failed to fetch" alone sends people hunting the wrong bug.+ showError(+ `Could not fetch that model: ${err?.message || 'the request failed'}. If the file is on another domain it must send CORS headers, otherwise download it and drop it in.`,+ );+ }+}++function updateShareLink() {+ const btn = $('ins-share');+ btn.hidden = !state.sourceUrl;+ btn.dataset.url = state.sourceUrl+ ? `${window.location.origin}/inspect?url=${encodeURIComponent(state.sourceUrl)}&category=${state.category}`+ : '';+}++async function copy(text, btn, done = 'Copied') {+ const original = btn.textContent;+ try {+ await navigator.clipboard.writeText(text);+ btn.textContent = done;+ } catch {+ btn.textContent = 'Copy failed';+ }+ setTimeout(() => {+ btn.textContent = original;+ }, 1600);+}++// ── Wiring ───────────────────────────────────────────────────────────────────++function wire() {+ const drop = $('ins-drop');+ const fileInput = $('ins-file');++ $('ins-browse').addEventListener('click', () => fileInput.click());+ fileInput.addEventListener('change', () => {+ if (fileInput.files?.[0]) inspectFile(fileInput.files[0]);+ });++ // dragover must be cancelled or the browser navigates to the file instead.+ let depth = 0;+ drop.addEventListener('dragenter', (e) => {+ e.preventDefault();+ depth++;+ drop.classList.add('is-over');+ });+ drop.addEventListener('dragover', (e) => e.preventDefault());+ drop.addEventListener('dragleave', () => {+ if (--depth <= 0) drop.classList.remove('is-over');+ });+ drop.addEventListener('drop', (e) => {+ e.preventDefault();+ depth = 0;+ drop.classList.remove('is-over');+ const file = e.dataTransfer?.files?.[0];+ if (file) inspectFile(file);+ });++ const urlForm = $('ins-url-form');+ urlForm.addEventListener('submit', (e) => {+ e.preventDefault();+ const v = $('ins-url').value.trim();+ if (v) inspectUrl(v);+ });++ for (const btn of document.querySelectorAll('[data-category]')) {+ btn.addEventListener('click', () => {+ state.category = btn.dataset.category;+ for (const b of document.querySelectorAll('[data-category]')) {+ b.setAttribute('aria-pressed', String(b === btn));+ }+ // Re-judging locally is free, so switching category is instant and+ // shows the mesh-count rule turning itself off for props.+ runGate();+ updateShareLink();+ });+ }++ $('ins-presets').innerHTML = PRESETS.map(+ (p) =>+ `<button type="button" class="ins-preset" data-url="${p.url}" data-name="${p.label}">+ <span class="ins-preset-name">${p.label}</span>+ <span class="ins-preset-note">${p.note}</span>+ </button>`,+ ).join('');+ $('ins-presets').addEventListener('click', (e) => {+ const btn = e.target.closest('.ins-preset');+ if (btn) inspectUrl(btn.dataset.url);+ });++ $('ins-copy-json').addEventListener('click', (e) => {+ copy(JSON.stringify(state.lastReport, null, 2), e.currentTarget);+ });+ $('ins-share').addEventListener('click', (e) => {+ copy(e.currentTarget.dataset.url, e.currentTarget, 'Link copied');+ });++ $('ins-gate-version').textContent = `gate v${SEED_GATE_VERSION}`;+}++function bootFromQuery() {+ const q = new URLSearchParams(window.location.search);+ const cat = q.get('category');+ if (cat === 'accessory' || cat === 'avatar') {+ state.category = cat;+ for (const b of document.querySelectorAll('[data-category]')) {+ b.setAttribute('aria-pressed', String(b.dataset.category === cat));+ }+ }+ const url = q.get('url');+ if (url) {+ $('ins-url').value = url;+ inspectUrl(url);+ }+}++wire();+bootFromQuery();diff --git a/src/rig-doctor-page.js b/src/rig-doctor-page.jsnew file mode 100644index 000000000..caa5c6c7c--- /dev/null+++ b/src/rig-doctor-page.js@@ -0,0 +1,655 @@+// Rig Doctor page controller.+//+// Three jobs, in the order the user experiences them:+// 1. Get bytes. Drag-drop, file picker, keyboard shortcut, or a sample rig.+// 2. Diagnose. src/rig-report.js does the analysis; this file renders it.+// 3. Prove and repair. Mount the real PoseStage on a blob URL of the file so+// the user watches their own rig perform, and offer the canonicalized GLB+// as a download when the bone names needed rewriting.+//+// The privacy claim in the copy is load-bearing, so it constrains the code: the+// only network requests this page makes are for the animation clip library and+// the sample rigs, both of which are three.ws assets. The user's file is read+// with FileReader and never posted anywhere. PoseStage consumes a blob: URL+// created from the in-memory buffer, which never leaves the tab.+//+// The stage is imported lazily. Three.js plus the GLTF/DRACO/meshopt loaders are+// the heaviest thing on the page, and a visitor who reads the explainer and+// leaves should not pay for them.++import { analyzeGlb, manifestFromReport, formatBytes, CANONICAL_TOTAL } from './rig-report.js';+import { canonicalizeGLBBones } from './glb-canonicalize.js';++// Clips offered under the preview, chosen so each one exercises a different+// limb group: idle reads the torso, wave the arms, walk the legs. A rig whose+// legs failed to map shows that failure most obviously under `walk`.+const CLIPS = [+ { name: 'idle', label: 'Idle', group: 'torso' },+ { name: 'walk', label: 'Walk', group: 'legs' },+ { name: 'wave', label: 'Wave', group: 'arms' },+ { name: 'dance', label: 'Dance', group: 'legs' },+];++const VERDICT_MARK = {+ pass: '<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="m5 13 4.5 4.5L19 7" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg>',+ warn: '<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 8v5" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/><circle cx="12" cy="17" r="1.35" fill="currentColor"/></svg>',+ fail: '<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M7 7l10 10M17 7 7 17" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></svg>',+};++const VERDICT_WORD = { pass: 'Ready', warn: 'Partial', fail: 'Will not animate' };++const $ = (id) => document.getElementById(id);++/** Live page state. One file at a time; loading a second one tears the first down. */+const state = {+ report: null,+ buffer: null,+ repaired: null,+ blobUrl: null,+ stage: null,+ busy: false,+};++// ── Entry ────────────────────────────────────────────────────────────────────++function init() {+ wireDropZone();+ wireSamples();+ wireTabs();+ wireCopyButtons();+ wireTooltips();+ wireShortcut();+ // A ?sample= parameter makes every verdict state shareable and linkable,+ // which is what lets the docs point at a live failing rig instead of+ // describing one.+ const preset = new URLSearchParams(location.search).get('sample');+ if (preset) {+ const btn = document.querySelector(`.rd-sample[data-sample="${CSS.escape(preset)}"]`);+ if (btn) loadSample(btn.dataset.sample, btn.dataset.sampleName);+ }+}++// ── Input ────────────────────────────────────────────────────────────────────++function wireDropZone() {+ const drop = $('rd-drop');+ const input = $('rd-file');+ if (!drop || !input) return;++ input.addEventListener('change', () => {+ const file = input.files?.[0];+ if (file) readFile(file);+ // Reset so re-picking the same file fires `change` again.+ input.value = '';+ });++ // dragenter/dragleave fire for every child element, so count depth rather+ // than toggling on each event or the zone flickers as the cursor moves.+ let depth = 0;+ const setDragging = (on) => drop.setAttribute('data-state', on ? 'dragging' : 'idle');++ for (const type of ['dragenter', 'dragover']) {+ drop.addEventListener(type, (e) => {+ e.preventDefault();+ if (type === 'dragenter') depth++;+ setDragging(true);+ });+ }+ drop.addEventListener('dragleave', () => {+ depth = Math.max(0, depth - 1);+ if (depth === 0) setDragging(false);+ });+ drop.addEventListener('drop', (e) => {+ e.preventDefault();+ depth = 0;+ setDragging(false);+ const file = e.dataTransfer?.files?.[0];+ if (file) readFile(file);+ });++ // The page itself must swallow drops, or a miss drops the user's avatar into+ // the browser's own GLB viewer and loses the session.+ for (const type of ['dragover', 'drop']) {+ window.addEventListener(type, (e) => {+ if (!drop.contains(e.target)) e.preventDefault();+ });+ }+}++function wireSamples() {+ for (const btn of document.querySelectorAll('.rd-sample')) {+ btn.addEventListener('click', () => loadSample(btn.dataset.sample, btn.dataset.sampleName));+ }+}++// `D` focuses and opens the picker from anywhere, so a returning user never+// hunts for the drop zone. Guarded against firing while typing in a field.+function wireShortcut() {+ window.addEventListener('keydown', (e) => {+ if (e.key !== 'd' && e.key !== 'D') return;+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ const t = e.target;+ if (t instanceof HTMLElement && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;+ e.preventDefault();+ $('rd-file')?.click();+ });+}++function readFile(file) {+ if (state.busy) return;+ if (!/\.glb$/i.test(file.name)) {+ showError(file.name, 'Only .glb files can be read here. Export as binary glTF, not .gltf, .fbx, or .vrm.');+ return;+ }+ setDropState('reading', file.name);+ const reader = new FileReader();+ reader.onerror = () => showError(file.name, 'The browser could not read that file.');+ reader.onload = () => diagnose(reader.result, file.name);+ reader.readAsArrayBuffer(file);+}++async function loadSample(url, name) {+ if (state.busy) return;+ setDropState('reading', name);+ try {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`sample unavailable (${res.status})`);+ diagnose(await res.arrayBuffer(), name);+ } catch (err) {+ showError(name, `Could not load the sample: ${err.message}`);+ }+}++function setDropState(name, label) {+ const drop = $('rd-drop');+ if (!drop) return;+ drop.setAttribute('data-state', name);+ const title = drop.querySelector('.rd-drop-title');+ if (title) {+ title.textContent = name === 'reading' ? `Reading ${label}` : name === 'loaded' ? label : 'Drop a .glb here';+ }+}++// ── Diagnosis ────────────────────────────────────────────────────────────────++function diagnose(buffer, fileName) {+ state.busy = true;+ let report;+ try {+ report = analyzeGlb(buffer, { fileName });+ } catch (err) {+ state.busy = false;+ showError(fileName, err.message);+ return;+ }++ teardownStage();+ state.report = report;+ state.buffer = buffer;+ state.repaired = null;++ setDropState('loaded', fileName);+ renderVerdict(report);+ renderGroups(report);+ renderStats(report);+ renderRenames(report);+ renderUnmapped(report);+ renderOutputs(report);++ const results = $('rd-results');+ results.hidden = false;+ results.scrollIntoView({ behavior: prefersReducedMotion() ? 'auto' : 'smooth', block: 'start' });++ state.busy = false;+ mountStage(report);+}++function showError(fileName, message) {+ const results = $('rd-results');+ teardownStage();+ state.report = null;+ setDropState('idle');+ $('rd-verdict').setAttribute('data-level', 'fail');+ $('rd-verdict-mark').innerHTML = VERDICT_MARK.fail;+ $('rd-verdict-file').textContent = fileName;+ $('rd-verdict-headline').textContent = 'That file could not be read as a GLB.';+ $('rd-verdict-detail').textContent = message;+ $('rd-verdict-notes').innerHTML = '';+ $('rd-verdict-actions').innerHTML = '';+ for (const id of ['rd-groups', 'rd-stats', 'rd-unmapped', 'rd-renames']) {+ const el = $(id);+ if (el) el.innerHTML = '';+ }+ $('rd-renames-panel').hidden = true;+ $('rd-unmapped-panel').hidden = true;+ // Hide the panels that would render empty rather than showing four blank+ // cards under a failure the user cannot act on.+ for (const panel of document.querySelectorAll('.rd-col-report .rd-panel')) panel.hidden = true;+ $('rd-stage').setAttribute('data-state', 'failed');+ setStageStatus('Nothing to preview');+ results.hidden = false;+ results.scrollIntoView({ behavior: prefersReducedMotion() ? 'auto' : 'smooth', block: 'start' });+}++function renderVerdict(report) {+ const v = report.verdict;+ for (const panel of document.querySelectorAll('.rd-col-report .rd-panel')) panel.hidden = false;+ $('rd-verdict').setAttribute('data-level', v.level);+ $('rd-verdict-mark').innerHTML = VERDICT_MARK[v.level];+ $('rd-verdict-file').innerHTML = `<span class="rd-verdict-word">${VERDICT_WORD[v.level]}</span> ${escapeHtml(report.fileName)} <span class="rd-verdict-size">${formatBytes(report.bytes)}</span>`;+ $('rd-verdict-headline').textContent = v.headline;+ $('rd-verdict-detail').textContent = v.detail;++ const notes = $('rd-verdict-notes');+ notes.innerHTML = '';+ for (const line of [...v.notes, ...v.fixes.map((f) => `Fix: ${f}`)]) {+ const li = document.createElement('li');+ li.className = /^Fix: /.test(line) ? 'rd-note-fix' : '';+ li.textContent = line.replace(/^Fix: /, '');+ notes.appendChild(li);+ }++ renderActions(report);+}++// The repair button only appears when a repair would actually change something.+// A button that downloads a byte-identical file is a lie about having helped.+function renderActions(report) {+ const host = $('rd-verdict-actions');+ host.innerHTML = '';+ if (!report.skeleton.renames.length) return;++ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'rd-action-primary';+ btn.dataset.tip = 'Rewrites joint names only. Geometry, materials, and textures are copied through untouched.';+ btn.innerHTML = `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v12m0 0 4-4m-4 4-4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg> Download the repaired GLB`;+ btn.addEventListener('click', () => downloadRepaired(btn));+ host.appendChild(btn);++ const note = document.createElement('span');+ note.className = 'rd-action-note';+ note.textContent = `${report.skeleton.renames.length} joints renamed`;+ host.appendChild(note);+ applyTooltip(btn);+}++function downloadRepaired(btn) {+ const report = state.report;+ if (!report || !state.buffer) return;+ const label = btn.innerHTML;+ try {+ if (!state.repaired) state.repaired = canonicalizeGLBBones(state.buffer);+ const blob = new Blob([state.repaired.buffer], { type: 'model/gltf-binary' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = report.fileName.replace(/\.glb$/i, '') + '.canonical.glb';+ document.body.appendChild(a);+ a.click();+ a.remove();+ // Revoke on the next task so Safari has finished starting the download.+ setTimeout(() => URL.revokeObjectURL(url), 0);+ btn.classList.add('is-done');+ btn.innerHTML = 'Downloaded';+ setTimeout(() => {+ btn.classList.remove('is-done');+ btn.innerHTML = label;+ }, 2200);+ } catch (err) {+ btn.innerHTML = `Repair failed: ${escapeHtml(err.message)}`;+ }+}++function renderGroups(report) {+ const s = report.skeleton;+ $('rd-coverage-note').textContent = `${s.mapped} of ${CANONICAL_TOTAL} canonical joints`;+ const host = $('rd-groups');+ host.innerHTML = '';+ for (const g of s.groups) {+ const row = document.createElement('div');+ row.className = 'rd-group';+ row.dataset.driven = String(g.driven);+ row.dataset.tip = g.driven+ ? `${g.blurb} All key joints mapped.`+ : `${g.blurb} Missing: ${g.missingKey.join(', ')}.`;+ row.innerHTML = `+ <div class="rd-group-head">+ <span class="rd-group-label">${escapeHtml(g.label)}</span>+ <span class="rd-group-count">${g.have}/${g.total}</span>+ </div>+ <div class="rd-group-bar"><span class="rd-group-fill" style="width:${g.pct}%"></span></div>+ <p class="rd-group-state">${g.driven ? 'Will animate' : `Frozen: missing ${escapeHtml(g.missingKey.join(', '))}`}</p>+ `;+ host.appendChild(row);+ applyTooltip(row);+ }+}++function renderStats(report) {+ $('rd-inventory-note').textContent = report.generator === 'unknown' ? 'No generator recorded' : `Exported by ${report.generator}`;+ const host = $('rd-stats');+ host.innerHTML = '';+ const rows = [+ ['Convention', report.skeleton.convention.label, report.skeleton.convention.evidence],+ ['Triangles', report.geometry.triangles.toLocaleString(), `${report.geometry.vertices.toLocaleString()} vertices across ${report.geometry.primitives} primitives`],+ ['Joints', String(report.skeleton.jointCount), `${report.skeleton.mapped} recognised, ${report.skeleton.unmapped.length} not`],+ ['Materials', String(report.counts.materials), `${report.counts.textures} textures, ${formatBytes(report.textureBytes)}`],+ ['Blendshapes', String(report.morphs.total), report.morphs.lipSync ? `${report.morphs.visemeCount} visemes, lip-sync ready` : 'No visemes, so no lip-sync'],+ ['Embedded clips', String(report.animations.length), report.animations.length ? report.animations.map((a) => a.name).slice(0, 4).join(', ') : 'None; the library supplies the motion'],+ ['Extensions', report.extensions.length ? String(report.extensions.length) : 'none', report.extensions.length ? report.extensions.join(', ') : 'Plain glTF 2.0'],+ ['File', formatBytes(report.bytes), `${formatBytes(report.jsonBytes)} JSON, ${formatBytes(report.binBytes)} binary`],+ ];+ for (const [term, value, tip] of rows) {+ const wrap = document.createElement('div');+ wrap.className = 'rd-stat';+ wrap.dataset.tip = tip;+ wrap.innerHTML = `<dt>${escapeHtml(term)}</dt><dd>${escapeHtml(value)}</dd>`;+ host.appendChild(wrap);+ applyTooltip(wrap);+ }+}++function renderRenames(report) {+ const renames = report.skeleton.renames;+ const panel = $('rd-renames-panel');+ if (!renames.length) {+ panel.hidden = true;+ return;+ }+ panel.hidden = false;+ $('rd-renames-note').textContent = `${renames.length} of ${report.skeleton.jointCount} joints`;+ const host = $('rd-renames');+ host.innerHTML = '';+ // Show a readable slice, then say plainly how many were withheld. A silent+ // truncation would read as "that is all of them".+ const shown = renames.slice(0, 10);+ for (const r of shown) {+ const row = document.createElement('div');+ row.className = 'rd-rename';+ row.innerHTML = `<code class="rd-rename-from">${escapeHtml(r.from)}</code><span class="rd-rename-arrow" aria-hidden="true">→</span><code class="rd-rename-to">${escapeHtml(r.to)}</code>`;+ host.appendChild(row);+ }+ if (renames.length > shown.length) {+ const more = document.createElement('p');+ more.className = 'rd-panel-foot';+ more.textContent = `and ${renames.length - shown.length} more, all applied in the repaired file.`;+ host.appendChild(more);+ }+}++function renderUnmapped(report) {+ const list = report.skeleton.unmapped;+ const panel = $('rd-unmapped-panel');+ if (!list.length) {+ panel.hidden = true;+ return;+ }+ panel.hidden = false;+ const host = $('rd-unmapped');+ host.innerHTML = '';+ for (const name of list.slice(0, 40)) {+ const chip = document.createElement('code');+ chip.className = 'rd-chip';+ chip.textContent = name;+ host.appendChild(chip);+ }+ if (list.length > 40) {+ const chip = document.createElement('span');+ chip.className = 'rd-chip rd-chip-more';+ chip.textContent = `+${list.length - 40} more`;+ host.appendChild(chip);+ }+}++function renderOutputs(report) {+ const slug = report.fileName.replace(/\.glb$/i, '').replace(/[^a-z0-9]+/gi, '-').toLowerCase() || 'avatar';+ const meshUri = `https://your-host.example/${slug}.glb`;+ const manifest = manifestFromReport(report, {+ id: slug,+ name: slug.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),+ meshUri,+ owner: 'YOUR_SOLANA_ADDRESS',+ createdAt: new Date().toISOString(),+ });+ $('rd-out-manifest').textContent = JSON.stringify(manifest, null, 2);++ $('rd-out-embed').textContent = [+ '<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"><\/script>',+ '',+ `<agent-3d src="${meshUri}" style="width:400px;height:600px"></agent-3d>`,+ ].join('\n');++ $('rd-out-cli').textContent = [+ 'npx @three-ws/avatar-cli init \\',+ ` --name "${manifest.name}" \\`,+ ` --mesh ./${report.fileName} \\`,+ ` --mesh-uri ${meshUri} \\`,+ ' --owner YOUR_SOLANA_ADDRESS \\',+ ` --out ${slug}.avatar.json`,+ '',+ `npx @three-ws/avatar-cli validate ${slug}.avatar.json`,+ ].join('\n');+}++// ── Live preview ─────────────────────────────────────────────────────────────++function setStageStatus(text, spinning = false) {+ const status = $('rd-stage-status');+ const label = $('rd-stage-status-text');+ if (label) label.textContent = text;+ if (status) status.classList.toggle('is-static', !spinning);+}++function teardownStage() {+ state.stage?.dispose();+ state.stage = null;+ if (state.blobUrl) {+ URL.revokeObjectURL(state.blobUrl);+ state.blobUrl = null;+ }+ $('rd-clips').innerHTML = '';+}++async function mountStage(report) {+ const host = $('rd-stage');+ host.setAttribute('data-state', 'loading');+ setStageStatus('Loading the scene', true);+ $('rd-stage-note').textContent = 'Retargeting the clip library';++ // The blob URL is created from the ORIGINAL bytes, not the repaired ones, so+ // the preview shows what the user has today. Retargeting canonicalizes bone+ // names in memory anyway, so a Mixamo rig still performs; what the preview+ // cannot hide is a limb group that never mapped at all.+ const blob = new Blob([state.buffer], { type: 'model/gltf-binary' });+ state.blobUrl = URL.createObjectURL(blob);++ let PoseStage;+ try {+ ({ PoseStage } = await import('./avatar-pose.js'));+ } catch {+ host.setAttribute('data-state', 'failed');+ setStageStatus('The 3D scene could not load in this browser.');+ $('rd-stage-note').textContent = 'Preview unavailable';+ return;+ }++ const stage = new PoseStage(host, { glbUrl: state.blobUrl, framing: 'full' });+ state.stage = stage;+ try {+ const { supported } = await stage.mount();+ // A second file dropped mid-load supersedes this one.+ if (state.stage !== stage) return;+ stage.start();+ host.setAttribute('data-state', 'ready');+ renderClipButtons(report, supported);+ $('rd-stage-note').textContent = supported ? 'Drag to orbit' : 'Static: no drivable rig';+ $('rd-stage-foot').textContent = supported+ ? 'Play a clip and watch which limbs move. This is the same retargeting path the platform uses.'+ : 'This rig cannot be driven by the clip library, so the platform substitutes the default avatar rather than showing a frozen pose.';+ } catch (err) {+ if (state.stage !== stage) return;+ host.setAttribute('data-state', 'failed');+ setStageStatus(`The scene could not render this file: ${err.message}`);+ $('rd-stage-note').textContent = 'Preview unavailable';+ }+}++function renderClipButtons(report, supported) {+ const host = $('rd-clips');+ host.innerHTML = '';+ if (!supported) return;+ const groups = new Map(report.skeleton.groups.map((g) => [g.id, g]));+ for (const clip of CLIPS) {+ const group = groups.get(clip.group);+ const frozen = group && !group.driven;+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'rd-clip';+ btn.textContent = clip.label;+ btn.dataset.frozen = String(!!frozen);+ btn.dataset.tip = frozen+ ? `Plays, but this rig's ${group.label.toLowerCase()} are unmapped so they stay still.`+ : `Drives the ${group ? group.label.toLowerCase() : 'rig'}.`;+ btn.addEventListener('click', async () => {+ for (const other of host.querySelectorAll('.rd-clip')) other.classList.remove('is-active');+ btn.classList.add('is-active');+ try {+ await state.stage?.play(clip.name);+ } catch {+ btn.classList.remove('is-active');+ btn.dataset.tip = 'This clip is not available right now.';+ }+ });+ host.appendChild(btn);+ applyTooltip(btn);+ }+ host.querySelector('.rd-clip')?.classList.add('is-active');+}++// ── Small UI plumbing ────────────────────────────────────────────────────────++function wireTabs() {+ const tabs = [...document.querySelectorAll('.rd-tab')];+ const select = (name) => {+ for (const tab of tabs) {+ const on = tab.dataset.pane === name;+ tab.setAttribute('aria-selected', String(on));+ $(`rd-pane-${tab.dataset.pane}`).hidden = !on;+ }+ };+ for (const tab of tabs) {+ tab.addEventListener('click', () => select(tab.dataset.pane));+ // Roving arrow-key navigation, which is what a tablist owes a keyboard user.+ tab.addEventListener('keydown', (e) => {+ const i = tabs.indexOf(tab);+ const next = e.key === 'ArrowRight' ? i + 1 : e.key === 'ArrowLeft' ? i - 1 : -1;+ if (next < 0 || next >= tabs.length) return;+ e.preventDefault();+ tabs[next].focus();+ select(tabs[next].dataset.pane);+ });+ }+}++function wireCopyButtons() {+ for (const btn of document.querySelectorAll('.rd-copy')) {+ btn.addEventListener('click', async () => {+ const source = $(btn.dataset.copyTarget);+ if (!source) return;+ const label = btn.textContent;+ try {+ await navigator.clipboard.writeText(source.textContent);+ btn.textContent = 'Copied';+ } catch {+ // Clipboard access is denied over plain HTTP and in some embedded+ // browsers. Select the text so the user can still take it.+ const range = document.createRange();+ range.selectNodeContents(source);+ const sel = window.getSelection();+ sel.removeAllRanges();+ sel.addRange(range);+ btn.textContent = 'Selected: press Ctrl+C';+ }+ btn.classList.add('is-done');+ setTimeout(() => {+ btn.textContent = label;+ btn.classList.remove('is-done');+ }, 1800);+ });+ }+}++// Tooltips: one shared floating element rather than a bubble per trigger, so+// adding `data-tip` to anything (including nodes rendered later) is free. It is+// mirrored into `aria-describedby` so the text reaches a screen reader too,+// which a CSS-only `::after` tooltip never does.+let tipEl = null;+let tipHost = null;++function ensureTipEl() {+ if (tipEl) return tipEl;+ tipEl = document.createElement('div');+ tipEl.className = 'rd-tip';+ tipEl.id = 'rd-tip';+ tipEl.setAttribute('role', 'tooltip');+ tipEl.hidden = true;+ document.body.appendChild(tipEl);+ return tipEl;+}++function showTip(host) {+ const text = host.dataset.tip;+ if (!text) return;+ const el = ensureTipEl();+ el.textContent = text;+ el.hidden = false;+ tipHost = host;+ host.setAttribute('aria-describedby', 'rd-tip');++ const r = host.getBoundingClientRect();+ const t = el.getBoundingClientRect();+ const margin = 10;+ // Prefer above; flip below when the trigger sits near the top of the viewport.+ const above = r.top > t.height + margin;+ let left = r.left + r.width / 2 - t.width / 2;+ left = Math.max(margin, Math.min(left, window.innerWidth - t.width - margin));+ el.style.left = `${Math.round(left)}px`;+ el.style.top = `${Math.round(above ? r.top - t.height - 8 : r.bottom + 8)}px`;+ el.dataset.placement = above ? 'top' : 'bottom';+}++function hideTip() {+ if (!tipEl) return;+ tipEl.hidden = true;+ tipHost?.removeAttribute('aria-describedby');+ tipHost = null;+}++function applyTooltip(el) {+ if (!el?.dataset.tip || el.dataset.tipWired === '1') return;+ el.dataset.tipWired = '1';+ el.addEventListener('mouseenter', () => showTip(el));+ el.addEventListener('mouseleave', hideTip);+ el.addEventListener('focus', () => showTip(el));+ el.addEventListener('blur', hideTip);+}++function wireTooltips() {+ for (const el of document.querySelectorAll('[data-tip]')) applyTooltip(el);+ window.addEventListener('scroll', hideTip, { passive: true });+ window.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') hideTip();+ });+}++function prefersReducedMotion() {+ return window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();diff --git a/src/rig-report.js b/src/rig-report.jsnew file mode 100644index 000000000..ecb29b772--- /dev/null+++ b/src/rig-report.js@@ -0,0 +1,497 @@+// Rig report — read a GLB's glTF JSON chunk and answer the one question every+// creator asks before they upload: "will this thing actually move on three.ws?"+//+// The answer has always existed, but only after an upload, a conversion, and a+// look at the result. That is a slow, discouraging loop, and the failure mode is+// silent: a rig whose bones are named `Bip001 L UpperArm` loads fine, renders+// fine, and then stands in a frozen T-pose forever because the clip library's+// tracks address `LeftArm`. This module moves that verdict to the front of the+// funnel and makes it local.+//+// Everything here is a pure function of the GLB bytes. No network, no WebGL, no+// DOM. That is what lets the browser run it on a file the user never uploads,+// and what lets the test suite run it on fixtures without a headless GPU.+//+// The verdict deliberately mirrors AnimationManager's runtime gate+// (`_modelSupportsCanonicalClips`: a SkinnedMesh plus >= MIN_CANONICAL_BONES+// name-mapped joints) rather than approximating it. If this file and that gate+// ever disagree, this file is wrong: the runtime is the product.++import { canonicalizeBoneName, CANONICAL_BONES } from './glb-canonicalize.js';++const GLB_MAGIC = 0x46546c67; // 'glTF' little-endian+const CHUNK_TYPE_JSON = 0x4e4f534a; // 'JSON'++/** Mirrors MIN_CANONICAL_BONES in src/animation-manager.js. */+export const MIN_CANONICAL_BONES = 8;++/** Total joints in the canonical set, so coverage reads as a real fraction. */+export const CANONICAL_TOTAL = CANONICAL_BONES.length;++// Limb groups, in the order a person reads a body. Each group is scored on its+// own because "62% covered" tells a creator nothing actionable, while "arms and+// torso yes, legs no" tells them their character will glide instead of walk.+// The `key` bones are the ones whose absence is visible in motion; finger joints+// are counted but never gate a group, since a walk cycle survives without them.+export const LIMB_GROUPS = Object.freeze([+ {+ id: 'torso',+ label: 'Torso',+ blurb: 'Root motion, sway, and the anchor every other track hangs off.',+ bones: ['Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head'],+ key: ['Hips'],+ },+ {+ id: 'arms',+ label: 'Arms',+ blurb: 'Waves, claps, gestures. Unmapped arms freeze at the bind pose.',+ bones: ['LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand', 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand'],+ key: ['LeftArm', 'LeftForeArm', 'RightArm', 'RightForeArm'],+ },+ {+ id: 'hands',+ label: 'Hands',+ blurb: 'Finger joints. Required for sign language and detailed emotes.',+ bones: CANONICAL_BONES.filter((b) => /Hand(Index|Middle|Pinky|Ring|Thumb)/.test(b)),+ key: ['LeftHandIndex1', 'RightHandIndex1'],+ },+ {+ id: 'legs',+ label: 'Legs',+ blurb: 'Walk and run cycles. Without these the avatar slides across the floor.',+ bones: ['LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase', 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase'],+ key: ['LeftUpLeg', 'LeftLeg', 'RightUpLeg', 'RightLeg'],+ },+]);++// Skeleton-convention fingerprints, most specific first. `test` sees the raw+// joint-name list plus the node/mesh names, because some conventions are only+// identifiable from what surrounds the skeleton (Ready Player Me ships Mixamo+// bone names and is distinguishable solely by its `Wolf3D_*` mesh nodes).+//+// `schema` maps onto the avatar-manifest `skeleton` enum+// (packages/avatar-schema/schema/avatar.v1.json), so the generated manifest+// declares the right value instead of defaulting everything to `custom`.+const CONVENTIONS = [+ {+ id: 'rpm', label: 'Ready Player Me', schema: 'rpm',+ test: (ctx) => ctx.meshNames.some((n) => /^Wolf3D_/i.test(n)) && ctx.joints.some((n) => /Hips$/i.test(n)),+ evidence: 'Wolf3D_* mesh nodes alongside a Mixamo-named skeleton',+ },+ {+ id: 'mixamo', label: 'Mixamo', schema: 'mixamo',+ test: (ctx) => ctx.joints.some((n) => /^mixamorig\d*[_:]/i.test(n)),+ evidence: 'mixamorig: joint prefix',+ },+ {+ id: 'vrm', label: 'VRM / VRoid', schema: 'vrm-humanoid',+ test: (ctx) => ctx.joints.some((n) => /^J_(Bip|Sec|Adj)_/i.test(n)),+ evidence: 'J_Bip_* humanoid joint names',+ },+ {+ id: 'reallusion', label: 'Reallusion Character Creator', schema: 'custom',+ test: (ctx) => ctx.joints.some((n) => /^CC_Base_/i.test(n)),+ evidence: 'CC_Base_* joint prefix',+ },+ {+ id: 'unreal', label: 'Unreal Engine mannequin', schema: 'custom',+ test: (ctx) => ctx.joints.some((n) => /^pelvis$/i.test(n)) && ctx.joints.some((n) => /^(thigh|calf|clavicle|upperarm)_[lr]$/i.test(n)),+ evidence: 'pelvis / thigh_l / clavicle_l mannequin naming',+ },+ {+ id: 'biped', label: '3ds Max Biped', schema: 'custom',+ test: (ctx) => ctx.joints.some((n) => /^Bip\d+[\s_]/i.test(n)),+ evidence: 'Bip01/Bip001 joint prefix',+ },+ {+ id: 'rigify', label: 'Blender Rigify', schema: 'custom',+ test: (ctx) => ctx.joints.some((n) => /^(DEF|ORG|MCH)[-_]/i.test(n)),+ evidence: 'DEF-/ORG-/MCH- Rigify bone layers',+ },+ {+ id: 'humanik', label: 'Autodesk HumanIK / MotionBuilder', schema: 'custom',+ test: (ctx) => ctx.joints.filter((n) => /^[A-Za-z]\w*:/.test(n) && !/^mixamorig/i.test(n)).length >= 4,+ evidence: 'character-namespaced joints (Character1:Hips)',+ },+ {+ id: 'daz', label: 'Daz Genesis', schema: 'custom',+ test: (ctx) => ctx.joints.some((n) => /^(lShldr|rShldr|abdomen|lThigh|rThigh)/i.test(n)),+ evidence: 'Daz lShldr / abdomen / lThigh naming',+ },+ {+ id: 'makehuman', label: 'MakeHuman / Blender side-suffix', schema: 'custom',+ test: (ctx) => ctx.joints.filter((n) => /\.[LR]$/.test(n)).length >= 4,+ evidence: 'Blender .L/.R side suffixes',+ },+ {+ id: 'avaturn', label: 'Avaturn / three.ws canonical', schema: 'avaturn',+ test: (ctx) => {+ const set = new Set(ctx.joints);+ return ['Hips', 'Spine2', 'LeftUpLeg', 'RightForeArm'].every((b) => set.has(b));+ },+ evidence: 'joint names already match the canonical set exactly',+ },+];++// Oculus/OVR viseme set — what the lip-sync pipeline drives. An avatar missing+// these can still animate; it just cannot speak with its mouth.+const OVR_VISEMES = ['viseme_sil', 'viseme_PP', 'viseme_FF', 'viseme_TH', 'viseme_DD', 'viseme_kk', 'viseme_CH', 'viseme_SS', 'viseme_nn', 'viseme_RR', 'viseme_aa', 'viseme_E', 'viseme_I', 'viseme_O', 'viseme_U'];+// A representative ARKit blendshape slice. Presence of these means the face can+// be driven expressively (brows, jaw, smile) rather than just phonetically.+const ARKIT_SAMPLE = ['jawOpen', 'mouthSmileLeft', 'mouthSmileRight', 'browInnerUp', 'eyeBlinkLeft', 'eyeBlinkRight'];++/**+ * Read the glTF JSON chunk out of a GLB ArrayBuffer.+ * Kept separate from analysis so a caller can inspect the raw document.+ *+ * @param {ArrayBuffer} buffer+ * @returns {{ json: object, jsonBytes: number, binBytes: number }}+ * @throws {Error} with a message written for a human, not a stack trace+ */+export function readGlbJson(buffer) {+ if (!(buffer instanceof ArrayBuffer)) throw new TypeError('readGlbJson: ArrayBuffer required');+ if (buffer.byteLength < 20) throw new Error('This file is too small to be a GLB.');+ const view = new DataView(buffer);+ if (view.getUint32(0, true) !== GLB_MAGIC) {+ throw new Error('Not a binary glTF. Export as .glb (binary), not .gltf (JSON) or .fbx.');+ }+ if (view.getUint32(4, true) !== 2) throw new Error('Only glTF 2.0 binaries are supported.');+ const c0Len = view.getUint32(12, true);+ if (view.getUint32(16, true) !== CHUNK_TYPE_JSON) throw new Error('Malformed GLB: the first chunk is not JSON.');+ if (20 + c0Len > buffer.byteLength) throw new Error('Malformed GLB: the JSON chunk runs past the end of the file.');+ let json;+ try {+ json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, c0Len)));+ } catch (err) {+ throw new Error(`Malformed GLB: the JSON chunk did not parse (${err.message}).`);+ }+ const binOffset = 20 + c0Len;+ const binBytes = binOffset + 8 <= buffer.byteLength ? view.getUint32(binOffset, true) : 0;+ return { json, jsonBytes: c0Len, binBytes };+}++// Every node index reachable from skins[].joints[]. This is the authoritative+// definition of "is a bone" — a node named `Head` that no skin references is a+// prop, and counting it would inflate coverage on a rig that cannot deform.+function jointNodeIndices(json) {+ const set = new Set();+ for (const skin of json.skins || []) {+ for (const j of skin.joints || []) set.add(j);+ }+ return set;+}++function detectConvention(ctx) {+ for (const c of CONVENTIONS) {+ let hit = false;+ try {+ hit = c.test(ctx);+ } catch {+ hit = false;+ }+ if (hit) return { id: c.id, label: c.label, schema: c.schema, evidence: c.evidence };+ }+ return { id: 'unknown', label: 'Unrecognised', schema: 'custom', evidence: 'no known vendor fingerprint in the joint names' };+}++// Triangles across every primitive, honouring the glTF `mode` enum: only modes+// 4/5/6 (TRIANGLES, STRIP, FAN) produce triangles, and strips/fans yield+// count-2 rather than count/3. Getting this wrong would misreport a stylised+// low-poly avatar as three times heavier than it is.+function countGeometry(json) {+ const accessors = json.accessors || [];+ let triangles = 0;+ let vertices = 0;+ let primitives = 0;+ for (const mesh of json.meshes || []) {+ for (const prim of mesh.primitives || []) {+ primitives++;+ const posIdx = prim.attributes?.POSITION;+ const vcount = posIdx != null ? accessors[posIdx]?.count || 0 : 0;+ vertices += vcount;+ const mode = prim.mode == null ? 4 : prim.mode;+ const elements = prim.indices != null ? accessors[prim.indices]?.count || 0 : vcount;+ if (mode === 4) triangles += Math.floor(elements / 3);+ else if (mode === 5 || mode === 6) triangles += Math.max(0, elements - 2);+ }+ }+ return { triangles, vertices, primitives, meshes: (json.meshes || []).length };+}++function collectTextures(json) {+ const views = json.bufferViews || [];+ return (json.images || []).map((img, i) => {+ const bytes = img.bufferView != null ? views[img.bufferView]?.byteLength || 0 : 0;+ return {+ index: i,+ name: img.name || `image_${i}`,+ mimeType: img.mimeType || (img.uri ? guessMime(img.uri) : 'unknown'),+ bytes,+ external: !!img.uri && !/^data:/i.test(img.uri),+ };+ });+}++function guessMime(uri) {+ if (/^data:([^;,]+)/i.test(uri)) return uri.match(/^data:([^;,]+)/i)[1];+ if (/\.png$/i.test(uri)) return 'image/png';+ if (/\.jpe?g$/i.test(uri)) return 'image/jpeg';+ if (/\.webp$/i.test(uri)) return 'image/webp';+ if (/\.ktx2$/i.test(uri)) return 'image/ktx2';+ return 'unknown';+}++// Morph-target names live on mesh.extras.targetNames (the glTF convention every+// major exporter follows) rather than on the targets themselves. Union them+// across meshes so a head-and-body split avatar reports one coherent set.+function collectMorphs(json) {+ const names = new Set();+ for (const mesh of json.meshes || []) {+ const fromMesh = mesh.extras?.targetNames;+ if (Array.isArray(fromMesh)) fromMesh.forEach((n) => typeof n === 'string' && names.add(n));+ for (const prim of mesh.primitives || []) {+ const fromPrim = prim.extras?.targetNames;+ if (Array.isArray(fromPrim)) fromPrim.forEach((n) => typeof n === 'string' && names.add(n));+ }+ }+ const list = [...names];+ const lower = new Set(list.map((n) => n.toLowerCase()));+ const visemes = OVR_VISEMES.filter((v) => lower.has(v.toLowerCase()));+ const arkit = ARKIT_SAMPLE.filter((v) => lower.has(v.toLowerCase()));+ return {+ total: list.length,+ names: list,+ visemes,+ visemeCount: visemes.length,+ visemeComplete: visemes.length === OVR_VISEMES.length,+ arkit,+ arkitCount: arkit.length,+ lipSync: visemes.length >= 8,+ };+}++/**+ * Full diagnostic for a GLB, ready to render.+ *+ * @param {ArrayBuffer} buffer raw .glb bytes+ * @param {{ fileName?: string }} [opts]+ * @returns {object} report; never throws for a readable GLB+ * @throws {Error} only when the bytes are not a readable glTF 2.0 binary+ */+export function analyzeGlb(buffer, opts = {}) {+ const { json, jsonBytes, binBytes } = readGlbJson(buffer);+ const nodes = json.nodes || [];+ const jointIdx = jointNodeIndices(json);++ // Skinned = at least one mesh primitive is bound to a skin. This is the+ // glTF-level equivalent of three.js's `node.isSkinnedMesh` check, which the+ // runtime gate uses; a skinless mesh cannot be deformed by any clip.+ const skinned = nodes.some((n) => n.skin != null && n.mesh != null);++ const joints = [...jointIdx].map((i) => nodes[i]?.name || '').filter(Boolean);+ const meshNames = nodes.filter((n) => n.mesh != null).map((n) => n.name || '');++ // canonical → the first source joint that claimed it. Later duplicates are+ // recorded as collisions rather than silently overwriting, because a rig+ // with two nodes both mapping to `Hips` is a real authoring bug worth naming.+ const mapped = new Map();+ const collisions = [];+ const unmapped = [];+ const renames = [];+ for (const name of joints) {+ const canonical = canonicalizeBoneName(name);+ if (!canonical) {+ unmapped.push(name);+ continue;+ }+ if (mapped.has(canonical)) collisions.push({ canonical, names: [mapped.get(canonical), name] });+ else mapped.set(canonical, name);+ if (name !== canonical) renames.push({ from: name, to: canonical });+ }++ const convention = detectConvention({ joints, meshNames, json });+ const groups = LIMB_GROUPS.map((g) => {+ const have = g.bones.filter((b) => mapped.has(b));+ const keyHave = g.key.filter((b) => mapped.has(b));+ return {+ id: g.id,+ label: g.label,+ blurb: g.blurb,+ have: have.length,+ total: g.bones.length,+ pct: g.bones.length ? Math.round((have.length / g.bones.length) * 100) : 0,+ driven: keyHave.length === g.key.length,+ missingKey: g.key.filter((b) => !mapped.has(b)),+ };+ });++ const geometry = countGeometry(json);+ const textures = collectTextures(json);+ const morphs = collectMorphs(json);+ const animations = (json.animations || []).map((a, i) => ({+ name: a.name || `animation_${i}`,+ channels: (a.channels || []).length,+ }));++ const drivable = skinned && mapped.size >= MIN_CANONICAL_BONES;+ const report = {+ fileName: opts.fileName || 'model.glb',+ bytes: buffer.byteLength,+ jsonBytes,+ binBytes,+ generator: json.asset?.generator || 'unknown',+ gltfVersion: json.asset?.version || '2.0',+ extensions: [...new Set([...(json.extensionsUsed || []), ...(json.extensionsRequired || [])])].sort(),+ extensionsRequired: json.extensionsRequired || [],+ counts: {+ nodes: nodes.length,+ meshes: geometry.meshes,+ materials: (json.materials || []).length,+ textures: (json.textures || []).length,+ images: textures.length,+ skins: (json.skins || []).length,+ animations: animations.length,+ },+ geometry,+ textures,+ textureBytes: textures.reduce((sum, t) => sum + t.bytes, 0),+ morphs,+ animations,+ skeleton: {+ skinned,+ jointCount: joints.length,+ joints,+ convention,+ mapped: mapped.size,+ total: CANONICAL_TOTAL,+ pct: Math.round((mapped.size / CANONICAL_TOTAL) * 100),+ mappedNames: Object.fromEntries(mapped),+ unmapped,+ collisions,+ renames,+ groups,+ },+ };+ report.verdict = buildVerdict(report, drivable);+ return report;+}++// The verdict is the whole product: one sentence a creator can act on, plus the+// specific reasons behind it. Ordering matters — the first blocker a creator can+// actually fix should be the first thing they read.+function buildVerdict(report, drivable) {+ const s = report.skeleton;+ const notes = [];+ const fixes = [];++ if (!s.skinned) {+ return {+ level: 'fail',+ headline: 'This model has no skinned mesh, so no clip can deform it.',+ detail: 'three.ws will still display it, but it will render as a static prop and every animation control is hidden.',+ notes: [s.jointCount ? `${s.jointCount} joints found, but no mesh is bound to a skin.` : 'No skin definitions at all.'],+ fixes: ['Re-export with skinning enabled, or host the mesh and run it through the auto-rigger (POST /api/forge?action=rig with a glb_url) to get a humanoid skeleton bound to it.'],+ drivable: false,+ };+ }++ if (!drivable) {+ return {+ level: 'fail',+ headline: `Only ${s.mapped} of this rig's joints map to the canonical skeleton, under the ${MIN_CANONICAL_BONES} needed to drive a clip.`,+ detail: 'three.ws falls back to the default rig for models like this rather than leaving them in a T-pose, so your own mesh will not be the one moving.',+ notes: [+ `Detected convention: ${s.convention.label} (${s.convention.evidence}).`,+ s.unmapped.length ? `${s.unmapped.length} joint names were not recognised, including ${s.unmapped.slice(0, 3).join(', ')}.` : 'The skeleton has very few joints.',+ ],+ fixes: [+ 'Rename the joints to the canonical set below, or let the auto-rigger rebuild the skeleton (POST /api/forge?action=rig).',+ 'If this is a common rig convention we should already know, the unmapped names below are exactly what belongs in src/glb-canonicalize.js.',+ ],+ drivable: false,+ };+ }++ const frozen = s.groups.filter((g) => !g.driven);+ if (frozen.length) {+ for (const g of frozen) {+ notes.push(`${g.label}: ${g.have}/${g.total} joints mapped, missing ${g.missingKey.join(', ')}.`);+ }+ fixes.push('Rename the missing joints listed under Coverage. Every other group will animate regardless.');+ if (frozen.some((g) => g.id === 'legs')) fixes.push('Legs specifically: without them a walk cycle plays as a slide. This is the most-reported rig complaint.');+ return {+ level: 'warn',+ headline: `This rig animates, but ${frozen.map((g) => g.label.toLowerCase()).join(' and ')} will not move.`,+ detail: `${s.mapped} of ${s.total} canonical joints mapped. Clips retarget onto the joints that resolved and leave the rest at their authored bind pose.`,+ notes,+ fixes,+ drivable: true,+ };+ }++ notes.push(`${s.mapped} of ${s.total} canonical joints mapped from a ${s.convention.label} rig.`);+ if (report.morphs.lipSync) notes.push(`${report.morphs.visemeCount} visemes present, so lip-sync will work too.`);+ else notes.push('No viseme blendshapes, so this avatar animates but cannot lip-sync.');+ if (!report.morphs.lipSync) fixes.push('Add the 15 Oculus visemes (viseme_aa, viseme_PP, …) if you want speech.');+ if (report.geometry.triangles > 150000) fixes.push(`${report.geometry.triangles.toLocaleString()} triangles is heavy for a web avatar. Decimate toward 60k for smooth mobile playback.`);+ if (report.textureBytes > 12 * 1024 * 1024) fixes.push('Textures exceed 12 MB. Compress with KTX2/Basis to cut first-load time.');++ return {+ level: 'pass',+ headline: 'Every limb group is drivable. This rig performs the full clip library.',+ detail: 'Torso, arms, hands, and legs all resolved to canonical joints, so retargeted clips will move the whole character.',+ notes,+ fixes,+ drivable: true,+ };+}++/**+ * Build a schema-v1 avatar manifest skeleton from a report. Everything the+ * report can know is filled in; the caller supplies identity (id/name/owner)+ * and the public mesh URI, which no local file can provide.+ *+ * @param {object} report from analyzeGlb+ * @param {{ id: string, name: string, meshUri: string, owner: string, sha256?: string, createdAt: string }} identity+ * @returns {object} manifest matching packages/avatar-schema/schema/avatar.v1.json+ */+export function manifestFromReport(report, identity) {+ const manifest = {+ schemaVersion: 1,+ id: identity.id,+ name: identity.name,+ mesh: {+ uri: identity.meshUri,+ sha256: identity.sha256 || '',+ format: 'glb',+ kBytes: Math.round(report.bytes / 1024),+ },+ skeleton: report.skeleton.convention.schema,+ traits: {+ triangles: report.geometry.triangles,+ joints: report.skeleton.jointCount,+ canonicalJoints: report.skeleton.mapped,+ morphTargets: report.morphs.total,+ lipSync: report.morphs.lipSync,+ },+ owner: { chain: 'solana', address: identity.owner },+ createdAt: identity.createdAt,+ };+ if (report.animations.length) {+ manifest.traits.embeddedClips = report.animations.map((a) => a.name);+ }+ return manifest;+}++/**+ * Human-readable byte size. Used in the UI and in the CLI-style summary, so it+ * lives here rather than in the page module.+ * @param {number} n+ * @returns {string}+ */+export function formatBytes(n) {+ if (!Number.isFinite(n) || n <= 0) return '0 B';+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;+}diff --git a/tests/rig-report.test.js b/tests/rig-report.test.jsnew file mode 100644index 000000000..0cd3c7862--- /dev/null+++ b/tests/rig-report.test.js@@ -0,0 +1,190 @@+// Rig report tests — run against the real GLBs shipped in public/avatars rather+// than synthetic fixtures. Those files are the exact rigs the platform serves,+// so a regression here is a regression a user would actually hit, and the suite+// covers every verdict level without anyone having to hand-author a broken rig.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import {+ analyzeGlb,+ readGlbJson,+ manifestFromReport,+ formatBytes,+ MIN_CANONICAL_BONES,+ CANONICAL_TOTAL,+ LIMB_GROUPS,+} from '../src/rig-report.js';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++function load(name) {+ const buf = readFileSync(join(ROOT, 'public/avatars', `${name}.glb`));+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);+}++function report(name) {+ return analyzeGlb(load(name), { fileName: `${name}.glb` });+}++describe('readGlbJson', () => {+ it('rejects a file that is not a GLB with a message a creator can act on', () => {+ const notGlb = new TextEncoder().encode('this is plainly not a binary glTF file');+ expect(() => readGlbJson(notGlb.buffer)).toThrow(/Export as \.glb/);+ });++ it('rejects a truncated buffer instead of reading past its end', () => {+ expect(() => readGlbJson(new ArrayBuffer(8))).toThrow(/too small/);+ });++ it('reports a truncated JSON chunk rather than throwing a RangeError', () => {+ // Valid header claiming a 4 KB JSON chunk in a 40-byte file.+ const buf = new ArrayBuffer(40);+ const v = new DataView(buf);+ v.setUint32(0, 0x46546c67, true);+ v.setUint32(4, 2, true);+ v.setUint32(8, 40, true);+ v.setUint32(12, 4096, true);+ v.setUint32(16, 0x4e4f534a, true);+ expect(() => readGlbJson(buf)).toThrow(/runs past the end/);+ });+});++describe('analyzeGlb verdicts', () => {+ it('passes the canonical Avaturn reference rig with every joint mapped', () => {+ const r = report('cz');+ expect(r.verdict.level).toBe('pass');+ expect(r.skeleton.convention.id).toBe('avaturn');+ expect(r.skeleton.mapped).toBe(CANONICAL_TOTAL);+ expect(r.skeleton.groups.every((g) => g.driven)).toBe(true);+ });++ it('passes a Mixamo rig and names the convention from its joint prefix', () => {+ const r = report('michelle');+ expect(r.verdict.level).toBe('pass');+ expect(r.skeleton.convention.id).toBe('mixamo');+ expect(r.skeleton.renames.length).toBeGreaterThan(0);+ expect(r.skeleton.renames[0].from).toMatch(/^mixamorig/i);+ });++ it('identifies Ready Player Me from its Wolf3D mesh nodes, not its bone names', () => {+ const r = report('default');+ expect(r.skeleton.convention.id).toBe('rpm');+ expect(r.skeleton.convention.schema).toBe('rpm');+ });++ it('fails a model with no skinned mesh and says so plainly', () => {+ const r = report('mannequin');+ expect(r.skeleton.skinned).toBe(false);+ expect(r.verdict.level).toBe('fail');+ expect(r.verdict.drivable).toBe(false);+ expect(r.verdict.headline).toMatch(/no skinned mesh/i);+ });++ it('fails a skinned but non-humanoid rig for lack of canonical joints', () => {+ const r = report('fox');+ expect(r.skeleton.skinned).toBe(true);+ expect(r.skeleton.jointCount).toBeGreaterThan(0);+ expect(r.skeleton.mapped).toBeLessThan(MIN_CANONICAL_BONES);+ expect(r.verdict.level).toBe('fail');+ expect(r.verdict.headline).toMatch(/canonical skeleton/i);+ });++ it('warns on a halfbody rig and names exactly which groups stay frozen', () => {+ const r = report('realistic-halfbody');+ expect(r.verdict.level).toBe('warn');+ expect(r.verdict.drivable).toBe(true);+ const legs = r.skeleton.groups.find((g) => g.id === 'legs');+ expect(legs.driven).toBe(false);+ expect(legs.missingKey).toContain('LeftUpLeg');+ // Hands are fully rigged on this avatar, so the warning must not smear+ // the failure across every group.+ expect(r.skeleton.groups.find((g) => g.id === 'hands').driven).toBe(true);+ });++ it('mirrors the runtime gate: skinned plus MIN_CANONICAL_BONES decides drivability', () => {+ for (const name of ['cz', 'michelle', 'fox', 'mannequin', 'realistic-halfbody']) {+ const r = report(name);+ const expected = r.skeleton.skinned && r.skeleton.mapped >= MIN_CANONICAL_BONES;+ expect(r.verdict.drivable).toBe(expected);+ }+ });+});++describe('analyzeGlb inventory', () => {+ it('counts triangles, materials, and joints for a real avatar', () => {+ const r = report('michelle');+ expect(r.geometry.triangles).toBeGreaterThan(1000);+ expect(r.geometry.vertices).toBeGreaterThan(1000);+ expect(r.counts.materials).toBeGreaterThan(0);+ expect(r.skeleton.jointCount).toBeGreaterThanOrEqual(CANONICAL_TOTAL);+ expect(r.bytes).toBe(r.jsonBytes + r.binBytes + 28);+ });++ it('finds the full Oculus viseme set on an avatar that ships lip-sync', () => {+ const r = report('realistic-female');+ expect(r.morphs.visemeCount).toBe(15);+ expect(r.morphs.visemeComplete).toBe(true);+ expect(r.morphs.lipSync).toBe(true);+ expect(r.verdict.notes.some((n) => /lip-sync/i.test(n))).toBe(true);+ });++ it('reports no lip-sync, and suggests visemes, on a rig with none', () => {+ const r = report('cz');+ expect(r.morphs.visemeCount).toBe(0);+ expect(r.morphs.lipSync).toBe(false);+ expect(r.verdict.fixes.some((f) => /viseme/i.test(f))).toBe(true);+ });++ it('lists every limb group exactly once, in body order', () => {+ const r = report('cz');+ expect(r.skeleton.groups.map((g) => g.id)).toEqual(LIMB_GROUPS.map((g) => g.id));+ });++ it('surfaces unmapped joint names so they can become new canonicalizer rules', () => {+ const r = report('cesium-man');+ expect(r.skeleton.unmapped.length).toBeGreaterThan(0);+ expect(r.skeleton.unmapped.every((n) => typeof n === 'string' && n.length)).toBe(true);+ });+});++describe('manifestFromReport', () => {+ it('produces a manifest that satisfies every required schema-v1 field', () => {+ const r = report('michelle');+ const m = manifestFromReport(r, {+ id: 'avatar-test',+ name: 'Michelle',+ meshUri: 'https://three.ws/avatars/michelle.glb',+ owner: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ sha256: 'a'.repeat(64),+ createdAt: '2026-07-31T00:00:00.000Z',+ });+ for (const key of ['schemaVersion', 'id', 'name', 'mesh', 'skeleton', 'owner', 'createdAt']) {+ expect(m[key], `missing required field ${key}`).toBeDefined();+ }+ expect(m.schemaVersion).toBe(1);+ expect(m.mesh.format).toBe('glb');+ expect(m.mesh.kBytes).toBeGreaterThan(0);+ expect(m.owner.chain).toBe('solana');+ });++ it('declares a skeleton value the schema enum actually accepts', () => {+ const allowed = ['avaturn', 'mixamo', 'rpm', 'vrm-humanoid', 'custom'];+ for (const name of ['cz', 'michelle', 'default', 'fox', 'cesium-man']) {+ const m = manifestFromReport(report(name), {+ id: 'x', name: 'x', meshUri: 'https://example.com/x.glb', owner: 'x', createdAt: '2026-07-31T00:00:00.000Z',+ });+ expect(allowed).toContain(m.skeleton);+ }+ });+});++describe('formatBytes', () => {+ it('scales through B, KB, and MB', () => {+ expect(formatBytes(0)).toBe('0 B');+ expect(formatBytes(512)).toBe('512 B');+ expect(formatBytes(2048)).toBe('2.0 KB');+ expect(formatBytes(5 * 1024 * 1024)).toBe('5.0 MB');+ });+});diff --git a/tests/seed-mesh-gate.test.js b/tests/seed-mesh-gate.test.jsnew file mode 100644index 000000000..4c73764fb--- /dev/null+++ b/tests/seed-mesh-gate.test.js@@ -0,0 +1,288 @@+// The shared catalog bar: api/_lib/seed-mesh-gate.js.+//+// This module is unusual in that it has two consumers with opposite constraints:+// the seeding cron runs it on Cloud Run, and the public inspector at /inspect+// runs it inside a visitor's browser. The whole value of sharing it is that a+// creator's verdict cannot disagree with the catalog's verdict, so the tests+// here defend the two properties that would silently destroy that:+//+// 1. It stays browser-safe. One `node:` import, or one bare `process` /+// `Buffer` read, and the inspector dies at runtime while every server-side+// test stays green.+// 2. The explain layer stays complete. A new reason code with no guidance+// renders as a blank card, so the rule table is checked against the reasons+// the gate can actually emit, read out of the source rather than restated.+//+// Fixtures are REAL binary glTF 2.0, built the way tests/seed-quality.test.js+// and tests/glb-quality.test.js build them.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ gateMesh,+ explainMeshGate,+ MESH_GATE_RULES,+ SEED_MESH_BOUNDS,+ SEED_GATE_VERSION,+} from '../api/_lib/seed-mesh-gate.js';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');++function buildGlb(gltf, { binBytes = 0 } = {}) {+ const json = Buffer.from(JSON.stringify(gltf), 'utf8');+ const jsonPad = (4 - (json.length % 4)) % 4;+ const jsonChunk = Buffer.concat([json, Buffer.alloc(jsonPad, 0x20)]);+ const binPad = (4 - (binBytes % 4)) % 4;+ const binChunk = binBytes ? Buffer.alloc(binBytes + binPad, 0) : Buffer.alloc(0);++ const total = 12 + (8 + jsonChunk.length) + (binBytes ? 8 + binChunk.length : 0);+ const out = Buffer.alloc(total);+ out.writeUInt32LE(0x46546c67, 0); // 'glTF'+ out.writeUInt32LE(2, 4);+ out.writeUInt32LE(total, 8);+ out.writeUInt32LE(jsonChunk.length, 12);+ out.writeUInt32LE(0x4e4f534a, 16); // 'JSON'+ jsonChunk.copy(out, 20);+ if (binBytes) {+ const off = 20 + jsonChunk.length;+ out.writeUInt32LE(binChunk.length, off);+ out.writeUInt32LE(0x004e4942, off + 4); // 'BIN\0'+ binChunk.copy(out, off + 8);+ }+ return out;+}++function healthyGltf({ verts = 12_000, meshes = 1, textured = true, bbox = [-1, 1] } = {}) {+ const tris = verts * 2;+ const accessors = [+ { componentType: 5126, count: verts, type: 'VEC3', min: [bbox[0], bbox[0], bbox[0]], max: [bbox[1], bbox[1], bbox[1]] },+ { componentType: 5125, count: tris * 3, type: 'SCALAR' },+ ];+ const primitive = { attributes: { POSITION: 0 }, indices: 1, mode: 4, ...(textured ? { material: 0 } : {}) };+ return {+ asset: { version: '2.0', generator: 'TRELLIS' },+ accessors,+ meshes: Array.from({ length: meshes }, () => ({ primitives: [primitive] })),+ ...(textured+ ? {+ materials: [{ pbrMetallicRoughness: { baseColorTexture: { index: 0 } } }],+ textures: [{ source: 0 }],+ images: [{ mimeType: 'image/png', bufferView: 0 }],+ }+ : { materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.5, 0.5, 0.5, 1] } }] }),+ nodes: Array.from({ length: meshes }, (_, i) => ({ mesh: i })),+ };+}++const healthy = (opts, glbOpts = { binBytes: 400_000 }) => buildGlb(healthyGltf(opts), glbOpts);++// ── 1. Browser safety ────────────────────────────────────────────────────────++describe('stays runnable in a browser', () => {+ // The gate and everything it reaches. `npm run check:browser-graph` walks the+ // real bundler graph from the HTML entries and would also catch a leak here,+ // but only at build time, and only once the page is wired into an entry.+ // Asserting it at the module level fails the moment the import is added.+ const CHAIN = ['api/_lib/seed-mesh-gate.js', 'api/_lib/glb-quality.js', 'api/_lib/glb-inspect.js'];++ const sourceOf = (rel) => readFileSync(resolve(ROOT, rel), 'utf8');++ it.each(CHAIN)('%s imports no Node built-in', (rel) => {+ const src = sourceOf(rel);+ const specifiers = [...src.matchAll(/(?:^|\n)\s*import\s[^;]*?from\s*['"]([^'"]+)['"]/g)].map((m) => m[1]);+ const builtins = specifiers.filter((s) => s.startsWith('node:'));+ expect(builtins, `${rel} must not import Node built-ins`).toEqual([]);+ });++ it.each(CHAIN)('%s never reads a bare process/Buffer identifier', (rel) => {+ // A browser has no binding for either, and `process?.env` still throws a+ // ReferenceError when `process` was never declared: optional chaining+ // guards a null VALUE, not an undeclared NAME. Only `typeof` is safe.+ //+ // This is a static early-warning, not the proof: the authoritative check is+ // the globals-deleted run below. Scope analysis is out of scope for a regex,+ // so a read counts as guarded when a `typeof <name>` appears close enough+ // above it to be the same function. That covers both real forms in the+ // chain (`typeof x !== 'undefined' ? …` and an early-return guard) while+ // still failing on a fresh unguarded read somewhere new.+ const src = sourceOf(rel)+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/(^|[^:])\/\/.*$/gm, '$1');+ for (const name of ['process', 'Buffer']) {+ for (const m of src.matchAll(new RegExp(`\\b${name}\\b\\s*[?.]`, 'g'))) {+ const before = src.slice(Math.max(0, m.index - 220), m.index);+ expect(+ new RegExp(`typeof\\s+${name}\\b`).test(before),+ `${rel} reads \`${name}\` without a typeof guard near: ${src.slice(Math.max(0, m.index - 60), m.index + 40)}`,+ ).toBe(true);+ }+ }+ });++ it('produces a verdict with process and Buffer deleted from globalThis', async () => {+ // The strongest available proof short of a real browser: run the gate with+ // both globals genuinely absent.+ const bytes = new Uint8Array(healthy());+ const realProcess = globalThis.process;+ const realBuffer = globalThis.Buffer;+ // @ts-expect-error deliberately removing a global for the duration+ delete globalThis.process;+ // @ts-expect-error deliberately removing a global for the duration+ delete globalThis.Buffer;+ try {+ const report = explainMeshGate(gateMesh(bytes, { category: 'avatar' }), { category: 'avatar' });+ expect(report.pass).toBe(true);+ expect(report.checks.length).toBeGreaterThan(0);+ } finally {+ globalThis.process = realProcess;+ globalThis.Buffer = realBuffer;+ }+ });++ it('accepts a Uint8Array, which is all a browser can produce from a File', () => {+ const buf = healthy();+ expect(gateMesh(new Uint8Array(buf), { category: 'avatar' }).pass).toBe(true);+ });+});++// ── 2. The explain layer cannot drift from the gate ──────────────────────────++describe('explain layer covers the gate', () => {+ it('has guidance for every reason code the gate can emit', () => {+ // Read the reasons out of the source rather than restating them here: a+ // restated list drifts silently, a derived one fails the moment a new+ // `reasons.push('…')` lands without a rule beside it.+ const src = readFileSync(resolve(ROOT, 'api/_lib/seed-mesh-gate.js'), 'utf8');+ const emitted = new Set(+ [...src.matchAll(/reasons\.push\(\s*'([a-z_]+)'\s*\)/g)].map((m) => m[1]).concat('not_valid_glb'),+ );+ expect(emitted.size).toBeGreaterThan(5);+ for (const reason of emitted) {+ expect(MESH_GATE_RULES, `no guidance for reason "${reason}"`).toHaveProperty(reason);+ }+ });++ it('gives every rule a label, a why and a fix', () => {+ for (const [id, rule] of Object.entries(MESH_GATE_RULES)) {+ expect(rule.label, `${id}.label`).toBeTruthy();+ expect(rule.why.length, `${id}.why`).toBeGreaterThan(20);+ expect(rule.fix.length, `${id}.fix`).toBeGreaterThan(20);+ }+ });++ it('never renders a check without a bound and a measurement', () => {+ const report = explainMeshGate(gateMesh(healthy(), { category: 'avatar' }), { category: 'avatar' });+ for (const c of report.checks) {+ expect(c.actual, c.id).toBeTruthy();+ expect(c.bound, c.id).toBeTruthy();+ expect(['pass', 'fail', 'skipped']).toContain(c.status);+ }+ });++ it('marks exactly the failed reasons as fail and nothing else', () => {+ const verdict = gateMesh(healthy({ verts: 300, textured: false }), { category: 'avatar' });+ const report = explainMeshGate(verdict, { category: 'avatar' });+ const failed = report.checks.filter((c) => c.status === 'fail').map((c) => c.id).sort();+ expect(failed).toEqual([...verdict.reasons].sort());+ });+});++// ── 3. The verdict a person reads ────────────────────────────────────────────++describe('explainMeshGate', () => {+ it('reports headroom on a pass, not just a boolean', () => {+ const report = explainMeshGate(gateMesh(healthy({ verts: 12_000 }), { category: 'avatar' }), { category: 'avatar' });+ expect(report.pass).toBe(true);+ expect(report.headline).toBe('Clears the catalog bar');+ const density = report.checks.find((c) => c.id === 'vertices_below_floor');+ expect(density.actual).toBe('12,000 vertices');+ expect(density.bound).toBe(`at least ${SEED_MESH_BOUNDS.minVertices.toLocaleString('en-US')}`);+ });++ it('stamps the gate version so a verdict is comparable only within one', () => {+ const report = explainMeshGate(gateMesh(healthy(), {}), {});+ expect(report.gateVersion).toBe(SEED_GATE_VERSION);+ });++ it('reports only the parse failure when the file is not a GLB, claiming nothing else', () => {+ // Every other measurement is meaningless once parsing failed. Listing the+ // remaining checks as passed would be a lie by omission.+ const report = explainMeshGate(gateMesh(Buffer.from('this is a PNG, actually'), {}), {});+ expect(report.pass).toBe(false);+ expect(report.checks).toHaveLength(1);+ expect(report.checks[0].id).toBe('not_valid_glb');+ expect(report.headline).toBe('Not a readable .glb');+ });++ it('counts the failures in the headline', () => {+ const report = explainMeshGate(+ gateMesh(healthy({ verts: 300, textured: false }), { category: 'avatar' }),+ { category: 'avatar' },+ );+ const failures = report.checks.filter((c) => c.status === 'fail').length;+ expect(report.headline).toBe(`${failures} checks short of the catalog bar`);+ });++ it('says "1 check" rather than "1 checks"', () => {+ const report = explainMeshGate(gateMesh(healthy({ textured: false }), { category: 'avatar' }), { category: 'avatar' });+ expect(report.headline).toBe('1 check short of the catalog bar');+ });++ it('skips the character-only mesh rule for a prop rather than passing it', () => {+ // "Skipped" and "passed" are different claims. A prop with 22 meshes did+ // not satisfy the rule, the rule did not apply.+ const bytes = healthy({ meshes: 22 });+ const avatar = explainMeshGate(gateMesh(bytes, { category: 'avatar' }), { category: 'avatar' });+ const prop = explainMeshGate(gateMesh(bytes, { category: 'accessory' }), { category: 'accessory' });++ expect(avatar.checks.find((c) => c.id === 'too_many_meshes_for_a_character').status).toBe('fail');+ expect(prop.checks.find((c) => c.id === 'too_many_meshes_for_a_character').status).toBe('skipped');+ expect(avatar.pass).toBe(false);+ expect(prop.pass).toBe(true);+ });++ it('formats bytes and counts for a human, not in raw units', () => {+ const report = explainMeshGate(gateMesh(healthy({}, { binBytes: 2_500_000 }), {}), {});+ const size = report.checks.find((c) => c.id === 'file_too_large');+ expect(size.actual).toMatch(/^2\.\d MB$/);+ expect(size.bound).toBe('at most 80.0 MB');+ });++ it('names the failing checks in the summary so the reason is visible unopened', () => {+ const report = explainMeshGate(gateMesh(healthy({ textured: false }), {}), {});+ expect(report.summary).toContain('Surface texture');+ });+});++// ── 4. Against the real library ──────────────────────────────────────────────++describe('the models this site actually serves', () => {+ // The /inspect page ships these as its samples. If a preset's verdict changes,+ // the page starts teaching the wrong lesson, so the presets are pinned here.+ const read = (name) => readFileSync(resolve(ROOT, 'public/avatars', name));++ it('michelle.glb clears the bar (the page presents it as a clean pass)', () => {+ const v = gateMesh(read('michelle.glb'), { category: 'avatar' });+ expect(v.pass).toBe(true);+ expect(v.rigged).toBe(true);+ });++ it('fox.glb clears the bar close to the density floor', () => {+ const v = gateMesh(read('fox.glb'), { category: 'avatar' });+ expect(v.pass).toBe(true);+ expect(v.metrics.vertexCount).toBeGreaterThanOrEqual(SEED_MESH_BOUNDS.minVertices);+ expect(v.metrics.vertexCount).toBeLessThan(SEED_MESH_BOUNDS.minVertices * 2);+ });++ it('xbot.glb fails on texture alone', () => {+ expect(gateMesh(read('xbot.glb'), { category: 'avatar' }).reasons).toEqual(['no_textures']);+ });++ it('mannequin.glb fails two rules, one of which a prop would not be held to', () => {+ const asAvatar = gateMesh(read('mannequin.glb'), { category: 'avatar' });+ expect([...asAvatar.reasons].sort()).toEqual(['no_textures', 'too_many_meshes_for_a_character']);+ expect(gateMesh(read('mannequin.glb'), { category: 'accessory' }).reasons).toEqual(['no_textures']);+ });+});