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(event): add /event, the public landing page for the live meetup
nirholasa2378d4688f5
diff --git a/api/_lib/war-ticket.js b/api/_lib/war-ticket.jsnew file mode 100644index 000000000..c8624a2ca--- /dev/null+++ b/api/_lib/war-ticket.js@@ -0,0 +1,109 @@+// War ticket — a short-lived, HMAC-signed pairing the Coin Wars arena trusts.+//+// Why this exists: ClashRoom is defined with filterBy(['matchKey']), so whoever+// joins a key FIRST also creates the room, and the room reads the two competing+// communities (mint, name, symbol, image) out of that first client's join+// options. Left unsigned, a fighter could open a room claiming any opponent they+// liked and post a league result against a community that never turned up.+//+// So the pairing is decided here, on the API side, by the matchmaker+// (multiplayer/src/war-matchmaking.js over the shared queue), and sealed into a+// ticket. The game server verifies it with nothing but a shared secret and takes+// the faction identities from the TICKET, never from the client. Same trust+// model as holder-pass.js, one layer up: the holder pass proves *you may fight+// for this coin*, the war ticket proves *this is a real match between these two*.+//+// Format: base64url(JSON(payload)) + '.' + base64url(HMAC-SHA256(body)).+// Payload: { k:'war', matchKey, network, a:{…}, b:{…}, iat, exp }. Verification+// lives in multiplayer/src/war-ticket.js, byte-for-byte compatible with sign().++import crypto from 'node:crypto';+import { mintMatchKey, parseMatchKey, orderMints } from '../../multiplayer/src/war-matchmaking.js';++// Lifetime of a ticket. Matches the pairing window in war-matchmaking.js+// (PAIR_TTL_MS) so a ticket never outlives the queue entry that produced it, and+// a player who parks the arena tab for an hour re-queues rather than dropping+// into a battle nobody else is still waiting for.+export const TICKET_TTL_S = 10 * 60;++const DEV_SECRET = 'three-ws-war-ticket-dev-secret';++let _warned = false;+function secret() {+ // WAR_RESULT_SECRET already exists for the result-reporting direction; reuse it+ // (then HOLDER_PASS_SECRET) so a deployment that has either one gets a working+ // arena without a third secret to provision.+ const s = process.env.WAR_TICKET_SECRET || process.env.WAR_RESULT_SECRET || process.env.HOLDER_PASS_SECRET;+ if (s) return s;+ if (process.env.NODE_ENV === 'production') {+ throw new Error(+ '[war-ticket] WAR_TICKET_SECRET (or WAR_RESULT_SECRET / HOLDER_PASS_SECRET) is required in production — refusing to mint tickets with the dev secret.',+ );+ }+ if (!_warned) {+ _warned = true;+ console.warn(+ '[war-ticket] no ticket secret set — using the insecure dev secret. ' ++ 'Set WAR_TICKET_SECRET in production or a war pairing can be forged.',+ );+ }+ return DEV_SECRET;+}++function b64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+}++function hmac(body) {+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());+}++function faction(coin) {+ return {+ mint: String(coin?.mint || ''),+ name: clip(coin?.name, 48) || clip(coin?.symbol, 16) || 'Community',+ symbol: clip(coin?.symbol, 16),+ image: clip(coin?.image, 400),+ };+}++function clip(v, max) {+ return typeof v === 'string' ? v.replace(/[\u0000-\u001f]/g, '').trim().slice(0, max) : '';+}++/**+ * Seal one pairing into a ticket. The two factions are stored in the SAME+ * canonical order the matchKey encodes (lower mint is A), so every ticket for a+ * given key describes the same match no matter which side asked for it, and the+ * arena's A/B scoreboard reads identically in both worlds.+ * @param {{ matchKey: string, network?: string, coinA: object, coinB: object }} pairing+ * @returns {string|null} the ticket, or null when the pairing is not a real match+ */+export function signWarTicket({ matchKey, network = 'mainnet', coinA, coinB }) {+ const parsed = parseMatchKey(matchKey);+ if (!parsed) return null;+ const a = faction(coinA);+ const b = faction(coinB);+ if (!a.mint || !b.mint || a.mint === b.mint) return null;+ const [lo] = orderMints(a.mint, b.mint);+ // Canonical order: A is the lower mint, which is exactly what the key encodes.+ const [first, second] = lo === a.mint ? [a, b] : [b, a];+ if (first.mint !== parsed.mints[0] || second.mint !== parsed.mints[1]) return null;++ const now = Math.floor(Date.now() / 1000);+ const payload = {+ k: 'war',+ matchKey,+ network: parsed.network || String(network || 'mainnet'),+ a: first,+ b: second,+ iat: now,+ exp: now + TICKET_TTL_S,+ };+ const body = b64url(JSON.stringify(payload));+ return `${body}.${hmac(body)}`;+}++// Re-exported so the endpoint mints keys and tickets from one import, and so the+// key format has exactly one owner (war-matchmaking.js).+export { mintMatchKey, parseMatchKey };diff --git a/data/pages.json b/data/pages.jsonindex 3e3567b80..5443d96f1 100644--- a/data/pages.json+++ b/data/pages.json@@ -2101,6 +2101,14 @@"priority": 0.6,"changefreq": "weekly"},+ {+ "path": "/event",+ "title": "Live event",+ "description": "The live three.ws community meetup: when it starts, what is on the agenda, who is in the world right now, and the event leaderboard.",+ "added": "2026-08-07",+ "priority": 0.6,+ "changefreq": "weekly"+ },{"path": "/mirror","title": "Copy Trading",diff --git a/pages/event.html b/pages/event.htmlnew file mode 100644index 000000000..572153dc1--- /dev/null+++ b/pages/event.html@@ -0,0 +1,320 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <script>/* three.ws theme boot - no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>The live event · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta+ name="description"+ content="One link for the live gathering in the three.ws world: a ticking countdown, the schedule in your own timezone, an add-to-calendar file, and the door into the shared 3D world. Bring a photo, get an avatar, drop in."+ />+ <meta name="theme-color" content="#000000" />+ <link rel="canonical" href="https://three.ws/event" />++ <meta property="og:type" content="website" />+ <meta property="og:title" content="The live event · three.ws" />+ <meta property="og:description" content="The countdown, the schedule in your timezone, and the one door into the shared 3D world. Bring a photo, get an avatar, drop in." />+ <meta property="og:url" content="https://three.ws/event" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=The+live+event&d=The+countdown%2C+the+schedule+in+your+timezone%2C+and+the+one+door+into+the+shared+3D+world.+Bring+a+photo%2C+get+an+avatar%2C+drop+in&p=%2Fevent" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="The live event · three.ws" />+ <meta name="twitter:description" content="The countdown, the schedule in your timezone, and the one door into the shared 3D world. Bring a photo, get an avatar, drop in." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=The+live+event&d=The+countdown%2C+the+schedule+in+your+timezone%2C+and+the+one+door+into+the+shared+3D+world.+Bring+a+photo%2C+get+an+avatar%2C+drop+in&p=%2Fevent" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="The live event - three.ws" />++ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <style>+ .ev-main, .ev-main *, .ev-main *::before, .ev-main *::after { box-sizing: border-box; }+ .ev-main { width: 100%; max-width: 1120px; margin: 0 auto; padding: 0 clamp(16px, 4vw, 40px) 96px; }++ /* ── Hero ───────────────────────────────────────────────────────── */+ .ev-hero { padding: clamp(28px, 5vw, 64px) 0 clamp(18px, 3vw, 32px); max-width: 82ch; }+ .ev-chip {+ display: inline-flex; align-items: center; gap: 9px;+ padding: 6px 14px; border: 1px solid var(--stroke); border-radius: 999px;+ background: var(--surface-1); font-size: 12px; letter-spacing: .1em;+ text-transform: uppercase; color: var(--ink-dim); font-family: var(--font-mono);+ transition: border-color var(--duration-base) var(--ease-standard), color var(--duration-base) var(--ease-standard), background var(--duration-base) var(--ease-standard);+ }+ .ev-dot {+ width: 8px; height: 8px; border-radius: 50%;+ background: var(--ink-dim);+ transition: background var(--duration-base) var(--ease-standard), box-shadow var(--duration-base) var(--ease-standard);+ }+ [data-state='live'] .ev-chip { color: var(--ink-bright); border-color: var(--stroke-strong); background: var(--surface-2); }+ [data-state='live'] .ev-dot { background: var(--success); box-shadow: 0 0 0 4px rgba(74, 222, 128, .18); animation: ev-pulse 1.4s ease-in-out infinite; }+ [data-state='ended'] .ev-dot { background: var(--ink-faint); }+ @keyframes ev-pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .4; transform: scale(.7); } }++ .ev-hero h1 {+ font-size: clamp(32px, 5.4vw, 60px); line-height: 1.02; letter-spacing: -.025em;+ margin: 18px 0 12px; color: var(--ink-bright);+ }+ .ev-lede { color: var(--ink-dim); font-size: clamp(15px, 1.4vw, 18px); line-height: 1.6; margin: 0; max-width: 62ch; }+ .ev-when {+ margin: 14px 0 0; color: var(--ink-faint); font-size: 13.5px; line-height: 1.6;+ font-family: var(--font-mono); font-variant-numeric: tabular-nums;+ }++ /* Skeletons — the hero has real shape before /event.json resolves. */+ .ev-skel {+ display: inline-block; border-radius: var(--skeleton-radius, 10px);+ background: linear-gradient(90deg, var(--skeleton-base) 25%, var(--skeleton-sheen) 37%, var(--skeleton-base) 63%);+ background-size: 400% 100%; animation: ev-shimmer 1.4s ease infinite;+ color: transparent; user-select: none;+ }+ @keyframes ev-shimmer { 0% { background-position: 100% 50%; } 100% { background-position: 0 50%; } }++ /* ── Countdown ──────────────────────────────────────────────────── */+ .ev-clock { display: flex; flex-wrap: wrap; gap: clamp(10px, 1.6vw, 18px); margin: clamp(22px, 3vw, 32px) 0 0; }+ .ev-seg {+ min-width: 78px; padding: 12px 16px 10px; text-align: center;+ border: 1px solid var(--stroke); border-radius: var(--radius-card);+ background: var(--surface-1);+ transition: border-color var(--duration-base) var(--ease-standard), background var(--duration-base) var(--ease-standard);+ }+ .ev-seg b {+ display: block; font-size: clamp(26px, 3.4vw, 38px); line-height: 1.05; font-weight: 700;+ color: var(--ink-bright); font-variant-numeric: tabular-nums; letter-spacing: -.02em;+ }+ .ev-seg span {+ display: block; margin-top: 5px; font-size: 10.5px; letter-spacing: .16em;+ text-transform: uppercase; color: var(--ink-dim); font-family: var(--font-mono);+ }+ [data-state='live'] .ev-seg { border-color: var(--stroke-strong); background: var(--surface-2); }+ .ev-seg-wide { min-width: 0; padding-inline: clamp(16px, 3vw, 28px); }+ .ev-seg-wide b { font-size: clamp(20px, 2.6vw, 28px); }++ /* ── CTA row ────────────────────────────────────────────────────── */+ .ev-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-top: clamp(22px, 3vw, 30px); }+ .ev-cta {+ display: inline-flex; align-items: center; gap: 10px;+ padding: 15px 28px; border-radius: 999px; text-decoration: none;+ background: var(--btn-primary-bg); color: var(--btn-primary-fg);+ border: 1px solid var(--btn-primary-border);+ font-size: clamp(15px, 1.3vw, 17px); font-weight: 650; letter-spacing: -.01em;+ transition: background var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard), box-shadow var(--duration-fast) var(--ease-standard);+ }+ .ev-cta:hover { background: var(--btn-primary-bg-hover); transform: translateY(-2px); box-shadow: var(--shadow-2); }+ .ev-cta:active { background: var(--btn-primary-bg-active); transform: translateY(0); }+ .ev-cta:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+ .ev-cta-arrow { font-size: 1.1em; line-height: 1; transition: transform var(--duration-fast) var(--ease-standard); }+ .ev-cta:hover .ev-cta-arrow { transform: translateX(3px); }++ .ev-ghost {+ appearance: none; cursor: pointer; font: inherit; font-size: 14px; font-weight: 550;+ display: inline-flex; align-items: center; gap: 8px;+ padding: 14px 22px; border-radius: 999px;+ border: 1px solid var(--stroke-strong); background: transparent; color: var(--ink);+ transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard);+ }+ .ev-ghost:hover { background: var(--surface-2); color: var(--ink-bright); }+ .ev-ghost:active { background: var(--surface-3); }+ .ev-ghost:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+ .ev-cal-note { margin: 10px 0 0; font-size: 12.5px; color: var(--ink-faint); min-height: 1.2em; }++ /* ── Live panel ─────────────────────────────────────────────────── */+ .ev-live {+ display: flex; align-items: center; gap: clamp(14px, 2.5vw, 28px); flex-wrap: wrap;+ margin-top: clamp(24px, 3.5vw, 36px); padding: clamp(18px, 2.5vw, 24px) clamp(20px, 3vw, 28px);+ border: 1px solid var(--stroke-strong); border-radius: var(--radius-card);+ background: var(--surface-glass); box-shadow: var(--shadow-1);+ }+ .ev-live-num {+ font-size: clamp(34px, 5vw, 50px); font-weight: 700; line-height: 1; letter-spacing: -.03em;+ color: var(--ink-bright); font-variant-numeric: tabular-nums;+ }+ .ev-live-copy { flex: 1 1 240px; min-width: 0; }+ .ev-live-copy strong { display: block; font-size: 15px; color: var(--ink-bright); font-weight: 600; }+ .ev-live-copy span { display: block; margin-top: 4px; font-size: 13px; color: var(--ink-dim); line-height: 1.5; }++ /* ── Sections ───────────────────────────────────────────────────── */+ .ev-sec { margin-top: clamp(48px, 7vw, 84px); }+ .ev-sec > h2 { font-size: clamp(21px, 2.4vw, 30px); letter-spacing: -.022em; margin: 0 0 10px; color: var(--ink-bright); }+ .ev-sec > p.ev-sec-lede { color: var(--ink-dim); font-size: 15px; line-height: 1.65; max-width: 68ch; margin: 0 0 24px; }++ .ev-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(238px, 1fr)); gap: 16px; }+ .ev-card {+ border: 1px solid var(--stroke); border-radius: var(--radius-card);+ background: var(--surface-1); padding: 20px 22px;+ transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard);+ }+ .ev-card:hover { border-color: var(--stroke-strong); background: var(--surface-2); transform: translateY(-2px); }+ .ev-card h3 { margin: 0 0 7px; font-size: 15.5px; letter-spacing: -.012em; color: var(--ink-bright); }+ .ev-card p { margin: 0; font-size: 13.5px; line-height: 1.6; color: var(--ink-dim); }+ .ev-card-mark { display: block; font-size: 20px; line-height: 1; margin-bottom: 12px; }++ /* ── Agenda ─────────────────────────────────────────────────────── */+ .ev-agenda { display: grid; gap: 0; border: 1px solid var(--stroke); border-radius: var(--radius-card); overflow: hidden; background: var(--surface-1); }+ .ev-slot {+ display: grid; grid-template-columns: 108px 34px 1fr; align-items: start; gap: 16px;+ padding: 16px clamp(16px, 2.4vw, 24px);+ border-top: 1px solid var(--hairline);+ transition: background var(--duration-fast) var(--ease-standard);+ }+ .ev-slot:first-child { border-top: 0; }+ .ev-slot:hover { background: var(--surface-2); }+ .ev-slot-time { font-family: var(--font-mono); font-size: 13px; color: var(--ink-bright); font-variant-numeric: tabular-nums; padding-top: 1px; }+ .ev-slot-mark { font-size: 19px; line-height: 1.2; }+ .ev-slot-title { margin: 0; font-size: 14.5px; font-weight: 600; color: var(--ink); letter-spacing: -.01em; }+ .ev-slot-detail { margin: 4px 0 0; font-size: 13px; line-height: 1.55; color: var(--ink-dim); }+ .ev-slot[data-past='true'] { opacity: .5; }+ .ev-slot[data-now='true'] { background: var(--surface-2); box-shadow: inset 3px 0 0 var(--success); }+ .ev-slot-badge {+ display: inline-block; margin-left: 8px; padding: 2px 8px; border-radius: 999px;+ font-family: var(--font-mono); font-size: 10px; letter-spacing: .12em; text-transform: uppercase;+ background: var(--surface-3); color: var(--ink-bright); vertical-align: 2px;+ }++ /* ── Empty / error ──────────────────────────────────────────────── */+ .ev-empty {+ border: 1px dashed var(--stroke-strong); border-radius: var(--radius-card);+ padding: clamp(26px, 4vw, 40px); text-align: center; background: var(--surface-1);+ }+ .ev-empty h2 { margin: 0 0 8px; font-size: 19px; color: var(--ink-bright); letter-spacing: -.015em; }+ .ev-empty p { margin: 0 auto 20px; max-width: 52ch; font-size: 14px; line-height: 1.6; color: var(--ink-dim); }++ .ev-foot {+ margin-top: clamp(44px, 6vw, 72px); border-left: 2px solid var(--stroke-strong);+ padding: 4px 0 4px 18px; color: var(--ink-dim); font-size: 14px; line-height: 1.7; max-width: 74ch;+ }+ .ev-foot a { color: var(--ink); text-underline-offset: 3px; }+ .ev-foot a:hover { color: var(--ink-bright); }++ @media (max-width: 720px) {+ .ev-slot { grid-template-columns: 78px 26px 1fr; gap: 12px; padding-inline: 16px; }+ .ev-slot-mark { font-size: 17px; }+ .ev-seg { min-width: 66px; padding: 10px 12px 8px; }+ .ev-actions { gap: 10px; }+ .ev-cta, .ev-ghost { width: 100%; justify-content: center; }+ }+ @media (max-width: 380px) {+ .ev-clock { gap: 8px; }+ .ev-seg { min-width: 60px; }+ }+ @media (prefers-reduced-motion: reduce) {+ .ev-card:hover, .ev-cta:hover { transform: none; }+ .ev-skel { animation: none; }+ }+ </style>+ </head>+ <body>+ <header>+ <div id="nav-container"></div>+ </header>+ <script src="/nav.js"></script>++ <main class="ev-main">+ <section class="ev-hero" id="ev-hero" data-state="loading" aria-labelledby="ev-name">+ <span class="ev-chip">+ <span class="ev-dot" aria-hidden="true"></span>+ <span id="ev-chip-label">Loading</span>+ </span>+ <h1 id="ev-name"><span class="ev-skel">Loading the event</span></h1>+ <p class="ev-lede" id="ev-tagline"><span class="ev-skel">Reading the event schedule</span></p>+ <div class="ev-clock" id="ev-clock" role="timer" aria-live="off"></div>+ <div class="ev-actions">+ <a class="ev-cta" id="ev-cta" href="/play">+ <span id="ev-cta-label">Enter the three.ws world</span>+ <span class="ev-cta-arrow" aria-hidden="true">→</span>+ </a>+ <button class="ev-ghost" id="ev-cal" type="button" hidden>+ <span aria-hidden="true">📅</span>+ <span>Add to calendar</span>+ </button>+ </div>+ <p class="ev-cal-note" id="ev-cal-note" role="status" aria-live="polite"></p>+ <p class="ev-when" id="ev-when"></p>+ </section>++ <section class="ev-live" id="ev-live" hidden aria-label="Live world population">+ <span class="ev-live-num" id="ev-live-num">—</span>+ <span class="ev-live-copy">+ <strong id="ev-live-title">In the world right now</strong>+ <span id="ev-live-note">Counting the avatars standing in the event world.</span>+ </span>+ </section>++ <section class="ev-sec" aria-labelledby="ev-expect-h">+ <h2 id="ev-expect-h">Never been here? This is the whole thing.</h2>+ <p class="ev-sec-lede">+ No download, no wallet, no account. It runs in the browser tab you already have open,+ on a phone or a laptop.+ </p>+ <div class="ev-cards">+ <article class="ev-card">+ <span class="ev-card-mark" aria-hidden="true">🧍</span>+ <h3>First, you get a body</h3>+ <p>+ Make an avatar from a selfie, pick one from the library, or drag in your own+ <code>.glb</code>. It animates properly either way: idle, walk and gestures are+ retargeted onto whatever skeleton you bring.+ </p>+ </article>+ <article class="ev-card">+ <span class="ev-card-mark" aria-hidden="true">🌍</span>+ <h3>Then you drop into the world</h3>+ <p>+ A shared 3D town built from the coin itself, with a real day/night clock everyone+ agrees on. Walk it, drive it, and see everyone else who is in there with you.+ </p>+ </article>+ <article class="ev-card">+ <span class="ev-card-mark" aria-hidden="true">💬</span>+ <h3>You can actually do things</h3>+ <p>+ Town chat and voice, emotes and a dance floor, jobs from the board, the general+ store and bank, King of the Totem at the landmark, and the wheel in the plaza.+ </p>+ </article>+ <article class="ev-card">+ <span class="ev-card-mark" aria-hidden="true">🎡</span>+ <h3>And you can leave with something</h3>+ <p>+ A free spin on Fortune's Folly every 12 hours, cosmetics you own, and a+ commemorative photo of the crowd taken from inside the world.+ </p>+ </article>+ </div>+ </section>++ <section class="ev-sec" id="ev-schedule-sec" aria-labelledby="ev-schedule-h" hidden>+ <h2 id="ev-schedule-h">The run of show</h2>+ <p class="ev-sec-lede" id="ev-schedule-lede">Every time below is your local time, converted in your browser.</p>+ <div class="ev-agenda" id="ev-agenda"></div>+ </section>++ <p class="ev-foot">+ The world is at <a href="/play">/play</a> and it is open whether or not an event is running.+ Build an avatar first at <a href="/create">/create</a>, read what the in-world economy pays+ at <a href="/play/economy">/play/economy</a>, and see everything that shipped recently on the+ <a href="/changelog">changelog</a>.+ </p>++ <noscript>+ <div class="ev-empty" style="margin-top: 32px">+ <h2>The countdown needs JavaScript</h2>+ <p>+ The schedule on this page is converted into your own timezone in the browser, so it+ cannot render without JavaScript. The world itself is always open.+ </p>+ <a class="ev-cta" href="/play">Enter the three.ws world</a>+ </div>+ </noscript>+ </main>++ <script src="/footer.js" defer></script>+ <script type="module" src="/src/event-page.js"></script>+ </body>+</html>diff --git a/src/event-page.js b/src/event-page.jsnew file mode 100644index 000000000..5be66040d--- /dev/null+++ b/src/event-page.js@@ -0,0 +1,426 @@+// /event — the one link the community shares before and during a live event.+//+// Everything on this page is derived from ONE file: public/event.json, served at+// /event.json. That is the same config the /play lobby banner and in-world pill+// read (src/game/event-countdown.js) and the same one the in-world experience+// layer reads (src/game/meetup-event.js), so the countdown here and the countdown+// there can never disagree. There is deliberately no copy of the times in this+// module or in pages/event.html: change the schedule in one file and every+// surface moves together.+//+// Three states, all designed, all reachable:+// upcoming — ticking days/hours/minutes/seconds to the doors opening+// live — a LIVE marker plus the real population of the event world+// ended — says the event happened and still routes people into the world,+// because /play is open whether or not an event is running+// A missing or malformed config is a fourth, honest state: "no event scheduled",+// with the same door into the world. The page never invents an event.+//+// The schedule is rendered in the visitor's own timezone (Intl, no server round+// trip) and the "Add to calendar" button builds a real RFC 5545 .ics in the+// browser, so no third-party calendar service ever sees who is coming.++import { log } from './shared/log.js';++const CONFIG_URL = '/event.json';++// How often the live panel re-reads the world population. Slow on purpose: the+// number moves on a human timescale and this page is left open for hours.+const POPULATION_POLL_MS = 20_000;++const $ = (sel) => document.querySelector(sel);++const els = {+ hero: $('#ev-hero'),+ chipLabel: $('#ev-chip-label'),+ name: $('#ev-name'),+ tagline: $('#ev-tagline'),+ clock: $('#ev-clock'),+ cta: $('#ev-cta'),+ ctaLabel: $('#ev-cta-label'),+ cal: $('#ev-cal'),+ calNote: $('#ev-cal-note'),+ when: $('#ev-when'),+ live: $('#ev-live'),+ liveNum: $('#ev-live-num'),+ liveTitle: $('#ev-live-title'),+ liveNote: $('#ev-live-note'),+ scheduleSec: $('#ev-schedule-sec'),+ scheduleLede: $('#ev-schedule-lede'),+ agenda: $('#ev-agenda'),+};++// ── config ──────────────────────────────────────────────────────────────────+// Deliberately the same shape and the same fallbacks as event-countdown.js: an+// event with no usable end time is treated as six hours long by both surfaces.+function parseConfig(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const startsAt = Date.parse(raw.startsAt);+ if (!Number.isFinite(startsAt)) return null;+ const endsAt = Date.parse(raw.endsAt);+ return {+ id: String(raw.id || 'three-ws-event'),+ name: String(raw.name || 'Live event'),+ tagline: raw.tagline ? String(raw.tagline) : '',+ startsAt,+ endsAt: Number.isFinite(endsAt) ? endsAt : startsAt + 6 * 3600 * 1000,+ link: raw.link ? String(raw.link) : '/play',+ linkLabel: raw.linkLabel ? String(raw.linkLabel) : 'Join the event',+ agenda: Array.isArray(raw.agenda)+ ? raw.agenda+ .filter((a) => a && Number.isFinite(Number(a.atMin)) && a.title)+ .map((a) => ({+ atMin: Math.max(0, Math.floor(Number(a.atMin))),+ title: String(a.title),+ detail: a.detail ? String(a.detail) : '',+ icon: a.icon ? String(a.icon) : '·',+ }))+ .sort((a, b) => a.atMin - b.atMin)+ : [],+ };+}++// ── formatting ──────────────────────────────────────────────────────────────+const pad = (n) => String(n).padStart(2, '0');++function fmtDateTime(ts) {+ return new Intl.DateTimeFormat(undefined, {+ weekday: 'long', month: 'long', day: 'numeric',+ hour: 'numeric', minute: '2-digit', timeZoneName: 'short',+ }).format(new Date(ts));+}++function fmtTimeOnly(ts) {+ return new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(new Date(ts));+}++function fmtDateOnly(ts) {+ return new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' }).format(new Date(ts));+}++function localZoneName() {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || '';+ } catch {+ return '';+ }+}++function segments(ms) {+ const s = Math.max(0, Math.floor(ms / 1000));+ return { d: Math.floor(s / 86400), h: Math.floor((s % 86400) / 3600), m: Math.floor((s % 3600) / 60), s: s % 60 };+}++function el(tag, attrs = {}, children = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null) continue;+ if (k === 'text') n.textContent = v;+ else n.setAttribute(k, v);+ }+ for (const c of children) if (c) n.appendChild(c);+ return n;+}++function segTile(value, label, wide = false) {+ return el('div', { class: wide ? 'ev-seg ev-seg-wide' : 'ev-seg' }, [+ el('b', { text: value }),+ el('span', { text: label }),+ ]);+}++// ── .ics ────────────────────────────────────────────────────────────────────+// A real RFC 5545 file, built here rather than handed to a calendar service, so+// the guest list never leaves the browser.+function icsEscape(s) {+ return String(s).replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');+}++function icsStamp(ts) {+ const d = new Date(ts);+ return (+ d.getUTCFullYear() + pad(d.getUTCMonth() + 1) + pad(d.getUTCDate()) + 'T' ++ pad(d.getUTCHours()) + pad(d.getUTCMinutes()) + pad(d.getUTCSeconds()) + 'Z'+ );+}++// RFC 5545 caps a content line at 75 octets; longer lines continue on the next+// line prefixed with a single space. Folding on octets (not characters) keeps a+// multi-byte glyph in an agenda title from being split down the middle.+function icsFold(line) {+ const enc = new TextEncoder();+ const dec = new TextDecoder();+ const bytes = enc.encode(line);+ if (bytes.length <= 75) return line;+ const out = [];+ let start = 0;+ let limit = 75;+ while (start < bytes.length) {+ let end = Math.min(start + limit, bytes.length);+ // Back off the cut point until it lands on a character boundary.+ while (end > start && end < bytes.length && (bytes[end] & 0b1100_0000) === 0b1000_0000) end -= 1;+ out.push((start === 0 ? '' : ' ') + dec.decode(bytes.subarray(start, end)));+ start = end;+ limit = 74; // continuation lines spend one octet on the leading space+ }+ return out.join('\r\n');+}++function buildIcs(cfg, absoluteLink) {+ const agendaLines = cfg.agenda.map((a) => `${fmtTimeOnly(cfg.startsAt + a.atMin * 60_000)} — ${a.title}`);+ const description = [cfg.tagline, ...agendaLines, `Join: ${absoluteLink}`].filter(Boolean).join('\n');+ const lines = [+ 'BEGIN:VCALENDAR',+ 'VERSION:2.0',+ 'PRODID:-//three.ws//Live event//EN',+ 'CALSCALE:GREGORIAN',+ 'METHOD:PUBLISH',+ 'BEGIN:VEVENT',+ `UID:${icsEscape(cfg.id)}@three.ws`,+ `DTSTAMP:${icsStamp(Date.now())}`,+ `DTSTART:${icsStamp(cfg.startsAt)}`,+ `DTEND:${icsStamp(cfg.endsAt)}`,+ `SUMMARY:${icsEscape(cfg.name)}`,+ `DESCRIPTION:${icsEscape(description)}`,+ `LOCATION:${icsEscape(absoluteLink)}`,+ `URL:${icsEscape(absoluteLink)}`,+ 'END:VEVENT',+ 'END:VCALENDAR',+ ];+ return lines.map(icsFold).join('\r\n') + '\r\n';+}++function downloadIcs(cfg, absoluteLink) {+ const blob = new Blob([buildIcs(cfg, absoluteLink)], { type: 'text/calendar;charset=utf-8' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `${cfg.id || 'three-ws-event'}.ics`;+ document.body.appendChild(a);+ a.click();+ a.remove();+ // Revoke on the next frame: revoking synchronously races the download start+ // in Safari and the file arrives empty.+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}++// ── live population ─────────────────────────────────────────────────────────+// /play presence lives in Colyseus rooms, so the count comes from the multiplayer+// server via /api/play/population. When that is unreachable the panel keeps the+// live state and drops the number: a landing page must never invent a crowd.+function coinFromLink(link) {+ try {+ return new URL(link, location.origin).searchParams.get('coin') || '';+ } catch {+ return '';+ }+}++class Population {+ constructor(coin) {+ this.coin = coin;+ this.timer = 0;+ this.stopped = false;+ }++ start() {+ if (this.timer) return;+ this._read();+ this.timer = setInterval(() => this._read(), POPULATION_POLL_MS);+ }++ stop() {+ clearInterval(this.timer);+ this.timer = 0;+ }++ async _read() {+ const url = this.coin+ ? `/api/play/population?coin=${encodeURIComponent(this.coin)}`+ : '/api/play/population';+ let body = null;+ try {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (res.ok) body = await res.json();+ } catch (err) {+ log.warn('[event] population read failed:', err?.message || err);+ }+ this._render(body);+ }++ _render(body) {+ if (!body || body.ok !== true) {+ els.liveNum.hidden = true;+ els.liveTitle.textContent = 'The doors are open';+ els.liveNote.textContent = 'The event world is live right now. Walk in and find the plaza.';+ return;+ }+ const n = Math.max(0, Math.floor(Number(body.players) || 0));+ els.liveNum.hidden = false;+ els.liveNum.textContent = String(n);+ els.liveTitle.textContent = n === 1 ? 'person is in the world right now' : 'people are in the world right now';+ els.liveNote.textContent = n === 0+ ? 'Nobody has walked in yet. Be the one who starts it.'+ : 'A live count from the event world, refreshed every 20 seconds.';+ }+}++// ── render ──────────────────────────────────────────────────────────────────+function renderAgenda(cfg, now) {+ if (!cfg.agenda.length) {+ els.scheduleSec.hidden = true;+ return;+ }+ els.scheduleSec.hidden = false;+ const zone = localZoneName();+ els.scheduleLede.textContent = zone+ ? `Doors at ${fmtTimeOnly(cfg.startsAt)}, wrap at ${fmtTimeOnly(cfg.endsAt)}. Every time below is converted into your own timezone (${zone}).`+ : `Doors at ${fmtTimeOnly(cfg.startsAt)}, wrap at ${fmtTimeOnly(cfg.endsAt)}. Every time below is in your own timezone.`;++ const rows = cfg.agenda.map((a, i) => {+ const at = cfg.startsAt + a.atMin * 60_000;+ const nextAt = i + 1 < cfg.agenda.length ? cfg.startsAt + cfg.agenda[i + 1].atMin * 60_000 : cfg.endsAt;+ const isNow = now >= at && now < nextAt;+ const isPast = now >= nextAt;+ const title = el('p', { class: 'ev-slot-title', text: a.title });+ if (isNow) title.appendChild(el('span', { class: 'ev-slot-badge', text: 'now' }));+ return el('div', { class: 'ev-slot', 'data-now': String(isNow), 'data-past': String(isPast) }, [+ el('div', { class: 'ev-slot-time', text: fmtTimeOnly(at) }),+ el('div', { class: 'ev-slot-mark', 'aria-hidden': 'true', text: a.icon }),+ el('div', {}, [title, a.detail ? el('p', { class: 'ev-slot-detail', text: a.detail }) : null]),+ ]);+ });+ els.agenda.replaceChildren(...rows);+}++function renderNoEvent() {+ els.hero.setAttribute('data-state', 'ended');+ els.chipLabel.textContent = 'No event scheduled';+ els.name.textContent = 'The world is open anyway.';+ els.tagline.textContent =+ 'Nothing is on the calendar right this minute. The three.ws world does not wait for one: ' ++ 'build an avatar, walk into the shared town, and see who is already there.';+ els.clock.replaceChildren();+ els.cta.href = '/play';+ els.ctaLabel.textContent = 'Enter the three.ws world';+ els.cal.hidden = true;+ els.when.textContent = 'Follow the changelog to hear about the next one before it starts.';+ els.live.hidden = true;+ els.scheduleSec.hidden = true;+}++class EventPage {+ constructor(cfg) {+ this.cfg = cfg;+ this.absoluteLink = new URL(cfg.link, location.origin).href;+ this.population = new Population(coinFromLink(cfg.link));+ this.state = null;+ this.agendaMinute = -1;++ els.name.textContent = cfg.name;+ els.tagline.textContent = cfg.tagline || 'A live gathering inside the three.ws world.';+ els.cta.href = cfg.link;++ els.cal.addEventListener('click', () => {+ try {+ downloadIcs(cfg, this.absoluteLink);+ els.calNote.textContent = 'Calendar file downloaded. Open it to add the event.';+ } catch (err) {+ log.warn('[event] ics build failed:', err?.message || err);+ els.calNote.textContent = 'That download was blocked. The event runs ' + fmtDateTime(cfg.startsAt) + '.';+ }+ });++ this._tick();+ this.timer = setInterval(() => this._tick(), 1000);+ // A tab left open for hours drifts: recompute the moment it comes back.+ document.addEventListener('visibilitychange', () => {+ if (!document.hidden) this._tick();+ });+ }++ _tick() {+ const now = Date.now();+ const state = now >= this.cfg.endsAt ? 'ended' : now >= this.cfg.startsAt ? 'live' : 'upcoming';+ if (state !== this.state) this._enterState(state);+ this.state = state;++ if (state === 'upcoming') {+ const t = segments(this.cfg.startsAt - now);+ const tiles = [];+ if (t.d > 0) tiles.push(segTile(String(t.d), t.d === 1 ? 'day' : 'days'));+ tiles.push(segTile(pad(t.h), 'hours'), segTile(pad(t.m), 'minutes'), segTile(pad(t.s), 'seconds'));+ els.clock.replaceChildren(...tiles);+ } else if (state === 'live') {+ const t = segments(this.cfg.endsAt - now);+ els.clock.replaceChildren(+ segTile('LIVE', 'right now', true),+ segTile((t.d > 0 ? `${t.d}d ` : '') + `${pad(t.h)}:${pad(t.m)}:${pad(t.s)}`, 'left to join', true),+ );+ }++ // The agenda only changes on a minute boundary; redrawing it every second+ // would fight the hover state for no gain.+ const minute = Math.floor(now / 60_000);+ if (minute !== this.agendaMinute) {+ this.agendaMinute = minute;+ renderAgenda(this.cfg, now);+ }+ }++ _enterState(state) {+ els.hero.setAttribute('data-state', state);+ const zone = localZoneName();+ const zoneSuffix = zone ? ` (${zone})` : '';++ if (state === 'upcoming') {+ els.chipLabel.textContent = 'Upcoming';+ els.ctaLabel.textContent = this.cfg.linkLabel;+ els.cal.hidden = false;+ els.when.textContent = `Doors open ${fmtDateTime(this.cfg.startsAt)}${zoneSuffix}. Runs until ${fmtTimeOnly(this.cfg.endsAt)}.`;+ els.live.hidden = true;+ this.population.stop();+ return;+ }++ if (state === 'live') {+ els.chipLabel.textContent = 'Live now';+ els.ctaLabel.textContent = this.cfg.linkLabel;+ els.cal.hidden = false;+ els.when.textContent = `Running now until ${fmtTimeOnly(this.cfg.endsAt)}${zoneSuffix}.`;+ els.live.hidden = false;+ this.population.start();+ return;+ }++ // Ended. The event is over; the world is not. Say what happened, then hold+ // the door open rather than leaving a dead page behind.+ els.chipLabel.textContent = 'This event has ended';+ els.clock.replaceChildren();+ els.cta.href = this.cfg.link;+ els.ctaLabel.textContent = 'Enter the world anyway';+ els.cal.hidden = true;+ els.calNote.textContent = '';+ els.when.textContent = `It ran on ${fmtDateOnly(this.cfg.startsAt)}. The world is still open, and the next event will show up here.`;+ els.live.hidden = true;+ this.population.stop();+ }+}++async function boot() {+ let raw = null;+ try {+ const res = await fetch(CONFIG_URL, { cache: 'no-cache', headers: { accept: 'application/json' } });+ if (res.ok) raw = await res.json();+ } catch (err) {+ log.warn('[event] config fetch failed:', err?.message || err);+ }+ const cfg = parseConfig(raw);+ if (!cfg) {+ renderNoEvent();+ return;+ }+ new EventPage(cfg);+}++boot();diff --git a/src/shared/stage-voice.js b/src/shared/stage-voice.jsnew file mode 100644index 000000000..08f815afa--- /dev/null+++ b/src/shared/stage-voice.js@@ -0,0 +1,219 @@+// Living Stages — the host's voice, shared by every surface that renders a show.+//+// A StageRoom beat arrives as a timed `utterance` broadcast: { id, text, voice,+// cue, durationMs }. Turning that into a performance is the same job everywhere+// it happens — fetch /api/tts/speak for the words, route the audio through the+// host avatar's PositionalAudio (so it gets louder as you walk toward the stage),+// tap an AnalyserNode off it to drive lip-sync on whatever the rig supports, and+// stop cleanly when the next beat pre-empts this one.+//+// The /stage page (src/stage.js) and the in-world plaza stage+// (src/game/plaza-stage-show.js) both use this, so the two surfaces speak with+// one implementation: a fix to the audio path lands on both at once, and neither+// can drift into rendering a different show from the same broadcast.+//+// Audio is best-effort by design. Captions carry the words, so a TTS failure, a+// blocked autoplay, or a rig with no mouth degrades the performance, never+// breaks it.++import { AudioAnalyser } from 'three';+import { LipsyncDriver } from '../voice/lipsync-driver.js';+import { apiFetch } from '../api.js';++const TTS_URL = '/api/tts/speak';++export class StageVoice {+ /**+ * @param {object} opts+ * @param {() => (import('three').PositionalAudio|null)} [opts.getPositionalAudio]+ * The host's spatial audio node, once its avatar has mounted. Called per+ * utterance so a late-loading avatar still gets spatial voice.+ * @param {() => (object|null)} [opts.getMouthTarget] the rig's MouthTarget.+ * @param {() => void} [opts.onAutoplayBlocked] browser gated playback on a gesture.+ * @param {(speaking:boolean) => void} [opts.onSpeaking] playback started/ended.+ * @param {number} [opts.gain] lip-sync open-shape multiplier.+ */+ constructor({ getPositionalAudio, getMouthTarget, onAutoplayBlocked, onSpeaking, gain = 1.5 } = {}) {+ this.getPositionalAudio = getPositionalAudio || (() => null);+ this.getMouthTarget = getMouthTarget || (() => null);+ this.onAutoplayBlocked = onAutoplayBlocked || (() => {});+ this.onSpeaking = onSpeaking || (() => {});+ this.gain = gain;+ this.muted = false;+ this.audio = null;+ this.lipsync = null;+ this._url = null;+ this._destroyed = false;+ }++ setMuted(muted) {+ this.muted = !!muted;+ if (this.muted) this.stop();+ }++ /** Speak one beat. Resolves once playback has started (or been given up on). */+ async speak(text, voice) {+ if (this._destroyed || this.muted || !text) return;+ this.stop();++ let buf;+ try {+ const res = await apiFetch(TTS_URL, {+ method: 'POST',+ allowAnonymous: true,+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ text, voice: voice || 'nova', format: 'mp3' }),+ });+ if (!res.ok) throw new Error(`tts ${res.status}`);+ buf = await res.arrayBuffer();+ } catch {+ return; // captions already carry the words; audio is best-effort+ }+ if (this._destroyed || this.muted) return;++ const url = URL.createObjectURL(new Blob([buf], { type: 'audio/mpeg' }));+ const audio = new Audio();+ audio.src = url;+ audio.crossOrigin = 'anonymous';+ this.audio = audio;+ this._url = url;+ audio.addEventListener('ended', () => {+ this._release(url);+ this.stopLipsync();+ this.onSpeaking(false);+ }, { once: true });++ // Spatial + lip-sync when the host avatar is mounted; plain playback while+ // it is still streaming in (or on a device with no 3D at all).+ const analyser = this._attachSpatial(audio);+ if (analyser) this.startLipsync(analyser);++ try {+ await audio.play();+ this.onSpeaking(true);+ } catch {+ this.onAutoplayBlocked();+ }+ }++ /** Retry playback of the current line after the user's first gesture. */+ resume() {+ if (!this.audio || this.muted) return;+ this.audio.play().then(() => this.onSpeaking(true)).catch(() => {});+ }++ _attachSpatial(audioEl) {+ const positional = this.getPositionalAudio();+ if (!positional) return null;+ try {+ const ctx = positional.context;+ if (ctx?.state === 'suspended') ctx.resume().catch(() => {});+ // A MediaElementSource can be created once per element; this element is+ // fresh per utterance, so this is safe.+ positional.setMediaElementSource(audioEl);+ return new AudioAnalyser(positional, 256).analyser;+ } catch {+ return null; // fall through to plain playback+ }+ }++ startLipsync(analyser) {+ this.stopLipsync();+ const target = this.getMouthTarget();+ if (!target) return;+ try {+ this.lipsync = new LipsyncDriver({ analyser, target, gain: this.gain });+ this.lipsync.start();+ } catch { /* lip-sync is enhancement, never required */ }+ }++ stopLipsync() {+ if (!this.lipsync) return;+ try { this.lipsync.stop(); } catch {}+ this.lipsync = null;+ try { this.getMouthTarget()?.setMouthShape({ open: 0, wide: 0, round: 0 }); } catch {}+ }++ stop() {+ if (this.audio) {+ try { this.audio.pause(); } catch {}+ this.audio = null;+ this.onSpeaking(false);+ }+ this._release(this._url);+ this.stopLipsync();+ }++ _release(url) {+ if (!url) return;+ try { URL.revokeObjectURL(url); } catch {}+ if (this._url === url) this._url = null;+ }++ dispose() {+ this._destroyed = true;+ this.stop();+ }+}++/**+ * Maps lip-sync {open,wide,round} onto whatever the GLB rig supports: morph+ * targets (visemes / mouthOpen / jawOpen) when present, else a jaw bone, else a+ * subtle head scale — so lip-sync is real where the rig allows and degrades+ * gracefully where it doesn't (no T-pose, never a hard failure).+ */+export class MouthTarget {+ constructor(model) {+ this.influences = [];+ this.jaw = null;+ this.head = findHead(model);+ const openNames = /(mouthopen|jawopen|viseme_aa|viseme_o|vrc\.v_aa|mouth_open|aa)/i;+ model.traverse((o) => {+ if (o.isMesh && o.morphTargetDictionary) {+ for (const [name, idx] of Object.entries(o.morphTargetDictionary)) {+ if (openNames.test(name)) this.influences.push({ mesh: o, idx });+ }+ }+ if (o.isBone && /jaw/i.test(o.name) && !this.jaw) this.jaw = o;+ });+ }++ setMouthShape({ open }) {+ const v = Math.max(0, Math.min(1, open));+ if (this.influences.length) {+ for (const { mesh, idx } of this.influences) mesh.morphTargetInfluences[idx] = v;+ } else if (this.jaw) {+ this.jaw.rotation.x = v * 0.35;+ } else if (this.head) {+ this.head.scale.y = 1 + v * 0.03;+ }+ }++ dispose() {+ for (const { mesh, idx } of this.influences) if (mesh.morphTargetInfluences) mesh.morphTargetInfluences[idx] = 0;+ if (this.jaw) this.jaw.rotation.x = 0;+ if (this.head) this.head.scale.y = 1;+ }+}++/** The rig's head bone, when it has one (the spatial audio + mouth anchor). */+export function findHead(model) {+ let head = null;+ model.traverse((o) => { if (!head && o.isBone && /head/i.test(o.name)) head = o; });+ return head;+}++/** Geometry height of a loaded model, for normalizing an avatar to human scale. */+export function modelHeight(model) {+ let minY = Infinity;+ let maxY = -Infinity;+ model.traverse((o) => {+ if (o.isMesh && o.geometry) {+ o.geometry.computeBoundingBox?.();+ const b = o.geometry.boundingBox;+ if (b) { minY = Math.min(minY, b.min.y); maxY = Math.max(maxY, b.max.y); }+ }+ });+ const h = maxY - minY;+ return Number.isFinite(h) && h > 0 ? h : 0;+}diff --git a/src/stage.js b/src/stage.jsindex 67dca5af6..560d33fcc 100644--- a/src/stage.js+++ b/src/stage.js@@ -28,7 +28,7 @@ import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';import { apiFetch } from './api.js';import { StageNet } from './stage-net.js';import { tipAgent, TipError } from './shared/agent-tip.js';-import { LipsyncDriver } from './voice/lipsync-driver.js';+import { StageVoice, MouthTarget, findHead, modelHeight } from './shared/stage-voice.js';import { loadEnvironment } from './shared/cinematic-render.js';const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';@@ -168,10 +168,17 @@ class VenueController {this.tipping = false;this.three = null; // {renderer,scene,camera,listener,host,mouth,...}this.audioCtxResumed = false;- this.currentAudio = null;- this.lipsync = null;this.audPositions = new Map();- this.muted = false;+ // The host's voice: TTS → the avatar's spatial audio → lip-sync. Shared with+ // the in-world plaza stage (src/shared/stage-voice.js) so both surfaces+ // render the same broadcast identically. Reads `this.three` lazily, so a+ // still-streaming avatar simply plays flat until its rig lands.+ this.voice = new StageVoice({+ getPositionalAudio: () => this.three?.positionalAudio || null,+ getMouthTarget: () => this.three?.mouthTarget || null,+ onAutoplayBlocked: () => { this.els.soundBtn.hidden = false; },+ onSpeaking: (speaking) => { if (!speaking) this.three?.setCue('idle', false); },+ });}start() {@@ -259,68 +266,9 @@ class VenueController {}// ── host voice: spatial + lip-sync, synced across clients ───────────────────- async speak(text, voice, durationMs) {- if (this.muted || !text) return;- this.stopAudio();- let buf;- try {- const res = await apiFetch('/api/tts/speak', {- method: 'POST',- allowAnonymous: true,- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ text, voice: voice || 'nova', format: 'mp3' }),- });- if (!res.ok) throw new Error(`tts ${res.status}`);- buf = await res.arrayBuffer();- } catch {- return; // captions already carry the words; audio is best-effort- }- const blob = new Blob([buf], { type: 'audio/mpeg' });- const url = URL.createObjectURL(blob);- const audio = new Audio();- audio.src = url;- audio.crossOrigin = 'anonymous';- this.currentAudio = audio;- audio.addEventListener('ended', () => { URL.revokeObjectURL(url); this.stopLipsync(); }, { once: true });-- // Route through the host's PositionalAudio when 3D is up (spatial + analyser- // lip-sync); otherwise just play the element (no-WebGL audio still works).- if (this.three?.attachVoice) {- try {- const analyser = this.three.attachVoice(audio);- if (analyser) this.startLipsync(analyser);- } catch {- /* fall through to plain playback */- }- }- try {- await audio.play();- } catch {- // Autoplay blocked until a gesture — surface the sound button.- this.els.soundBtn.hidden = false;- }- }-- startLipsync(analyser) {- this.stopLipsync();- if (!this.three?.mouthTarget) return;- try {- this.lipsync = new LipsyncDriver({ analyser, target: this.three.mouthTarget, gain: 1.5 });- this.lipsync.start();- } catch { /* lip-sync is enhancement, never required */ }- }-- stopLipsync() {- if (this.lipsync) { try { this.lipsync.stop(); } catch {} this.lipsync = null; }- if (this.three) this.three.setCue('idle', false);- }-- stopAudio() {- if (this.currentAudio) {- try { this.currentAudio.pause(); } catch {}- this.currentAudio = null;- }- this.stopLipsync();+ async speak(text, voice) {+ this.three?.resumeAudio();+ await this.voice.speak(text, voice);}// ── tipping ─────────────────────────────────────────────────────────────────@@ -512,7 +460,7 @@ class VenueController {this.els.soundBtn.hidden = true;this.audioCtxResumed = true;// Replay the current line so a gesture-gated first utterance is heard.- if (this.currentAudio) this.currentAudio.play?.().catch(() => {});+ this.voice.resume();};this.els.soundBtn.addEventListener('click', resume);this.els.closer?.addEventListener('click', () => this.three?.dolly(-1));@@ -523,7 +471,7 @@ class VenueController {dispose() {try { this.net?.destroy(); } catch {}- this.stopAudio();+ this.voice.dispose();try { this.three?.dispose(); } catch {}}}diff --git a/vercel.json b/vercel.jsonindex 8b2dbb988..0638d3c56 100644--- a/vercel.json+++ b/vercel.json@@ -1370,6 +1370,10 @@"src": "/play/?","dest": "/play.html"},+ {+ "src": "/event/?",+ "dest": "/event.html"+ },{"src": "/game(/.*)?","status": 308,diff --git a/vite.config.js b/vite.config.jsindex 122def997..b035fea24 100644--- a/vite.config.js+++ b/vite.config.js@@ -637,6 +637,7 @@ const appConfig = {'play-agent-wallet': resolve(__dirname, 'pages/play/agent-wallet.html'),'play-arena': resolve(__dirname, 'pages/play/arena.html'),'play-ufo': resolve(__dirname, 'pages/play/ufo.html'),+ event: resolve(__dirname, 'pages/event.html'),'play-economy': resolve(__dirname, 'pages/play/economy.html'),'play-solver': resolve(__dirname, 'pages/play/solver.html'),agi: resolve(__dirname, 'pages/agi.html'),