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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n="demos_3d_home.meta_title">three.ws — Give Your AI a Body</title>
<meta name="robots" content="noindex" />
<link rel="stylesheet" href="/fonts/fonts.css" />
<style>
:root { color-scheme: dark; }
*, *::before, *::after { box-sizing: border-box; }
html, body { height: 100%; margin: 0; background: #050505; color: #eee; font: 15px/1.5 'Inter', -apple-system, system-ui, sans-serif; }
/* Canvas sits above all HTML — pointer-events:none so clicks pass through */
#avatar-canvas {
position: fixed;
top: 0; left: 0;
width: 100vw; height: 100vh;
pointer-events: none;
z-index: 999;
}
/* Page content — left column, visible through transparent canvas */
.page {
position: relative;
z-index: 10;
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
padding: 100px 56px 60px;
max-width: 520px;
}
.eyebrow {
display: inline-flex; align-items: center; gap: 9px;
font-size: 11px; font-weight: 600;
letter-spacing: 0.17em; text-transform: uppercase;
color: #3dc1ff; margin-bottom: 24px;
font-family: 'Space Grotesk', 'Inter', sans-serif;
}
.eyebrow-dot {
width: 7px; height: 7px; border-radius: 50%;
background: #3dc1ff; box-shadow: 0 0 8px rgba(61, 193, 255,0.7);
animation: blink 2.2s ease-in-out infinite;
}
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.2} }
.hero-title {
font-family: 'Space Grotesk', 'Inter', sans-serif;
font-size: clamp(38px, 4.5vw, 68px);
font-weight: 800; letter-spacing: -0.03em;
line-height: 1.04; margin: 0 0 20px; color: #fff;
}
.hero-title em { color: #3dc1ff; font-style: normal; }
/* Proximity shadow — JS updates --agent-shadow as the avatar nears #sit-line.
Sharper + darker as he sits down on the text. */
#sit-line {
text-shadow: var(--agent-shadow, none);
transition: text-shadow 90ms linear;
}
.hero-sub {
color: #555870; font-size: 15.5px; line-height: 1.7;
max-width: 38ch; margin: 0 0 44px;
}
/* Physical 3D buttons */
.cta-row { display: flex; flex-direction: column; gap: 14px; align-items: flex-start; }
.btn {
display: inline-flex; align-items: center; gap: 10px;
padding: 16px 32px; border: none; border-radius: 14px;
font: 700 15px/1 'Inter', inherit; cursor: pointer; text-decoration: none;
user-select: none;
/* GSAP squishes downward into the page, not into its own center */
transform-origin: bottom center;
will-change: transform;
}
.btn-primary {
background: linear-gradient(160deg, #5ad1ff, #2cb0ef);
color: #0b0b0b;
box-shadow: 0 8px 0 0 #005a8a, 0 10px 28px rgba(61, 193, 255,0.28);
}
.btn-primary:hover { filter: brightness(1.07); }
.btn-ghost {
background: rgba(255,255,255,0.05); color: #bbb;
border: 1.5px solid rgba(255,255,255,0.1);
box-shadow: 0 5px 0 0 rgba(255,255,255,0.04);
}
/* Animation control chips — trigger one-shot clips on the avatar */
.anim-controls {
display: flex; flex-wrap: wrap; gap: 8px;
margin-top: 30px;
}
.anim-label {
width: 100%; margin: 0 0 4px;
font: 600 10px/1 'Space Grotesk','Inter',sans-serif;
letter-spacing: 0.18em; text-transform: uppercase;
color: #555870;
}
.chip {
display: inline-flex; align-items: center; gap: 6px;
padding: 9px 14px; border-radius: 999px;
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.1);
color: #ccd; font: 600 12px/1 'Inter', sans-serif;
cursor: pointer; user-select: none;
letter-spacing: 0.02em;
transition: background 120ms ease, border-color 120ms ease,
color 120ms ease, transform 120ms ease;
}
.chip:hover { background: rgba(61, 193, 255,0.08); border-color: rgba(61, 193, 255,0.35); color: #fff; }
.chip:active { transform: translateY(1px); }
.chip[aria-pressed="true"] {
background: rgba(61, 193, 255,0.16);
border-color: rgba(61, 193, 255,0.55);
color: #3dc1ff;
}
.chip[disabled] { opacity: 0.4; cursor: wait; }
/* Nav */
.nav {
position: fixed; top: 0; left: 0; right: 0; z-index: 20;
display: flex; align-items: center; gap: 16px; padding: 14px 28px;
background: rgba(4,5,13,0.55); backdrop-filter: blur(14px);
border-bottom: 1px solid rgba(255,255,255,0.04);
}
.nav .brand { font: 700 15px/1 'Space Grotesk','Inter',sans-serif; color:#fff; text-decoration:none; display:flex; align-items:center; gap:7px; }
.brand-dot { width:8px; height:8px; border-radius:50%; background:linear-gradient(135deg,#3dc1ff,#aacc00); box-shadow:0 0 10px rgba(61, 193, 255,0.6); }
.nav a.link { color:#555870; text-decoration:none; font-size:13px; margin-left:auto; }
.nav a.link:hover { color:#3dc1ff; }
/* Mobile: tighter padding, top-aligned so chips stay onscreen, smaller buttons */
@media (max-width: 640px) {
.page {
padding: 84px 22px 40px;
justify-content: flex-start;
max-width: 100%;
}
.hero-sub { margin-bottom: 28px; }
.btn { padding: 14px 22px; font-size: 14px; }
.cta-row { gap: 10px; }
.anim-controls { margin-top: 22px; }
.chip { padding: 8px 12px; font-size: 11.5px; }
}
</style>
</head>
<body>
<div class="nav">
<a href="/" class="brand">
<img src="/three.svg" width="20" height="20" alt="" />
<span class="brand-dot"></span>
three.ws
</a>
<a href="/demos/" class="link" data-i18n="demos_3d_home.lab">← lab</a>
</div>
<div class="page">
<div class="eyebrow">
<span class="eyebrow-dot"></span>
<span data-i18n="demos_3d_home.the_3d_layer_for_onchain_ai_agents">The 3D layer for onchain AI agents</span>
</div>
<h1 class="hero-title" data-i18n-html="demos_3d_home.give_your_ai_a_body"><span id="sit-line">Give</span> your AI<br />a <em>body.</em></h1>
<p class="hero-sub" data-i18n="demos_3d_home.born_in_3d_raised_on_chain_yours">
Born in 3D. Raised on-chain. Yours forever.
Your AI has been a chatbox long enough — give it a body,
a personality, and a permanent home.
</p>
<div class="cta-row">
<a href="/create" class="btn btn-primary" id="cta-btn" data-i18n-html="demos_3d_home.build_your_agent_free">
<span>Build your agent — free</span>
<span>→</span>
</a>
<a href="/app" class="btn btn-ghost" target="_blank" rel="noopener" data-i18n-html="demos_3d_home.watch_it_live">
<span>Watch it live</span>
<span style="opacity:.4">↗</span>
</a>
</div>
<div class="anim-controls" id="anim-controls" role="group" aria-label="Avatar animations">
<div class="anim-label">Make her…</div>
<button class="chip" data-clip="wave" type="button" disabled data-i18n="demos_3d_home.wave">👋 Wave</button>
<button class="chip" data-clip="rumba" type="button" disabled data-i18n="demos_3d_home.dance">💃 Dance</button>
<button class="chip" data-clip="celebrate" type="button" disabled data-i18n="demos_3d_home.celebrate">🎉 Celebrate</button>
<button class="chip" data-clip="taunt" type="button" disabled data-i18n="demos_3d_home.taunt">😝 Taunt</button>
</div>
</div>
<!-- Transparent overlay canvas — avatar renders above all HTML -->
<canvas id="avatar-canvas"></canvas>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { getDecoders } from '/src/viewer/internal.js';
import { gsap } from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';
const canvas = document.getElementById('avatar-canvas');
const ctaBtn = document.getElementById('cta-btn');
const sitLine = document.getElementById('sit-line');
const animPanel = document.getElementById('anim-controls');
const chips = [...animPanel.querySelectorAll('.chip')];
// ── Tracked timers ────────────────────────────────────────────────
// Every setTimeout used by the sit→stand→jump cycle is registered
// here so a performAction() click can cancel all pending steps
// without leaking phase transitions onto the perform animation.
const pendingTimers = new Set();
function later(fn, ms) {
const id = setTimeout(() => { pendingTimers.delete(id); fn(); }, ms);
pendingTimers.add(id);
return id;
}
function clearTimers() {
for (const id of pendingTimers) clearTimeout(id);
pendingTimers.clear();
}
// ── Renderer: alpha:true → transparent background ─────────────────
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
const scene = new THREE.Scene();
// scene.background intentionally NOT set → transparent
// ── OrthographicCamera: 1 world unit = PX_PER_UNIT pixels ────────
// This makes screen→world mapping trivially exact: no perspective math.
// Avatar (1.8u tall) = 216px on desktop, scales down on narrow viewports
// so the figure doesn't dominate a phone screen.
let PX_PER_UNIT = 120;
function computePxPerUnit() {
return window.innerWidth < 640 ? 92 : 120;
}
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
camera.position.z = 10;
function updateFrustum() {
PX_PER_UNIT = computePxPerUnit();
const hw = window.innerWidth / PX_PER_UNIT / 2;
const hh = window.innerHeight / PX_PER_UNIT / 2;
camera.left = -hw; camera.right = hw;
camera.top = hh; camera.bottom = -hh;
camera.updateProjectionMatrix();
}
// DOM rect → world position (standard NDC + unproject pipeline)
// Works for any DOM element regardless of camera type.
const _v3 = new THREE.Vector3();
function domToWorld(screenX, screenY) {
_v3.set(
(screenX / window.innerWidth) * 2 - 1,
-(screenY / window.innerHeight) * 2 + 1,
0
);
_v3.unproject(camera);
return { x: _v3.x, y: _v3.y };
}
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight, false);
updateFrustum();
}
window.addEventListener('resize', () => { resize(); recalibrateSitAnchor(); });
resize();
// ── Smooth lerp to a new world position (used for ResizeObserver) ─
// We only retarget while the avatar is "at rest" on the sit-line — during
// jump/standup the trajectory math owns position and we mustn't fight it.
let recalSlide = null;
function lerpAvatarTo(target, ms = 280) {
if (!avatar) return;
if (recalSlide) cancelAnimationFrame(recalSlide);
const fromX = avatar.position.x, fromY = avatar.position.y;
const t0 = performance.now();
(function step(now) {
const sp = Math.min((now - t0) / ms, 1);
const e = smoothstep(sp);
avatar.position.x = fromX + (target.x - fromX) * e;
avatar.position.y = fromY + (target.y - fromY) * e;
if (sp < 1) recalSlide = requestAnimationFrame(step);
else recalSlide = null;
})(performance.now());
}
function recalibrateSitAnchor() {
if (!avatar) return;
const next = getSitWorld();
startW = next; // keep the resting anchor authoritative
if (phase === 'sitting' || phase === 'standingUp' || phase === 'loading') {
lerpAvatarTo(next, 280);
}
}
// ResizeObserver: the window resize event fires once, but text reflow
// (font load, line-wrap on viewport shrink) changes the rect bounds without
// a window resize. Observe the target element directly so we always re-anchor.
const sitLineRO = new ResizeObserver(() => recalibrateSitAnchor());
sitLineRO.observe(sitLine);
// ── Lights ────────────────────────────────────────────────────────
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
const key = new THREE.DirectionalLight(0xfff4dc, 2.0);
key.position.set(3, 6, 5);
scene.add(key);
const rim = new THREE.DirectionalLight(0x4060ff, 0.6);
rim.position.set(-4, 3, -2);
scene.add(rim);
const fill = new THREE.DirectionalLight(0xffeedd, 0.4);
fill.position.set(0, 2, 7);
scene.add(fill);
// ── Avatar ────────────────────────────────────────────────────────
let avatar = null, mixer = null, rootBone = null, baseRootPos = null;
let sitAction = null, standupAction = null, fallAction = null;
// On-demand clips played by the animation chips. Each is a one-shot
// (clampWhenFinished:true) action whose 'finished' event hands control
// back to the sit cycle. Looping clips (e.g. rumba) use a tracked
// timer to stop after PERFORM_LOOP_MS.
const performActions = {}; // { wave, rumba, celebrate, taunt }
let currentPerform = null;
const PERFORM_LOOP_MS = 6200; // dwell on looping clips
const PERFORM_CLIPS = [
{ name: 'wave', file: '/animations/clips/wave.json', loop: false },
{ name: 'rumba', file: '/animations/clips/rumba.json', loop: true },
{ name: 'celebrate', file: '/animations/clips/celebrate.json', loop: false },
{ name: 'taunt', file: '/animations/clips/taunt.json', loop: false },
];
let phase = 'loading'; // loading → sitting → standingUp → jumping → resting → performing
let startW = { x: 0, y: 0 }; // sit/stand anchor (above the text)
let seqT = 0, landed = false, jumpTarget = { x: 0, y: 0 };
const STAND_S = 2.566; // standup clip duration
// Jumpdown clip runs at 1.7x via fallAction.timeScale so the drop
// feels decisive rather than floaty; JUMP_S mirrors the played-back
// duration (2.667 / 1.7) so the position math finishes with the clip.
const JUMP_CLIP_S = 2.667;
const JUMP_RATE = 1.7;
const JUMP_S = JUMP_CLIP_S / JUMP_RATE;
const SIT_DWELL_S = 2.4; // how long he sits before standing
// Earliest-possible fraction at which the impact effects MAY fire.
// The actual trigger is gated on screen-space proximity below — this
// just prevents the squish from going off during the arc's apex.
const LAND_P = 0.92;
// Feet must be within this many SCREEN px of the button top before the
// squish/splash fire. The parabolic arc only returns to 0 at p≈1.0, so
// gating on real px (not the fraction p) keeps the impact synced.
const LAND_PX = 14;
// Straight drop: no arc, no yaw. Reads as a deliberate fall rather
// than a hesitating leap. She lands on whatever sits directly below
// her perch (the CTA button extends past "Give" to the right, so a
// vertical drop lands her on the button's left portion).
const PEAK_U = 0;
const JUMP_YAW = 0;
// cz.glb origin is at the feet (verified in /demos/button-jump.html).
// FEET_OFFSET stays 0 so the visible feet land on the button top.
// SIT_OFFSET pushes the origin DOWN by the seated feet→butt distance,
// so the butt — not the feet — rests on the text line. Tuned to the
// sitidle pose where legs dangle below the hips; scales with the
// avatar's on-screen size so a mobile-sized figure perches correctly.
// Lowered from 120 so her butt clears the line-box top and visibly
// perches ON TOP of "Give" rather than sinking onto the baseline.
const FEET_OFFSET_PX = 0;
const SIT_OFFSET_PX_BASE = 90;
function sitOffsetPx() {
return SIT_OFFSET_PX_BASE * (PX_PER_UNIT / 120);
}
function smoothstep(t) { return t * t * (3 - 2 * t); }
// Sit anchor: perched centered on top of "Give".
// SIT_OFFSET_PX shifts the GLB origin DOWN in screen px so the visible
// butt rests on the text rather than the origin landing on the text.
function getSitWorld() {
const rect = sitLine.getBoundingClientRect();
const sx = rect.left + rect.width / 2;
const sy = rect.top + sitOffsetPx();
return domToWorld(sx, sy);
}
// Jump target: visible feet land on the top edge of the button.
// FEET_OFFSET_PX shifts the origin DOWN so feet (which sit above origin
// for this GLB) align to rect.top instead of clearing it.
function getButtonWorld() {
const rect = ctaBtn.getBoundingClientRect();
return domToWorld(rect.left + rect.width / 2, rect.top + FEET_OFFSET_PX);
}
function placeAtStart() {
if (!avatar) return;
startW = getSitWorld();
if (phase === 'sitting' || phase === 'loading') {
avatar.position.set(startW.x, startW.y, 0);
}
}
function fireSquish() {
// Kill any in-flight tween so rapid re-fires don't stack
gsap.killTweensOf(ctaBtn);
// HARD landing: deep slam (50% compression, exaggerated bulge),
// faster than a gentle bounce, with a stronger elastic recoil.
// transform-origin:bottom center → squishes into the page.
gsap.to(ctaBtn, {
scaleY: 0.5,
scaleX: 1.15,
duration: 0.07,
ease: 'power4.out',
onComplete: () => {
gsap.to(ctaBtn, {
scaleY: 1,
scaleX: 1,
duration: 1.0,
ease: 'elastic.out(1.4, 0.25)',
});
},
});
// Screen shake — short, sharp, vertical-biased. Three quick
// oscillations of the page wrapper read as "the impact rattled
// the layout" without disorienting the reader.
const pageEl = document.querySelector('.page');
if (pageEl) {
gsap.killTweensOf(pageEl);
gsap.fromTo(
pageEl,
{ x: 0, y: -6 },
{
x: 0, y: 0,
duration: 0.55,
ease: 'elastic.out(1.6, 0.22)',
},
);
}
}
// Splash on impact: a fan of lime droplets squirts from the button's
// top edge with real ballistic motion (initial velocity + gravity),
// so the landing reads as wet/squishy rather than a purely synthetic
// bounce. DOM nodes so the splash composites with the button itself.
const SPLASH_GRAVITY = 1800; // px/s² — heavier so drops fall faster
const SPLASH_COUNT = 36; // more spray for the harder landing
function fireSplash(ox, oy) {
if (ox == null || oy == null) {
const rect = ctaBtn.getBoundingClientRect();
ox = rect.left + rect.width / 2;
oy = rect.top + 2;
}
const drops = [];
for (let i = 0; i < SPLASH_COUNT; i++) {
const size = 6 + Math.random() * 10;
const el = document.createElement('div');
el.style.cssText =
`position:fixed;` +
`left:${ox - size / 2}px;top:${oy - size / 2}px;` +
`width:${size}px;height:${size}px;border-radius:50%;` +
`background:radial-gradient(circle at 35% 30%,#c4ecff,#3dc1ff 55%,#0070b0);` +
`box-shadow:0 0 6px rgba(61, 193, 255,0.65);` +
`pointer-events:none;z-index:30;will-change:transform,opacity;`;
document.body.appendChild(el);
// Fan upward: ~-150° to -30°, biased toward overhead spray
const angle = -Math.PI / 2 + (Math.random() - 0.5) * Math.PI * 1.15;
const speed = 340 + Math.random() * 460;
drops.push({
el, x: 0, y: 0,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed,
life: 0,
max: 0.85 + Math.random() * 0.5,
});
}
let last = performance.now();
(function step(now) {
const dt = Math.min((now - last) / 1000, 0.04);
last = now;
let alive = false;
for (const d of drops) {
if (!d.el) continue;
d.life += dt;
d.vy += SPLASH_GRAVITY * dt;
d.x += d.vx * dt;
d.y += d.vy * dt;
const t = d.life / d.max;
if (t >= 1) { d.el.remove(); d.el = null; continue; }
d.el.style.opacity = String(1 - t * t);
d.el.style.transform = `translate(${d.x.toFixed(1)}px, ${d.y.toFixed(1)}px)`;
alive = true;
}
if (alive) requestAnimationFrame(step);
})(last);
}
function startSit() {
if (!sitAction) return;
phase = 'sitting';
placeAtStart();
fallAction?.stop();
standupAction?.stop();
// Stop any in-flight perform clip so it doesn't blend into sitidle
for (const a of Object.values(performActions)) a.stop();
currentPerform = null;
// Face the camera the entire cycle — no turning around
gsap.killTweensOf(avatar.rotation);
avatar.rotation.set(0, 0, 0);
sitAction.reset().play();
later(startStandup, SIT_DWELL_S * 1000);
}
// Crossfade duration tuned for organic blending between morph targets
// and skeletal animations. ~0.3s reads as "intentional" rather than a snap.
const FADE_S = 0.3;
function startStandup() {
if (!standupAction || phase !== 'sitting') return;
phase = 'standingUp';
// Crossfade sit → standup, no rotation change
standupAction.reset();
standupAction.crossFadeFrom(sitAction, FADE_S, false).play();
// Trigger jump just before standup ends, leaving room for the next fade
later(triggerJump, (STAND_S - FADE_S) * 1000);
}
function triggerJump() {
if (!avatar || !fallAction || phase === 'jumping') return;
// Re-read endpoints fresh so the trajectory is always layout-correct.
// Straight drop: X stays at the sit anchor; only Y falls to the button.
startW = getSitWorld();
const btn = getButtonWorld();
jumpTarget = { x: startW.x, y: btn.y };
phase = 'jumping'; seqT = 0; landed = false;
fallAction.reset();
fallAction.crossFadeFrom(standupAction, FADE_S, false).play();
}
function updateSeq(dt) {
if (phase !== 'jumping' || !avatar) return;
seqT += dt;
const p = Math.min(seqT / JUMP_S, 1);
// Straight drop: X is locked (jumpTarget.x === startW.x) and Y
// follows a gravity-like p² curve — barely moves at the top,
// accelerates into the landing. No upward arc and no yaw, so
// the motion reads as "fell off the perch" instead of "leapt".
const x = startW.x;
const y = startW.y + (jumpTarget.y - startW.y) * (p * p);
avatar.position.set(x, y, 0);
// Squish + splash gate on real screen-space contact so the
// effects fire on the actual landing frame.
if (!landed && p >= LAND_P) {
const dyPx = Math.abs(avatar.position.y - jumpTarget.y) * PX_PER_UNIT;
if (dyPx < LAND_PX) {
landed = true;
fireSquish();
const btnRect = ctaBtn.getBoundingClientRect();
const sitRect = sitLine.getBoundingClientRect();
const landX = sitRect.left + sitRect.width / 2;
fireSplash(landX, btnRect.top + 2);
}
}
if (p >= 1) {
phase = 'resting';
later(() => {
// 60% of landings, surprise the user with a perform clip on
// the button instead of an immediate slide back — breaks the
// sit→jump→sit monotony and showcases the chip animations
// without requiring a click. The perform's own resume path
// handles the slide back to sit, so we just bail here.
if (maybeAutoPerform()) return;
const fromX = avatar.position.x;
const fromY = avatar.position.y;
const back = getSitWorld();
startW = back;
// Settle yaw back to 0 just in case the trajectory ended mid-arc
avatar.rotation.y = 0;
const t0 = performance.now();
(function slide(now) {
const sp = Math.min((now - t0) / 700, 1);
avatar.position.x = fromX + (back.x - fromX) * smoothstep(sp);
avatar.position.y = fromY + (back.y - fromY) * smoothstep(sp);
if (sp < 1) requestAnimationFrame(slide);
else {
avatar.position.set(back.x, back.y, 0);
startSit();
}
})(performance.now());
}, 1600);
}
}
// Click skips straight to the jump (still must crossfade from current pose)
ctaBtn.addEventListener('click', e => {
e.preventDefault();
if (phase === 'sitting' || phase === 'standingUp') triggerJump();
});
// ── On-demand performance: chip click → one-shot clip, then resume cycle
let returnSlide = null; // rAF id for the post-perform slide back to sit
function cancelReturnSlide() {
if (returnSlide) { cancelAnimationFrame(returnSlide); returnSlide = null; }
}
function activeAction() {
if (sitAction?.isRunning()) return sitAction;
if (standupAction?.isRunning()) return standupAction;
if (fallAction?.isRunning()) return fallAction;
return currentPerform;
}
function setChipPressed(name) {
for (const c of chips) c.setAttribute('aria-pressed', String(c.dataset.clip === name));
}
function performAction(name) {
const act = performActions[name];
if (!avatar || !act) return;
if (phase === 'performing' && currentPerform === act) return;
// Hand-off: stop the sit/jump cycle and any in-flight position lerp.
// cancelReturnSlide() is critical — without it, a previous perform's
// slide-back rAF would still complete and call startSit(), nuking
// the perform we just started.
clearTimers();
cancelReturnSlide();
if (recalSlide) { cancelAnimationFrame(recalSlide); recalSlide = null; }
phase = 'performing';
// Stand at the CTA button — keeps the avatar centered in the
// reader's eye-line where the page already focuses attention.
const stage = getButtonWorld();
avatar.position.set(stage.x, stage.y, 0);
gsap.killTweensOf(avatar.rotation);
avatar.rotation.set(0, 0, 0);
const prev = activeAction();
act.reset();
if (prev && prev !== act) act.crossFadeFrom(prev, FADE_S, false);
act.play();
currentPerform = act;
setChipPressed(name);
// Loops have no 'finished' event — schedule the resume manually.
const def = PERFORM_CLIPS.find(c => c.name === name);
if (def?.loop) later(() => resumeCycleAfterPerform(act), PERFORM_LOOP_MS);
}
function resumeCycleAfterPerform(act) {
if (phase !== 'performing' || currentPerform !== act) return;
setChipPressed(null);
// Slide the avatar from the CTA back to the sit anchor before
// startSit teleports + plays sitidle, so the return reads as
// "walked back to perch" rather than a hard cut.
phase = 'resting';
cancelReturnSlide();
const fromX = avatar.position.x, fromY = avatar.position.y;
const back = getSitWorld();
startW = back;
avatar.rotation.y = 0;
const t0 = performance.now();
(function slide(now) {
// If a new perform took over mid-slide, abandon: phase has
// already advanced and the new perform is owning the avatar.
if (phase !== 'resting') { returnSlide = null; return; }
const sp = Math.min((now - t0) / 700, 1);
avatar.position.x = fromX + (back.x - fromX) * smoothstep(sp);
avatar.position.y = fromY + (back.y - fromY) * smoothstep(sp);
if (sp < 1) returnSlide = requestAnimationFrame(slide);
else {
returnSlide = null;
avatar.position.set(back.x, back.y, 0);
startSit(); // resets perform clip + plays sitidle
}
})(performance.now());
}
for (const chip of chips) {
chip.addEventListener('click', () => performAction(chip.dataset.clip));
}
// Auto-perform: occasionally play a one-shot clip after landing so the
// loop reads as "alive" instead of mechanical. Skips rumba (long, looping)
// and only fires once every couple of cycles so it stays surprising.
const AUTO_PERFORM_CLIPS = ['wave', 'celebrate', 'taunt'];
let landingsSinceAutoPerform = 0;
function maybeAutoPerform() {
landingsSinceAutoPerform++;
if (landingsSinceAutoPerform < 2) return false;
if (!performActions.wave) return false; // clips not loaded yet
if (Math.random() >= 0.6) return false;
landingsSinceAutoPerform = 0;
const pick = AUTO_PERFORM_CLIPS[Math.floor(Math.random() * AUTO_PERFORM_CLIPS.length)];
performAction(pick);
return true;
}
// ── Load avatar + animations ──────────────────────────────────────
// Realistic Avaturn-rigged humanoid; clips in /public/animations/clips
// are retargeted to this rig (see public/animations/registry.json).
// default.glb declares EXT_meshopt_compression + KHR_mesh_quantization in
// extensionsRequired, so a bare GLTFLoader throws "setMeshoptDecoder must be
// called before loading compressed files" and the avatar never appears. Wire
// the shared decoder set first, same as /demos/audio2face.html.
const avatarLoader = new GLTFLoader();
getDecoders().then(({ dracoLoader, ktx2Loader, meshoptDecoder }) => {
avatarLoader.setDRACOLoader(dracoLoader)
.setKTX2Loader(ktx2Loader.detectSupport(renderer))
.setMeshoptDecoder(meshoptDecoder);
loadAvatar();
});
function loadAvatar() {
avatarLoader.load('/avatars/default.glb', gltf => {
avatar = gltf.scene;
avatar.traverse(n => {
if (!rootBone && /^(Hips|Root|mixamorig:?Hips)$/i.test(n.name))
rootBone = n;
});
// Yaw is choreographed per-phase: facing camera while seated, rotates
// toward the jump direction during standup.
avatar.rotation.y = 0;
scene.add(avatar);
mixer = new THREE.AnimationMixer(avatar);
mixer.addEventListener('finished', e => {
if (phase === 'performing' && e.action === currentPerform) {
resumeCycleAfterPerform(e.action);
}
});
const fetchClip = (file) => fetch(file).then(r => r.json());
Promise.all([
fetchClip('/animations/clips/sitidle.json'),
fetchClip('/animations/clips/standup.json'),
fetchClip('/animations/clips/jumpdown.json'),
...PERFORM_CLIPS.map(c => fetchClip(c.file)),
]).then(([sitJson, standJson, jumpJson, ...performJsons]) => {
sitAction = mixer.clipAction(THREE.AnimationClip.parse(sitJson));
sitAction.setLoop(THREE.LoopRepeat, Infinity);
standupAction = mixer.clipAction(THREE.AnimationClip.parse(standJson));
standupAction.setLoop(THREE.LoopOnce, 1);
standupAction.clampWhenFinished = true;
fallAction = mixer.clipAction(THREE.AnimationClip.parse(jumpJson));
fallAction.setLoop(THREE.LoopOnce, 1);
fallAction.clampWhenFinished = true;
fallAction.timeScale = JUMP_RATE;
PERFORM_CLIPS.forEach((def, i) => {
const a = mixer.clipAction(THREE.AnimationClip.parse(performJsons[i]));
if (def.loop) {
a.setLoop(THREE.LoopRepeat, Infinity);
} else {
a.setLoop(THREE.LoopOnce, 1);
a.clampWhenFinished = true;
}
performActions[def.name] = a;
});
// Chips were disabled until clips landed — enable now.
for (const c of chips) c.disabled = false;
if (rootBone) baseRootPos = rootBone.position.clone();
// Root-bone lock. The jump clip's root translation must be
// fully clamped during 'jumping' so it doesn't compete with
// our JS-driven parabolic arc. For sit / standup / resting,
// we leave Hips.y alone (vertical pose matters: seated vs
// standing height comes from the clip), but clamp X and Z
// so root motion baked into the clips can't drift her
// horizontally before she jumps — she stays parked on the
// sit anchor until triggerJump fires.
const _r = renderer.render.bind(renderer);
renderer.render = (sc, cam) => {
try {
if (rootBone && baseRootPos) {
if (phase === 'jumping') {
rootBone.position.copy(baseRootPos);
} else {
rootBone.position.x = baseRootPos.x;
rootBone.position.z = baseRootPos.z;
}
}
} catch (_) {}
_r(sc, cam);
};
// Begin the cycle: sit on the text, stand up, jump to the button
startSit();
});
});
}
// ── Proximity shadow: ground the avatar by sharpening the text shadow
// on #sit-line as he descends onto it. We project the avatar's world
// position to screen px, compare against the rect's top edge, then map
// vertical distance → shadow blur/darkness. As he sits (distance≈0),
// the shadow is sharp + dark; as he leaves (distance≫), shadow fades.
const _proj = new THREE.Vector3();
function avatarScreenY() {
_proj.set(avatar.position.x, avatar.position.y, avatar.position.z);
_proj.project(camera);
return (1 - _proj.y) * 0.5 * window.innerHeight;
}
function updateProximityShadow() {
if (!avatar) return;
const rect = sitLine.getBoundingClientRect();
const ay = avatarScreenY();
// Distance from avatar origin (feet) to text top edge, in px.
// Negative = he's below the text line, clamp to 0 so shadow stays max.
const dy = Math.max(0, rect.top - ay);
// Map 0..220px → proximity 1..0 (closer = stronger shadow)
const prox = 1 - Math.min(dy / 220, 1);
if (prox <= 0.01) {
sitLine.style.setProperty('--agent-shadow', 'none');
return;
}
// Sharper (smaller blur) + darker as he gets closer.
const blur = (10 * (1 - prox) + 2).toFixed(2); // 2px → 12px
const offsetY = (2 + 6 * prox).toFixed(2); // 2px → 8px
const alpha = (0.55 * prox).toFixed(3); // 0 → 0.55
sitLine.style.setProperty(
'--agent-shadow',
`0 ${offsetY}px ${blur}px rgba(0,0,0,${alpha})`
);
}
// ── Render loop ───────────────────────────────────────────────────
const clock = new THREE.Timer();
(function tick(timestamp) {
requestAnimationFrame(tick);
try {
clock.update(timestamp);
const dt = Math.min(clock.getDelta(), 0.05);
mixer?.update(dt);
updateSeq(dt);
updateProximityShadow();
renderer.render(scene, camera);
} catch (_) {}
})();
</script>
<script src="/brand.js" defer></script>
<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
<script type="module" src="/i18n.js"></script>
</body>
</html>