Skip to content

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

feat: enhance garment assembly and skin transfer processes with new algorithms and tests

nirholas63b65598dbf5
diff --git a/docs/avatar-reconstruction.md b/docs/avatar-reconstruction.md
index cdde3d0a8..c42394695 100644
--- a/docs/avatar-reconstruction.md
+++ b/docs/avatar-reconstruction.md
@@ -40,10 +40,19 @@ closes that gap:
3. That displacement is carried onto the head's corresponding vertices (a
nearest-vertex map precomputed by `precompute_uv.py`), scaled into head units,
and clamped to reject landmark/pose outliers.
-4. A **normalised-Gaussian RBF** (partition of unity — local, bounded, no
- extrapolation) diffuses the sparse displacements across all 2162 head vertices,
- with a locality mask that fades the morph to zero off the face so the scalp,
- ears and neck stay put.
+4. A **thin-plate spline** interpolates the sparse displacements across all 2162
+ head vertices. TPS passes exactly through its control points, so localised
+ identity (a wider jaw, a longer nose) survives instead of being averaged away
+ — the failure mode of normalised-Gaussian/Shepard weighting. TPS extrapolates
+ freely, so a Gaussian locality mask fades the field to zero off the face and
+ the scalp, ears and neck stay put.
+
+`strength` and `max_displacement_frac` default to **0.6 / 0.45**, chosen by an
+ISE sweep over the 40-face reference set (`python -m eval.tune_morph`), not by
+eye. They cut mean ISE 43% against the original 0.75 / 0.18, whose ~1.9 cm
+displacement ceiling was throttling genuine facial variation rather than
+rejecting outliers. See [avatar-fidelity-program.md](avatar-fidelity-program.md)
+for why the sweep's own looser optimum was deliberately not shipped.
Because vertex count and order never change, `glb_ops.set_head_geometry` writes
the morphed positions (and recomputed normals) back **without disturbing the
diff --git a/tests/garment-forge-skin-transfer.test.js b/tests/garment-forge-skin-transfer.test.js
new file mode 100644
index 000000000..0956923bf
--- /dev/null
+++ b/tests/garment-forge-skin-transfer.test.js
@@ -0,0 +1,175 @@
+/**
+ * Garment forge — fit, proximity skin transfer, and assembly, verified against
+ * the REAL canonical body (public/avatars/parametric-base.glb) and closed
+ * end-to-end through the REAL runtime binder (src/avatar-garment.js).
+ *
+ * The last test is the one that matters commercially: a synthetic "shirt"
+ * tube, never rigged by a human, goes through the worker's assembly path and
+ * must come out attachable at >= MIN_BIND_COVERAGE by attachGarment(). That is
+ * the exact contract a generated garment must satisfy to enter the catalog
+ * (specs/GARMENT_MANIFEST.md §Validation, rule 5).
+ */
+
+import { readFile } from 'node:fs/promises';
+import { describe, it, expect, beforeAll } from 'vitest';
+import { Document, NodeIO } from '@gltf-transform/core';
+import {
+ SLOT_REGIONS,
+ findBodyMesh,
+ regionBounds,
+ fitGarmentToBody,
+ transferSkinWeights,
+ deriveOccludes,
+} from '../workers/garment-forge/lib/skin-transfer.mjs';
+import { assembleGarment } from '../workers/garment-forge/lib/assemble.mjs';
+import { MIN_BIND_COVERAGE } from '../src/garment-taxonomy.js';
+
+const BASE_GLB = new URL('../public/avatars/parametric-base.glb', import.meta.url);
+
+let io;
+let baseBytes;
+
+beforeAll(async () => {
+ io = new NodeIO();
+ baseBytes = new Uint8Array(await readFile(BASE_GLB));
+});
+
+/** A closed tube (12-sided prism) around the origin — a crude "shirt". */
+function buildTubeDoc({ radius = 7, height = 9, segments = 12 } = {}) {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const scene = doc.createScene('scene');
+ doc.getRoot().setDefaultScene(scene);
+
+ const positions = [];
+ const indices = [];
+ for (let s = 0; s <= segments; s++) {
+ const a = (s / segments) * Math.PI * 2;
+ positions.push(Math.cos(a) * radius, -height / 2, Math.sin(a) * radius);
+ positions.push(Math.cos(a) * radius, height / 2, Math.sin(a) * radius);
+ }
+ for (let s = 0; s < segments; s++) {
+ const i = s * 2;
+ indices.push(i, i + 1, i + 2, i + 1, i + 3, i + 2);
+ }
+
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', doc.createAccessor().setType('VEC3')
+ .setArray(new Float32Array(positions)).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType('SCALAR')
+ .setArray(new Uint16Array(indices)).setBuffer(buffer));
+ const mesh = doc.createMesh('tube').addPrimitive(prim);
+ const node = doc.createNode('tubeNode').setMesh(mesh);
+ scene.addChild(node);
+ return { doc, mesh };
+}
+
+describe('canonical body analysis', () => {
+ it('finds the skinned body mesh in parametric-base.glb', async () => {
+ const doc = await io.readBinary(baseBytes);
+ const node = findBodyMesh(doc);
+ expect(node).toBeTruthy();
+ expect(node.getSkin().listJoints().length).toBeGreaterThanOrEqual(50);
+ });
+
+ it('resolves region bounds for every slot region', async () => {
+ const doc = await io.readBinary(baseBytes);
+ const bounds = regionBounds(doc);
+ for (const regions of Object.values(SLOT_REGIONS)) {
+ for (const r of regions) {
+ expect(bounds.has(r), `region ${r} missing from body bounds`).toBe(true);
+ }
+ }
+ // Sanity: the torso sits above the hips on a standing human.
+ const torso = bounds.get('torso');
+ const hips = bounds.get('hips');
+ expect((torso.min[1] + torso.max[1]) / 2).toBeGreaterThan((hips.min[1] + hips.max[1]) / 2);
+ });
+});
+
+describe('fit + transfer on the real body', () => {
+ it('fits an arbitrary-scale tube over the torso and transfers full weights', async () => {
+ const bodyDoc = await io.readBinary(baseBytes);
+ const { doc, mesh } = buildTubeDoc();
+
+ const { scale } = fitGarmentToBody(mesh, bodyDoc, 'top');
+ expect(scale).toBeGreaterThan(0);
+
+ // After fitting, the tube's bounds must overlap the torso's.
+ const bounds = regionBounds(bodyDoc);
+ const torso = bounds.get('torso');
+ const pos = mesh.listPrimitives()[0].getAttribute('POSITION').getArray();
+ let minY = Infinity;
+ let maxY = -Infinity;
+ for (let i = 1; i < pos.length; i += 3) {
+ if (pos[i] < minY) minY = pos[i];
+ if (pos[i] > maxY) maxY = pos[i];
+ }
+ expect(maxY).toBeGreaterThan(torso.min[1]);
+ expect(minY).toBeLessThan(torso.max[1]);
+
+ const { transferred } = transferSkinWeights(mesh, bodyDoc, doc);
+ const vertCount = pos.length / 3;
+ expect(transferred).toBe(vertCount);
+
+ // Every vertex ends up with normalised-ish weight mass.
+ const w = mesh.listPrimitives()[0].getAttribute('WEIGHTS_0').getArray();
+ for (let v = 0; v < vertCount; v++) {
+ const sum = w[v * 4] + w[v * 4 + 1] + w[v * 4 + 2] + w[v * 4 + 3];
+ expect(sum).toBeGreaterThan(0.5);
+ }
+ });
+
+ it('derives occludes that include the slot floor', async () => {
+ const bodyDoc = await io.readBinary(baseBytes);
+ const { doc, mesh } = buildTubeDoc();
+ fitGarmentToBody(mesh, bodyDoc, 'top');
+ transferSkinWeights(mesh, bodyDoc, doc);
+ const occludes = deriveOccludes(mesh, findBodyMesh(bodyDoc).getSkin(), 'top');
+ expect(occludes).toContain('torso');
+ expect(occludes).toContain('upperArms');
+ });
+});
+
+describe('assembleGarment → attachGarment (the commercial contract)', () => {
+ it('a generated tube becomes a garment GLB the runtime binds at >= MIN_BIND_COVERAGE', async () => {
+ const { doc } = buildTubeDoc();
+ const garmentBytes = await io.writeBinary(doc);
+
+ const { bytes, occludes, stats } = await assembleGarment(io, baseBytes, garmentBytes, 'top');
+ expect(stats.transferred).toBeGreaterThan(0);
+ expect(occludes).toContain('torso');
+
+ // The emitted GLB must not ship the body mesh (skeleton only + cloth).
+ const outDoc = await io.readBinary(bytes);
+ const meshes = outDoc.getRoot().listMeshes();
+ expect(meshes.length).toBe(1);
+
+ // ── Close the loop through the real three.js runtime binder. ──
+ const [{ GLTFLoader }, { attachGarment }, { Group }] = await Promise.all([
+ import('three/examples/jsm/loaders/GLTFLoader.js'),
+ import('../src/avatar-garment.js'),
+ import('three'),
+ ]);
+
+ const loader = new GLTFLoader();
+ const parse = (buf) => new Promise((resolve, reject) => {
+ loader.parse(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength), '', resolve, reject);
+ });
+
+ // The "avatar" the user brings: the canonical body itself, loaded as a
+ // plain GLB. In production this is any humanoid; the runtime suite
+ // already proves foreign rigs and divergent rests bind.
+ const avatarGltf = await parse(new Uint8Array(baseBytes));
+ const avatarRoot = new Group();
+ avatarRoot.add(avatarGltf.scene);
+ avatarRoot.updateMatrixWorld(true);
+
+ const garmentGltf = await parse(bytes);
+ const result = attachGarment(avatarRoot, garmentGltf.scene, { slot: 'top' });
+
+ expect(result.ok).toBe(true);
+ expect(result.coverage).toBeGreaterThanOrEqual(MIN_BIND_COVERAGE);
+ }, 30000);
+});
diff --git a/workers/avatar-reconstruction/README.md b/workers/avatar-reconstruction/README.md
index 1d6827972..421046710 100644
--- a/workers/avatar-reconstruction/README.md
+++ b/workers/avatar-reconstruction/README.md
@@ -21,9 +21,12 @@ generate an arbitrary mesh). Two phases, both commercial-clean:
avatar reads as *that person* instead of their texture on a generic head.
Umeyama-aligns the landmarks to MediaPipe's neutral canonical face, carries
the identity residual onto the head's corresponding vertices (precomputed
- nearest-vertex map), and diffuses it with a normalised-Gaussian RBF that fades
- to zero off the face. Vertex count/order are preserved, so `glb_ops.set_head_geometry`
- writes it back **without disturbing skinning or any blendshape**.
+ nearest-vertex map), and interpolates it across the head with a thin-plate
+ spline that passes through the control points, under a Gaussian mask that
+ fades the field to zero off the face. Vertex count/order are preserved, so
+ `glb_ops.set_head_geometry` writes it back **without disturbing skinning or
+ any blendshape**. The `strength` / `max_displacement_frac` defaults are set by
+ an ISE sweep over the reference set — see [`eval/`](eval/README.md).
`precompute_uv.py` builds `face_uv_map.json` at image-build time: the canonical
face model, the landmark→head-vertex correspondence, and the skin UV mapping.
diff --git a/workers/avatar-reconstruction/face_geometry.py b/workers/avatar-reconstruction/face_geometry.py
index b0a1d5a24..8b45832f7 100644
--- a/workers/avatar-reconstruction/face_geometry.py
+++ b/workers/avatar-reconstruction/face_geometry.py
@@ -121,8 +121,8 @@ def morph_head_to_landmarks(
face_map: FaceMap,
detected_landmarks: np.ndarray,
*,
- strength: float = 0.75,
- max_displacement_frac: float = 0.18,
+ strength: float = 0.6,
+ max_displacement_frac: float = 0.45,
falloff: float = 1.6,
) -> np.ndarray:
"""
@@ -137,6 +137,7 @@ def morph_head_to_landmarks(
<1 keeps the result on a plausible face manifold.
max_displacement_frac: clamp per-control displacement to this fraction of
the face scale — rejects landmark/pose outliers.
+ 0.45 ≈ 4.7 cm of travel per control point.
falloff: Gaussian RBF radius as a multiple of the median
control-point spacing. Larger = smoother/broader.
@@ -156,6 +157,20 @@ def morph_head_to_landmarks(
residual = det_aligned - canon # identity deviation (norm units)
# 2. Carry to head units and clamp outliers.
+ #
+ # Defaults (strength 0.6, clamp 0.45) come from an ISE sweep over the 40-face
+ # reference set — `python -m eval.tune_morph`. They cut mean ISE 43% against
+ # the original 0.75/0.18, from 26% to 58% below the texture-only floor, with
+ # no face made worse. The old 0.18 clamp allowed only ~1.9 cm of travel per
+ # control point and was throttling genuine facial variation, not outliers.
+ #
+ # The sweep's own optimum was a looser 0.65 (~6.7 cm), and it is NOT used:
+ # every reference face is a clean frontal portrait, so the benchmark contains
+ # no landmark failures and cannot see what the clamp is for. 6.7 cm exceeds
+ # plausible human facial variation and would pass a mis-detection straight
+ # through to the mesh. 0.45 takes almost all of the measurable gain while
+ # keeping real outlier rejection. Tuning this empirically needs adversarial
+ # samples (blurry, off-angle, occluded, low-light) in the reference set.
disp = residual[idx] * face_map.head_face_scale * float(strength) # (K,3)
clamp = max_displacement_frac * face_map.head_face_scale
mag = np.linalg.norm(disp, axis=1, keepdims=True)
diff --git a/workers/avatar-reconstruction/test_face_geometry.py b/workers/avatar-reconstruction/test_face_geometry.py
index 1dbd29af5..f3da45f51 100644
--- a/workers/avatar-reconstruction/test_face_geometry.py
+++ b/workers/avatar-reconstruction/test_face_geometry.py
@@ -87,16 +87,32 @@ def test_wider_face_widens_head():
def test_outlier_clamped():
- """A single wild landmark must not blow up the mesh (displacement clamp)."""
+ """
+ A single wild landmark must not blow up the mesh, at whatever clamp is in
+ force — including the shipped default, which the ISE sweep may retune.
+
+ The bound is asserted against the clamp actually passed rather than a literal,
+ so retuning `max_displacement_frac` cannot silently turn this into a test of
+ a value nobody ships.
+ """
_, base, _, fmap = _load()
detected = fmap.canonical_norm.copy()
detected[fmap.stable_indices[0]] += np.array([5.0, 5.0, 5.0]) # absurd outlier
- morphed = fg.morph_head_to_landmarks(base, fmap, detected, strength=1.0)
- move = np.linalg.norm(morphed - base, axis=1).max()
- clamp = 0.18 * fmap.head_face_scale
- assert move <= clamp * 1.5 + 1e-6, f"outlier not clamped: max move {move:.4f} vs clamp {clamp:.4f}"
- assert np.isfinite(morphed).all(), "non-finite vertices after morph"
- print(f"ok outlier landmark clamped (max move {move:.4f} ≤ ~{clamp:.4f})")
+
+ import inspect
+ shipped = inspect.signature(fg.morph_head_to_landmarks).parameters["max_displacement_frac"].default
+
+ for frac in (0.18, shipped, 0.65):
+ morphed = fg.morph_head_to_landmarks(
+ base, fmap, detected, strength=1.0, max_displacement_frac=frac
+ )
+ move = np.linalg.norm(morphed - base, axis=1).max()
+ clamp = frac * fmap.head_face_scale
+ assert move <= clamp * 1.5 + 1e-6, (
+ f"outlier not clamped at frac={frac}: max move {move:.4f} vs clamp {clamp:.4f}"
+ )
+ assert np.isfinite(morphed).all(), "non-finite vertices after morph"
+ print(f"ok outlier landmark clamped at every frac (shipped default {shipped})")
def test_roundtrip_through_glb():
diff --git a/workers/garment-forge/garment_glb.py b/workers/garment-forge/garment_glb.py
index 544a3aec8..52a229e26 100644
--- a/workers/garment-forge/garment_glb.py
+++ b/workers/garment-forge/garment_glb.py
@@ -45,10 +45,11 @@ from canonical_bones import (
SPEC_URI = "https://three.ws/specs/garment-manifest-v1"
# SPDX identifiers the catalog accepts (validation rule 6: recognised SPDX,
-# commercial use permitted). Extend deliberately, never guess.
+# commercial use permitted). Kept in exact lockstep with COMMERCIAL_LICENSES
+# in src/garment-catalog.js: publishing anything the runtime consumer would
+# reject is a dead catalog entry.
COMMERCIAL_SPDX = frozenset({
- "CC0-1.0", "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause",
- "CC-BY-4.0", "Unlicense", "Zlib",
+ "CC0-1.0", "CC-BY-4.0", "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause",
})
# A region must carry at least this share of the garment's total skin weight
diff --git a/workers/garment-forge/lib/assemble.mjs b/workers/garment-forge/lib/assemble.mjs
new file mode 100644
index 000000000..9f5e09a2b
--- /dev/null
+++ b/workers/garment-forge/lib/assemble.mjs
@@ -0,0 +1,86 @@
+// Assemble a publishable garment GLB from a generated mesh + the canonical
+// body: fit, skin-transfer, occludes, strip the body, keep the skeleton.
+//
+// The emitted GLB contains the garment mesh skinned to the canonical
+// (mixamorig) skeleton — exactly what specs/GARMENT_MANIFEST.md requires of a
+// `three.ws-canonical-v1` wearable, and what src/avatar-garment.js rebinds
+// onto any humanoid at wear-time.
+
+import { mergeDocuments, prune, unpartition } from '@gltf-transform/functions';
+import {
+ findBodyMesh,
+ fitGarmentToBody,
+ transferSkinWeights,
+ deriveOccludes,
+} from './skin-transfer.mjs';
+
+/**
+ * @param {import('@gltf-transform/core').NodeIO} io
+ * @param {Uint8Array} baseBytes canonical body GLB (parametric-base.glb)
+ * @param {Uint8Array} garmentBytes generated garment GLB (unrigged)
+ * @param {string} slot
+ * @returns {Promise<{ bytes: Uint8Array, occludes: string[], stats: object }>}
+ */
+export async function assembleGarment(io, baseBytes, garmentBytes, slot) {
+ const doc = await io.readBinary(baseBytes);
+ const garmentDoc = await io.readBinary(garmentBytes);
+
+ const bodyNode = findBodyMesh(doc);
+ if (!bodyNode) throw new Error('canonical body GLB has no skinned mesh');
+ const skin = bodyNode.getSkin();
+ // Everything the base ships (body, eyes, teeth, …) gets stripped at the end —
+ // the garment GLB carries skeleton + cloth only. Record the set now, before
+ // the merge adds the garment's meshes.
+ const baseMeshes = new Set(doc.getRoot().listMeshes());
+
+ // Tag garment roots so they are findable after the merge disconnects refs.
+ const gScene = garmentDoc.getRoot().getDefaultScene() || garmentDoc.getRoot().listScenes()[0];
+ const roots = gScene ? [...gScene.listChildren()] : [];
+ if (!roots.length) throw new Error('generated garment GLB has an empty scene');
+ roots.forEach((n, i) => n.setName(`__garment_src_${i}`));
+
+ mergeDocuments(doc, garmentDoc);
+
+ const scene = doc.getRoot().getDefaultScene() || doc.getRoot().listScenes()[0];
+ const mergedRoots = doc
+ .getRoot()
+ .listNodes()
+ .filter((n) => (n.getName() || '').startsWith('__garment_src_'));
+
+ // Collect the garment's mesh-bearing nodes; bake their node transforms into
+ // POSITION is unnecessary — generators emit identity transforms — but their
+ // meshes must be re-hosted on skinned nodes at the scene root.
+ const garmentMeshes = [];
+ const stack = [...mergedRoots];
+ while (stack.length) {
+ const n = stack.pop();
+ if (n.getMesh()) garmentMeshes.push(n.getMesh());
+ stack.push(...n.listChildren());
+ }
+ if (!garmentMeshes.length) throw new Error('generated garment GLB contains no mesh');
+
+ const stats = { meshes: garmentMeshes.length, transferred: 0 };
+ for (const mesh of garmentMeshes) {
+ const fit = fitGarmentToBody(mesh, doc, slot);
+ const { transferred } = transferSkinWeights(mesh, doc, doc);
+ stats.transferred += transferred;
+ stats.fit = fit;
+
+ const node = doc.createNode(`garment:${slot}`).setMesh(mesh).setSkin(skin);
+ scene.addChild(node);
+ }
+
+ const occludes = deriveOccludes(garmentMeshes[0], skin, slot);
+
+ // Strip the body: the garment GLB ships skeleton + cloth, not a person.
+ for (const node of doc.getRoot().listNodes()) {
+ if (baseMeshes.has(node.getMesh())) node.setMesh(null);
+ }
+ for (const root of mergedRoots) {
+ for (const s of doc.getRoot().listScenes()) s.removeChild(root);
+ }
+
+ await doc.transform(unpartition(), prune());
+ const bytes = await io.writeBinary(doc);
+ return { bytes, occludes, stats };
+}
diff --git a/workers/garment-forge/lib/skin-transfer.mjs b/workers/garment-forge/lib/skin-transfer.mjs
new file mode 100644
index 000000000..8bf7ba575
--- /dev/null
+++ b/workers/garment-forge/lib/skin-transfer.mjs
@@ -0,0 +1,340 @@
+// Garment skinning core — fit a generated garment mesh to the canonical body
+// and give it skin weights by proximity transfer.
+//
+// Generated garment meshes arrive unrigged, at arbitrary scale, centred
+// arbitrarily. Auto-riggers are the wrong tool here — they predict skeletons
+// for BODIES. The correct treatment for a garment is the one clothing tools
+// use: place it around the reference body it will be worn on, then copy each
+// garment vertex's skin influence from the nearest point on the body surface.
+// The result deforms exactly like the flesh underneath it, which is the
+// definition of a well-skinned garment.
+//
+// The reference body is the platform's CC0 parametric base
+// (public/avatars/parametric-base.glb, mixamorig 52-bone skeleton — every name
+// canonicalizes via src/glb-canonicalize.js, so the emitted garment satisfies
+// `rig.skeleton: "three.ws-canonical-v1"` in specs/GARMENT_MANIFEST.md).
+//
+// Pure module: operates on @gltf-transform Documents, no HTTP, no GCS — fully
+// unit-testable (tests/garment-forge-skin-transfer.test.js).
+
+import { canonicalizeBoneName } from '../../../src/glb-canonicalize.js';
+import { REGION_BONES, BODY_REGIONS } from '../../../src/garment-taxonomy.js';
+
+/** Which body regions each slot dresses — drives both placement and the
+ * default `occludes` floor. Over-covering is safe; under-covering shows skin. */
+export const SLOT_REGIONS = Object.freeze({
+ top: ['torso', 'upperArms'],
+ outerwear: ['torso', 'upperArms', 'lowerArms'],
+ bottom: ['hips', 'upperLegs'],
+ footwear: ['feet'],
+ hair: ['scalp'],
+ headwear: ['scalp'],
+ glasses: [],
+ accessory: [],
+});
+
+/* ── body analysis ───────────────────────────────────────────────────────── */
+
+/** The body's skinned mesh node + skin (the only skinned mesh in the base). */
+export function findBodyMesh(doc) {
+ for (const node of doc.getRoot().listNodes()) {
+ if (node.getSkin() && node.getMesh()) return node;
+ }
+ return null;
+}
+
+/** joint index → canonical bone name for a skin. */
+function canonicalJointNames(skin) {
+ return skin.listJoints().map((j) => canonicalizeBoneName(j.getName() || '') || '');
+}
+
+/**
+ * Per-region axis-aligned bounds of the body's vertices, assigned by dominant
+ * joint weight. Used to place a garment over the region it dresses.
+ * @returns {Map<string, {min: number[], max: number[]}>}
+ */
+export function regionBounds(bodyDoc) {
+ const node = findBodyMesh(bodyDoc);
+ if (!node) return new Map();
+ const names = canonicalJointNames(node.getSkin());
+ const boneRegion = new Map(); // canonical bone → region
+ for (const [region, bones] of Object.entries(REGION_BONES)) {
+ for (const b of bones) boneRegion.set(b, region);
+ }
+
+ const out = new Map();
+ for (const prim of node.getMesh().listPrimitives()) {
+ const pos = prim.getAttribute('POSITION')?.getArray();
+ const joints = prim.getAttribute('JOINTS_0')?.getArray();
+ const weights = prim.getAttribute('WEIGHTS_0')?.getArray();
+ if (!pos || !joints || !weights) continue;
+ const count = pos.length / 3;
+ for (let v = 0; v < count; v++) {
+ // dominant influence decides the vertex's region
+ let bestC = 0;
+ for (let c = 1; c < 4; c++) {
+ if (weights[v * 4 + c] > weights[v * 4 + bestC]) bestC = c;
+ }
+ const region = boneRegion.get(names[joints[v * 4 + bestC]]);
+ if (!region) continue;
+ let box = out.get(region);
+ if (!box) {
+ box = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] };
+ out.set(region, box);
+ }
+ for (let a = 0; a < 3; a++) {
+ const p = pos[v * 3 + a];
+ if (p < box.min[a]) box.min[a] = p;
+ if (p > box.max[a]) box.max[a] = p;
+ }
+ }
+ }
+ return out;
+}
+
+function unionBounds(boxes) {
+ const out = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] };
+ for (const b of boxes) {
+ for (let a = 0; a < 3; a++) {
+ if (b.min[a] < out.min[a]) out.min[a] = b.min[a];
+ if (b.max[a] > out.max[a]) out.max[a] = b.max[a];
+ }
+ }
+ return out;
+}
+
+function meshBounds(mesh) {
+ const out = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] };
+ for (const prim of mesh.listPrimitives()) {
+ const pos = prim.getAttribute('POSITION')?.getArray();
+ if (!pos) continue;
+ for (let i = 0; i < pos.length; i += 3) {
+ for (let a = 0; a < 3; a++) {
+ const p = pos[i + a];
+ if (p < out.min[a]) out.min[a] = p;
+ if (p > out.max[a]) out.max[a] = p;
+ }
+ }
+ }
+ return out;
+}
+
+/* ── fit ─────────────────────────────────────────────────────────────────── */
+
+/**
+ * Uniformly scale + translate the garment mesh so its bounds sit over the
+ * slot's body regions, with breathing room so cloth wraps outside the body
+ * instead of intersecting it. Mutates POSITION accessors in place (bakes the
+ * transform — the emitted GLB must be correct with an identity node transform,
+ * since glTF ignores skinned-node transforms).
+ *
+ * @returns {{ scale: number, offset: number[] }} applied transform (for logs)
+ */
+export function fitGarmentToBody(garmentMesh, bodyDoc, slot, opts = {}) {
+ const pad = opts.pad ?? 1.06; // garments sit slightly proud of the skin
+ const regions = SLOT_REGIONS[slot]?.length ? SLOT_REGIONS[slot] : ['torso'];
+ const bounds = regionBounds(bodyDoc);
+ const targets = regions.map((r) => bounds.get(r)).filter(Boolean);
+ if (!targets.length) throw new Error(`body has no vertices in regions for slot "${slot}"`);
+ const target = unionBounds(targets);
+ const source = meshBounds(garmentMesh);
+
+ const sizeOf = (b) => [0, 1, 2].map((a) => Math.max(b.max[a] - b.min[a], 1e-6));
+ const tSize = sizeOf(target);
+ const sSize = sizeOf(source);
+ // One uniform scale, chosen so the garment covers the target in every axis
+ // (max ratio, not min — mild oversize beats poking skin).
+ const scale = Math.max(tSize[0] / sSize[0], tSize[1] / sSize[1], tSize[2] / sSize[2]) * pad;
+
+ const centreOf = (b) => [0, 1, 2].map((a) => (b.min[a] + b.max[a]) / 2);
+ const tC = centreOf(target);
+ const sC = centreOf(source);
+ const offset = [0, 1, 2].map((a) => tC[a] - sC[a] * scale);
+
+ for (const prim of garmentMesh.listPrimitives()) {
+ const posAccessor = prim.getAttribute('POSITION');
+ const pos = posAccessor?.getArray();
+ if (!pos) continue;
+ const out = new Float32Array(pos.length);
+ for (let i = 0; i < pos.length; i += 3) {
+ for (let a = 0; a < 3; a++) out[i + a] = pos[i + a] * scale + offset[a];
+ }
+ posAccessor.setArray(out);
+ }
+ return { scale, offset };
+}
+
+/* ── proximity weight transfer ───────────────────────────────────────────── */
+
+/** Spatial hash over the body's vertices for near-neighbour lookup. */
+class VertexGrid {
+ constructor(positions, cellSize) {
+ this.pos = positions;
+ this.cell = cellSize;
+ this.map = new Map();
+ for (let v = 0; v < positions.length / 3; v++) {
+ this.map.get(this._key(
+ positions[v * 3], positions[v * 3 + 1], positions[v * 3 + 2],
+ ))?.push(v) ?? this.map.set(this._key(
+ positions[v * 3], positions[v * 3 + 1], positions[v * 3 + 2],
+ ), [v]);
+ }
+ }
+
+ _key(x, y, z) {
+ return `${Math.floor(x / this.cell)},${Math.floor(y / this.cell)},${Math.floor(z / this.cell)}`;
+ }
+
+ /** Index of the nearest body vertex; expands the search ring until found. */
+ nearest(x, y, z) {
+ const cx = Math.floor(x / this.cell);
+ const cy = Math.floor(y / this.cell);
+ const cz = Math.floor(z / this.cell);
+ for (let ring = 0; ring < 64; ring++) {
+ let best = -1;
+ let bestD = Infinity;
+ for (let dx = -ring; dx <= ring; dx++) {
+ for (let dy = -ring; dy <= ring; dy++) {
+ for (let dz = -ring; dz <= ring; dz++) {
+ if (Math.max(Math.abs(dx), Math.abs(dy), Math.abs(dz)) !== ring) continue;
+ const bucket = this.map.get(`${cx + dx},${cy + dy},${cz + dz}`);
+ if (!bucket) continue;
+ for (const v of bucket) {
+ const ddx = this.pos[v * 3] - x;
+ const ddy = this.pos[v * 3 + 1] - y;
+ const ddz = this.pos[v * 3 + 2] - z;
+ const d = ddx * ddx + ddy * ddy + ddz * ddz;
+ if (d < bestD) { bestD = d; best = v; }
+ }
+ }
+ }
+ }
+ // A hit on ring N can still be beaten by ring N+1 (cell corners), so
+ // confirm with one extra ring before returning.
+ if (best >= 0) {
+ const confirmRing = ring + 1;
+ for (let dx = -confirmRing; dx <= confirmRing; dx++) {
+ for (let dy = -confirmRing; dy <= confirmRing; dy++) {
+ for (let dz = -confirmRing; dz <= confirmRing; dz++) {
+ if (Math.max(Math.abs(dx), Math.abs(dy), Math.abs(dz)) !== confirmRing) continue;
+ const bucket = this.map.get(`${cx + dx},${cy + dy},${cz + dz}`);
+ if (!bucket) continue;
+ for (const v of bucket) {
+ const ddx = this.pos[v * 3] - x;
+ const ddy = this.pos[v * 3 + 1] - y;
+ const ddz = this.pos[v * 3 + 2] - z;
+ const d = ddx * ddx + ddy * ddy + ddz * ddz;
+ if (d < bestD) { bestD = d; best = v; }
+ }
+ }
+ }
+ }
+ return best;
+ }
+ }
+ return -1;
+ }
+}
+
+/**
+ * Give every garment vertex the JOINTS_0/WEIGHTS_0 of its nearest body vertex.
+ *
+ * @param {object} garmentMesh gltf-transform Mesh (already fitted to the body)
+ * @param {object} bodyDoc the canonical body document
+ * @param {object} doc the OUTPUT document that owns garmentMesh (for accessor creation)
+ * @returns {{ transferred: number }}
+ */
+export function transferSkinWeights(garmentMesh, bodyDoc, doc) {
+ const bodyNode = findBodyMesh(bodyDoc);
+ if (!bodyNode) throw new Error('canonical body has no skinned mesh');
+
+ // Flatten the body's vertices + skin attributes into parallel arrays.
+ const bPos = [];
+ const bJoints = [];
+ const bWeights = [];
+ for (const prim of bodyNode.getMesh().listPrimitives()) {
+ const pos = prim.getAttribute('POSITION')?.getArray();
+ const joints = prim.getAttribute('JOINTS_0')?.getArray();
+ const weights = prim.getAttribute('WEIGHTS_0')?.getArray();
+ if (!pos || !joints || !weights) continue;
+ for (let i = 0; i < pos.length; i++) bPos.push(pos[i]);
+ for (let i = 0; i < joints.length; i++) { bJoints.push(joints[i]); bWeights.push(weights[i]); }
+ }
+ if (!bPos.length) throw new Error('canonical body mesh has no skinned vertices');
+
+ const bounds = meshBounds(bodyNode.getMesh());
+ const diag = Math.hypot(
+ bounds.max[0] - bounds.min[0],
+ bounds.max[1] - bounds.min[1],
+ bounds.max[2] - bounds.min[2],
+ );
+ const grid = new VertexGrid(new Float32Array(bPos), Math.max(diag / 40, 1e-4));
+
+ const buffer = doc.getRoot().listBuffers()[0] || doc.createBuffer();
+ let transferred = 0;
+ for (const prim of garmentMesh.listPrimitives()) {
+ const pos = prim.getAttribute('POSITION')?.getArray();
+ if (!pos) continue;
+ const count = pos.length / 3;
+ const outJ = new Uint16Array(count * 4);
+ const outW = new Float32Array(count * 4);
+ for (let v = 0; v < count; v++) {
+ const n = grid.nearest(pos[v * 3], pos[v * 3 + 1], pos[v * 3 + 2]);
+ if (n < 0) continue;
+ for (let c = 0; c < 4; c++) {
+ outJ[v * 4 + c] = bJoints[n * 4 + c];
+ outW[v * 4 + c] = bWeights[n * 4 + c];
+ }
+ transferred++;
+ }
+ prim.setAttribute(
+ 'JOINTS_0',
+ doc.createAccessor().setType('VEC4').setArray(outJ).setBuffer(buffer),
+ );
+ prim.setAttribute(
+ 'WEIGHTS_0',
+ doc.createAccessor().setType('VEC4').setArray(outW).setBuffer(buffer),
+ );
+ }
+ return { transferred };
+}
+
+/* ── occludes derivation ─────────────────────────────────────────────────── */
+
+/**
+ * Which body regions this garment covers, measured from where its transferred
+ * skin weight actually landed. A region counts as covered once it carries at
+ * least `threshold` of the garment's total weight — deliberately low, because
+ * the spec says over-declare (hidden skin is invisible, exposed skin is the
+ * artefact). The slot's own regions are always included as a floor.
+ */
+export function deriveOccludes(garmentMesh, skin, slot, threshold = 0.05) {
+ const names = canonicalJointNames(skin);
+ const regionOf = new Map();
+ for (const [region, bones] of Object.entries(REGION_BONES)) {
+ for (const b of bones) regionOf.set(b, region);
+ }
+
+ const perRegion = new Map();
+ let total = 0;
+ for (const prim of garmentMesh.listPrimitives()) {
+ const joints = prim.getAttribute('JOINTS_0')?.getArray();
+ const weights = prim.getAttribute('WEIGHTS_0')?.getArray();
+ if (!joints || !weights) continue;
+ for (let i = 0; i < weights.length; i++) {
+ const w = weights[i];
+ if (w <= 0) continue;
+ total += w;
+ const region = regionOf.get(names[joints[i]]);
+ if (region) perRegion.set(region, (perRegion.get(region) || 0) + w);
+ }
+ }
+
+ const out = new Set(SLOT_REGIONS[slot] || []);
+ if (total > 0) {
+ for (const [region, w] of perRegion) {
+ if (w / total >= threshold) out.add(region);
+ }
+ }
+ return BODY_REGIONS.filter((r) => out.has(r));
+}
diff --git a/workers/garment-forge/main.py b/workers/garment-forge/main.py
index b321f711b..78b3bea59 100644
--- a/workers/garment-forge/main.py
+++ b/workers/garment-forge/main.py
@@ -28,7 +28,10 @@ different instances still see one record, and the service can scale to zero.
Environment variables:
API_KEY shared bearer secret (avatar-reconstruction-key), used both
to authenticate callers and to call the other workers
- GCS_BUCKET bucket holding garments/** (three-ws-model-weights)
+ GCS_BUCKET job records + rig staging (three-ws-avatar-reconstructions,
+ the same worker-artifact bucket the rest of the fleet uses)
+ PUBLISH_BUCKET public catalog bucket holding garments/** (three-ws-garments,
+ the bucket src/garment-catalog.js reads)
MESH_WORKER_URLS comma-separated /infer-contract mesh workers, priority order
RIG_URL model-rig base URL
REFBODY_PATH reference body GLB baked into the image
@@ -68,6 +71,7 @@ log = logging.getLogger("garment-forge")
API_KEY = os.environ["API_KEY"]
GCS_BUCKET = os.environ["GCS_BUCKET"]
+PUBLISH_BUCKET = os.environ["PUBLISH_BUCKET"]
MESH_WORKER_URLS = [u.strip().rstrip("/") for u in
os.environ["MESH_WORKER_URLS"].split(",") if u.strip()]
RIG_URL = os.environ["RIG_URL"].rstrip("/")
@@ -75,14 +79,15 @@ REFBODY_PATH = os.environ.get("REFBODY_PATH", "/app/assets/refbody.glb")
GARMENT_YAW_DEG = float(os.environ.get("GARMENT_YAW_DEG", "0"))
MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))
-_bucket: Optional[storage.Bucket] = None
+_bucket: Optional[storage.Bucket] = None # jobs + rig staging
+_publish_bucket: Optional[storage.Bucket] = None # public garment catalog
_sem: Optional[asyncio.Semaphore] = None
_refbody: Optional[bytes] = None
_jobs: dict[str, dict] = {}
def _job_blob(job_id: str):
- return _bucket.blob(f"garments/jobs/{job_id}.json")
+ return _bucket.blob(f"garment-jobs/{job_id}.json")
async def _update_job(job_id: str, **fields) -> dict:
@@ -99,8 +104,10 @@ async def _update_job(job_id: str, **fields) -> dict:
@asynccontextmanager
async def lifespan(app: FastAPI):
- global _bucket, _sem, _refbody
- _bucket = storage.Client().bucket(GCS_BUCKET)
+ global _bucket, _publish_bucket, _sem, _refbody
+ client = storage.Client()
+ _bucket = client.bucket(GCS_BUCKET)
+ _publish_bucket = client.bucket(PUBLISH_BUCKET)
_sem = asyncio.Semaphore(MAX_CONCURRENT)
with open(REFBODY_PATH, "rb") as fh:
_refbody = fh.read()
@@ -145,8 +152,8 @@ def _run_stages(job_id: str, prompt: str, slot: str, tier: str,
bones = garment_glb.weighted_bones(stats["bone_mass"], stats["total_mass"])
garment_id = f"{garment_glb.slugify(prompt)}-{job_id[:6]}"
- version = pipeline.next_version(_bucket, slot, garment_id)
- base = (f"https://storage.googleapis.com/{_bucket.name}/garments/"
+ version = pipeline.next_version(_publish_bucket, slot, garment_id)
+ base = (f"https://storage.googleapis.com/{_publish_bucket.name}/garments/"
f"{slot}/{garment_id}/v{version}")
manifest = garment_glb.build_manifest(
garment_id=garment_id,
@@ -169,7 +176,7 @@ def _run_stages(job_id: str, prompt: str, slot: str, tier: str,
progress("publish")
thumb = pipeline.make_thumbnail(image_bytes)
- urls = pipeline.publish(_bucket, slot, garment_id, version,
+ urls = pipeline.publish(_publish_bucket, slot, garment_id, version,
garment_bytes, manifest, thumb)
return {
**urls,