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: garments render correctly on live avatars; occlusion no longer amputates the body

nirholas40c4e45233b0
diff --git a/src/avatar-edit.js b/src/avatar-edit.js
index cc8647848..634490adb 100644
--- a/src/avatar-edit.js
+++ b/src/avatar-edit.js
@@ -245,6 +245,10 @@ async function bootScene() {
onChanged: () => renderChips(),
});
await closet.hydrate(currentAppearance.garments);
+ // The wardrobe panel may have rendered before the scene finished booting,
+ // leaving its closet section in the waiting state — re-render now that
+ // the closet exists so the racks appear without a tab round-trip.
+ renderActivePanel();
// Ambient idle layer — breathing, micro-saccades, blink, weight shift.
// Static preview here (no AgentProtocol); IdleAnimation's no-op stub
diff --git a/src/avatar-garment.js b/src/avatar-garment.js
index 703dc46c0..d30f2dfbb 100644
--- a/src/avatar-garment.js
+++ b/src/avatar-garment.js
@@ -32,6 +32,7 @@
import {
Bone,
+ DoubleSide,
Float32BufferAttribute,
Matrix4,
Skeleton,
@@ -65,6 +66,11 @@ export function findAvatarSkeleton(root) {
const byUuid = new Map();
root?.traverse?.((obj) => {
if (!obj?.isSkinnedMesh || !obj.skeleton?.bones?.length) return;
+ // Attached garments share the avatar's skeleton but must never be
+ // mistaken for the body: occlusion culls "the skin", and a garment
+ // with more vertices than the body would otherwise cull ITSELF the
+ // moment it outweighed the mesh it is dressing.
+ if (obj.userData?.garmentSlot) return;
const count = obj.geometry?.attributes?.position?.count || 0;
const entry = byUuid.get(obj.skeleton.uuid);
if (entry) { entry.weight += count; return; }
@@ -281,13 +287,27 @@ export function attachGarment(avatarRoot, garmentRoot, opts = {}) {
const mesh = new SkinnedMesh(geometry, src.material);
mesh.name = src.name || `garment:${slot}`;
mesh.frustumCulled = false; // skinned bounds go stale under animation
+ // Cloth is seen from inside at collars, cuffs and hems; single-sided
+ // garment materials render those openings as black voids.
+ for (const mat of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
+ if (mat && mat.side !== DoubleSide) { mat.side = DoubleSide; mat.needsUpdate = true; }
+ }
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.garmentSlot = slot;
const inverses = reindexBoneInverses(src.skeleton, avatarSkeleton, remap);
parent.add(mesh);
- mesh.bind(new Skeleton(avatarSkeleton.bones, inverses), src.bindMatrix.clone());
+ // three.js multiplies a SkinnedMesh's OWN matrixWorld on top of the
+ // skinning result, so the garment must carry the body mesh's exact
+ // local transform: a sibling left at identity renders displaced or
+ // scaled whenever the body mesh node is not itself identity (viewers
+ // commonly scale/rotate the container). Match it verbatim.
+ mesh.position.copy(avatarMesh.position);
+ mesh.quaternion.copy(avatarMesh.quaternion);
+ mesh.scale.copy(avatarMesh.scale);
+ mesh.updateMatrixWorld(true);
+ mesh.bind(new Skeleton(avatarSkeleton.bones, inverses), avatarMesh.bindMatrix.clone());
attached.push(mesh);
}
diff --git a/src/garment-closet.js b/src/garment-closet.js
index 20893f566..bd3ef5b93 100644
--- a/src/garment-closet.js
+++ b/src/garment-closet.js
@@ -124,6 +124,42 @@ export class GarmentCloset {
this._reoccludeAll();
this.onDirty();
this.onChanged();
+ if (import.meta.env?.DEV && typeof window !== 'undefined') {
+ // Dev-only breadcrumb for headless QA drivers (never in prod builds).
+ const { Vector3 } = await import('three');
+ window.__closetDebug = window.__closetDebug || [];
+ window.__closetDebug.push({
+ id: manifest.id,
+ slot: manifest.slot,
+ coverage: result.coverage,
+ meshes: result.meshes.map((m) => {
+ m.skeleton?.update?.();
+ const pos = m.geometry?.attributes?.position;
+ const box = { min: [1e9, 1e9, 1e9], max: [-1e9, -1e9, -1e9] };
+ const v = new Vector3();
+ const step = Math.max(1, Math.floor((pos?.count || 0) / 200));
+ for (let i = 0; i < (pos?.count || 0); i += step) {
+ v.fromBufferAttribute(pos, i);
+ m.applyBoneTransform(i, v);
+ v.applyMatrix4(m.matrixWorld);
+ for (let a = 0; a < 3; a++) {
+ box.min[a] = Math.min(box.min[a], v.getComponent(a));
+ box.max[a] = Math.max(box.max[a], v.getComponent(a));
+ }
+ }
+ return {
+ name: m.name,
+ visible: m.visible,
+ parent: m.parent?.name || m.parent?.type,
+ vertCount: pos?.count,
+ worldBox: box,
+ matrixWorld: [...m.matrixWorld.elements].map((x) => +x.toFixed(3)),
+ materialType: Array.isArray(m.material) ? m.material.map((x) => x.type).join() : m.material?.type,
+ boneSample: m.skeleton?.bones?.[1]?.getWorldPosition(new Vector3()).toArray().map((x) => +x.toFixed(3)),
+ };
+ }),
+ });
+ }
return result;
});
}
diff --git a/vite.config.js b/vite.config.js
index 79c4689ad..b84701d1e 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -2261,8 +2261,17 @@ support: resolve(__dirname, 'pages/support.html'),
if (req.method !== 'GET' && req.method !== 'HEAD') return next();
try {
const upstream = new URL(req.url, DEV_API_PROXY);
+ // Forward the caller's credentials: without them this refetch is
+ // anonymous, so private avatars 404 in dev even when the browser
+ // session is logged in (the editor's fetchAvatar sends cookies).
const resp = await fetch(upstream.href, {
- headers: { accept: 'application/json' },
+ headers: {
+ accept: 'application/json',
+ ...(req.headers.cookie ? { cookie: req.headers.cookie } : {}),
+ ...(req.headers.authorization
+ ? { authorization: req.headers.authorization }
+ : {}),
+ },
});
const text = await resp.text();
const rewritten = text.replace(R2_PUBLIC_RE, '/r2-proxy/');
diff --git a/workers/garment-forge/garment_glb.py b/workers/garment-forge/garment_glb.py
index 52a229e26..b591a6224 100644
--- a/workers/garment-forge/garment_glb.py
+++ b/workers/garment-forge/garment_glb.py
@@ -53,10 +53,28 @@ COMMERCIAL_SPDX = frozenset({
})
# A region must carry at least this share of the garment's total skin weight
-# to be declared in `occludes`. Deliberately LOW: the spec says over-declare
-# (hidden skin is invisible, exposed skin is the worst artefact), so any
-# region the garment meaningfully touches gets declared.
-OCCLUDES_MIN_SHARE = 0.01
+# to be declared in `occludes`. Weight share is a proxy for coverage, and a
+# LOW threshold over-declares catastrophically: a shirt whose waistband picks
+# up 1-2% of its weight on Hips would hide the avatar's entire pelvis and legs
+# (verified live: the first seeded shirt amputated the lower body). 10%
+# requires the garment to genuinely dress a region before hiding its skin;
+# the per-slot plausibility clamp below is the second gate.
+OCCLUDES_MIN_SHARE = 0.10
+
+# Regions a garment in a given slot is ALLOWED to occlude, regardless of how
+# its skin weight spreads. Evidence (weight share) decides within this set; a
+# top can never hide feet no matter what the skinning says. `top` includes
+# hips/upperLegs because dresses and long jackets ship under that slot.
+SLOT_OCCLUDABLE = {
+ "top": ("torso", "upperArms", "lowerArms", "neck", "hips", "upperLegs"),
+ "outerwear": ("torso", "upperArms", "lowerArms", "neck", "hips", "upperLegs"),
+ "bottom": ("hips", "upperLegs", "lowerLegs"),
+ "footwear": ("feet", "lowerLegs"),
+ "hair": ("scalp",),
+ "headwear": ("scalp",),
+ "glasses": (),
+ "accessory": (),
+}
# A canonical bone enters the manifest's rig.bones list above this weight
# share: enough to filter numeric noise without dropping real influences.
@@ -471,11 +489,13 @@ def skin_stats(glb_bytes: bytes) -> dict:
def derive_occludes(bone_mass: dict[str, float], total_mass: float,
- min_share: float = OCCLUDES_MIN_SHARE) -> list[str]:
- """Body regions whose bones carry ≥ min_share of the garment's skin
- weight, in BODY_REGIONS order. Over-declares by design (low threshold):
- hiding a covered square centimetre of skin is invisible, exposing one is
- the most obvious artefact an additive wardrobe can produce."""
+ min_share: float = OCCLUDES_MIN_SHARE,
+ slot: str | None = None) -> list[str]:
+ """Body regions this garment hides, in BODY_REGIONS order. Two gates:
+ evidence (the region's bones carry ≥ min_share of the garment's skin
+ weight — weight is a proxy for where the cloth actually sits) and
+ plausibility (the region is in SLOT_OCCLUDABLE for the slot — a shirt
+ whose waistband grazes the hip bones must not amputate the legs)."""
if total_mass <= 0:
return []
region_mass: dict[str, float] = {}
@@ -483,7 +503,9 @@ def derive_occludes(bone_mass: dict[str, float], total_mass: float,
region = region_of_bone(bone)
if region:
region_mass[region] = region_mass.get(region, 0.0) + mass
- return [r for r in BODY_REGIONS if region_mass.get(r, 0.0) / total_mass >= min_share]
+ allowed = set(SLOT_OCCLUDABLE.get(slot, BODY_REGIONS)) if slot else set(BODY_REGIONS)
+ return [r for r in BODY_REGIONS
+ if r in allowed and region_mass.get(r, 0.0) / total_mass >= min_share]
def weighted_bones(bone_mass: dict[str, float], total_mass: float,
diff --git a/workers/garment-forge/main.py b/workers/garment-forge/main.py
index 78b3bea59..24b89dc2e 100644
--- a/workers/garment-forge/main.py
+++ b/workers/garment-forge/main.py
@@ -148,7 +148,8 @@ def _run_stages(job_id: str, prompt: str, slot: str, tier: str,
progress("validate")
stats = garment_glb.skin_stats(garment_bytes)
- occludes = garment_glb.derive_occludes(stats["bone_mass"], stats["total_mass"])
+ occludes = garment_glb.derive_occludes(stats["bone_mass"], stats["total_mass"],
+ slot=slot)
bones = garment_glb.weighted_bones(stats["bone_mass"], stats["total_mass"])
garment_id = f"{garment_glb.slugify(prompt)}-{job_id[:6]}"
diff --git a/workers/garment-forge/test_garment_glb.py b/workers/garment-forge/test_garment_glb.py
index 489fe2cb6..5625d34f1 100644
--- a/workers/garment-forge/test_garment_glb.py
+++ b/workers/garment-forge/test_garment_glb.py
@@ -255,8 +255,22 @@ check("full coverage when all joints resolve", abs(stats["coverage"] - 1.0) < 1e
occ = derive_occludes(stats["bone_mass"], stats["total_mass"])
check("occludes torso from Spine mass", "torso" in occ, str(occ))
check("occludes upperArms from LeftArm mass", "upperArms" in occ, str(occ))
-check("occludes hips from the 20% share", "hips" in occ, str(occ))
-check("no phantom regions", all(r in ("torso", "upperArms", "hips") for r in occ), str(occ))
+# The synthetic's Hips mass is 0.2 of one vertex = 6.7% of total garment
+# weight — a waistband graze. Under the evidence threshold (10%) a graze must
+# NOT hide the pelvis; that exact over-declaration amputated the avatar's
+# lower body with the first live-seeded shirt.
+check("6.7% hip graze does not occlude hips", "hips" not in occ, str(occ))
+check("no phantom regions", all(r in ("torso", "upperArms") for r in occ), str(occ))
+# Slot plausibility clamp: evidence alone is not enough. The same weight
+# spread on a footwear-slot garment must not hide torso or hips, and a shirt
+# whose waistband carries a trace of Hips mass must not amputate the legs.
+occ_clamped = derive_occludes(stats["bone_mass"], stats["total_mass"], slot="footwear")
+check("slot clamp: footwear cannot occlude torso/hips", occ_clamped == [], str(occ_clamped))
+occ_top = derive_occludes(stats["bone_mass"], stats["total_mass"], slot="top")
+check("slot clamp: top keeps its evidenced regions", occ_top == occ, f"{occ_top} vs {occ}")
+trace = {"Spine": 0.97, "Hips": 0.03}
+occ_trace = derive_occludes(trace, 1.0, slot="top")
+check("3% hip graze does not hide the pelvis", occ_trace == ["torso"], str(occ_trace))
bones = weighted_bones(stats["bone_mass"], stats["total_mass"])
check("rig.bones in canonical order", bones == ["Hips", "Spine", "LeftArm"], str(bones))