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
feat: pose studio mirroring, avatar studio and walk-embed enhancements
nirholasde10c860be52
diff --git a/pages/avatar-studio.html b/pages/avatar-studio.htmlindex f1bc3da56..a8ec819eb 100644--- a/pages/avatar-studio.html+++ b/pages/avatar-studio.html@@ -444,6 +444,46 @@border-style: dashed;}+ /* ── Animate panel ──────────────────────────────────────── */+ .as-animate-intro {+ font-size: 12px;+ line-height: 1.45;+ color: var(--text-2, var(--text-3));+ margin: 2px 2px 12px;+ }+ .as-anim-grid {+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));+ }+ .as-anim-tile {+ text-align: center;+ }+ .as-anim-tile .as-tile-preview {+ font-size: 30px;+ margin-bottom: 6px;+ }+ .as-anim-tile.selected .as-tile-preview {+ background:+ radial-gradient(ellipse at center, rgba(255,255,255,0.12), transparent 70%),+ var(--panel-2);+ }+ .as-anim-tile .as-tile-name { white-space: normal; }+ .as-skeleton {+ pointer-events: none;+ min-height: 120px;+ background:+ linear-gradient(100deg, rgba(255,255,255,0.02) 30%, rgba(255,255,255,0.06) 50%, rgba(255,255,255,0.02) 70%)+ var(--panel);+ background-size: 200% 100%;+ animation: as-shimmer 1.2s ease-in-out infinite;+ }+ @keyframes as-shimmer {+ from { background-position: 200% 0; }+ to { background-position: -200% 0; }+ }+ @media (prefers-reduced-motion: reduce) {+ .as-skeleton { animation: none; }+ }+/* ── Status bar ────────────────────────────────────────── */.as-status {padding: 10px 16px;diff --git a/pages/create-next.html b/pages/create-next.htmlindex 2724f31b0..d7e9e1f46 100644--- a/pages/create-next.html+++ b/pages/create-next.html@@ -9,7 +9,6 @@<meta name="robots" content="noindex" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="stylesheet" href="/fonts/fonts.css" />- <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script><style>*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }@@ -37,59 +36,67 @@position: relative;background: radial-gradient(ellipse 80% 60% at 50% 60%, rgba(99,102,241,.1) 0%, transparent 70%);border-right: 1px solid rgba(255,255,255,.06);+ overflow: hidden;+ }++ .cn-confetti {+ position: absolute; inset: 0;+ pointer-events: none; z-index: 3;}.cn-avatar-wrap {position: relative;width: clamp(200px, 40vw, 320px);- height: clamp(200px, 40vw, 320px);- opacity: 0; transform: scale(.92);- transition: opacity .8s ease-out, transform .8s ease-out;+ height: clamp(220px, 44vw, 360px);+ animation: cn-fade-scale .8s ease-out .08s both;}- .cn-avatar-wrap.show { opacity: 1; transform: none; }.cn-avatar-glow {position: absolute; inset: -24px;border-radius: 50%;background: radial-gradient(circle at center, rgba(99,102,241,.22) 0%, transparent 70%);animation: glow-pulse 3s ease-in-out infinite;- opacity: 0; transition: opacity .6s ease-out;}- .cn-avatar-glow.show { opacity: 1; }- model-viewer.cn-mv, .cn-initial {+ .cn-stage, .cn-initial {+ position: absolute; inset: 0;width: 100%; height: 100%;- border-radius: 50%;- --progress-bar-color: transparent;+ border: 0; background: transparent;}+ .cn-stage {+ opacity: 0; transition: opacity .6s ease-out;+ z-index: 2;+ }+ .cn-stage.show { opacity: 1; }.cn-initial {display: flex; align-items: center; justify-content: center;+ border-radius: 50%;background: linear-gradient(135deg, #312e81, #4f46e5);font-size: 4rem; font-weight: 800;color: rgba(255,255,255,.9);+ z-index: 1;}.cn-avatar-label {margin-top: 20px;font-size: 1.1rem; font-weight: 700; color: #f9fafb;letter-spacing: -.01em; text-align: center;- opacity: 0; transition: opacity .6s ease-out;+ animation: cn-fade .6s ease-out .6s both;}- .cn-avatar-label.show { opacity: 1; }.cn-avatar-tag {margin-top: 8px;font-size: 11px; font-weight: 600; letter-spacing: .1em;text-transform: uppercase; color: #a5b4fc;- opacity: 0; transition: opacity .6s ease-out;+ animation: cn-fade .6s ease-out .7s both;}- .cn-avatar-tag.show { opacity: 1; }.cn-back {position: absolute; bottom: 24px;font-size: 12px; color: #6b7280;text-decoration: none;transition: color .15s;+ z-index: 4;}.cn-back:hover { color: #9ca3af; }@@ -103,10 +110,8 @@}.cn-header {- opacity: 0; transform: translateY(10px);- transition: opacity .6s ease-out, transform .6s ease-out;+ animation: cn-fade-up .6s ease-out both;}- .cn-header.show { opacity: 1; transform: none; }.cn-kicker {font-size: 11px; font-weight: 700;@@ -134,17 +139,20 @@cursor: pointer;transition: border-color .2s, background .2s, transform .15s;text-decoration: none; color: inherit;- opacity: 0; transform: translateX(14px);position: relative;margin-bottom: 10px;+ animation: cn-fade-x .5s ease-out both;}.cn-step:last-child { margin-bottom: 0; }- .cn-step.show { opacity: 1; transform: none; }.cn-step:hover {border-color: rgba(99,102,241,.5);background: rgba(99,102,241,.07);transform: translateX(3px);}+ .cn-step:focus-visible {+ outline: 2px solid #818cf8;+ outline-offset: 2px;+ }.cn-step.primary {border-color: rgba(99,102,241,.4);background: rgba(99,102,241,.1);@@ -157,6 +165,14 @@border-style: dashed;border-color: rgba(255,255,255,.1);}+ .cn-step.done {+ border-color: rgba(52,211,153,.32);+ background: rgba(16,185,129,.06);+ }+ .cn-step.done:hover {+ border-color: rgba(52,211,153,.5);+ background: rgba(16,185,129,.1);+ }.cn-step-num {width: 32px; height: 32px;@@ -172,8 +188,11 @@.cn-step.optional .cn-step-num {background: rgba(255,255,255,.06); color: #6b7280;}+ .cn-step.done .cn-step-num {+ background: rgba(16,185,129,.22); color: #6ee7b7;+ }- .cn-step-body { flex: 1; }+ .cn-step-body { flex: 1; min-width: 0; }.cn-step-title {font-size: 14px; font-weight: 700;@@ -188,6 +207,12 @@border: 1px solid rgba(255,255,255,.1);padding: 1px 6px; border-radius: 4px;}+ .cn-done-pill {+ font-size: 9px; font-weight: 700; letter-spacing: .1em;+ text-transform: uppercase; color: #6ee7b7;+ border: 1px solid rgba(52,211,153,.3);+ padding: 1px 6px; border-radius: 4px;+ }.cn-step-desc {margin-top: 3px;@@ -204,11 +229,104 @@.cn-step:hover .cn-step-arrow { transform: translateX(3px); color: #a5b4fc; }.cn-step.optional:hover .cn-step-arrow { transform: translateX(3px); color: #6b7280; }+ /* ── inline embed snippet ── */+ .cn-embed {+ margin: -2px 0 10px;+ padding: 14px 16px;+ border-radius: 12px;+ border: 1px solid rgba(255,255,255,.07);+ background: rgba(255,255,255,.02);+ animation: cn-fade .5s ease-out .28s both;+ }+ .cn-embed-head {+ display: flex; align-items: center; justify-content: space-between;+ gap: 12px; margin-bottom: 10px;+ }+ .cn-embed-head span {+ font-size: 11px; font-weight: 600; letter-spacing: .04em;+ text-transform: uppercase; color: #9ca3af;+ }+ .cn-embed-copy {+ font-family: inherit; font-size: 11.5px; font-weight: 600;+ color: #c7d2fe; cursor: pointer;+ background: rgba(99,102,241,.16);+ border: 1px solid rgba(99,102,241,.35);+ padding: 5px 12px; border-radius: 7px;+ transition: background .15s, border-color .15s, color .15s;+ }+ .cn-embed-copy:hover { background: rgba(99,102,241,.28); border-color: rgba(99,102,241,.6); }+ .cn-embed-copy:focus-visible { outline: 2px solid #818cf8; outline-offset: 2px; }+ .cn-embed-copy.copied { color: #6ee7b7; border-color: rgba(52,211,153,.5); background: rgba(16,185,129,.14); }+ .cn-embed-code {+ margin: 0;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px; line-height: 1.55; color: #cbd5e1;+ background: #0a0a12; border-radius: 8px;+ padding: 12px 14px;+ overflow-x: auto; white-space: pre;+ border: 1px solid rgba(255,255,255,.05);+ }++ /* ── footer: share + later ── */+ .cn-footer {+ margin-top: 22px;+ display: flex; align-items: center; gap: 12px;+ flex-wrap: wrap;+ animation: cn-fade .5s ease-out .36s both;+ }+ .cn-share-btn {+ display: inline-flex; align-items: center; gap: 7px;+ font-family: inherit; font-size: 12.5px; font-weight: 600;+ color: #e5e7eb; cursor: pointer;+ background: rgba(255,255,255,.04);+ border: 1px solid rgba(255,255,255,.1);+ padding: 8px 14px; border-radius: 9px;+ transition: background .15s, border-color .15s, color .15s;+ text-decoration: none;+ }+ .cn-share-btn:hover { background: rgba(255,255,255,.08); border-color: rgba(255,255,255,.2); }+ .cn-share-btn:focus-visible { outline: 2px solid #818cf8; outline-offset: 2px; }+ .cn-share-btn svg { width: 14px; height: 14px; }+ .cn-share-btn.copied { color: #6ee7b7; border-color: rgba(52,211,153,.45); }+ .cn-later {+ margin-left: auto;+ font-size: 12px; color: #6b7280; text-decoration: none;+ transition: color .15s;+ }+ .cn-later:hover { color: #9ca3af; }++ /* toast */+ .cn-toast {+ position: fixed; left: 50%; bottom: 28px;+ transform: translateX(-50%) translateY(12px);+ background: #11131c; color: #e5e7eb;+ border: 1px solid rgba(255,255,255,.12);+ padding: 10px 18px; border-radius: 10px;+ font-size: 13px; font-weight: 500;+ box-shadow: 0 12px 40px rgba(0,0,0,.5);+ opacity: 0; pointer-events: none;+ transition: opacity .2s, transform .2s;+ z-index: 50;+ }+ .cn-toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }+/* ── animations ── */@keyframes glow-pulse {0%,100% { opacity: .5; transform: scale(1); }50% { opacity: 1; transform: scale(1.06); }}+ @keyframes cn-fade { from { opacity: 0; } to { opacity: 1; } }+ @keyframes cn-fade-up { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }+ @keyframes cn-fade-scale { from { opacity: 0; transform: scale(.92); } to { opacity: 1; transform: none; } }+ @keyframes cn-fade-x { from { opacity: 0; transform: translateX(14px); } to { opacity: 1; transform: none; } }++ @media (prefers-reduced-motion: reduce) {+ .cn-avatar-wrap, .cn-avatar-glow, .cn-avatar-label, .cn-avatar-tag,+ .cn-header, .cn-step, .cn-embed, .cn-footer {+ animation: none !important;+ }+ .cn-stage { transition: none; }+ }/* ── mobile ── */@media (max-width: 700px) {@@ -223,18 +341,18 @@background: radial-gradient(ellipse 120% 100% at 50% 80%, rgba(99,102,241,.09) 0%, transparent 70%);}.cn-avatar-wrap {- width: clamp(140px, 50vw, 200px);- height: clamp(140px, 50vw, 200px);+ width: clamp(150px, 52vw, 220px);+ height: clamp(165px, 56vw, 250px);}.cn-right { padding: 28px 20px 40px; }.cn-step { padding: 16px 18px; }}</style>- <script type="module" src="/model-viewer-meshopt.js"></script></head><body><div class="cn-shell"><div class="cn-left">+ <canvas class="cn-confetti" id="cnConfetti" aria-hidden="true"></canvas><div class="cn-avatar-wrap" id="cnAvatarWrap"><div class="cn-avatar-glow" id="cnAvatarGlow"></div><div class="cn-initial" id="cnInitial">?</div>@@ -251,15 +369,15 @@</div><div class="cn-steps" id="cnSteps">- <a class="cn-step primary show" id="cnStep1" href="#" style="transition-delay:.05s">- <div class="cn-step-num">1</div>+ <a class="cn-step primary" id="cnStep1" href="/create-agent" style="animation-delay:.05s">+ <div class="cn-step-num" id="cnStep1Num">1</div><div class="cn-step-body"><div class="cn-step-title" id="cnStep1Title">Give it a brain</div><div class="cn-step-desc" id="cnStep1Desc">Set its personality, system prompt, and voice. Your avatar becomes a real AI agent in minutes.</div></div><div class="cn-step-arrow">→</div></a>- <a class="cn-step show" id="cnStep2" href="#" style="transition-delay:.12s">+ <a class="cn-step" id="cnStep2" href="/embed.html" style="animation-delay:.12s"><div class="cn-step-num">2</div><div class="cn-step-body"><div class="cn-step-title">Embed it anywhere</div>@@ -267,25 +385,44 @@</div><div class="cn-step-arrow">→</div></a>- <a class="cn-step optional show" id="cnStep3" href="#" style="transition-delay:.2s">- <div class="cn-step-num">3</div>+ <div class="cn-embed" id="cnEmbed" hidden>+ <div class="cn-embed-head">+ <span>Or grab the snippet now</span>+ <button class="cn-embed-copy" id="cnEmbedCopy" type="button" aria-label="Copy embed snippet">Copy</button>+ </div>+ <pre class="cn-embed-code"><code id="cnEmbedCode"></code></pre>+ </div>+ <a class="cn-step optional" id="cnStep3" href="/launchpad" style="animation-delay:.2s">+ <div class="cn-step-num" id="cnStep3Num">3</div><div class="cn-step-body">- <div class="cn-step-title">Deploy on-chain <span class="cn-opt-pill">Optional</span></div>+ <div class="cn-step-title" id="cnStep3Title">Deploy on-chain <span class="cn-opt-pill">Optional</span></div><div class="cn-step-desc">Mint your agent as a collectible. Make it discoverable and tradeable.</div></div><div class="cn-step-arrow">→</div></a></div>++ <div class="cn-footer">+ <button class="cn-share-btn" id="cnShareCopy" type="button" hidden aria-label="Copy public link to your agent">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>+ Copy link+ </button>+ <a class="cn-share-btn" id="cnShareX" target="_blank" rel="noopener" hidden aria-label="Share your agent on X">+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231Zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77Z"/></svg>+ Share on X+ </a>+ <a class="cn-later" id="cnLater" href="/dashboard">I'll do this later →</a>+ </div></div></div>- <script type="module">- import { agentAvatarGlb, MANNEQUIN_GLB } from '/src/shared/agent-3d.js';+ <div class="cn-toast" id="cnToast" role="status" aria-live="polite"></div>+ <script type="module">const p = new URLSearchParams(location.search);const avatarId = p.get('avatarId') || '';const agentId = p.get('agentId') || '';- const fromFlow = p.get('from') || 'object';+ const origin = location.origin;// If this is an agent save (has agentId), step 1 goes to /app (AI chat).// If avatar-only, step 1 goes to /create-agent (build an agent from the avatar).@@ -294,13 +431,12 @@const step1Desc = agentId? 'Talk to your agent, customize its personality, and set a system prompt.': 'Set its personality, system prompt, and voice. Your avatar becomes a real AI agent in minutes.';- const step2Href = avatarId ? `/embed.html?avatar=${encodeURIComponent(avatarId)}` : '/embed.html';+ const step2Href = avatarId ? `/embed.html?avatar=${encodeURIComponent(avatarId)}` : (agentId ? `/embed.html?agent=${encodeURIComponent(agentId)}` : '/embed.html');const step3Href = agentId ? `/deploy?agent=${encodeURIComponent(agentId)}` : (avatarId ? `/create-agent?avatar=${encodeURIComponent(avatarId)}&then=deploy` : '/launchpad');const headline = agentId ? 'Your agent is ready.<br>Here\'s where it gets powerful.' : 'Your avatar is ready.<br>Here\'s where it gets powerful.';const backHref = agentId ? `/app?agent=${encodeURIComponent(agentId)}` : '/dashboard/avatars';const avatarTag = agentId ? '3D AI Agent' : '3D Avatar';- // Wire static links that don't need datadocument.getElementById('cnStep1').href = step1Href;document.getElementById('cnStep1Title').textContent = step1Label;document.getElementById('cnStep1Desc').textContent = step1Desc;@@ -309,94 +445,244 @@document.getElementById('cnHeadline').innerHTML = headline;document.querySelector('.cn-back').href = backHref;document.getElementById('cnAvatarTag').textContent = avatarTag;+ document.getElementById('cnLater').href = agentId ? '/dashboard/agents' : '/dashboard/avatars';++ // ── Live, idle-animated avatar stage ──────────────────────────────────+ // /walk-embed is the production renderer: it retargets the canonical idle+ // clip onto any rig, so the figure breathes here instead of standing in a+ // dead T-pose. `controls=none&click=false` makes it a non-interactive+ // portrait; `orbit` stays on so the visitor can spin it. The initial-letter+ // placeholder shows until the stage's first frame loads (or forever, if the+ // avatar can't be resolved — a graceful fallback, never a broken void).+ function mountStage() {+ if (!agentId && !avatarId) return; // no model to show — keep the initial placeholder+ const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ const q = new URLSearchParams({+ controls: 'none',+ click: 'false',+ ground: 'false',+ badge: 'false',+ bg: 'transparent',+ env: 'studio',+ orbit: reduce ? 'false' : 'true',+ });+ if (agentId) q.set('agent', agentId);+ else q.set('avatar', avatarId);+ const wrap = document.getElementById('cnAvatarWrap');+ const ph = document.getElementById('cnInitial');+ const frame = document.createElement('iframe');+ frame.className = 'cn-stage';+ frame.src = `/walk-embed?${q.toString()}`;+ frame.title = 'Your live 3D avatar';+ frame.setAttribute('allow', 'autoplay; xr-spatial-tracking');+ frame.setAttribute('loading', 'eager');+ frame.addEventListener('load', () => {+ frame.classList.add('show');+ setTimeout(() => { ph.style.display = 'none'; }, 650);+ });+ wrap.appendChild(frame);+ }- // Stagger reveals- function after(ms, fn) { setTimeout(fn, ms); }- after(0, () => document.getElementById('cnHeader').classList.add('show'));- after(80, () => document.getElementById('cnAvatarWrap').classList.add('show'));- after(500, () => document.getElementById('cnAvatarGlow').classList.add('show'));- after(600, () => document.getElementById('cnAvatarLabel').classList.add('show'));- after(700, () => document.getElementById('cnAvatarTag').classList.add('show'));- // Step cards already have show class, transition-delay handles stagger-- // Fetch one avatar's loadable model URL + name. The avatar endpoint wraps its- // payload in `{ avatar: {...} }` and serves the model under `url` (a presigned- // link for the owner, so it works even when the avatar is private — which the- // agent record's `avatar_model_url` is gated against). Returns null on failure.- async function fetchAvatar(id) {- try {- const r = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });- if (!r.ok) return null;- const data = await r.json();- const avatar = data.avatar || data;- return { name: avatar.name || '', url: avatar.url || avatar.model_url || avatar.glb_url || null };- } catch {- return null;+ // ── Inline embed snippet (agents only) ────────────────────────────────+ function wireEmbedSnippet() {+ if (!agentId) return;+ const snippet =+ `<iframe\n` ++ ` src="${origin}/agent/${agentId}/embed"\n` ++ ` width="420" height="640"\n` ++ ` title="three.ws agent"\n` ++ ` style="border:0;border-radius:12px"\n` ++ ` allow="autoplay; xr-spatial-tracking"\n` ++ ` sandbox="allow-scripts allow-same-origin allow-popups"\n` ++ ` loading="lazy"\n` ++ `></iframe>`;+ document.getElementById('cnEmbedCode').textContent = snippet;+ document.getElementById('cnEmbed').hidden = false;+ const btn = document.getElementById('cnEmbedCopy');+ btn.addEventListener('click', async () => {+ const ok = await copyText(snippet);+ btn.textContent = ok ? 'Copied' : 'Press ⌘C';+ btn.classList.toggle('copied', ok);+ toast(ok ? 'Snippet copied — paste it on any site.' : 'Copy failed — select and copy manually.');+ setTimeout(() => { btn.textContent = 'Copy'; btn.classList.remove('copied'); }, 2200);+ });+ }++ // ── Share (agents only) ───────────────────────────────────────────────+ function wireShare() {+ if (!agentId) return;+ const publicUrl = `${origin}/agents/${agentId}`;+ const copyBtn = document.getElementById('cnShareCopy');+ const xLink = document.getElementById('cnShareX');+ copyBtn.hidden = false;+ xLink.hidden = false;++ copyBtn.addEventListener('click', async () => {+ const ok = await copyText(publicUrl);+ copyBtn.classList.toggle('copied', ok);+ toast(ok ? 'Public link copied.' : 'Copy failed.');+ setTimeout(() => copyBtn.classList.remove('copied'), 2000);+ });++ const update = (name) => {+ const text = `I just built ${name ? name : 'a 3D AI agent'} on three.ws — a live, talking 3D agent you can embed anywhere.`;+ xLink.href = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(publicUrl)}`;+ };+ update('');+ return update;+ }++ // ── Completion state ──────────────────────────────────────────────────+ function markDone(stepEl, numEl, label) {+ stepEl.classList.add('done');+ numEl.textContent = '✓';+ const title = stepEl.querySelector('.cn-step-title');+ if (title && !title.querySelector('.cn-done-pill')) {+ const pill = document.createElement('span');+ pill.className = 'cn-done-pill';+ pill.textContent = label;+ title.appendChild(pill);}}- async function loadData() {+ async function loadAgent(updateShare) {let name = '';- let glbUrl = null;-if (agentId) {try {const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, { credentials: 'include' });if (r.ok) {- const agent = await r.json();- name = agent.name || '';- const g = agentAvatarGlb(agent);- // Only adopt it when it's the agent's own model — never the mannequin,- // so the avatarId fallback below can supply the real one.- if (g && g !== MANNEQUIN_GLB) glbUrl = g;+ const a = await r.json();+ name = a.name || '';+ if (a.system_prompt || a.persona_prompt) {+ markDone(document.getElementById('cnStep1'), document.getElementById('cnStep1Num'), 'Done');+ }+ if (a.onchain || a.is_registered) {+ markDone(document.getElementById('cnStep3'), document.getElementById('cnStep3Num'), 'Live');+ }+ }+ } catch { /* non-fatal — the screen still works without it */ }+ } else if (avatarId) {+ try {+ const r = await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`, { credentials: 'include' });+ if (r.ok) {+ const d = await r.json();+ name = (d.avatar || d).name || '';}} catch { /* non-fatal */ }}- // Avatar-only saves, or agent saves whose record hasn't surfaced a public- // model URL yet (e.g. a freshly created private avatar): pull the model- // straight from the avatar the user just made.- if (!glbUrl && avatarId) {- const av = await fetchAvatar(avatarId);- if (av) {- if (!name) name = av.name;- glbUrl = av.url;- }- }-- // Try URL-param name as fallbackif (!name) name = p.get('name') || (agentId ? 'Your agent' : 'Your avatar');-document.getElementById('cnAvatarLabel').textContent = name;document.getElementById('cnInitial').textContent = (name[0] || 'A').toUpperCase();document.title = `${name} · three.ws`;+ if (updateShare) updateShare(name);+ }++ // ── Helpers ───────────────────────────────────────────────────────────+ async function copyText(text) {+ try {+ if (navigator.clipboard && window.isSecureContext) {+ await navigator.clipboard.writeText(text);+ return true;+ }+ } catch { /* fall through to legacy path */ }+ try {+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ const ok = document.execCommand('copy');+ ta.remove();+ return ok;+ } catch { return false; }+ }++ let toastTimer = null;+ function toast(msg) {+ const t = document.getElementById('cnToast');+ t.textContent = msg;+ t.classList.add('show');+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => t.classList.remove('show'), 2600);+ }++ // ── One-shot celebration burst ────────────────────────────────────────+ // A single confetti pop anchored to the avatar — sells the "it's done"+ // moment, then gets out of the way. Skipped entirely under reduced-motion.+ function celebrate() {+ if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;+ const canvas = document.getElementById('cnConfetti');+ const left = document.querySelector('.cn-left');+ const ctx = canvas.getContext('2d');+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ let raf = 0;++ function size() {+ const r = left.getBoundingClientRect();+ canvas.width = r.width * dpr;+ canvas.height = r.height * dpr;+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ return r;+ }+ const rect = size();+ const colors = ['#6366f1', '#818cf8', '#a5b4fc', '#34d399', '#f9fafb', '#c7d2fe'];+ const cx = rect.width / 2;+ const cy = rect.height * 0.46;+ const N = Math.min(120, Math.round(rect.width / 6));+ const parts = [];+ for (let i = 0; i < N; i++) {+ const ang = (Math.PI * 2 * i) / N + (i % 2 ? 0.18 : 0);+ const spd = 5 + (i % 7);+ parts.push({+ x: cx, y: cy,+ vx: Math.cos(ang) * spd * (0.6 + (i % 5) / 8),+ vy: Math.sin(ang) * spd * (0.6 + (i % 4) / 7) - 3,+ w: 5 + (i % 4) * 2, h: 3 + (i % 3) * 2,+ rot: i, vr: (i % 2 ? 0.3 : -0.25),+ color: colors[i % colors.length],+ });+ }- if (glbUrl) {- const wrap = document.getElementById('cnAvatarWrap');- const ph = document.getElementById('cnInitial');-- const mv = document.createElement('model-viewer');- mv.className = 'cn-mv';- mv.setAttribute('src', glbUrl);- mv.setAttribute('auto-rotate', '');- mv.setAttribute('auto-rotate-delay', '0');- mv.setAttribute('rotation-per-second', '20deg');- mv.setAttribute('camera-controls', '');- mv.setAttribute('interaction-prompt', 'none');- mv.setAttribute('environment-image', 'neutral');- mv.setAttribute('exposure', '0.9');- mv.setAttribute('shadow-intensity', '0.3');- mv.setAttribute('loading', 'eager');- mv.setAttribute('reveal', 'auto');- mv.setAttribute('style', 'width:100%;height:100%;background:transparent;border-radius:50%');- mv.setAttribute('alt', `${name} 3D avatar`);-- mv.addEventListener('load', () => { ph.style.display = 'none'; });- wrap.appendChild(mv);+ let frames = 0;+ const total = 90;+ function tick() {+ frames++;+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ const fade = Math.max(0, 1 - frames / total);+ for (const pt of parts) {+ pt.vy += 0.32; // gravity+ pt.vx *= 0.985; // drag+ pt.x += pt.vx;+ pt.y += pt.vy;+ pt.rot += pt.vr;+ ctx.save();+ ctx.globalAlpha = fade;+ ctx.translate(pt.x, pt.y);+ ctx.rotate(pt.rot);+ ctx.fillStyle = pt.color;+ ctx.fillRect(-pt.w / 2, -pt.h / 2, pt.w, pt.h);+ ctx.restore();+ }+ if (frames < total) {+ raf = requestAnimationFrame(tick);+ } else {+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ }}+ cancelAnimationFrame(raf);+ tick();}- loadData();+ // ── Boot ──────────────────────────────────────────────────────────────+ mountStage();+ wireEmbedSnippet();+ const updateShare = wireShare();+ loadAgent(updateShare);+ // Let the avatar finish its scale-in before the burst (matches the .08s+ // stage delay + a beat), then celebrate once.+ requestAnimationFrame(() => setTimeout(celebrate, 450));</script><script src="/getting-started.js" defer></script></body>diff --git a/pages/embed.html b/pages/embed.htmlindex 1a1dbfccd..6fd0503ef 100644--- a/pages/embed.html+++ b/pages/embed.html@@ -54,6 +54,10 @@width: q.get('width') || '',height: q.get('height') || '',autoplay: q.get('autoplay'),+ speed: q.get('speed'),+ ground: q.get('ground'),+ gestures: q.get('gestures'),+ badge: q.get('badge'),});</script></body>diff --git a/pages/pose.html b/pages/pose.htmlindex 33496ea8f..9a67f7076 100644--- a/pages/pose.html+++ b/pages/pose.html@@ -157,6 +157,11 @@background: rgba(255, 255, 255, 0.18);color: #e8e8e8;}+ #pose-undo,+ #pose-redo {+ font-size: 15px;+ line-height: 1;+ }.spacer {flex: 1;}@@ -202,6 +207,14 @@outline: 2px solid var(--accent);outline-offset: 2px;}+ .pose-btn:disabled {+ opacity: 0.38;+ cursor: not-allowed;+ }+ #pose-top .pose-btn:disabled:hover {+ background: transparent;+ color: var(--text-2);+ }/* Top-bar buttons read as a calm toolbar: quiet until hover,so the single primary (Save) is the only thing that pops. */@@ -1667,6 +1680,57 @@<span class="sep"></span>+ <div class="mode-group" role="group" aria-label="Undo and redo">+ <button+ type="button"+ class="mode-btn"+ id="pose-undo"+ title="Undo (Ctrl/Cmd+Z)"+ aria-label="Undo"+ disabled+ >+ ↺+ </button>+ <button+ type="button"+ class="mode-btn"+ id="pose-redo"+ title="Redo (Ctrl/Cmd+Shift+Z)"+ aria-label="Redo"+ disabled+ >+ ↻+ </button>+ </div>++ <button+ type="button"+ id="pose-mirror"+ class="pose-btn"+ title="Mirror the pose left ↔ right (M)"+ >+ Mirror+ </button>+ <button+ type="button"+ id="pose-copy"+ class="pose-btn"+ title="Copy the current pose (C)"+ >+ Copy+ </button>+ <button+ type="button"+ id="pose-paste"+ class="pose-btn"+ title="Paste the copied pose (V)"+ disabled+ >+ Paste+ </button>++ <span class="sep"></span>+<buttontype="button"id="pose-load-avatar"@@ -1756,7 +1820,8 @@<div id="pose-joint-picker"></div><p class="pose-shortcuts"><kbd>F</kbd> FK · <kbd>I</kbd> IK · <kbd>R</kbd> reset bone ·- <kbd>Esc</kbd> deselect+ <kbd>M</kbd> mirror · <kbd>C</kbd> copy · <kbd>V</kbd> paste ·+ <kbd>⌘Z</kbd> undo · <kbd>Esc</kbd> deselect</p></section>diff --git a/public/walk-embed-sdk.js b/public/walk-embed-sdk.jsindex 6d2992243..19f8b5d56 100644--- a/public/walk-embed-sdk.js+++ b/public/walk-embed-sdk.js@@ -100,6 +100,12 @@// Floating-corner embeds default to no ground disc and no orbit drag —// hosts that mount into a full-size container can opt back in with// `data-ground="true"` / `data-orbit="true"`.+ function attrNum(name, fallback, lo, hi) {+ var n = Number(attr(name, null));+ if (!isFinite(n)) return fallback;+ return Math.min(hi, Math.max(lo, n));+ }+var defaults = {avatar: attr('data-avatar', ''),position: attr('data-position', 'bottom-right'),@@ -111,6 +117,9 @@ground: attrBool('data-ground', false),orbit: attrBool('data-orbit', false),bg: attr('data-bg', 'transparent'),+ speed: attrNum('data-speed', 1, 0.3, 3),+ gestures: attrBool('data-gestures', false),+ badge: attrBool('data-badge', true),zIndex: parseInt(attr('data-z-index', '2147483640'), 10) || 2147483640,};@@ -137,6 +146,9 @@if (opts.orbit === false) p.set('orbit', 'false');if (opts.bg && opts.bg !== 'transparent') p.set('bg', opts.bg);if (opts.env && opts.env !== 'studio') p.set('env', opts.env);+ if (opts.speed && opts.speed !== 1) p.set('speed', String(opts.speed));+ if (opts.gestures) p.set('gestures', 'true');+ if (opts.badge === false) p.set('badge', 'false');return EMBED_ORIGIN + '/walk-embed?' + p.toString();}@@ -433,7 +445,7 @@if (!SCRIPT) return false;var keys = ['data-avatar', 'data-position', 'data-width', 'data-height','data-controls', 'data-env', 'data-autoplay', 'data-ground', 'data-orbit',- 'data-bg', 'data-z-index'];+ 'data-bg', 'data-speed', 'data-gestures', 'data-badge', 'data-z-index'];for (var i = 0; i < keys.length; i++) {if (SCRIPT.getAttribute(keys[i]) != null) return true;}diff --git a/src/avatar-studio.js b/src/avatar-studio.jsindex 3fe9aa8e1..1684b8819 100644--- a/src/avatar-studio.js+++ b/src/avatar-studio.js@@ -70,6 +70,14 @@ let previewToken = 0;let opQueue = Promise.resolve();let searchQuery = '';+// Animation state. `emotesReady` flips true once the clip library loads and the+// idle clip binds to the rig; until then the Animate tab shows a loading state.+// `currentEmote` is the looping clip the avatar rests in (one-shots settle back+// to it). `activeIdleClip` is the looping baseline that Save bakes in.+let emotesReady = false;+let currentEmote = DEFAULT_EMOTE;+let activeIdleClip = DEFAULT_EMOTE;+function queueOp(fn) {const next = opQueue.then(fn).catch((err) => {log.warn('[avatar-studio] queued op failed:', err);@@ -84,7 +92,35 @@ const TABS = [{ id: 'glasses', label: 'Glasses', kinds: ['glasses'], emoji: '🕶️', single: true },{ id: 'earrings', label: 'Earrings', kinds: ['earrings'], emoji: '💎', single: false },{ id: 'sculpt', label: 'Face', kinds: [], emoji: '✨', single: true, sculpt: true },+ { id: 'animate', label: 'Animate', kinds: [], emoji: '🎬', animate: true },+];++// ── Animate — drive the rig live with the shared canonical clip library ──────+// These names resolve against /animations/manifest.json (loaded by the scene's+// emote controller) and retarget onto the avatar's skeleton at runtime. Proof+// the avatar is fully rigged — and a customization dimension of its own: the+// chosen idle loop is what the saved avatar settles into. `loop` clips hold+// until the user picks another; one-shots play once and settle back to idle.+const EMOTES = [+ { name: 'idle', label: 'Idle', emoji: '🧍', loop: true },+ { name: 'av-waiting', label: 'Waiting', emoji: '⏳', loop: true },+ { name: 'av-chilling', label: 'Chill', emoji: '😎', loop: true },+ { name: 'wave', label: 'Wave', emoji: '👋', loop: false },+ { name: 'av-cheering', label: 'Cheer', emoji: '🙌', loop: false },+ { name: 'celebrate', label: 'Celebrate', emoji: '🎉', loop: false },+ { name: 'av-arm-flex', label: 'Flex', emoji: '💪', loop: false },+ { name: 'jump', label: 'Jump', emoji: '⬆️', loop: false },+ { name: 'pray', label: 'Pray', emoji: '🙏', loop: false },+ { name: 'kiss', label: 'Blow Kiss', emoji: '😘', loop: false },+ { name: 'taunt', label: 'Taunt', emoji: '😏', loop: false },+ { name: 'dance', label: 'Dance', emoji: '💃', loop: true },+ { name: 'av-dance-shuffle', label: 'Shuffle', emoji: '🕺', loop: true },+ { name: 'rumba', label: 'Rumba', emoji: '🌹', loop: true },+ { name: 'thriller', label: 'Thriller', emoji: '🧟', loop: true },+ { name: 'capoeira', label: 'Capoeira', emoji: '🤸', loop: true },];+const EMOTE_BY_NAME = new Map(EMOTES.map((e) => [e.name, e]));+const DEFAULT_EMOTE = 'idle';const KIND_EMOJI = { hat: '🎩', glasses: '🕶️', earrings: '💎' };const KIND_LABEL = { hat: 'Hat', glasses: 'Glasses', earrings: 'Earrings' };let activeTab = 'color';@@ -414,6 +450,13 @@ async function bootScene(glbUrl, editAvatar) {});scene.addOnTick((dt) => idle.update(dt));+ // Bring the rig to life: load the clip library and settle the avatar into+ // a looping idle so it leaves its bind T-pose. The clip drives the whole+ // skeleton (breathing included), so the procedural idle layer is narrowed+ // to blinking only — otherwise it would overwrite the clip's spine/head+ // rotations back to the T-pose rest each frame (it runs after the mixer).+ startIdleClip();+setStatus('', editAvatar? 'Loaded your saved avatar. Make changes and save to update it.': 'Choose a style below to get started.');@@ -423,6 +466,64 @@ async function bootScene(glbUrl, editAvatar) {}}+// ── Animate — live rig playback ──────────────────────────────────────++/**+ * Load the emote library and settle the avatar into its idle loop. On success+ * the procedural idle layer drops to blink-only so it stops fighting the clip;+ * on failure (manifest 404 / rig can't bind) the avatar keeps the full+ * procedural idle (breathing + blink) so it's never a dead T-pose either way.+ */+async function startIdleClip() {+ const emotes = scene?.getEmoteController?.();+ if (!emotes) return;+ try {+ const ok = await emotes.loadManifest();+ if (ok && (await scene.playEmote(DEFAULT_EMOTE))) {+ emotesReady = true;+ currentEmote = DEFAULT_EMOTE;+ activeIdleClip = DEFAULT_EMOTE;+ idle?.setChannels({ breathing: false, saccade: false, weightShift: false, blink: true });+ }+ } catch (err) {+ log.warn('[avatar-studio] idle clip unavailable; using procedural idle', err?.message);+ }+ if (activeTab === 'animate') renderActivePanel();+}++/**+ * Play an emote on the live rig. Looping clips become the new resting state+ * (and the idle baked into Save); one-shots play once and settle back to the+ * current idle so the avatar never freezes on a final frame.+ */+async function playEmote(name) {+ if (!emotesReady || !scene) return;+ const def = EMOTE_BY_NAME.get(name);+ if (!def) return;+ try {+ if (def.loop) {+ await scene.playEmote(name);+ currentEmote = name;+ activeIdleClip = name;+ } else {+ currentEmote = name;+ await scene.playEmoteOnce(name, { settleTo: activeIdleClip });+ }+ } catch (err) {+ log.warn(`[avatar-studio] emote "${name}" failed:`, err?.message);+ }+ if (activeTab === 'animate') markActiveEmote();+}++/** Await N animation frames — used to let a crossfade land before exporting. */+function nextFrames(n) {+ return new Promise((resolve) => {+ let left = Math.max(1, n | 0);+ const step = () => (--left <= 0 ? resolve() : requestAnimationFrame(step));+ requestAnimationFrame(step);+ });+}+// ── Fetch presets ────────────────────────────────────────────────────async function fetchPresets() {@@ -510,6 +611,11 @@ function renderActivePanel() {return;}+ if (tab.animate) {+ renderAnimatePanel(panel);+ return;+ }+const q = searchQuery.trim().toLowerCase();const items = presets.filter((p) => tab.kinds.includes(p.kind) && (!q || p.name.toLowerCase().includes(q)),@@ -580,6 +686,54 @@ function tilePreviewMarkup(preset) {`;}+// ── Animate panel ────────────────────────────────────────────────────++function renderAnimatePanel(panel) {+ if (!scene?.root) {+ panel.innerHTML = `<div class="as-empty">Waiting for avatar to load...</div>`;+ return;+ }+ if (!emotesReady) {+ panel.innerHTML = `+ <div class="as-animate-intro">Loading the motion library…</div>+ <div class="as-grid as-anim-grid">${EMOTES.map(() =>+ `<div class="as-tile as-skeleton" aria-hidden="true"></div>`,+ ).join('')}</div>`;+ return;+ }++ const tiles = EMOTES.map((e) => {+ const active = currentEmote === e.name;+ return `+ <button class="as-tile as-anim-tile${active ? ' selected' : ''}" type="button"+ data-emote="${esc(e.name)}" aria-pressed="${active ? 'true' : 'false'}"+ title="${esc(e.label)}">+ <div class="as-tile-preview" aria-hidden="true">${e.emoji}</div>+ <div class="as-tile-name">${esc(e.label)}</div>+ <div class="as-tile-kind">${e.loop ? 'loop' : 'play once'}</div>+ </button>`;+ }).join('');++ panel.innerHTML = `+ <div class="as-animate-intro">Drive the rig live. A looping motion becomes your avatar's resting idle when you save.</div>+ <div class="as-grid as-anim-grid">${tiles}</div>`;++ panel.querySelectorAll('[data-emote]').forEach((btn) => {+ btn.addEventListener('click', () => playEmote(btn.dataset.emote));+ });+}++/** Refresh the pressed/selected state of the emote tiles without a full re-render. */+function markActiveEmote() {+ const panel = $('as-panel');+ if (!panel) return;+ panel.querySelectorAll('[data-emote]').forEach((btn) => {+ const on = btn.dataset.emote === currentEmote;+ btn.classList.toggle('selected', on);+ btn.setAttribute('aria-pressed', on ? 'true' : 'false');+ });+}+// ── Color panel ──────────────────────────────────────────────────────function renderColorPanel(panel) {@@ -1317,6 +1471,18 @@ async function saveAvatar() {// This captures all colours, morphs, and accessories already applied// to the Three.js scene — no server-side bake needed.updateSaveOverlay('Exporting model...', 'Capturing colours and accessories');+ // GLTFExporter bakes each bone's *current* transform into the saved rest+ // pose. Settle the rig into its chosen looping idle (not a frozen mid-emote+ // frame) and let the crossfade land before capturing, so the saved avatar's+ // first-frame / thumbnail pose is a clean relaxed stance.+ if (emotesReady) {+ try {+ await scene.playEmote(activeIdleClip);+ await nextFrames(18);+ } catch (err) {+ log.warn('[avatar-studio] idle settle before export failed:', err?.message);+ }+ }const rawGlbBlob = await exportSceneGlb();updateProgress(15);diff --git a/src/editor/embed-editor.js b/src/editor/embed-editor.jsindex b55490894..90cf11e93 100644--- a/src/editor/embed-editor.js+++ b/src/editor/embed-editor.js@@ -54,6 +54,11 @@ const DEFAULTS = {width: 320,height: 480,autoplay: true,+ speed: 1, // walk-pace multiplier (?speed=0.3…3)+ ground: true, // show the ground disc + shadow (?ground=false floats the avatar)+ gestures: false, // show end-user wave/jump buttons (?gestures=true)+ badge: true, // show the three.ws attribution badge (?badge=false to remove)+ responsive: false, // emit a fluid (width:100%) snippet instead of fixed pxsnippetVariant: 'iframe', // 'iframe' | 'script'};@@ -317,7 +322,40 @@ function mountEmbedEditor(root, opts = {}) {autoplayWrap.append(autoplayCheck, autoplayLabel);const autoplayField = field('Autoplay', autoplayWrap);- panel.append(avatarField, controlsField, envField, bgField, sizeField, dimField, autoplayField);+ // Speed (avatar modes) — walk-pace multiplier baked into ?speed=.+ const speedWrap = el('div', { className: 'ee-bgrow' });+ const speedInput = el('input', { type: 'range', min: '0.3', max: '3', step: '0.1', value: String(cfg.speed), className: 'ee-range' });+ const speedVal = el('span', { className: 'ee-rangeval', textContent: `${cfg.speed.toFixed(1)}×` });+ speedInput.addEventListener('input', () => {+ cfg.speed = Math.min(3, Math.max(0.3, Number(speedInput.value) || 1));+ speedVal.textContent = `${cfg.speed.toFixed(1)}×`;+ sync();+ });+ speedWrap.append(speedInput, speedVal);+ const speedField = field('Walk speed', speedWrap);++ // A reusable on/off toggle row for the boolean embed options below.+ function toggleField(labelText, id, checked, hint, onChange) {+ const wrap = el('div', { className: 'ee-bgrow' });+ const box = el('input', { type: 'checkbox', id, checked });+ const lab = el('label', { htmlFor: id, className: 'ee-checklabel', textContent: hint });+ box.addEventListener('change', () => { onChange(box.checked); sync(); });+ wrap.append(box, lab);+ const f = field(labelText, wrap);+ f._box = box;+ return f;+ }++ const groundField = toggleField('Ground', 'ee-ground', cfg.ground,+ 'Show the ground disc + shadow', (v) => { cfg.ground = v; });+ const gesturesField = toggleField('Gestures', 'ee-gestures', cfg.gestures,+ 'Show wave / jump buttons to visitors', (v) => { cfg.gestures = v; });+ const badgeField = toggleField('Badge', 'ee-badge', cfg.badge,+ 'Show the three.ws badge', (v) => { cfg.badge = v; });+ const responsiveField = toggleField('Responsive', 'ee-responsive', cfg.responsive,+ 'Fluid width (fills its container)', (v) => { cfg.responsive = v; });++ panel.append(avatarField, controlsField, envField, bgField, sizeField, dimField, autoplayField, speedField, groundField, gesturesField, badgeField, responsiveField);// ── Right: preview + snippet ────────────────────────────────────────────const previewWrap = el('div', { className: 'ee-preview-wrap' });@@ -427,6 +465,13 @@ function mountEmbedEditor(root, opts = {}) {autoplayField.style.display = isWalking ? '' : 'none';envField.style.display = isAvatar ? '' : 'none';bgField.style.display = isAvatar ? '' : 'none';+ // Avatar-runtime-only knobs (walk-embed params); chat is a plain agent iframe.+ speedField.style.display = isAvatar ? '' : 'none';+ groundField.style.display = isAvatar ? '' : 'none';+ gesturesField.style.display = isAvatar ? '' : 'none';+ badgeField.style.display = isAvatar ? '' : 'none';+ // Responsive layout applies to every snippet (chat included).+ responsiveField.style.display = '';// Size applies to every mode — all runtimes render a sized iframe.sizeField.style.display = '';dimField.style.display = '';@@ -501,8 +546,13 @@ function mountEmbedEditor(root, opts = {}) {if (cfg.mode !== 'chat') {q.set('env', cfg.env);q.set('bg', cfg.bg);+ if (cfg.speed !== 1) q.set('speed', String(cfg.speed)); else q.delete('speed');+ if (!cfg.ground) q.set('ground', 'false'); else q.delete('ground');+ if (cfg.gestures) q.set('gestures', 'true'); else q.delete('gestures');+ if (!cfg.badge) q.set('badge', 'false'); else q.delete('badge');} else {- q.delete('env'); q.delete('bg');+ q.delete('env'); q.delete('bg'); q.delete('speed');+ q.delete('ground'); q.delete('gestures'); q.delete('badge');}if (cfg.mode === 'walking') { q.set('controls', cfg.controls); q.set('autoplay', String(cfg.autoplay)); }else { q.delete('controls'); q.delete('autoplay'); }@@ -532,6 +582,11 @@ function walkSrc(cfg, preview = false) {}if (cfg.bg && cfg.bg !== 'transparent') q.set('bg', cfg.bg);if (cfg.env && cfg.env !== 'studio') q.set('env', cfg.env);+ // Only serialize non-default runtime knobs so the URL stays clean.+ if (cfg.speed && cfg.speed !== 1) q.set('speed', String(cfg.speed));+ if (cfg.ground === false) q.set('ground', 'false');+ if (cfg.gestures) q.set('gestures', 'true');+ if (cfg.badge === false) q.set('badge', 'false');// Preview frames load over the dev/local origin so the iframe actually// renders here; the copied snippet always points at the production origin.if (preview) return u.toString().replace(ORIGIN, location.origin);@@ -556,7 +611,7 @@ function buildSnippet(cfg) {return '<!-- Chat embeds need an agent id — pick an agent from the gallery above -->';}if (cfg.mode === 'chat') {- return `<iframe\n src="${chatSrc(cfg)}"\n width="${cfg.width}"\n height="${cfg.height}"\n style="border:0;border-radius:16px"\n allow="microphone; autoplay; clipboard-write"\n loading="lazy"><\/iframe>`;+ return iframeSnippet(cfg, chatSrc(cfg), 'microphone; autoplay; clipboard-write');}if (cfg.snippetVariant === 'script') {const attrs = [@@ -566,14 +621,29 @@ function buildSnippet(cfg) {cfg.bg !== 'transparent' ? `data-bg="${cfg.bg}"` : null,cfg.env !== 'studio' ? `data-env="${cfg.env}"` : null,autoplayFor(cfg) ? `data-autoplay="true"` : null,+ cfg.speed !== 1 ? `data-speed="${cfg.speed}"` : null,+ cfg.ground === false ? `data-ground="false"` : null,+ cfg.gestures ? `data-gestures="true"` : null,+ cfg.badge === false ? `data-badge="false"` : null,`data-width="${cfg.width}"`,`data-height="${cfg.height}"`,].filter(Boolean);return `<script\n ${attrs.join('\n ')}><\/script>`;}// iframe variant- const src = walkSrc(cfg);- return `<iframe\n src="${src}"\n width="${cfg.width}"\n height="${cfg.height}"\n style="border:0;border-radius:16px"\n allow="accelerometer; gyroscope; autoplay"\n loading="lazy"><\/iframe>`;+ return iframeSnippet(cfg, walkSrc(cfg), 'accelerometer; gyroscope; autoplay');+}++// Build an <iframe> snippet. Fixed-pixel by default; when cfg.responsive is set,+// wrap it in an aspect-ratio box so it fills its container fluidly (the layout+// most modern sites actually need). referrerpolicy keeps the host's full URL out+// of our logs — only the origin is sent.+function iframeSnippet(cfg, src, allow) {+ if (cfg.responsive) {+ const ratio = `${cfg.width} / ${cfg.height}`;+ return `<div style="position:relative;width:100%;max-width:${cfg.width}px;aspect-ratio:${ratio}">\n <iframe\n src="${src}"\n style="position:absolute;inset:0;width:100%;height:100%;border:0;border-radius:16px"\n allow="${allow}"\n referrerpolicy="strict-origin-when-cross-origin"\n loading="lazy"><\/iframe>\n</div>`;+ }+ return `<iframe\n src="${src}"\n width="${cfg.width}"\n height="${cfg.height}"\n style="border:0;border-radius:16px"\n allow="${allow}"\n referrerpolicy="strict-origin-when-cross-origin"\n loading="lazy"><\/iframe>`;}function autoplayFor(cfg) {@@ -595,6 +665,13 @@ function sanitize(opts) {if (opts.height) out.height = clampDim(opts.height);if (opts.width || opts.height) out.size = 'custom';if (opts.autoplay != null && opts.autoplay !== '') out.autoplay = opts.autoplay === true || opts.autoplay === 'true';+ if (opts.speed != null && opts.speed !== '') {+ const n = Number(opts.speed);+ if (Number.isFinite(n)) out.speed = Math.min(3, Math.max(0.3, n));+ }+ if (opts.ground != null && opts.ground !== '') out.ground = !(opts.ground === false || opts.ground === 'false');+ if (opts.gestures != null && opts.gestures !== '') out.gestures = opts.gestures === true || opts.gestures === 'true';+ if (opts.badge != null && opts.badge !== '') out.badge = !(opts.badge === false || opts.badge === 'false');return out;}@@ -661,6 +738,8 @@ function injectStyles() {.embed-editor input[type=color] { width:44px; height:34px; padding:2px; background:#15181d; border:1px solid #2a2f37; border-radius:8px; cursor:pointer; }.embed-editor input[type=color]:disabled { opacity:.4; cursor:not-allowed; }.embed-editor input[type=checkbox] { width:16px; height:16px; accent-color:#6366f1; cursor:pointer; }+ .ee-range { flex:1; accent-color:#6366f1; cursor:pointer; height:4px; }+ .ee-rangeval { flex:0 0 auto; min-width:34px; text-align:right; font-size:12px; font-weight:600; color:#d4d4d8; font-variant-numeric:tabular-nums; }.ee-dimrow { display:flex; gap:10px; }.ee-dim { display:flex; align-items:center; gap:6px; flex:1; }.ee-dim-label { font-size:12px; color:#71717a; font-weight:600; }diff --git a/src/pose-animation.js b/src/pose-animation.jsindex 8ae94d58e..1815a7fea 100644--- a/src/pose-animation.js+++ b/src/pose-animation.js@@ -58,7 +58,7 @@ export function createDocument(overrides = {}) {};}-function clonePose(pose) {+export function clonePose(pose) {if (!pose) return null;const bones = {};for (const [key, q] of Object.entries(pose.bones || {})) {@@ -68,6 +68,31 @@ function clonePose(pose) {return { bones, rootPosition: { x: rp.x || 0, y: rp.y || 0, z: rp.z || 0 } };}+// True when two canonical poses are equal within `eps` — the same quaternion per+// bone and the same root position. Used by the studio's undo stack to skip+// no-op edits (a gizmo click that didn't actually rotate anything).+export function posesEqual(a, b, eps = 1e-4) {+ if (!a || !b) return a === b;+ const ba = a.bones || {};+ const bb = b.bones || {};+ const keys = new Set([...Object.keys(ba), ...Object.keys(bb)]);+ for (const key of keys) {+ const qa = ba[key];+ const qb = bb[key];+ if (!qa || !qb) return false;+ for (let i = 0; i < 4; i++) {+ if (Math.abs((qa[i] || 0) - (qb[i] || 0)) > eps) return false;+ }+ }+ const ra = a.rootPosition || { x: 0, y: 0, z: 0 };+ const rb = b.rootPosition || { x: 0, y: 0, z: 0 };+ return (+ Math.abs((ra.x || 0) - (rb.x || 0)) <= eps &&+ Math.abs((ra.y || 0) - (rb.y || 0)) <= eps &&+ Math.abs((ra.z || 0) - (rb.z || 0)) <= eps+ );+}+function sortKeyframes(doc) {doc.keyframes.sort((a, b) => a.time - b.time);return doc;diff --git a/src/pose-rig.js b/src/pose-rig.jsindex a53ae530e..6fd85405c 100644--- a/src/pose-rig.js+++ b/src/pose-rig.js@@ -67,6 +67,20 @@ const NORMALIZED_CANONICAL = new Map(CANONICAL_BONES.map((c) => [normalizeBoneName(c), c]),);+// Left ↔ right bone name (canonical). Center bones (Hips, Spine, Head…) map to+// themselves. Used to mirror a pose across the sagittal plane.+export function mirrorBoneName(key) {+ if (key.startsWith('Left')) return `Right${key.slice(4)}`;+ if (key.startsWith('Right')) return `Left${key.slice(5)}`;+ return key;+}++// Reflect a world-space rotation across the x=0 (sagittal) plane: conjugation by+// diag(-1,1,1) keeps x, negates y and z. Operates in place on a THREE.Quaternion.+export function reflectWorldQuaternion(q) {+ return q.set(q.x, -q.y, -q.z, q.w);+}+// IK chains: drag the end-effector, the link bones rotate to reach it. Defined// once in canonical space and resolved per-rig (links present on the rig only).// Order: links go from the effector's parent outward toward the root.@@ -216,6 +230,35 @@ class BaseRig {solveCCD(chain.links, chain.effector, targetWorld);}+ // Mirror the current pose left ↔ right. Works on any rig (mannequin or GLB),+ // including ones whose left/right rest frames aren't symmetric, by mirroring+ // in WORLD space and reprojecting each bone into its own parent frame. Bones+ // are processed root→leaf (CANONICAL_BONES order is topological) so each+ // parent's new world rotation is current before its children reproject.+ mirrorPose() {+ if (!this.root) return;+ this.root.updateWorldMatrix(true, true);+ const ordered = this.getBones();+ // Snapshot every posable bone's ORIGINAL world rotation first, so swaps+ // read pre-mirror values and the operation is its own inverse.+ const origWorld = new Map();+ for (const { key, node } of ordered) {+ origWorld.set(key, node.getWorldQuaternion(new Quaternion()));+ }+ const parentWorld = new Quaternion();+ for (const { key, node } of ordered) {+ const source = origWorld.get(mirrorBoneName(key)) || origWorld.get(key);+ const targetWorld = reflectWorldQuaternion(source.clone());+ if (node.parent) {+ node.parent.getWorldQuaternion(parentWorld);+ node.quaternion.copy(parentWorld.invert().multiply(targetWorld));+ } else {+ node.quaternion.copy(targetWorld);+ }+ node.updateWorldMatrix(false, false);+ }+ }+getSelectableMeshes() { return this.selectableMeshes; }dispose() {}}diff --git a/src/pose-studio.js b/src/pose-studio.jsindex 60d866086..13a37ceac 100644--- a/src/pose-studio.js+++ b/src/pose-studio.js@@ -55,6 +55,8 @@ import {sampleAtTime,bakeClip,serializeClip,+ clonePose,+ posesEqual,EASINGS,DEFAULT_EASING,} from './pose-animation.js';@@ -535,6 +537,7 @@ function boot() {state.draggingIK = null;controls.enabled = true;syncIKHandles();+ commitEdit();}canvas.addEventListener('pointerup', endIKDrag);canvas.addEventListener('pointercancel', endIKDrag);@@ -543,6 +546,87 @@ function boot() {gizmo.addEventListener('objectChange', () => {if (state.selectedBone) renderControlsPanel();});+ // A gizmo drag is one undoable edit: snapshot on grab, commit on release.+ gizmo.addEventListener('mouseDown', beginEdit);+ gizmo.addEventListener('mouseUp', commitEdit);++ // ── Pose history (undo / redo) ───────────────────────────────────────────+ // A bounded stack of canonical pose snapshots. Discrete actions (preset,+ // reset, mirror, paste, import) call recordHistory() before mutating;+ // continuous gestures (gizmo, IK drag, FK slider) bracket themselves with+ // beginEdit()/commitEdit() so the whole drag collapses to a single step.+ const HISTORY_LIMIT = 100;+ const history = { undo: [], redo: [], pending: null };++ function pushUndo(before) {+ history.undo.push(before);+ if (history.undo.length > HISTORY_LIMIT) history.undo.shift();+ history.redo.length = 0;+ updateHistoryButtons();+ }+ function recordHistory() {+ pushUndo(state.rig.getPose());+ }+ function beginEdit() {+ if (!history.pending) history.pending = state.rig.getPose();+ }+ function commitEdit() {+ const before = history.pending;+ history.pending = null;+ if (before && !posesEqual(before, state.rig.getPose())) pushUndo(before);+ }+ function restorePose(pose) {+ state.rig.applyPose(pose);+ if (state.poseMode === 'fk') attachGizmo();+ else syncIKHandles();+ renderControlsPanel();+ }+ function undoPose() {+ if (!history.undo.length) return setStatus('Nothing to undo.');+ history.redo.push(state.rig.getPose());+ if (history.redo.length > HISTORY_LIMIT) history.redo.shift();+ restorePose(history.undo.pop());+ updateHistoryButtons();+ setStatus('Undo.');+ }+ function redoPose() {+ if (!history.redo.length) return setStatus('Nothing to redo.');+ history.undo.push(state.rig.getPose());+ restorePose(history.redo.pop());+ updateHistoryButtons();+ setStatus('Redo.');+ }+ function updateHistoryButtons() {+ const u = $('#pose-undo');+ const r = $('#pose-redo');+ if (u) u.disabled = !history.undo.length;+ if (r) r.disabled = !history.redo.length;+ }++ // ── Mirror / copy / paste ────────────────────────────────────────────────+ function mirrorPose() {+ recordHistory();+ state.rig.mirrorPose();+ if (state.poseMode === 'fk') attachGizmo();+ else syncIKHandles();+ renderControlsPanel();+ setStatus('Pose mirrored left ↔ right.');+ }+ function copyPose() {+ state.clipboardPose = clonePose(state.rig.getPose());+ try {+ navigator.clipboard?.writeText(JSON.stringify(state.clipboardPose)).catch(() => {});+ } catch {}+ const pasteBtn = $('#pose-paste');+ if (pasteBtn) pasteBtn.disabled = false;+ setStatus('Pose copied.');+ }+ function pastePose() {+ if (!state.clipboardPose) return setStatus('Copy a pose first.', 'error');+ recordHistory();+ restorePose(state.clipboardPose);+ setStatus('Pose pasted.');+ }// ── FK gizmo ───────────────────────────────────────────────────────────function attachGizmo() {@@ -595,6 +679,7 @@ function boot() {// Drag plane: faces the camera, passes through the handle.const normal = camera.getWorldDirection(new Vector3()).negate();const plane = new Plane().setFromNormalAndCoplanarPoint(normal, handle.position.clone());+ beginEdit();state.draggingIK = { effectorKey, plane };controls.enabled = false;canvas.setPointerCapture(ev.pointerId);@@ -676,6 +761,9 @@ function boot() {value: String(value),'aria-label': `${CANONICAL_LABELS[key] || key} ${label}`,});+ slider.addEventListener('pointerdown', beginEdit);+ slider.addEventListener('keydown', beginEdit);+ slider.addEventListener('change', commitEdit);slider.addEventListener('input', () => {const cur = state.rig.getBoneEuler(key);cur[axis] = parseFloat(slider.value);@@ -692,6 +780,7 @@ function boot() {'Reset this bone',]);resetBtn.addEventListener('click', () => {+ recordHistory();state.rig.setBoneEuler(key, { x: 0, y: 0, z: 0 });renderControlsPanel();});@@ -749,6 +838,7 @@ function boot() {[preset.label],);btn.addEventListener('click', () => {+ recordHistory();state.rig.applyPose(poseFromMannequinPreset(preset.pose));if (state.poseMode === 'fk') attachGizmo();renderControlsPanel();@@ -888,6 +978,7 @@ function boot() {// ── Top toolbar ──────────────────────────────────────────────────────────$('#pose-reset')?.addEventListener('click', () => {+ recordHistory();state.rig.resetPose();if (state.poseMode === 'fk') attachGizmo();else syncIKHandles();@@ -928,6 +1019,7 @@ function boot() {reader.onload = () => {try {const pose = JSON.parse(String(reader.result));+ recordHistory();state.rig.applyPose(pose);if (state.poseMode === 'fk') attachGizmo();renderControlsPanel();@@ -1033,10 +1125,33 @@ function boot() {}}+ // ── Top-toolbar pose actions ─────────────────────────────────────────────+ $('#pose-undo')?.addEventListener('click', undoPose);+ $('#pose-redo')?.addEventListener('click', redoPose);+ $('#pose-mirror')?.addEventListener('click', mirrorPose);+ $('#pose-copy')?.addEventListener('click', copyPose);+ $('#pose-paste')?.addEventListener('click', pastePose);+ updateHistoryButtons();+// ── Keyboard shortcuts ───────────────────────────────────────────────────window.addEventListener('keydown', (ev) => {if (ev.target.matches('input, textarea, select')) return;const k = ev.key.toLowerCase();+ const mod = ev.ctrlKey || ev.metaKey;+ // Undo / redo — Ctrl/Cmd+Z, Shift+Z or Ctrl+Y to redo.+ if (mod && k === 'z') {+ ev.preventDefault();+ ev.shiftKey ? redoPose() : undoPose();+ return;+ }+ if (mod && k === 'y') {+ ev.preventDefault();+ redoPose();+ return;+ }+ // Remaining shortcuts are single-key (no modifier) so they never clobber+ // browser/OS chords like Ctrl+C.+ if (mod || ev.altKey) return;if (k === 'f') {state.poseMode = 'fk';applyPoseMode();@@ -1049,8 +1164,15 @@ function boot() {renderControlsPanel();}} else if (k === 'r' && state.selectedBone) {+ recordHistory();state.rig.setBoneEuler(state.selectedBone, { x: 0, y: 0, z: 0 });renderControlsPanel();+ } else if (k === 'm') {+ mirrorPose();+ } else if (k === 'c') {+ copyPose();+ } else if (k === 'v') {+ pastePose();} else if (k === 'escape') {state.selectedBone = null;gizmo.detach();diff --git a/src/voice/talk-emotes.js b/src/voice/talk-emotes.jsindex 97d1b929c..fa3cf6205 100644--- a/src/voice/talk-emotes.js+++ b/src/voice/talk-emotes.js@@ -140,6 +140,26 @@ export class TalkEmotes {return true;}+ /**+ * Play a one-shot emote once, then settle back into a looping clip (idle by+ * default) with a crossfade. For manifest entries whose `loop` is false+ * (wave, celebrate, flex, …) this avoids freezing the avatar on the final+ * frame. Lazily loads both the one-shot and the settle clip via the manager.+ *+ * @param {string} name+ * @param {{ settleTo?: string, fade?: number }} [opts]+ * @returns {Promise<boolean>} false if the emote isn't in the manifest.+ */+ async playOnce(name, { settleTo = 'idle', fade = 0.25 } = {}) {+ const def = this._defsByName.get(name);+ if (!def) {+ log.warn(`[talk-emotes] unknown emote: ${name}`);+ return false;+ }+ await this._manager.playOnce(name, { settleTo, fade });+ return true;+ }+get currentEmote() {return this._manager.currentName;}diff --git a/src/voice/talk-scene.js b/src/voice/talk-scene.jsindex 8de154265..f8c014723 100644--- a/src/voice/talk-scene.js+++ b/src/voice/talk-scene.js@@ -199,6 +199,15 @@ export class TalkScene {return this._emotes?.play(name) ?? Promise.resolve(false);}+ /**+ * Convenience: play a one-shot emote, settling back into a looping clip+ * (idle by default) when it finishes so the rig never freezes on the final+ * frame. Use for non-looping clips (wave, celebrate, flex, …).+ */+ playEmoteOnce(name, opts) {+ return this._emotes?.playOnce(name, opts) ?? Promise.resolve(false);+ }+attachMouthTarget(target) {this._mouthTarget = target;if (this.root) target.attach(this.root);diff --git a/src/walk-embed.js b/src/walk-embed.jsindex 929194029..cf72ee217 100644--- a/src/walk-embed.js+++ b/src/walk-embed.js@@ -217,6 +217,10 @@ const LEAN_LERP = 0.12;const CAM_OFFSET = new Vector3(0, 1.85, 3.6);const CAM_LOOK_OFFSET = new Vector3(0, 1.1, 0);const GROUND_RADIUS = 12;+// Idle cursor-glance: max body turn toward the cursor (radians) and how quickly+// the avatar eases toward it — slow enough to read as "noticing," not twitchy.+const GLANCE_MAX_RAD = 0.42;+const GLANCE_LERP = 0.045;// ── DOM ───────────────────────────────────────────────────────────────────const stage = document.getElementById('walk-stage');@@ -449,6 +453,22 @@ if (ORBIT_ENABLED) {canvas.addEventListener('pointercancel', onUp);}+// ── Idle cursor-glance ──────────────────────────────────────────────────────+// On hover-capable devices, track the cursor's horizontal position over the+// canvas and feed it to the idle-glance target so a standing avatar turns toward+// the visitor. Skipped under reduced-motion and on touch (no persistent cursor).+if (HAS_HOVER && !PREFERS_REDUCED_MOTION) {+ canvas.addEventListener('pointermove', (e) => {+ if (e.pointerType && e.pointerType !== 'mouse') return;+ const rect = canvas.getBoundingClientRect();+ if (!rect.width) return;+ const ndcX = ((e.clientX - rect.left) / rect.width) * 2 - 1; // [-1, 1]+ input.glance.targetYaw = -ndcX * GLANCE_MAX_RAD;+ input.glance.active = true;+ });+ canvas.addEventListener('pointerleave', () => { input.glance.active = false; });+}+// ── Input state ───────────────────────────────────────────────────────────const input = {keys: { forward: 0, back: 0, left: 0, right: 0, run: false },@@ -780,6 +800,15 @@ function tick() {animationManager.crossfadeTo(CLIP_IDLE, 0.25);}+ // Idle cursor-glance: while standing still, ease the body toward facing the+ // viewer (yaw 0), offset toward the cursor when it's over the canvas. Only the+ // idle state touches yaw here — locomotion above owns it while moving.+ if (mag <= 0.01 && avatar && HAS_HOVER && !PREFERS_REDUCED_MOTION) {+ const targetYaw = input.glance.active ? input.glance.targetYaw : 0;+ avatarYaw = lerpAngle(avatarYaw, targetYaw, GLANCE_LERP);+ avatarRig.quaternion.setFromAxisAngle(upY, avatarYaw);+ }+if (animationManager.mixer) {let ts = 1.0;if (currentMotion === 'walk') {@@ -829,7 +858,7 @@ function tick() {}renderer.render(scene, camera);- requestAnimationFrame(tick);+ if (loopRunning) rafHandle = requestAnimationFrame(tick);}function lerpAngle(a, b, t) {@@ -961,6 +990,67 @@ const runtime = {// runtime without importing it. Public methods only — no scene internals.window.__walkEmbed = runtime;+// ── Click / tap to walk ─────────────────────────────────────────────────────+// Raycast a tap on the canvas onto the ground plane (y=0) and send the avatar+// there via the same goto seek the host postMessage contract uses. This makes+// the most intuitive control discoverable to a visitor who'd never read docs.+// A tap is distinguished from an orbit drag (movement threshold) and a hold.+const _raycaster = new Raycaster();+const _groundPlane = new Plane(new Vector3(0, 1, 0), 0);+const _ndc = new Vector2();+const _hit = new Vector3();++function groundPointAt(clientX, clientY) {+ const rect = canvas.getBoundingClientRect();+ if (!rect.width || !rect.height) return null;+ _ndc.x = ((clientX - rect.left) / rect.width) * 2 - 1;+ _ndc.y = -((clientY - rect.top) / rect.height) * 2 + 1;+ _raycaster.setFromCamera(_ndc, camera);+ return _raycaster.ray.intersectPlane(_groundPlane, _hit);+}++if (CLICK_TO_MOVE) {+ let downX = 0, downY = 0, downT = 0, tracking = false;+ canvas.addEventListener('pointerdown', (e) => {+ // A tap starting over the joystick belongs to the joystick, not a goto.+ const jr = joystickEl.getBoundingClientRect();+ const overJoystick = CONTROLS === 'joystick' &&+ e.clientX >= jr.left && e.clientX <= jr.right &&+ e.clientY >= jr.top && e.clientY <= jr.bottom;+ if (overJoystick) { tracking = false; return; }+ downX = e.clientX; downY = e.clientY; downT = performance.now(); tracking = true;+ });+ canvas.addEventListener('pointerup', (e) => {+ if (!tracking) return;+ tracking = false;+ // A drag (orbit) or a hold isn't a click-to-walk.+ if (Math.hypot(e.clientX - downX, e.clientY - downY) > 6) return;+ if (performance.now() - downT > 400) return;+ const p = groundPointAt(e.clientX, e.clientY);+ if (!p) return;+ // Keep the target inside the walkable disc so the avatar never seeks a+ // point it would be clamped away from anyway.+ const r = Math.hypot(p.x, p.z);+ const max = GROUND_RADIUS - 0.5;+ let x = p.x, z = p.z;+ if (r > max) { const k = max / r; x *= k; z *= k; }+ runtime.goto(x, z);+ dismissHint();+ });+}++// ── Gesture buttons (opt-in) ────────────────────────────────────────────────+// Wire the floating wave/jump buttons (rendered only when ?gestures=true) to the+// same gesture path the host contract drives.+if (SHOW_GESTURE_UI && gesturesEl) {+ gesturesEl.querySelectorAll('.walk-gesture-btn').forEach((btn) => {+ btn.addEventListener('click', () => {+ const g = btn.dataset.gesture;+ if (g) { runtime.gesture(g); dismissHint(); }+ });+ });+}+// Apply a runtime background override (walk:config { bg }). 'transparent' lets// the host page show through; a hex/rgb paints a solid clear color.function applyBackground(bg) {@@ -1080,10 +1170,46 @@ function hideSpeechBubble() {if (bubbleEl) bubbleEl.style.opacity = '0';}+// ── Render-loop visibility gating ───────────────────────────────────────────+// Stop the rAF loop (and all WebGL work) whenever the embed is scrolled off the+// host viewport or its tab is hidden, then resume seamlessly when it returns —+// the per-frame dt cap (Math.min(getDelta(), 0.05)) absorbs the paused gap so+// the avatar never teleports. Without this an embed on a long page keeps burning+// GPU/battery while completely invisible.+let loopRunning = false;+let rafHandle = 0;+let canRender = false; // true once boot has a scene worth drawing+let onScreen = true;++function startLoop() {+ if (loopRunning || !canRender) return;+ loopRunning = true;+ clock.update(); // reset the delta baseline so the first frame's dt is small+ rafHandle = requestAnimationFrame(tick);+}+function stopLoop() {+ loopRunning = false;+ if (rafHandle) { cancelAnimationFrame(rafHandle); rafHandle = 0; }+}+function syncLoop() {+ if (canRender && onScreen && !document.hidden) startLoop();+ else stopLoop();+}++document.addEventListener('visibilitychange', syncLoop);+if (typeof IntersectionObserver === 'function') {+ const io = new IntersectionObserver((entries) => {+ onScreen = entries.some((en) => en.isIntersecting);+ syncLoop();+ }, { threshold: 0 });+ io.observe(stage);+}+// ── Boot ──────────────────────────────────────────────────────────────────loadAvatar().then(() => {- requestAnimationFrame(tick);+ canRender = true;+ syncLoop();}).catch((err) => {log.error('[walk-embed] failed to load avatar:', err);@@ -1092,6 +1218,8 @@ loadAvatar()statusEl.classList.add('is-error');statusEl.classList.remove('is-hidden');}+ hidePoster();emit(OUTBOUND.ERROR, { code: 'avatar_load_failed', message: String(err?.message || err) });- requestAnimationFrame(tick);+ canRender = true;+ syncLoop();});diff --git a/tests/pose-mirror.test.js b/tests/pose-mirror.test.jsnew file mode 100644index 000000000..5ae22da70--- /dev/null+++ b/tests/pose-mirror.test.js@@ -0,0 +1,95 @@+import { describe, it, expect } from 'vitest';+import { Quaternion, Euler } from 'three';+import {+ MannequinRig,+ mirrorBoneName,+ reflectWorldQuaternion,+} from '../src/pose-rig.js';+import { clonePose, posesEqual } from '../src/pose-animation.js';++describe('mirrorBoneName', () => {+ it('swaps Left ↔ Right and leaves center bones alone', () => {+ expect(mirrorBoneName('LeftArm')).toBe('RightArm');+ expect(mirrorBoneName('RightForeArm')).toBe('LeftForeArm');+ expect(mirrorBoneName('LeftHandIndex2')).toBe('RightHandIndex2');+ expect(mirrorBoneName('Hips')).toBe('Hips');+ expect(mirrorBoneName('Spine2')).toBe('Spine2');+ expect(mirrorBoneName('Head')).toBe('Head');+ });+});++describe('reflectWorldQuaternion', () => {+ it('keeps x, negates y and z (sagittal-plane reflection)', () => {+ const q = new Quaternion(0.1, 0.2, 0.3, 0.9);+ reflectWorldQuaternion(q);+ expect(q.x).toBeCloseTo(0.1, 12);+ expect(q.y).toBeCloseTo(-0.2, 12);+ expect(q.z).toBeCloseTo(-0.3, 12);+ expect(q.w).toBeCloseTo(0.9, 12);+ });+});++describe('posesEqual / clonePose', () => {+ const pose = {+ bones: { Hips: [0, 0, 0, 1], LeftArm: [0.1, 0.2, 0.3, 0.92] },+ rootPosition: { x: 0.5, y: 1, z: 0 },+ };++ it('clone is a deep, independent copy that compares equal', () => {+ const copy = clonePose(pose);+ expect(posesEqual(pose, copy)).toBe(true);+ copy.bones.LeftArm[0] = 0.99;+ expect(pose.bones.LeftArm[0]).toBe(0.1);+ expect(posesEqual(pose, copy)).toBe(false);+ });++ it('detects differing root position', () => {+ const copy = clonePose(pose);+ copy.rootPosition.x = 0.5 + 1e-2;+ expect(posesEqual(pose, copy)).toBe(false);+ });++ it('tolerates sub-epsilon noise', () => {+ const copy = clonePose(pose);+ copy.bones.LeftArm[1] += 1e-6;+ expect(posesEqual(pose, copy)).toBe(true);+ });+});++describe('rig.mirrorPose()', () => {+ function posed() {+ const rig = new MannequinRig();+ rig.setBoneEuler('LeftArm', { x: 0.4, y: 0.2, z: -0.7 });+ rig.setBoneEuler('RightLeg', { x: 0.3, y: 0, z: 0.1 });+ rig.setBoneEuler('Spine', { x: 0, y: 0.25, z: 0 });+ return rig;+ }++ it('is an involution — mirroring twice restores the original pose', () => {+ const rig = posed();+ const before = clonePose(rig.getPose());+ rig.mirrorPose();+ rig.mirrorPose();+ expect(posesEqual(before, rig.getPose(), 1e-6)).toBe(true);+ });++ it('actually changes an asymmetric pose', () => {+ const rig = posed();+ const before = clonePose(rig.getPose());+ rig.mirrorPose();+ expect(posesEqual(before, rig.getPose())).toBe(false);+ });++ it('reflects the left arm onto the right (and vice versa)', () => {+ const rig = posed();+ const before = clonePose(rig.getPose());+ rig.mirrorPose();+ const after = rig.getPose();+ // Left arm's pre-mirror rotation, reflected, lands on the right arm.+ const expected = reflectWorldQuaternion(+ new Quaternion(...before.bones.LeftArm),+ );+ const got = new Quaternion(...after.bones.RightArm);+ expect(got.angleTo(expected)).toBeLessThan(1e-6);+ });+});