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
test(selfie): cover the shared capture thresholds and document the graded scanner
nirholas73ce0b88ce26
diff --git a/data/changelog.json b/data/changelog.jsonindex 31c05f07f..d295c4e5e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -19575,6 +19575,16 @@"infra"],"link": "/wardrobe"+ },+ {+ "date": "2026-08-11",+ "title": "The selfie scanner now grades every shot before you commit to a build",+ "summary": "Taking a selfie for an avatar got a real quality copilot. The viewfinder already tracked your face live; now the hint line names the exact fix (turn back to the camera, hold steady, find better light) instead of a generic warning, and after the countdown fires the captured still itself is re-scored, so motion blur or a lighting change in those last three seconds is caught on the review screen rather than a minute into the build. Uploaded photos get a lighting check too. Every threshold behind these gates is derived from the ways the reconstruction engine actually fails, so a shot that passes on your phone is a shot the engine can build from. And if your browser refreshes mid-capture, the shots you already took come back instead of starting you over.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/create/selfie"}]}diff --git a/docs/selfie-to-avatar.md b/docs/selfie-to-avatar.mdindex 143e8d22c..e108a4335 100644--- a/docs/selfie-to-avatar.md+++ b/docs/selfie-to-avatar.md@@ -13,15 +13,16 @@ Every other surface on three.ws (agents, the marketplace, Play worlds, talking-a## How it works-The client half lives in three modules the page imports on demand: [`src/selfie-capture.js`](../src/selfie-capture.js) (camera and upload UI), [`src/selfie-refine.js`](../src/selfie-refine.js) (`assessPhoto` / `refineSelfie`), and [`src/selfie-pipeline.js`](../src/selfie-pipeline.js) (the bridge to the backend). A fourth module, [`src/face-quality.js`](../src/face-quality.js), runs a live 468-point face mesh for framing feedback.--1. **Capture, in the browser.** `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } } })` opens the front camera. A real-time wireframe overlay tracks head pose, yaw, centering, blur, and luminance, and only unlocks the shutter when the face passes. A 3-2-1 countdown fires, then `shoot()` draws the current video frame to a canvas and calls `canvas.toBlob(blob, 'image/jpeg', 0.92)`. This is a **single still**, not a video scan. Camera support is feature-detected; if none exists, the shutter is disabled and an "Upload instead" path takes any image file.-2. **Optional side angles.** Under an "Add side angles" disclosure you can capture two extra stills (`left`, `right`, turned ~45 degrees). They raise fidelity and the ETA, but only the frontal is required.-3. **Refine, in the browser.** `assessPhoto` gates the frontal (no face is the only hard block; blur, illustration, or a distant subject are non-fatal warnings). `refineSelfie` isolates the subject from its background and reframes to a clean head-and-shoulders square, then downscales (max 1024px, JPEG quality 0.88). The refined frontal is previewed so you see exactly what the engine sees.-4. **Submit.** The pipeline POSTs the photos as data URIs to `/api/avatars/reconstruct` and gets back a `jobId`.-5. **Reconstruct, server-side.** The reconstruct handler (`api/avatars/_actions.js`) selects a provider through [`api/_lib/regen-provider.js`](../api/_lib/regen-provider.js). The production lane is **GCP**: it POSTs `{ images, body_type }` to the Cloud Run service behind `GCP_RECONSTRUCTION_URL`, today the [`workers/avatar-reconstruction/`](../workers/avatar-reconstruction/) FastAPI app deployed as `avatar-reconstruction`. (The multi-backend [`workers/avatar-pipeline-controller/`](../workers/avatar-pipeline-controller/) speaks the identical contract and can take over that env var, but is not deployed today.) That pipeline (`face_texture_transfer_v2`) uses **MediaPipe FaceLandmarker** (468 landmarks, Apache-2.0) to transfer your face texture and geometry onto a fixed-topology, pre-rigged Wolf3D/Ready-Player-Me-style humanoid template carrying a Mixamo-compatible skeleton, 52 ARKit blendshapes, and 15 visemes. Full engine detail is in [avatar-reconstruction.md](./avatar-reconstruction.md).-6. **Auto-rig fallback.** The template is born rigged. If a generic mesh comes back unrigged and a rig model is configured, `reconstruct-finalize.js` chains a `rerig` job (the `model-rig` worker, `workers/rig`) and moves the job through a `rigging` status before surfacing the avatar. If rigging is impossible it delivers the static mesh tagged `unrigged` rather than nothing.-7. **Poll and finish.** The client polls `GET /api/avatars/regenerate-status?jobId=...` every ~3 seconds (backing off on errors). On `status: 'done'` it fetches the finished avatar from `GET /api/avatars/:id` and shows it in a `<model-viewer>`.+The client half lives in three modules the page imports on demand: [`src/selfie-capture.js`](../src/selfie-capture.js) (camera and upload UI), [`src/selfie-refine.js`](../src/selfie-refine.js) (`assessPhoto` / `refineSelfie`), and [`src/selfie-pipeline.js`](../src/selfie-pipeline.js) (the bridge to the backend). A fourth module, [`src/face-quality.js`](../src/face-quality.js), runs a live 468-point face mesh for framing feedback. Every quality threshold those modules apply lives in one shared, unit-tested module, [`src/selfie-gates.js`](../src/selfie-gates.js): each number is traced in its header comment to a real reconstruction-pipeline failure mode (the worker's no-face rejection, the 35-degree morph-yaw ceiling, provider blur failures, the dim/backlit band from the robustness benchmark), so the client rejects a shot for the same reasons the backend would.++1. **Capture, in the browser.** `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } } })` opens the front camera. A real-time wireframe overlay tracks head pose, yaw, centering, blur, and luminance, and only unlocks the shutter when a face is found; the hint line names the single most actionable fix ("Face the camera straight on.", "Hold steady. The image is blurry.", "Too dark. Find better light.") until every gate passes. A 3-2-1 countdown fires, then `shoot()` draws the current video frame to a canvas and calls `canvas.toBlob(blob, 'image/jpeg', 0.92)`. This is a **single still**, not a video scan. Camera support is feature-detected; if none exists, the shutter is disabled and an "Upload instead" path takes any image file.+2. **Review the still.** The countdown leaves ~3 seconds for motion blur, a head turn, or a lighting change to land in the actual capture, so the frozen still is re-scored (`checkImageQuality`) against the same gates before you accept it. The review screen shows per-gate chips plus a verdict line; only a missing face disables "Use this" (mirroring the worker's one hard input rejection), everything else is a warning you can accept.+3. **Optional side angles.** Under an "Add side angles" disclosure you can capture two extra stills (`left`, `right`, turned ~45 degrees). They raise fidelity and the ETA, but only the frontal is required. Confirmed shots (and the style choice) are mirrored to `sessionStorage`, so a refresh or accidental back-swipe mid-capture restores every slot instead of starting over; the build phase has its own resume rail (`selfie:pendingJobId`).+4. **Refine, in the browser.** `assessPhoto` gates the frontal (no face is the only hard block; blur, illustration, or a distant subject are non-fatal warnings). `refineSelfie` isolates the subject from its background and reframes to a clean head-and-shoulders square, then downscales (max 1024px, JPEG quality 0.88). The refined frontal is previewed so you see exactly what the engine sees.+5. **Submit.** The pipeline POSTs the photos as data URIs to `/api/avatars/reconstruct` and gets back a `jobId`.+6. **Reconstruct, server-side.** The reconstruct handler (`api/avatars/_actions.js`) selects a provider through [`api/_lib/regen-provider.js`](../api/_lib/regen-provider.js). The production lane is **GCP**: it POSTs `{ images, body_type }` to the Cloud Run service behind `GCP_RECONSTRUCTION_URL`, today the [`workers/avatar-reconstruction/`](../workers/avatar-reconstruction/) FastAPI app deployed as `avatar-reconstruction`. (The multi-backend [`workers/avatar-pipeline-controller/`](../workers/avatar-pipeline-controller/) speaks the identical contract and can take over that env var, but is not deployed today.) That pipeline (`face_texture_transfer_v2`) uses **MediaPipe FaceLandmarker** (468 landmarks, Apache-2.0) to transfer your face texture and geometry onto a fixed-topology, pre-rigged Wolf3D/Ready-Player-Me-style humanoid template carrying a Mixamo-compatible skeleton, 52 ARKit blendshapes, and 15 visemes. Full engine detail is in [avatar-reconstruction.md](./avatar-reconstruction.md).+7. **Auto-rig fallback.** The template is born rigged. If a generic mesh comes back unrigged and a rig model is configured, `reconstruct-finalize.js` chains a `rerig` job (the `model-rig` worker, `workers/rig`) and moves the job through a `rigging` status before surfacing the avatar. If rigging is impossible it delivers the static mesh tagged `unrigged` rather than nothing.+8. **Poll and finish.** The client polls `GET /api/avatars/regenerate-status?jobId=...` every ~3 seconds (backing off on errors). On `status: 'done'` it fetches the finished avatar from `GET /api/avatars/:id` and shows it in a `<model-viewer>`.### The text-to-avatar variantdiff --git a/tests/selfie-gates.test.js b/tests/selfie-gates.test.jsnew file mode 100644index 000000000..ed92b7c64--- /dev/null+++ b/tests/selfie-gates.test.js@@ -0,0 +1,140 @@+/**+ * Capture gate scoring: unit tests for the pure math behind the /create/selfie+ * viewfinder and review-still gates (src/selfie-gates.js). These pin the+ * thresholds to the reconstruction pipeline's real failure modes: the no-face+ * hard rejection, the 35-degree morph-yaw ceiling, provider blur failures,+ * and the dim/backlit lighting band the robustness benchmark models.+ */++import { describe, it, expect } from 'vitest';+import { GATES, SLOT_PRESETS, grayFaceStats, gradeFrame } from '../src/selfie-gates.js';++// Build a w*h grey buffer from a (x,y)=>value fn.+function grey(w, h, fn) {+ const a = new Float32Array(w * h);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) a[y * w + x] = fn(x, y);+ return a;+}++describe('grayFaceStats', () => {+ it('reports the mean luma of a flat buffer exactly', () => {+ const { luma } = grayFaceStats(grey(16, 16, () => 128), 16, 16);+ expect(luma).toBe(128);+ });++ it('reports zero blur response on a flat buffer', () => {+ const { blurStddev } = grayFaceStats(grey(16, 16, () => 128), 16, 16);+ expect(blurStddev).toBe(0);+ });++ it('reports a higher blur response for detailed content than smooth content', () => {+ const detail = grayFaceStats(grey(32, 32, (x, y) => ((x + y) % 2 ? 255 : 0)), 32, 32);+ const smooth = grayFaceStats(grey(32, 32, (x) => x * 4), 32, 32);+ expect(detail.blurStddev).toBeGreaterThan(smooth.blurStddev);+ });++ it('a checkerboard face crop clears the live blur gate; a gradient does not', () => {+ const detail = grayFaceStats(grey(64, 64, (x, y) => ((x + y) % 2 ? 255 : 0)), 64, 64);+ const smooth = grayFaceStats(grey(64, 64, (x) => x * 2), 64, 64);+ expect(detail.blurStddev).toBeGreaterThan(GATES.BLUR_STDDEV_MIN);+ expect(smooth.blurStddev).toBeLessThan(GATES.BLUR_STDDEV_MIN);+ });++ it('handles degenerate sizes without NaN', () => {+ expect(grayFaceStats(grey(2, 2, () => 50), 2, 2)).toEqual({ luma: 50, blurStddev: 0 });+ expect(grayFaceStats([], 0, 0)).toEqual({ luma: 0, blurStddev: 0 });+ });+});++describe('gradeFrame', () => {+ const goodFrontal = {+ faceFound: true,+ slot: 'frontal',+ yaw: 2,+ noseX: 0.5,+ noseY: 0.5,+ blur: 20,+ luma: 120,+ };++ it('fails everything and names the face gate when no face is found', () => {+ const g = gradeFrame({ faceFound: false });+ expect(g.allPass).toBe(false);+ expect(g.faceFound).toBe(false);+ expect(g.reason).toMatch(/face/i);+ });++ it('passes a sharp, lit, centred frontal with no retake reason', () => {+ const g = gradeFrame(goodFrontal);+ expect(g.allPass).toBe(true);+ expect(g.reason).toBeNull();+ });++ it('keeps the frontal window inside the morph-safe yaw ceiling', () => {+ expect(SLOT_PRESETS.frontal.max).toBeLessThan(GATES.MORPH_YAW_MAX);+ expect(Math.abs(SLOT_PRESETS.frontal.min)).toBeLessThan(GATES.MORPH_YAW_MAX);+ });++ it('rejects a turned head on the frontal slot and says to face the camera', () => {+ const g = gradeFrame({ ...goodFrontal, yaw: 25 });+ expect(g.yawOk).toBe(false);+ expect(g.allPass).toBe(false);+ expect(g.reason).toMatch(/straight on/i);+ });++ it('rejects a frontal pose on the left slot and says to turn left', () => {+ const g = gradeFrame({ ...goodFrontal, slot: 'left', yaw: 2 });+ expect(g.yawOk).toBe(false);+ expect(g.reason).toMatch(/left/i);+ });++ it('accepts a ~45 degree turn on the left slot', () => {+ const g = gradeFrame({ ...goodFrontal, slot: 'left', yaw: 45 });+ expect(g.yawOk).toBe(true);+ expect(g.allPass).toBe(true);+ });++ it('accepts a ~-45 degree turn on the right slot', () => {+ const g = gradeFrame({ ...goodFrontal, slot: 'right', yaw: -45 });+ expect(g.yawOk).toBe(true);+ });++ it('rejects an off-centre face and says to recenter', () => {+ const g = gradeFrame({ ...goodFrontal, noseX: 0.9 });+ expect(g.centered).toBe(false);+ expect(g.reason).toMatch(/center/i);+ });++ it('rejects a blurry frame and says to hold steady', () => {+ const g = gradeFrame({ ...goodFrontal, blur: GATES.BLUR_STDDEV_MIN - 0.5 });+ expect(g.blurOk).toBe(false);+ expect(g.reason).toMatch(/steady|blurry/i);+ });++ it('rejects a dark frame and says to find light', () => {+ const g = gradeFrame({ ...goodFrontal, luma: GATES.LUMA_MIN - 5 });+ expect(g.lumaOk).toBe(false);+ expect(g.reason).toMatch(/dark|light/i);+ });++ it('rejects a blown-out frame and says to reduce glare', () => {+ const g = gradeFrame({ ...goodFrontal, luma: GATES.LUMA_MAX + 5 });+ expect(g.lumaOk).toBe(false);+ expect(g.reason).toMatch(/bright|glare/i);+ });++ it('accepts the exact luma boundaries', () => {+ expect(gradeFrame({ ...goodFrontal, luma: GATES.LUMA_MIN }).lumaOk).toBe(true);+ expect(gradeFrame({ ...goodFrontal, luma: GATES.LUMA_MAX }).lumaOk).toBe(true);+ });++ it('names the yaw fix before the blur fix when both fail', () => {+ const g = gradeFrame({ ...goodFrontal, yaw: 30, blur: 0 });+ expect(g.reason).toMatch(/straight on/i);+ });++ it('falls back to the frontal window for an unknown slot', () => {+ const g = gradeFrame({ ...goodFrontal, slot: 'profile' });+ expect(g.yawOk).toBe(true);+ });+});diff --git a/tests/selfie-refine.test.js b/tests/selfie-refine.test.jsindex e50370662..420a38c34 100644--- a/tests/selfie-refine.test.js+++ b/tests/selfie-refine.test.js@@ -114,6 +114,23 @@ describe('assessPhotoQuality', () => {const r = assessPhotoQuality({ ...sharpClearFace, faceBox: { x: 470, y: 470, w: 90, h: 90 } });expect(r.issues).toContain('far');});++ it('warns "dark" when the measured face luma is below the lighting gate', () => {+ const r = assessPhotoQuality({ ...sharpClearFace, luma: 25 });+ expect(r.verdict).toBe('warn');+ expect(r.primary).toBe('dark');+ });++ it('warns "bright" when the measured face luma is blown out', () => {+ const r = assessPhotoQuality({ ...sharpClearFace, luma: 240 });+ expect(r.issues).toContain('bright');+ });++ it('does not judge lighting when luma was not measured', () => {+ const r = assessPhotoQuality(sharpClearFace);+ expect(r.issues).not.toContain('dark');+ expect(r.issues).not.toContain('bright');+ });});describe('computeSubjectFrame', () => {