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.

wip sweep 100712

nirholas41411dc104d3
diff --git a/api/mocap/[id].js b/api/mocap/[id].js
new file mode 100644
index 000000000..c00601fc6
--- /dev/null
+++ b/api/mocap/[id].js
@@ -0,0 +1,186 @@
+// GET /api/mocap/clips/:id — fetch a clip (frames included)
+// PATCH /api/mocap/clips/:id — update metadata (name, description, tags, visibility, price)
+// DELETE /api/mocap/clips/:id — soft-delete (owner only)
+
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { z } from 'zod';
+
+const patchSchema = z.object({
+ name: z.string().trim().min(1).max(120).optional(),
+ description: z.string().trim().max(2000).optional(),
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
+ visibility: z.enum(['private', 'unlisted', 'public']).optional(),
+ avatar_id: z.string().uuid().nullable().optional(),
+ price: z
+ .object({
+ amount: z.string().regex(/^\d+(\.\d{1,9})?$/),
+ currency: z.string().min(2).max(10),
+ })
+ .nullable()
+ .optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
+
+ const id =
+ req.query?.id ||
+ new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).pop();
+ if (!id || !/^[0-9a-f-]{8,}$/i.test(id)) {
+ return error(res, 400, 'invalid_request', 'id required');
+ }
+
+ const auth = await resolveAuth(req);
+
+ if (req.method === 'GET') return handleGet(req, res, auth, id);
+ if (!auth) return error(res, 401, 'unauthorized', 'authentication required');
+ if (req.method === 'PATCH') return handlePatch(req, res, auth, id);
+ return handleDelete(req, res, auth, id);
+});
+
+async function handleGet(req, res, auth, id) {
+ const [row] = await sql`
+ select id, owner_id, avatar_id, slug, name, description, kind, format,
+ duration_ms, frame_count, frames, tags, visibility,
+ price_amount, price_currency, play_count,
+ created_at, updated_at
+ from mocap_clips
+ where id = ${id} and deleted_at is null
+ limit 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'clip not found');
+ const ownerView = auth?.userId === row.owner_id;
+ if (!ownerView && row.visibility === 'private') {
+ return error(res, 404, 'not_found', 'clip not found');
+ }
+
+ // Bump play_count only when someone other than the owner fetches a
+ // playable clip — recording your own clip doesn't inflate counters.
+ if (!ownerView) {
+ // Fire-and-forget; failure must not block the response.
+ queueMicrotask(async () => {
+ try {
+ await sql`update mocap_clips set play_count = play_count + 1 where id = ${id}`;
+ } catch (err) {
+ console.warn('[mocap] play_count update failed', err?.message);
+ }
+ });
+ }
+
+ res.setHeader(
+ 'Cache-Control',
+ ownerView ? 'private, max-age=0' : 'public, s-maxage=60, stale-while-revalidate=300',
+ );
+ return json(res, 200, {
+ clip: {
+ id: row.id,
+ slug: row.slug,
+ name: row.name,
+ description: row.description,
+ kind: row.kind,
+ format: row.format,
+ duration_ms: row.duration_ms,
+ duration: row.duration_ms / 1000,
+ frame_count: row.frame_count,
+ frames: row.frames || [],
+ tags: row.tags || [],
+ visibility: row.visibility,
+ avatar_id: row.avatar_id,
+ play_count: Number(row.play_count || 0),
+ price: row.price_amount
+ ? { amount: String(row.price_amount), currency: row.price_currency }
+ : null,
+ owner: ownerView ? 'self' : 'other',
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ },
+ });
+}
+
+async function handlePatch(req, res, auth, id) {
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:write'))
+ return error(res, 403, 'insufficient_scope', 'avatars:write required');
+ }
+ const body = await readJson(req);
+ const parsed = patchSchema.safeParse(body);
+ if (!parsed.success) {
+ return error(res, 400, 'validation_error', parsed.error.issues.map((i) => i.message).join('; '));
+ }
+ const patch = parsed.data;
+
+ const sets = [];
+ if (patch.name !== undefined) sets.push(sql`name = ${patch.name}`);
+ if (patch.description !== undefined) sets.push(sql`description = ${patch.description}`);
+ if (patch.tags !== undefined) sets.push(sql`tags = ${patch.tags}`);
+ if (patch.visibility !== undefined) sets.push(sql`visibility = ${patch.visibility}`);
+ if (patch.avatar_id !== undefined) {
+ if (patch.avatar_id) {
+ const ok = await sql`
+ select 1 from avatars
+ where id = ${patch.avatar_id} and owner_id = ${auth.userId} and deleted_at is null
+ limit 1
+ `;
+ if (!ok[0]) return error(res, 404, 'not_found', 'avatar_id not owned by you');
+ }
+ sets.push(sql`avatar_id = ${patch.avatar_id}`);
+ }
+ if (patch.price !== undefined) {
+ if (patch.price === null) {
+ sets.push(sql`price_amount = null`);
+ sets.push(sql`price_currency = null`);
+ } else {
+ sets.push(sql`price_amount = ${patch.price.amount}`);
+ sets.push(sql`price_currency = ${patch.price.currency}`);
+ }
+ }
+ if (sets.length === 0) return error(res, 400, 'invalid_request', 'no patchable fields supplied');
+ const setClause = sets.reduce((acc, s, i) => (i === 0 ? sql`set ${s}` : sql`${acc}, ${s}`), sql``);
+
+ const [row] = await sql`
+ update mocap_clips
+ ${setClause}
+ where id = ${id} and owner_id = ${auth.userId} and deleted_at is null
+ returning id, slug, name, description, kind, format, duration_ms, frame_count,
+ tags, visibility, avatar_id, price_amount, price_currency,
+ created_at, updated_at
+ `;
+ if (!row) return error(res, 404, 'not_found', 'clip not found or not yours');
+ return json(res, 200, {
+ clip: {
+ ...row,
+ price: row.price_amount
+ ? { amount: String(row.price_amount), currency: row.price_currency }
+ : null,
+ },
+ });
+}
+
+async function handleDelete(req, res, auth, id) {
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:delete'))
+ return error(res, 403, 'insufficient_scope', 'avatars:delete required');
+ }
+ const [row] = await sql`
+ update mocap_clips
+ set deleted_at = now()
+ where id = ${id} and owner_id = ${auth.userId} and deleted_at is null
+ returning id
+ `;
+ if (!row) return error(res, 404, 'not_found', 'clip not found or not yours');
+ return json(res, 200, { ok: true });
+}
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session)
+ return {
+ userId: session.id,
+ source: 'session',
+ scope: 'avatars:read avatars:write avatars:delete',
+ };
+ return await authenticateBearer(extractBearer(req));
+}
diff --git a/docs/index.html b/docs/index.html
index 5cb3687e2..9429c69a7 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -618,6 +618,7 @@
{ label: 'SDK', path: 'sdk' },
{ label: 'Widgets', path: 'widgets' },
{ label: 'Widget Studio', path: 'widget-studio' },
+ { label: 'Widget API (JSON-RPC)', path: 'widget-api' },
{ label: 'Widget reference', href: '/docs/widgets', external: true },
],
},
diff --git a/docs/widget-api.md b/docs/widget-api.md
new file mode 100644
index 000000000..36016faa6
--- /dev/null
+++ b/docs/widget-api.md
@@ -0,0 +1,192 @@
+# Widget API
+
+The slim widget shell (`/widget`) is an embeddable 3D viewer. It supports:
+
+- **URL parameters** — declarative configuration (model, type, brand, poster, reveal mode).
+- **JSON-RPC 2.0 over `postMessage`** — programmatic control from the parent page (camera, animation, screenshot).
+- **Auto-poster + lazy boot** — show a static preview, defer WebGL until the visitor interacts. Critical on gallery / grid pages.
+
+## Quick start
+
+The simplest embed — a single `<script>` tag that injects a sized iframe and forwards resize events:
+
+```html
+<script async src="https://three.ws/embed.js"
+ data-widget="wdgt_abc123def456"
+ data-width="600"
+ data-height="600"
+ data-reveal="interaction"
+ data-poster="auto"></script>
+```
+
+That's it. The script:
+
+- Mounts an iframe at the script tag's location.
+- Uses `/api/widgets/<id>/og` (the OG image we already generate) as a poster — visitors see the avatar instantly.
+- Defers WebGL boot until the visitor clicks the play button.
+- Lazy-loads the iframe with `IntersectionObserver`.
+
+### `<script>` attributes
+
+| Attribute | Default | Values | Notes |
+|-----------------|-------------|---------------------------------------|-------|
+| `data-widget` | (required) | `wdgt_...` | The widget id from your dashboard. |
+| `data-width` | type-aware | px | Iframe width. |
+| `data-height` | type-aware | px | Iframe height. |
+| `data-radius` | `12` | px | Border-radius on the iframe. |
+| `data-border` | `0` | px | Iframe border width. |
+| `data-reveal` | `auto` | `auto` \| `interaction` | `interaction` defers WebGL until the visitor clicks the poster. Use for gallery pages. |
+| `data-poster` | `auto` | `auto` \| URL \| `off` | Static preview shown until first frame. `auto` uses the widget's OG image. |
+| `data-priority` | (unset) | `high` | Sets `loading="eager"` + `fetchpriority="high"`. Use only when the widget is the page's LCP element. |
+| `data-type` | (unset) | `turntable` \| `talking-agent` \| … | Lets the script pick a sensible default size for the type. |
+
+## URL forms
+
+You can also embed by hand — useful when you control the iframe directly:
+
+| URL | Notes |
+|-------------------------------------------|-------|
+| `/widget#widget=<id>&kiosk=true` | Canonical embed URL. Slim shell, no chrome. |
+| `/widget#model=<glb-url>&kiosk=true` | Embed any GLB without a saved widget. |
+| `/w/<id>` | Server-rendered share page with OG tags + iframe. |
+| `/app#widget=<id>&kiosk=true` | Legacy. Same engine but with the full marketing SPA shell — slower first paint. |
+
+### Hash params
+
+| Param | Type | Default | Notes |
+|------------------|----------|-----------|-------|
+| `widget` | id | — | Loads a saved widget config. |
+| `model` | URL | — | Direct GLB URL (mutually exclusive with `widget`). |
+| `type` | string | `turntable` | Widget type. Determines the UI overlay. |
+| `kiosk` | bool | `false` | Hide all viewer chrome. Always `true` for embeds. |
+| `reveal` | string | `auto` | `auto` boots immediately. `interaction` shows a play button and only loads the engine on click. |
+| `poster` | URL | — | Static image shown until first frame. Use `/api/widgets/<id>/og` for the auto-generated card. |
+| `preset` | string | — | Environment preset (`neutral`, `venice-sunset`, `footprint-court`). |
+| `cameraPosition` | csv | — | Initial camera position as `x,y,z`. |
+| `accent` | `#rrggbb`| — | UI accent color. |
+
+## JSON-RPC API
+
+The widget exposes a JSON-RPC 2.0 server inside the iframe. Drive it from the parent page using the bundled client:
+
+```html
+<iframe id="agent" src="https://three.ws/widget#widget=wdgt_abc"></iframe>
+<script src="https://three.ws/widget-client.js"></script>
+<script>
+ const client = ThreeWidget.attach(document.getElementById('agent'));
+
+ await client.ready();
+ await client.call('camera.setLookAt', {
+ eye: [0, 1.6, 3], target: [0, 1, 0], duration: 1.5,
+ });
+ await client.call('animation.play', { name: 'av-waving' });
+
+ const { dataUrl } = await client.call('screenshot.capture', { width: 800, height: 800 });
+ console.log('PNG:', dataUrl);
+</script>
+```
+
+### Client API
+
+| Method | Returns | Notes |
+|---------------------------------|-------------------|-------|
+| `ThreeWidget.attach(iframe)` | `Client` | Binds to an iframe. Validates `event.origin` against the iframe's `src`. |
+| `client.ready(timeoutMs?)` | `Promise<void>` | Resolves on first `viewer.ready` event (or if the widget is already up). |
+| `client.call(method, params?, timeoutMs?)` | `Promise<result>` | Calls an RPC method. Rejects with `Error` (`code` carries the JSON-RPC error code). |
+| `client.on(event, fn)` | `() => void` | Subscribes to events. Returns an off-handle. `on('*', fn)` catches every event. |
+| `client.close()` | `void` | Detaches the listener and rejects in-flight calls. |
+
+### RPC methods (server)
+
+| Method | Params | Result |
+|-------------------------|-----------------------------------------------------|-----------------------------------------|
+| `viewer.getInfo` | — | `{ version, ready, model, widget, type }` |
+| `viewer.setBackground` | `{ color: '#rrggbb' }` | `{}` |
+| `viewer.setAutoRotate` | `{ enabled?: bool, speed?: number }` | `{}` |
+| `viewer.setEnvironment` | `{ preset: string }` | `{}` |
+| `camera.getLookAt` | — | `{ eye: [x,y,z], target: [x,y,z], fov }`|
+| `camera.setLookAt` | `{ eye?, target?, duration?, ease? }` | `{ eye, target }` |
+| `camera.recenter` | `{ duration?: seconds }` | `{}` |
+| `animation.list` | — | `{ clips: [{ name, duration }] }` |
+| `animation.play` | `{ name: string, loop?: bool }` | `{ name }` |
+| `animation.stop` | — | `{}` |
+| `screenshot.capture` | `{ width?: int, height?: int, mime?: string }` | `{ dataUrl: 'data:image/png;base64,…' }`|
+| `model.load` | `{ url: string }` | `{ url }` |
+| `ping` | — | `{ pong: true, t: <ms> }` |
+
+### Events (server → parent)
+
+Notifications (no `id`) sent to the parent over `postMessage`:
+
+| Event | Payload | Fires when |
+|-------------------|--------------------------------------|------------|
+| `viewer.ready` | `{}` | First successful model frame. |
+| `model.loaded` | `{ url, success, error? }` | After every `model.load` (success or failure). |
+| `widget.revealed` | `{ mode: 'auto' \| 'interaction' }` | Visitor clicked the play button (interaction mode) or auto mode booted. |
+| `widget.resize` | `{ width, height, id? }` | The widget asks the host to resize its iframe. |
+
+### Wire format
+
+The server speaks JSON-RPC 2.0. Both request and response forms below:
+
+```js
+// Request (parent → iframe)
+{ jsonrpc: '2.0', id: 7, method: 'camera.setLookAt',
+ params: { eye: [0,1.6,3], target: [0,1,0], duration: 1.5 } }
+
+// Response (iframe → parent)
+{ jsonrpc: '2.0', id: 7, result: { eye: [...], target: [...] } }
+
+// Error
+{ jsonrpc: '2.0', id: 7, error: { code: -32601, message: 'Method not found' } }
+
+// Notification (iframe → parent, no id)
+{ jsonrpc: '2.0', method: 'viewer.ready', params: {} }
+```
+
+### Error codes
+
+| Code | Meaning |
+|----------|---------|
+| `-32700` | Parse error (malformed JSON). |
+| `-32600` | Invalid request (missing `jsonrpc` or `method`). |
+| `-32601` | Method not found. |
+| `-32602` | Invalid params. |
+| `-32603` | Internal error (wraps a thrown exception). |
+| `-32000` | Viewer not ready (model still loading). |
+
+## Performance patterns
+
+### Gallery / grid pages
+
+Use `reveal="interaction"` + `data-poster="auto"`. WebGL only initializes for the widgets the visitor opens — most browsers cap a tab at ~16 simultaneous WebGL contexts, so eager-loading a grid of 12 widgets is borderline.
+
+```html
+<!-- Repeat for each widget in the grid -->
+<script async src="https://three.ws/embed.js"
+ data-widget="wdgt_..."
+ data-reveal="interaction"
+ data-poster="auto"></script>
+```
+
+### Hero / above-the-fold
+
+Use `data-priority="high"` so the browser prioritises the iframe in the resource queue. Only set this on the widget that's actually the LCP element — high-priority every embed and you've defeated the point.
+
+```html
+<script async src="https://three.ws/embed.js"
+ data-widget="wdgt_..."
+ data-priority="high"
+ data-poster="auto"></script>
+```
+
+### Multiple widgets you control
+
+If you have multiple widgets and want to coordinate them (sync camera, broadcast events), keep one `ThreeWidget.attach()` client per iframe. The clients are independent — there's no global state.
+
+## Security
+
+- The widget shell validates `event.source` on every incoming message — only messages from a known parent are processed.
+- The client validates `event.origin` against the iframe's `src` origin. Pass `{ origin: '*' }` to `attach()` to opt out (e.g. for cross-origin embed-in-embed scenarios), but you give up the guarantee that the response came from us.
+- `screenshot.capture` returns the rendered canvas, so the parent gets exactly what the visitor sees. Nothing private leaks across the boundary.
+- `model.load` accepts any URL the iframe can fetch — same-origin policy still applies to the GLB itself. If you need a private model, gate it behind a cookie/header at the GLB host.
diff --git a/pages/mocap-studio.html b/pages/mocap-studio.html
new file mode 100644
index 000000000..40bde495e
--- /dev/null
+++ b/pages/mocap-studio.html
@@ -0,0 +1,304 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>Mocap Studio · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="Record, save, and replay face mocap clips on any three.ws avatar." />
+ <meta name="theme-color" content="#0b0d10" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --bg: #07090c;
+ --panel: #11141a;
+ --panel-edge: rgba(255, 255, 255, 0.07);
+ --ink: #e8ecf2;
+ --ink-dim: rgba(255, 255, 255, 0.6);
+ --accent: #5fa8ff;
+ --rec: #ff5b6b;
+ --ok: #5fce6a;
+ }
+ * { box-sizing: border-box; }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ background: radial-gradient(1200px 600px at 70% -10%, #1a1f29, var(--bg));
+ color: var(--ink);
+ font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
+ display: grid;
+ grid-template-columns: minmax(0, 1.2fr) minmax(320px, 0.9fr);
+ gap: 22px;
+ padding: 22px;
+ }
+ @media (max-width: 980px) {
+ body { grid-template-columns: 1fr; padding: 14px; gap: 14px; }
+ }
+ h1 { margin: 0 0 6px; font-size: 22px; }
+ .sub { color: var(--ink-dim); font-size: 13px; margin-bottom: 18px; }
+
+ .stage {
+ position: relative;
+ background: linear-gradient(180deg, #11141a, #0a0c10);
+ border-radius: 14px;
+ border: 1px solid var(--panel-edge);
+ min-height: 560px;
+ overflow: hidden;
+ }
+ .stage canvas {
+ display: block;
+ width: 100% !important;
+ height: 100% !important;
+ }
+ #webcam-pip {
+ position: absolute;
+ right: 12px;
+ top: 12px;
+ width: 160px;
+ height: 120px;
+ object-fit: cover;
+ border-radius: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ background: #000;
+ z-index: 3;
+ transform: scaleX(-1);
+ display: none;
+ }
+ #webcam-pip.live { display: block; }
+ .rec-pill {
+ position: absolute;
+ left: 12px;
+ top: 12px;
+ z-index: 3;
+ display: none;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 12px;
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.6);
+ color: #fff;
+ font-size: 11px;
+ letter-spacing: 0.06em;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ }
+ .rec-pill.on {
+ display: inline-flex;
+ }
+ .rec-pill .dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--rec);
+ box-shadow: 0 0 8px var(--rec);
+ animation: pulse 1s ease-in-out infinite;
+ }
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.4; }
+ }
+
+ .card {
+ background: var(--panel);
+ border: 1px solid var(--panel-edge);
+ border-radius: 14px;
+ padding: 16px;
+ margin-bottom: 14px;
+ }
+ .card h2 {
+ margin: 0 0 12px;
+ font-size: 13px;
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+ color: var(--ink-dim);
+ font-weight: 600;
+ }
+ .row { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
+ .row > label { color: var(--ink-dim); font-size: 13px; min-width: 90px; }
+ .row input,
+ .row select,
+ .row textarea {
+ flex: 1;
+ background: #06080b;
+ color: var(--ink);
+ border: 1px solid var(--panel-edge);
+ border-radius: 8px;
+ padding: 9px 11px;
+ font-size: 13px;
+ font-family: inherit;
+ min-width: 0;
+ }
+ .row textarea { resize: vertical; min-height: 56px; }
+ .actions { display: flex; gap: 8px; flex-wrap: wrap; }
+ button.btn {
+ appearance: none;
+ background: #fff;
+ color: #0a0c10;
+ border: 0;
+ border-radius: 8px;
+ padding: 10px 16px;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ font-family: inherit;
+ }
+ button.btn.danger { background: var(--rec); color: #fff; }
+ button.btn.ghost { background: transparent; color: var(--ink); border: 1px solid var(--panel-edge); }
+ button.btn[disabled] { opacity: 0.4; cursor: not-allowed; }
+
+ .clip-list { display: flex; flex-direction: column; gap: 8px; max-height: 380px; overflow: auto; }
+ .clip {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid var(--panel-edge);
+ border-radius: 10px;
+ padding: 12px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .clip .meta { flex: 1; min-width: 0; }
+ .clip .meta .n { font-size: 13px; font-weight: 500; color: var(--ink); }
+ .clip .meta .d { font-size: 11px; color: var(--ink-dim); margin-top: 2px; }
+ .clip .v-pill {
+ font-size: 10px;
+ padding: 2px 6px;
+ border-radius: 6px;
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--ink-dim);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+ .clip .v-pill.public { background: rgba(95, 206, 106, 0.18); color: var(--ok); }
+ .clip .actions { gap: 6px; }
+ .clip button {
+ appearance: none;
+ background: transparent;
+ color: var(--ink-dim);
+ border: 1px solid var(--panel-edge);
+ border-radius: 6px;
+ padding: 5px 9px;
+ font-size: 11px;
+ cursor: pointer;
+ font-family: inherit;
+ }
+ .clip button:hover { color: var(--ink); border-color: rgba(255, 255, 255, 0.2); }
+
+ .timer {
+ font-family: ui-monospace, SFMono-Regular, monospace;
+ font-size: 36px;
+ font-weight: 600;
+ letter-spacing: 0.03em;
+ color: var(--ink);
+ margin: 12px 0;
+ text-align: center;
+ }
+ .timer.recording { color: var(--rec); }
+ .empty {
+ color: var(--ink-dim);
+ font-size: 13px;
+ padding: 18px 0;
+ text-align: center;
+ font-style: italic;
+ }
+ .brand { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
+ .brand a { color: var(--ink); text-decoration: none; font-weight: 600; }
+ .signed-out {
+ background: rgba(255, 180, 84, 0.1);
+ border: 1px solid rgba(255, 180, 84, 0.3);
+ border-radius: 10px;
+ padding: 12px 14px;
+ font-size: 13px;
+ color: rgba(255, 180, 84, 0.95);
+ }
+ .signed-out a { color: rgba(255, 180, 84, 0.95); font-weight: 600; }
+ </style>
+ </head>
+ <body>
+ <section class="left">
+ <div class="brand">
+ <div>
+ <h1>Mocap studio</h1>
+ <div class="sub">Record your face, save the clip, replay it on any avatar — yours or someone else's.</div>
+ </div>
+ <a href="/">← three.ws</a>
+ </div>
+
+ <div id="auth-warning" class="signed-out" style="display:none;margin-bottom:14px;">
+ You're not signed in — clips can be recorded locally and replayed, but they can't be saved.
+ <a href="/login">Sign in</a> to save and share.
+ </div>
+
+ <div class="stage" id="stage-wrap">
+ <div id="stage"></div>
+ <div id="rec-pill" class="rec-pill"><span class="dot"></span><span>REC <span id="rec-time">0.0s</span></span></div>
+ <video id="webcam-pip" autoplay playsinline muted aria-hidden="true"></video>
+ </div>
+
+ <div class="card" style="margin-top:14px;">
+ <h2>Record</h2>
+ <div class="timer" id="timer">00.0s</div>
+ <div class="actions">
+ <button class="btn" id="start-cam">Start camera</button>
+ <button class="btn ghost" id="calibrate" disabled>Calibrate neutral</button>
+ <button class="btn danger" id="record" disabled>Record</button>
+ <button class="btn ghost" id="replay" disabled>Replay last</button>
+ <button class="btn ghost" id="discard" disabled>Discard</button>
+ </div>
+ </div>
+
+ <div class="card">
+ <h2>Save clip</h2>
+ <div class="row">
+ <label for="clip-name">Name</label>
+ <input id="clip-name" type="text" placeholder="head nod" maxlength="120" />
+ </div>
+ <div class="row">
+ <label for="clip-desc">Description</label>
+ <textarea id="clip-desc" placeholder="Optional — what is this for?" maxlength="2000"></textarea>
+ </div>
+ <div class="row">
+ <label for="clip-tags">Tags</label>
+ <input id="clip-tags" type="text" placeholder="comma, separated, tags" />
+ </div>
+ <div class="row">
+ <label for="clip-visibility">Visibility</label>
+ <select id="clip-visibility">
+ <option value="private">Private (just you)</option>
+ <option value="unlisted">Unlisted (anyone with the link)</option>
+ <option value="public">Public (in marketplace)</option>
+ </select>
+ </div>
+ <div class="actions">
+ <button class="btn" id="save-clip" disabled>Save clip</button>
+ <button class="btn ghost" id="download-clip" disabled>Download JSON</button>
+ </div>
+ </div>
+ </section>
+
+ <section class="right">
+ <div class="card">
+ <h2>Source avatar</h2>
+ <div class="row">
+ <label for="avatar-handle">Handle</label>
+ <input id="avatar-handle" type="text" placeholder="@yourname or leave blank" autocomplete="off" />
+ <button class="btn" id="load-avatar">Load</button>
+ </div>
+ <div class="sub" id="avatar-info" style="margin:0;">no avatar loaded</div>
+ </div>
+
+ <div class="card">
+ <h2>Saved clips</h2>
+ <div class="clip-list" id="clip-list"><div class="empty">Loading…</div></div>
+ </div>
+
+ <div class="card">
+ <h2>Format</h2>
+ <div class="sub" style="margin:0;">
+ Clips are stored as <code style="color:#cad6e8">three.ws.face-mocap.v1</code> — JSON of <code style="color:#cad6e8">{ format, duration, frames: [{ t, shapes, mat }] }</code>. Frame data is the raw MediaPipe ARKit-52 output plus an optional 4×4 head transform. Compatible with any three.ws avatar via the ARKit-52 canonical morph map.
+ </div>
+ </div>
+ </section>
+
+ <script type="module" src="/src/mocap-studio.js"></script>
+ </body>
+</html>
diff --git a/src/next-layout.js b/src/next-layout.js
index 1d726f3d5..635158a1e 100644
--- a/src/next-layout.js
+++ b/src/next-layout.js
@@ -134,12 +134,14 @@ export class NextLayout {
const viewer = await this._waitForViewer();
if (!viewer) return;
this.viewer = viewer;
- await this._waitForDefs(viewer);
- this._renderClipGrid();
+ // Subscribe and attach the rAF driver immediately. The driver re-renders
+ // the grid when defs arrive later, so it's fine if defs aren't ready yet.
this._subscribeOnChange();
this._attachDriver();
this._armIdleAutoRotate();
- // Seed dock state from the manager (it may already be playing 'idle').
+ // Best-effort: wait briefly for defs, then render once explicitly.
+ await this._waitForDefs(viewer);
+ this._renderClipGrid();
this._onManagerChange(viewer.animationManager.currentName);
}
@@ -314,8 +316,27 @@ export class NextLayout {
_attachDriver() {
if (this.driverAttached) return;
this.driverAttached = true;
+ let lastDefsLen = -1;
+ let lastName = '__init__';
const tick = () => {
this.rafId = requestAnimationFrame(tick);
+ // Re-render the grid when new defs arrive after first mount.
+ const defs = this._currentDefs();
+ if (defs.length !== lastDefsLen) {
+ lastDefsLen = defs.length;
+ this._defsRendered = false;
+ this._renderClipGrid();
+ // Refresh the clip-name label too in case it was '—' before defs landed.
+ const cur = this.viewer?.animationManager?.currentName ?? this._currentName;
+ const def = defs.find((d) => d.name === cur);
+ if (def) this._updateClipName(def.label || _stripIdx(cur));
+ }
+ // Mirror manager's currentName even if onChange fired before subscription.
+ const liveName = this.viewer?.animationManager?.currentName ?? null;
+ if (liveName !== lastName) {
+ lastName = liveName;
+ this._onManagerChange(liveName);
+ }
this._updateScrubAndTime();
};
this.rafId = requestAnimationFrame(tick);