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: barycentric garment skin transfer + baked body-region occlusion mask

nirholas856a12ef9ca1
diff --git a/docs/avatar-wardrobe.md b/docs/avatar-wardrobe.md
index 0c3cbfa4d..e63b5df4b 100644
--- a/docs/avatar-wardrobe.md
+++ b/docs/avatar-wardrobe.md
@@ -50,6 +50,7 @@ A garment with no skin at all (hat, glasses) is parented to a single joint
| Catalog loader | [`src/garment-catalog.js`](../src/garment-catalog.js) | Fetch + validate manifests; drops anything malformed or unlicensed |
| Closet UI + controller | [`src/garment-closet.js`](../src/garment-closet.js) | Racks/tiles in the editor, attach/detach queue, appearance sync |
| Editor wiring | [`src/avatar-edit.js`](../src/avatar-edit.js) | Hydrate on load, persist `appearance.garments`, reset/save |
+| Region mask (pixel-exact occlusion) | Baker [`scripts/build-body-region-mask.mjs`](../scripts/build-body-region-mask.mjs) → `public/avatars/parametric-base.regions.png`, sampler [`src/garment-region-mask.js`](../src/garment-region-mask.js) | On the parametric base, worn garments cut the skin via a baked UV mask (alphaMap) instead of triangle culling; any other body falls back to bone-cull |
| Server schema | [`api/_lib/validate.js`](../api/_lib/validate.js) | `appearance.garments` — one garment per slot, catalog-shaped refs |
| Bake pass | [`api/_lib/bake-garments.js`](../api/_lib/bake-garments.js) | Same rebind on the @gltf-transform document, so exports are dressed |
| Manifest contract | [`specs/GARMENT_MANIFEST.md`](../specs/GARMENT_MANIFEST.md) | What a wearable must declare to enter the catalog |
diff --git a/public/avatars/parametric-base.regions.png b/public/avatars/parametric-base.regions.png
new file mode 100644
index 000000000..ed63a5116
Binary files /dev/null and b/public/avatars/parametric-base.regions.png differ
diff --git a/scripts/build-body-region-mask.mjs b/scripts/build-body-region-mask.mjs
new file mode 100644
index 000000000..cf57660ee
--- /dev/null
+++ b/scripts/build-body-region-mask.mjs
@@ -0,0 +1,128 @@
+// Bake the body-region occlusion mask for the canonical parametric base.
+//
+// node scripts/build-body-region-mask.mjs
+//
+// Output: public/avatars/parametric-base.regions.png — a 1024² grayscale map
+// in the body's UV space where each pixel holds the REGION_MASK_VALUES code of
+// the body region that owns that patch of skin (0 = unassigned).
+//
+// Why: the additive wardrobe hides the body under a worn garment. The
+// fallback is bone-region triangle culling (works on any avatar, but leaves
+// stair-step seams on low-poly bodies). With this mask, the closet drives the
+// skin material's alphaMap instead and the cut is pixel-exact at the garment
+// edge. See applySkinOcclusion() in src/avatar-garment.js and the sampler in
+// src/garment-region-mask.js.
+//
+// Region assignment: a vertex belongs to the region of its dominant joint
+// (REGION_BONES); each UV triangle is rasterized with per-pixel nearest-corner
+// region (barycentric max), which keeps region boundaries on edge midlines.
+
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { MeshoptDecoder } from 'meshoptimizer';
+import sharp from 'sharp';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+import { canonicalizeBoneName } from '../src/glb-canonicalize.js';
+import { REGION_BONES, REGION_MASK_VALUES } from '../src/garment-taxonomy.js';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const GLB = path.join(ROOT, 'public/avatars/parametric-base.glb');
+const OUT = path.join(ROOT, 'public/avatars/parametric-base.regions.png');
+const SIZE = 1024;
+
+await MeshoptDecoder.ready;
+const io = new NodeIO()
+ .registerExtensions(ALL_EXTENSIONS)
+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
+const doc = await io.read(GLB);
+
+// The body: the skinned mesh with the most vertices (Eyes/Teeth/Tongue are
+// never occluded by garments and stay out of the mask).
+let body = null;
+for (const node of doc.getRoot().listNodes()) {
+ if (!node.getSkin() || !node.getMesh()) continue;
+ const count = node.getMesh().listPrimitives()
+ .reduce((n, p) => n + (p.getAttribute('POSITION')?.getCount() || 0), 0);
+ if (!body || count > body.count) body = { node, count };
+}
+if (!body) throw new Error('no skinned mesh in the base GLB');
+
+const skin = body.node.getSkin();
+const jointRegion = skin.listJoints().map((j) => {
+ const canonical = canonicalizeBoneName(j.getName() || '');
+ for (const [region, bones] of Object.entries(REGION_BONES)) {
+ if (bones.includes(canonical)) return REGION_MASK_VALUES[region];
+ }
+ return 0;
+});
+
+const mask = new Uint8Array(SIZE * SIZE); // 0 = unassigned
+
+for (const prim of body.node.getMesh().listPrimitives()) {
+ const uv = prim.getAttribute('TEXCOORD_0')?.getArray();
+ const joints = prim.getAttribute('JOINTS_0')?.getArray();
+ const weights = prim.getAttribute('WEIGHTS_0')?.getArray();
+ const index = prim.getIndices()?.getArray();
+ if (!uv || !joints || !weights || !index) continue;
+
+ // Per-vertex region: the region of the dominant joint.
+ const vertCount = uv.length / 2;
+ const vertRegion = new Uint8Array(vertCount);
+ for (let v = 0; v < vertCount; v++) {
+ let bestC = 0;
+ for (let c = 1; c < 4; c++) {
+ if (weights[v * 4 + c] > weights[v * 4 + bestC]) bestC = c;
+ }
+ vertRegion[v] = jointRegion[joints[v * 4 + bestC]] || 0;
+ }
+
+ // Rasterize each UV triangle; per pixel take the corner with max barycentric.
+ for (let t = 0; t < index.length; t += 3) {
+ const i0 = index[t];
+ const i1 = index[t + 1];
+ const i2 = index[t + 2];
+ const x0 = uv[i0 * 2] * SIZE, y0 = uv[i0 * 2 + 1] * SIZE;
+ const x1 = uv[i1 * 2] * SIZE, y1 = uv[i1 * 2 + 1] * SIZE;
+ const x2 = uv[i2 * 2] * SIZE, y2 = uv[i2 * 2 + 1] * SIZE;
+ const minX = Math.max(0, Math.floor(Math.min(x0, x1, x2)) - 1);
+ const maxX = Math.min(SIZE - 1, Math.ceil(Math.max(x0, x1, x2)) + 1);
+ const minY = Math.max(0, Math.floor(Math.min(y0, y1, y2)) - 1);
+ const maxY = Math.min(SIZE - 1, Math.ceil(Math.max(y0, y1, y2)) + 1);
+ const area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);
+ if (Math.abs(area) < 1e-9) continue;
+ for (let py = minY; py <= maxY; py++) {
+ for (let px = minX; px <= maxX; px++) {
+ const cx = px + 0.5, cy = py + 0.5;
+ const w0 = ((x1 - cx) * (y2 - cy) - (x2 - cx) * (y1 - cy)) / area;
+ const w1 = ((x2 - cx) * (y0 - cy) - (x0 - cx) * (y2 - cy)) / area;
+ const w2 = 1 - w0 - w1;
+ // Half-pixel tolerance keeps seams covered at UV island borders.
+ const eps = -0.02;
+ if (w0 < eps || w1 < eps || w2 < eps) continue;
+ const corner = w0 >= w1 && w0 >= w2 ? i0 : w1 >= w2 ? i1 : i2;
+ mask[py * SIZE + px] = vertRegion[corner];
+ }
+ }
+ }
+}
+
+const assigned = mask.reduce((n, v) => n + (v ? 1 : 0), 0);
+if (assigned < SIZE * SIZE * 0.05) {
+ throw new Error(`mask nearly empty (${assigned} px) — UV or weight read is broken`);
+}
+
+await sharp(Buffer.from(mask), { raw: { width: SIZE, height: SIZE, channels: 1 } })
+ // PNG must stay lossless and unfiltered-friendly; grayscale 8-bit is exact.
+ .png({ compressionLevel: 9 })
+ .toFile(OUT);
+
+const perRegion = {};
+for (const v of mask) {
+ if (!v) continue;
+ perRegion[v] = (perRegion[v] || 0) + 1;
+}
+console.log(`wrote ${path.relative(ROOT, OUT)} — ${assigned} px assigned`);
+for (const [region, value] of Object.entries(REGION_MASK_VALUES)) {
+ console.log(` ${region.padEnd(10)} code ${String(value).padStart(3)} ${perRegion[value] || 0} px`);
+}
diff --git a/src/avatar-edit.js b/src/avatar-edit.js
index 1329ba122..cc8647848 100644
--- a/src/avatar-edit.js
+++ b/src/avatar-edit.js
@@ -232,9 +232,15 @@ async function bootScene() {
// Additive wardrobe: re-attach saved catalog garments onto the live
// skeleton. Unknown/retired garments degrade to "not worn" inside
// hydrate rather than failing the whole boot.
+ const baseUrl = avatar.base_model_url || avatar.model_url || '';
closet = new GarmentCloset({
getRoot: () => scene?.root || null,
getWorking: () => workingAppearance,
+ // The parametric base ships a baked UV region mask, giving worn
+ // garments pixel-exact skin occlusion. Other bodies use bone-cull.
+ regionMaskUrl: baseUrl.includes('parametric-base')
+ ? '/avatars/parametric-base.regions.png'
+ : null,
onDirty: () => updateDirtyState(),
onChanged: () => renderChips(),
});
diff --git a/src/garment-closet.js b/src/garment-closet.js
index 1ec7ebeed..20893f566 100644
--- a/src/garment-closet.js
+++ b/src/garment-closet.js
@@ -42,12 +42,16 @@ export class GarmentCloset {
* @param {() => object} opts.getWorking workingAppearance accessor — a
* getter (not a reference) because the editor REASSIGNS the working
* object on load/save/reset; a captured reference would go stale.
+ * @param {string} [opts.regionMaskUrl] baked body-region mask PNG for
+ * this avatar's base body (pixel-exact occlusion; bone-cull otherwise)
* @param {() => void} [opts.onDirty]
* @param {() => void} [opts.onChanged] re-render hook (state text, chips)
*/
- constructor({ getRoot, getWorking, onDirty, onChanged }) {
+ constructor({ getRoot, getWorking, regionMaskUrl, onDirty, onChanged }) {
this.getRoot = getRoot;
this.getWorking = getWorking;
+ this.regionMaskUrl = regionMaskUrl || null;
+ this._alphaMapped = null; // material we last set an alphaMap on
this.onDirty = onDirty || (() => {});
this.onChanged = onChanged || (() => {});
// slot → { manifest, result } for what is live in the scene right now
@@ -184,11 +188,52 @@ export class GarmentCloset {
if (!root) return;
const body = findAvatarSkeleton(root);
if (body?.mesh?.geometry) restoreSkin(body.mesh.geometry);
+ if (this._alphaMapped) {
+ this._alphaMapped.alphaMap = null;
+ this._alphaMapped.alphaTest = 0;
+ this._alphaMapped.needsUpdate = true;
+ this._alphaMapped = null;
+ }
const regions = new Set();
for (const { manifest } of this._attached.values()) {
for (const r of manifest.occludes || []) regions.add(r);
}
- if (regions.size) applySkinOcclusion(root, [...regions]);
+ if (!regions.size) return;
+
+ if (this.regionMaskUrl) {
+ // Pixel-exact path: baked UV mask drives the skin's alphaMap. Async
+ // (mask + three load once); the cull below is NOT run first so the
+ // mesh never double-hides — on mask failure we fall through to it.
+ this._applyMaskOcclusion(root, body, [...regions]).catch((err) => {
+ log('garment-closet', `mask occlusion failed, falling back to bone-cull: ${err?.message || err}`);
+ applySkinOcclusion(root, [...regions]);
+ });
+ return;
+ }
+ applySkinOcclusion(root, [...regions]);
+ }
+
+ async _applyMaskOcclusion(root, body, regions) {
+ const [{ loadRegionMask, maskToAlphaRGBA }, THREE] = await Promise.all([
+ import('./garment-region-mask.js'),
+ import('three'),
+ ]);
+ const mask = await loadRegionMask(this.regionMaskUrl);
+ const material = Array.isArray(body.mesh.material) ? body.mesh.material[0] : body.mesh.material;
+ if (!material) throw new Error('body mesh has no material');
+
+ const rgba = maskToAlphaRGBA(mask.data, regions);
+ const texture = new THREE.DataTexture(rgba, mask.width, mask.height, THREE.RGBAFormat);
+ // glTF UV convention (v down, flipY=false) — matches how the mask was
+ // rasterized row 0 = v 0, and how GLTFLoader configures its textures.
+ texture.flipY = false;
+ texture.needsUpdate = true;
+
+ material.alphaMap = texture;
+ material.alphaTest = 0.5;
+ material.transparent = false; // alphaTest cuts; no blend cost
+ material.needsUpdate = true;
+ this._alphaMapped = material;
}
async _fetchModel(manifest) {
diff --git a/src/garment-region-mask.js b/src/garment-region-mask.js
new file mode 100644
index 000000000..d8976681a
--- /dev/null
+++ b/src/garment-region-mask.js
@@ -0,0 +1,84 @@
+// Body-region occlusion mask — client sampler.
+//
+// scripts/build-body-region-mask.mjs bakes parametric-base.regions.png: a
+// grayscale map in body-UV space where each pixel carries a REGION_MASK_VALUES
+// code. This module turns that map plus a set of occluded regions into the
+// RGBA pixels for a THREE alphaMap (green channel is what three.js samples),
+// giving pixel-exact skin cut-outs under worn garments instead of the
+// triangle-level bone-cull fallback.
+//
+// Pure data module — no three.js, no DOM in the transform itself — so the
+// decode logic is unit-testable in Node. Only loadRegionMask touches browser
+// APIs (Image + canvas).
+
+import { BODY_REGIONS, REGION_MASK_VALUES } from './garment-taxonomy.js';
+
+const CODE_STEP = 24; // spacing chosen in REGION_MASK_VALUES
+
+/** Region name for a mask pixel code, tolerant of ±11 resample error. 0/none → null. */
+export function decodeRegionCode(code) {
+ if (!code) return null;
+ const idx = Math.round(code / CODE_STEP) - 1;
+ if (idx < 0 || idx >= BODY_REGIONS.length) return null;
+ const region = BODY_REGIONS[idx];
+ return Math.abs(REGION_MASK_VALUES[region] - code) <= CODE_STEP / 2 ? region : null;
+}
+
+/**
+ * Build RGBA pixels for an alphaMap that hides `regions`.
+ * Green channel (three.js's alphaMap source) is 0 where the pixel's region is
+ * occluded, 255 elsewhere — including unassigned pixels, which must stay
+ * visible (they are UV gutter, not skin).
+ *
+ * @param {Uint8Array|Uint8ClampedArray} mask single-channel region codes
+ * @param {string[]} regions regions to hide
+ * @returns {Uint8Array} RGBA, mask.length * 4
+ */
+export function maskToAlphaRGBA(mask, regions) {
+ const hide = new Set(regions);
+ // Precompute code → visible for all 256 values; the hot loop is then a
+ // single table lookup per pixel.
+ const visible = new Uint8Array(256).fill(255);
+ for (let code = 1; code < 256; code++) {
+ const region = decodeRegionCode(code);
+ if (region && hide.has(region)) visible[code] = 0;
+ }
+ const out = new Uint8Array(mask.length * 4);
+ for (let i = 0; i < mask.length; i++) {
+ const a = visible[mask[i]];
+ out[i * 4] = a;
+ out[i * 4 + 1] = a; // green — the channel three.js reads
+ out[i * 4 + 2] = a;
+ out[i * 4 + 3] = 255;
+ }
+ return out;
+}
+
+// One decode per URL per session.
+const _maskCache = new Map();
+
+/**
+ * Fetch + decode a region-mask PNG into { data, width, height } (single
+ * channel — red of the decoded image, which for a grayscale PNG is the code).
+ * Browser-only (Image + canvas); callers in Node use the PNG via sharp.
+ */
+export function loadRegionMask(url) {
+ if (_maskCache.has(url)) return _maskCache.get(url);
+ const p = (async () => {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`region mask fetch failed: ${res.status}`);
+ const bitmap = await createImageBitmap(await res.blob());
+ const canvas = typeof OffscreenCanvas !== 'undefined'
+ ? new OffscreenCanvas(bitmap.width, bitmap.height)
+ : Object.assign(document.createElement('canvas'), { width: bitmap.width, height: bitmap.height });
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ ctx.drawImage(bitmap, 0, 0);
+ const { data } = ctx.getImageData(0, 0, bitmap.width, bitmap.height);
+ const mask = new Uint8Array(bitmap.width * bitmap.height);
+ for (let i = 0; i < mask.length; i++) mask[i] = data[i * 4]; // red = gray code
+ return { data: mask, width: bitmap.width, height: bitmap.height };
+ })();
+ p.catch(() => _maskCache.delete(url));
+ _maskCache.set(url, p);
+ return p;
+}
diff --git a/src/garment-taxonomy.js b/src/garment-taxonomy.js
index ee3c3fdf9..123d15731 100644
--- a/src/garment-taxonomy.js
+++ b/src/garment-taxonomy.js
@@ -36,3 +36,12 @@ export const REGION_BONES = Object.freeze({
/** 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;
+
+/** Pixel codes for the baked body-region occlusion mask
+ * (scripts/build-body-region-mask.mjs → parametric-base.regions.png).
+ * Spread values (not 1..10) so a resampled/filtered read still snaps to the
+ * right region: codes are 24 apart, so up to ±11 of interpolation error is
+ * recoverable by nearest-code matching. 0 = unassigned. */
+export const REGION_MASK_VALUES = Object.freeze(
+ Object.fromEntries(BODY_REGIONS.map((region, i) => [region, (i + 1) * 24])),
+);
diff --git a/tests/garment-forge-skin-transfer.test.js b/tests/garment-forge-skin-transfer.test.js
index 0956923bf..962113fe3 100644
--- a/tests/garment-forge-skin-transfer.test.js
+++ b/tests/garment-forge-skin-transfer.test.js
@@ -121,6 +121,55 @@ describe('fit + transfer on the real body', () => {
}
});
+ it('interpolates weights across the body surface instead of snapping to one vertex', async () => {
+ // A synthetic body: one triangle whose corners are fully weighted to
+ // three DIFFERENT joints. A garment vertex hovering over the triangle's
+ // centre must receive a ~equal blend of all three — a nearest-vertex
+ // snap would give it exactly one.
+ const { Document } = await import('@gltf-transform/core');
+ const bodyDoc = new Document();
+ const buffer = bodyDoc.createBuffer();
+ const scene = bodyDoc.createScene('s');
+ bodyDoc.getRoot().setDefaultScene(scene);
+ const j0 = bodyDoc.createNode('Hips');
+ const j1 = bodyDoc.createNode('Spine');
+ const j2 = bodyDoc.createNode('Head');
+ j0.addChild(j1); j1.addChild(j2); scene.addChild(j0);
+ const ibm = new Float32Array(3 * 16);
+ for (let i = 0; i < 3; i++) ibm.set([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], i * 16);
+ const skin = bodyDoc.createSkin('skin')
+ .setInverseBindMatrices(bodyDoc.createAccessor().setType('MAT4').setArray(ibm).setBuffer(buffer));
+ skin.addJoint(j0); skin.addJoint(j1); skin.addJoint(j2);
+ const prim = bodyDoc.createPrimitive()
+ .setAttribute('POSITION', bodyDoc.createAccessor().setType('VEC3')
+ .setArray(new Float32Array([0,0,0, 1,0,0, 0,1,0])).setBuffer(buffer))
+ .setAttribute('JOINTS_0', bodyDoc.createAccessor().setType('VEC4')
+ .setArray(new Uint16Array([0,0,0,0, 1,0,0,0, 2,0,0,0])).setBuffer(buffer))
+ .setAttribute('WEIGHTS_0', bodyDoc.createAccessor().setType('VEC4')
+ .setArray(new Float32Array([1,0,0,0, 1,0,0,0, 1,0,0,0])).setBuffer(buffer))
+ .setIndices(bodyDoc.createAccessor().setType('SCALAR')
+ .setArray(new Uint16Array([0, 1, 2])).setBuffer(buffer));
+ scene.addChild(bodyDoc.createNode('body').setMesh(bodyDoc.createMesh('m').addPrimitive(prim)).setSkin(skin));
+
+ // Garment: a single unindexed vertex above the triangle's centroid.
+ const gDoc = new Document();
+ const gBuf = gDoc.createBuffer();
+ const gPrim = gDoc.createPrimitive()
+ .setAttribute('POSITION', gDoc.createAccessor().setType('VEC3')
+ .setArray(new Float32Array([1 / 3, 1 / 3, 0.05])).setBuffer(gBuf));
+ const gMesh = gDoc.createMesh('g').addPrimitive(gPrim);
+
+ transferSkinWeights(gMesh, bodyDoc, gDoc);
+ const w = gMesh.listPrimitives()[0].getAttribute('WEIGHTS_0').getArray();
+ const j = gMesh.listPrimitives()[0].getAttribute('JOINTS_0').getArray();
+ const byJoint = new Map();
+ for (let c = 0; c < 4; c++) byJoint.set(j[c], (byJoint.get(j[c]) || 0) + w[c]);
+ // All three joints present, each near 1/3 — the barycentric signature.
+ expect(byJoint.get(0)).toBeGreaterThan(0.2);
+ expect(byJoint.get(1)).toBeGreaterThan(0.2);
+ expect(byJoint.get(2)).toBeGreaterThan(0.2);
+ });
+
it('derives occludes that include the slot floor', async () => {
const bodyDoc = await io.readBinary(baseBytes);
const { doc, mesh } = buildTubeDoc();
diff --git a/tests/garment-region-mask.test.js b/tests/garment-region-mask.test.js
new file mode 100644
index 000000000..96db5d80c
--- /dev/null
+++ b/tests/garment-region-mask.test.js
@@ -0,0 +1,69 @@
+/**
+ * Body-region mask sampler — src/garment-region-mask.js pure logic, plus a
+ * pixel-level round-trip against the REAL baked mask
+ * (public/avatars/parametric-base.regions.png) so a regenerated mask that
+ * drifts from REGION_MASK_VALUES fails here, not in a user's editor.
+ */
+
+import { readFile } from 'node:fs/promises';
+import { describe, it, expect } from 'vitest';
+import sharp from 'sharp';
+import { decodeRegionCode, maskToAlphaRGBA } from '../src/garment-region-mask.js';
+import { BODY_REGIONS, REGION_MASK_VALUES } from '../src/garment-taxonomy.js';
+
+describe('decodeRegionCode', () => {
+ it('decodes every canonical code', () => {
+ for (const region of BODY_REGIONS) {
+ expect(decodeRegionCode(REGION_MASK_VALUES[region])).toBe(region);
+ }
+ });
+
+ it('tolerates resample error up to half the code step', () => {
+ expect(decodeRegionCode(REGION_MASK_VALUES.torso + 11)).toBe('torso');
+ expect(decodeRegionCode(REGION_MASK_VALUES.torso - 11)).toBe('torso');
+ });
+
+ it('rejects 0 and out-of-range codes', () => {
+ expect(decodeRegionCode(0)).toBe(null);
+ expect(decodeRegionCode(255)).toBe(null);
+ });
+});
+
+describe('maskToAlphaRGBA', () => {
+ it('zeroes only occluded regions; unassigned pixels stay visible', () => {
+ const mask = new Uint8Array([
+ 0, // UV gutter → visible
+ REGION_MASK_VALUES.torso, // occluded → hidden
+ REGION_MASK_VALUES.scalp, // not occluded → visible
+ ]);
+ const rgba = maskToAlphaRGBA(mask, ['torso']);
+ // green channel is what three.js samples for alphaMap
+ expect(rgba[0 * 4 + 1]).toBe(255);
+ expect(rgba[1 * 4 + 1]).toBe(0);
+ expect(rgba[2 * 4 + 1]).toBe(255);
+ });
+});
+
+describe('the baked mask on disk', () => {
+ it('round-trips: every non-zero pixel decodes to a canonical region', async () => {
+ const png = await readFile(new URL('../public/avatars/parametric-base.regions.png', import.meta.url));
+ const { data, info } = await sharp(png).raw().toBuffer({ resolveWithObject: true });
+ expect(info.width).toBe(1024);
+
+ const channel = info.channels; // grayscale may decode as 1 or 3 channels
+ const counts = new Map();
+ let bad = 0;
+ for (let i = 0; i < info.width * info.height; i++) {
+ const code = data[i * channel];
+ if (!code) continue;
+ const region = decodeRegionCode(code);
+ if (!region) { bad++; continue; }
+ counts.set(region, (counts.get(region) || 0) + 1);
+ }
+ expect(bad).toBe(0);
+ // Every region the taxonomy defines is present on the body.
+ for (const region of BODY_REGIONS) {
+ expect(counts.get(region), `region ${region} absent from baked mask`).toBeGreaterThan(1000);
+ }
+ });
+});
diff --git a/workers/garment-forge/lib/skin-transfer.mjs b/workers/garment-forge/lib/skin-transfer.mjs
index 8bf7ba575..6355af56c 100644
--- a/workers/garment-forge/lib/skin-transfer.mjs
+++ b/workers/garment-forge/lib/skin-transfer.mjs
@@ -236,8 +236,65 @@ class VertexGrid {
}
}
+/** Closest point on triangle (a,b,c) to p — Ericson, Real-Time Collision
+ * Detection §5.1.5 — returned as clamped barycentric (u,v,w) for a,b,c. */
+function closestPointBary(px, py, pz, a, b, c) {
+ const abx = b[0] - a[0], aby = b[1] - a[1], abz = b[2] - a[2];
+ const acx = c[0] - a[0], acy = c[1] - a[1], acz = c[2] - a[2];
+ const apx = px - a[0], apy = py - a[1], apz = pz - a[2];
+ const d1 = abx * apx + aby * apy + abz * apz;
+ const d2 = acx * apx + acy * apy + acz * apz;
+ if (d1 <= 0 && d2 <= 0) return [1, 0, 0];
+ const bpx = px - b[0], bpy = py - b[1], bpz = pz - b[2];
+ const d3 = abx * bpx + aby * bpy + abz * bpz;
+ const d4 = acx * bpx + acy * bpy + acz * bpz;
+ if (d3 >= 0 && d4 <= d3) return [0, 1, 0];
+ const vc = d1 * d4 - d3 * d2;
+ if (vc <= 0 && d1 >= 0 && d3 <= 0) {
+ const t = d1 / (d1 - d3);
+ return [1 - t, t, 0];
+ }
+ const cpx = px - c[0], cpy = py - c[1], cpz = pz - c[2];
+ const d5 = abx * cpx + aby * cpy + abz * cpz;
+ const d6 = acx * cpx + acy * cpy + acz * cpz;
+ if (d6 >= 0 && d5 <= d6) return [0, 0, 1];
+ const vb = d5 * d2 - d1 * d6;
+ if (vb <= 0 && d2 >= 0 && d6 <= 0) {
+ const t = d2 / (d2 - d6);
+ return [1 - t, 0, t];
+ }
+ const va = d3 * d6 - d5 * d4;
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
+ const t = (d4 - d3) / ((d4 - d3) + (d5 - d6));
+ return [0, 1 - t, t];
+ }
+ const denom = 1 / (va + vb + vc);
+ const v = vb * denom;
+ const w = vc * denom;
+ return [1 - v - w, v, w];
+}
+
+/** Reduce an influence Map(joint → weight) to the top-4, renormalised. */
+function top4(influences, outJ, outW, offset) {
+ const entries = [...influences.entries()].sort((x, y) => y[1] - x[1]).slice(0, 4);
+ let sum = 0;
+ for (const [, w] of entries) sum += w;
+ for (let c = 0; c < 4; c++) {
+ outJ[offset + c] = entries[c] ? entries[c][0] : 0;
+ outW[offset + c] = entries[c] && sum > 0 ? entries[c][1] / sum : 0;
+ }
+}
+
/**
- * Give every garment vertex the JOINTS_0/WEIGHTS_0 of its nearest body vertex.
+ * Give every garment vertex skin influences interpolated from the nearest
+ * point on the body SURFACE (closest triangle, clamped barycentric blend of
+ * its three corners), then smooth once over the garment's own topology.
+ *
+ * Surface interpolation is what removes the candy-wrapper pinch a plain
+ * nearest-VERTEX snap produces at armpits and shoulders: a garment vertex
+ * midway between two body vertices gets the midway weights, not a coin flip.
+ * The smoothing pass then guarantees neighbouring cloth vertices never carry
+ * discontinuous influences, which is what shows up as creasing under motion.
*
* @param {object} garmentMesh gltf-transform Mesh (already fitted to the body)
* @param {object} bodyDoc the canonical body document
@@ -248,17 +305,25 @@ 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.
+ // Flatten body vertices + skin attributes + triangles into parallel arrays.
const bPos = [];
const bJoints = [];
const bWeights = [];
+ const bTris = [];
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;
+ const base = bPos.length / 3;
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]); }
+ const index = prim.getIndices()?.getArray();
+ if (index) {
+ for (let i = 0; i < index.length; i++) bTris.push(base + index[i]);
+ } else {
+ for (let v = 0; v < pos.length / 3; v++) bTris.push(base + v);
+ }
}
if (!bPos.length) throw new Error('canonical body mesh has no skinned vertices');
@@ -268,25 +333,121 @@ export function transferSkinWeights(garmentMesh, bodyDoc, doc) {
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 cell = Math.max(diag / 40, 1e-4);
+
+ // Grid over triangle CENTROIDS. A centroid hit on ring N can hide a closer
+ // surface point on ring N+1, so nearestTri scans two confirm rings past the
+ // first non-empty one before answering.
+ const triCount = bTris.length / 3;
+ const centroids = new Float32Array(triCount * 3);
+ for (let t = 0; t < triCount; t++) {
+ for (let a = 0; a < 3; a++) {
+ centroids[t * 3 + a] = (
+ bPos[bTris[t * 3] * 3 + a] + bPos[bTris[t * 3 + 1] * 3 + a] + bPos[bTris[t * 3 + 2] * 3 + a]
+ ) / 3;
+ }
+ }
+ const grid = new VertexGrid(centroids, cell);
+
+ const corner = (t, k) => {
+ const vi = bTris[t * 3 + k];
+ return [bPos[vi * 3], bPos[vi * 3 + 1], bPos[vi * 3 + 2]];
+ };
+
+ /** Nearest surface point: best clamped-barycentric hit over candidate tris. */
+ const nearestSurface = (x, y, z) => {
+ const seed = grid.nearest(x, y, z);
+ if (seed < 0) return null;
+ // Candidate set: every triangle whose centroid lies within the ring that
+ // produced the seed plus two rings — cheap because rings are tiny.
+ const cx = Math.floor(x / cell), cy = Math.floor(y / cell), cz = Math.floor(z / cell);
+ const sx = Math.floor(centroids[seed * 3] / cell);
+ const ringOfSeed = Math.max(Math.abs(sx - cx), Math.abs(Math.floor(centroids[seed * 3 + 1] / cell) - cy), Math.abs(Math.floor(centroids[seed * 3 + 2] / cell) - cz));
+ const reach = ringOfSeed + 2;
+ let best = null;
+ let bestD = Infinity;
+ for (let dx = -reach; dx <= reach; dx++) {
+ for (let dy = -reach; dy <= reach; dy++) {
+ for (let dz = -reach; dz <= reach; dz++) {
+ const bucket = grid.map.get(`${cx + dx},${cy + dy},${cz + dz}`);
+ if (!bucket) continue;
+ for (const t of bucket) {
+ const a = corner(t, 0), b = corner(t, 1), c = corner(t, 2);
+ const bary = closestPointBary(x, y, z, a, b, c);
+ const qx = a[0] * bary[0] + b[0] * bary[1] + c[0] * bary[2];
+ const qy = a[1] * bary[0] + b[1] * bary[1] + c[1] * bary[2];
+ const qz = a[2] * bary[0] + b[2] * bary[1] + c[2] * bary[2];
+ const d = (qx - x) ** 2 + (qy - y) ** 2 + (qz - z) ** 2;
+ if (d < bestD) { bestD = d; best = { t, bary }; }
+ }
+ }
+ }
+ }
+ return best;
+ };
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);
+
+ // Pass 1 — barycentric influence blend per vertex.
+ const influences = new Array(count);
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];
+ const hit = nearestSurface(pos[v * 3], pos[v * 3 + 1], pos[v * 3 + 2]);
+ if (!hit) { influences[v] = new Map(); continue; }
+ const map = new Map();
+ for (let k = 0; k < 3; k++) {
+ const share = hit.bary[k];
+ if (share <= 0) continue;
+ const vi = bTris[hit.t * 3 + k];
+ for (let c = 0; c < 4; c++) {
+ const w = bWeights[vi * 4 + c] * share;
+ if (w <= 0) continue;
+ const j = bJoints[vi * 4 + c];
+ map.set(j, (map.get(j) || 0) + w);
+ }
}
+ influences[v] = map;
transferred++;
}
+
+ // Pass 2 — one smoothing iteration over the garment's own edges, so
+ // adjacent cloth vertices never carry discontinuous influences.
+ const index = prim.getIndices()?.getArray();
+ if (index) {
+ const neighbours = new Array(count);
+ for (let i = 0; i < index.length; i += 3) {
+ for (let e = 0; e < 3; e++) {
+ const a = index[i + e];
+ const b = index[i + ((e + 1) % 3)];
+ (neighbours[a] ||= new Set()).add(b);
+ (neighbours[b] ||= new Set()).add(a);
+ }
+ }
+ const smoothed = new Array(count);
+ for (let v = 0; v < count; v++) {
+ const own = influences[v];
+ const ns = neighbours[v];
+ if (!ns || !ns.size || !own.size) { smoothed[v] = own; continue; }
+ const acc = new Map();
+ for (const [j, w] of own) acc.set(j, w * 0.5);
+ const share = 0.5 / ns.size;
+ for (const n of ns) {
+ for (const [j, w] of influences[n]) acc.set(j, (acc.get(j) || 0) + w * share);
+ }
+ smoothed[v] = acc;
+ }
+ for (let v = 0; v < count; v++) influences[v] = smoothed[v];
+ }
+
+ const outJ = new Uint16Array(count * 4);
+ const outW = new Float32Array(count * 4);
+ for (let v = 0; v < count; v++) top4(influences[v], outJ, outW, v * 4);
+
prim.setAttribute(
'JOINTS_0',
doc.createAccessor().setType('VEC4').setArray(outJ).setBuffer(buffer),