Skip to content

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

fix(wardrobe): refuse to WEAR a malformed garment, not just to publish one

nirholas9b175747c053
diff --git a/scripts/measure-garment-extents.mjs b/scripts/measure-garment-extents.mjs
new file mode 100644
index 000000000..c2bc90dc6
--- /dev/null
+++ b/scripts/measure-garment-extents.mjs
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+// Measure the world-space extents of every published garment, grouped by slot.
+//
+// Feeds the per-slot proportion envelopes that garment-forge enforces before
+// publishing (garment_glb.SLOT_ENVELOPE): the envelope has to sit above every
+// legitimately-shaped piece and below the malformed ones, so it is set from
+// measurements, not taste. Run it after a seeding batch or a placement change:
+//
+// node scripts/measure-garment-extents.mjs
+//
+// Output is one line per piece plus a per-slot max, which is the number to
+// compare against the envelope in workers/garment-forge/garment_glb.py.
+
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { MeshoptDecoder } from 'meshoptimizer';
+
+const CATALOG = 'https://storage.googleapis.com/three-ws-garments/garments/catalog.json';
+
+const io = new NodeIO()
+ .registerExtensions(ALL_EXTENSIONS)
+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
+
+async function extents(url) {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
+ const doc = await io.readBinary(new Uint8Array(await res.arrayBuffer()));
+ const lo = [Infinity, Infinity, Infinity];
+ const hi = [-Infinity, -Infinity, -Infinity];
+ const p = [0, 0, 0];
+ for (const mesh of doc.getRoot().listMeshes()) {
+ for (const prim of mesh.listPrimitives()) {
+ const pos = prim.getAttribute('POSITION');
+ if (!pos) continue;
+ for (let i = 0; i < pos.getCount(); i++) {
+ pos.getElement(i, p);
+ for (let a = 0; a < 3; a++) {
+ lo[a] = Math.min(lo[a], p[a]);
+ hi[a] = Math.max(hi[a], p[a]);
+ }
+ }
+ }
+ }
+ return { size: hi.map((v, i) => v - lo[i]), lo, hi };
+}
+
+const catalog = await (await fetch(CATALOG)).json();
+const bySlot = new Map();
+const f = (n) => (Number.isFinite(n) ? n.toFixed(3) : '?');
+
+for (const m of catalog) {
+ let e;
+ try {
+ e = await extents(m.model.uri);
+ } catch (err) {
+ console.log(`${m.slot.padEnd(10)} ${m.id.padEnd(46)} UNREADABLE ${err.message}`);
+ continue;
+ }
+ const rows = bySlot.get(m.slot) || [];
+ rows.push({ id: m.id, ...e });
+ bySlot.set(m.slot, rows);
+ console.log(
+ `${m.slot.padEnd(10)} ${m.id.padEnd(46)} w=${f(e.size[0])} h=${f(e.size[1])} d=${f(e.size[2])} y:[${f(e.lo[1])}..${f(e.hi[1])}]`,
+ );
+}
+
+console.log('\n=== per-slot maxima (w, h, d) ===');
+for (const [slot, rows] of [...bySlot].sort()) {
+ const max = [0, 1, 2].map((a) => Math.max(...rows.map((r) => r.size[a])));
+ const worst = [0, 1, 2].map((a) => rows.reduce((w, r) => (r.size[a] > w.size[a] ? r : w)).id);
+ console.log(`${slot.padEnd(10)} n=${String(rows.length).padStart(2)} max w=${f(max[0])} h=${f(max[1])} d=${f(max[2])}`);
+ console.log(`${''.padEnd(10)} widest=${worst[0]}\n${''.padEnd(10)} tallest=${worst[1]}\n${''.padEnd(10)} deepest=${worst[2]}`);
+}
diff --git a/src/avatar-garment.js b/src/avatar-garment.js
index 56a6a3d4d..aeacb3374 100644
--- a/src/avatar-garment.js
+++ b/src/avatar-garment.js
@@ -32,18 +32,21 @@
import {
Bone,
+ Box3,
DoubleSide,
Float32BufferAttribute,
Matrix4,
Skeleton,
SkinnedMesh,
Uint16BufferAttribute,
+ Vector3,
} from 'three';
import { canonicalizeBoneName } from './glb-canonicalize.js';
import {
GARMENT_SLOTS,
BODY_REGIONS,
REGION_BONES,
+ MAX_GARMENT_EXTENT_RATIO,
MIN_BIND_COVERAGE,
SLOT_OCCLUDABLE,
clampOccludes,
@@ -51,7 +54,39 @@ import {
// Shared vocabulary lives in src/garment-taxonomy.js (pure, also consumed by
// the server-side baker). Re-exported so existing consumers keep one import.
-export { GARMENT_SLOTS, BODY_REGIONS, REGION_BONES, MIN_BIND_COVERAGE, SLOT_OCCLUDABLE, clampOccludes };
+export {
+ GARMENT_SLOTS, BODY_REGIONS, REGION_BONES, MIN_BIND_COVERAGE,
+ MAX_GARMENT_EXTENT_RATIO, SLOT_OCCLUDABLE, clampOccludes,
+};
+
+/**
+ * Reject a garment whose bounding box is implausibly large next to the body it
+ * is being worn on. Returns a reason string, or null when the piece is sane.
+ *
+ * Bind coverage proves a garment DEFORMS correctly; it says nothing about its
+ * SIZE. A malformed mesh can be perfectly skinned and still be a curtain as
+ * big as the wearer (see MAX_GARMENT_EXTENT_RATIO). The forge refuses these at
+ * publish time, but the catalog is public and long-lived, so the wearer checks
+ * too. Scale-invariant by construction: garment and avatar are measured in the
+ * same scene, so centimetre-unit and metre-unit avatars behave identically.
+ */
+export function extentRejection(garmentRoot, avatarRoot, ratio = MAX_GARMENT_EXTENT_RATIO) {
+ const size = new Vector3();
+ const garment = new Box3().setFromObject(garmentRoot);
+ const avatar = new Box3().setFromObject(avatarRoot);
+ if (garment.isEmpty() || avatar.isEmpty()) return null;
+ avatar.getSize(size);
+ const avatarHeight = size.y;
+ if (!(avatarHeight > 0)) return null;
+ garment.getSize(size);
+ for (const [axis, extent] of [['width', size.x], ['height', size.y], ['depth', size.z]]) {
+ if (extent > avatarHeight * ratio) {
+ return `garment ${axis} is ${(extent / avatarHeight).toFixed(2)}x the avatar's height ` +
+ `(max ${ratio}x): the mesh is malformed, not just oversized`;
+ }
+ }
+ return null;
+}
/* ────────────────────────────────────────────────────────────────────────── *
* Skeleton discovery
@@ -264,6 +299,11 @@ export function attachGarment(avatarRoot, garmentRoot, opts = {}) {
});
if (!skinned.length && !rigid.length) return fail('garment contains no meshes');
+ // Size sanity before any binding work: a malformed mesh can pass every
+ // skinning gate and still be a curtain the size of the avatar.
+ const tooBig = extentRejection(garmentRoot, avatarRoot, opts.maxExtentRatio);
+ if (tooBig) return fail(tooBig);
+
const attached = [];
let worstCoverage = 1;
const allUnresolved = new Set();
diff --git a/src/garment-taxonomy.js b/src/garment-taxonomy.js
index bab8067a9..233ad21da 100644
--- a/src/garment-taxonomy.js
+++ b/src/garment-taxonomy.js
@@ -56,6 +56,20 @@ export function clampOccludes(slot, occludes) {
return (Array.isArray(occludes) ? occludes : []).filter((r) => allowed.includes(r));
}
+/** Largest plausible size for a worn garment, as a multiple of the avatar's
+ * own height. The wearer-side twin of the forge's per-slot `max_extent`
+ * publish gate (workers/garment-forge/garment_glb.py): that one stops a
+ * malformed mesh being published, this one stops an already-published or
+ * third-party malformed mesh being WORN.
+ *
+ * A generator asked for "long straight hair" returned a mesh 1.43 m deep on a
+ * 1.667 m body (0.86x its height) whose width profile was still perfect, so
+ * every skinning gate passed it. Nothing a person wears spans most of their
+ * own height on all axes: a full-length coat is ~0.55x tall and far less
+ * deep, so 0.75x on any one axis sits above every real garment and well
+ * below a runaway mesh. */
+export const MAX_GARMENT_EXTENT_RATIO = 0.75;
+
/** Below this share of *weighted* garment bones resolving to avatar bones, the
* garment cannot deform sanely and is refused rather than shipped mangled. */
export const MIN_BIND_COVERAGE = 0.6;
diff --git a/tests/avatar-garment.test.js b/tests/avatar-garment.test.js
index c63436238..01dc784d7 100644
--- a/tests/avatar-garment.test.js
+++ b/tests/avatar-garment.test.js
@@ -22,6 +22,7 @@ import {
Float32BufferAttribute,
Group,
Matrix4,
+ Mesh,
MeshStandardMaterial,
Skeleton,
SkinnedMesh,
@@ -36,6 +37,7 @@ import {
clampOccludes,
cullSkinByBones,
detachSlot,
+ extentRejection,
findAvatarSkeleton,
occupiedSlots,
reindexBoneInverses,
@@ -382,3 +384,57 @@ describe('clampOccludes', () => {
expect(clampOccludes('top', 'torso')).toEqual([]);
});
});
+
+describe('extentRejection', () => {
+ // Measured against the avatar being worn, so the verdict is scale
+ // invariant: identical in metres or centimetres.
+ function bodyRoot(height = 1.667) {
+ const root = new Group();
+ const geo = new BufferGeometry();
+ geo.setAttribute('position', new Float32BufferAttribute(
+ [-0.2, 0, -0.1, 0.2, 0, -0.1, 0, height, 0.1], 3));
+ root.add(new Mesh(geo, new MeshStandardMaterial()));
+ return root;
+ }
+ function boxRoot(w, h, d) {
+ const root = new Group();
+ const geo = new BufferGeometry();
+ geo.setAttribute('position', new Float32BufferAttribute(
+ [-w / 2, -h / 2, -d / 2, w / 2, h / 2, d / 2, 0, 0, 0], 3));
+ root.add(new Mesh(geo, new MeshStandardMaterial()));
+ return root;
+ }
+
+ it('accepts a normally proportioned garment', () => {
+ // A full-length coat on a 1.667m body.
+ expect(extentRejection(boxRoot(0.5, 0.9, 0.35), bodyRoot())).toBeNull();
+ });
+
+ it('rejects the malformed 1.43m-deep hair curtain that shipped', () => {
+ const reason = extentRejection(boxRoot(0.30, 0.896, 1.431), bodyRoot());
+ expect(reason).toMatch(/depth/);
+ expect(reason).toMatch(/malformed/);
+ });
+
+ it('is scale invariant (centimetre-unit avatar behaves identically)', () => {
+ expect(extentRejection(boxRoot(30, 89.6, 143.1), bodyRoot(166.7))).toMatch(/depth/);
+ expect(extentRejection(boxRoot(50, 90, 35), bodyRoot(166.7))).toBeNull();
+ });
+
+ it('abstains when the avatar has no measurable height', () => {
+ expect(extentRejection(boxRoot(9, 9, 9), new Group())).toBeNull();
+ });
+
+ it('refuses to attach an oversized garment through attachGarment', () => {
+ const avatar = buildRig();
+ const root = new Group();
+ root.add(buildSkinnedMesh(avatar.skeleton, [
+ { pos: new Vector3(0, 0, 0), bone: 0 },
+ { pos: new Vector3(0, 1.667, 0), bone: 2 },
+ ]));
+ root.updateMatrixWorld(true);
+ const res = attachGarment(root, boxRoot(0.3, 0.9, 1.5), { slot: 'hair' });
+ expect(res.ok).toBe(false);
+ expect(res.reason).toMatch(/malformed/);
+ });
+});