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: integrate spatial voice chat into Coin Communities
nirholas7fdd96194330
diff --git a/docs/coinmarketcap-article-play.md b/docs/coinmarketcap-article-play.mdnew file mode 100644index 000000000..4b0a945a9--- /dev/null+++ b/docs/coinmarketcap-article-play.md@@ -0,0 +1,124 @@+---+title: "Every Memecoin Is Now a 3D World You Can Walk Into"+target: CoinMarketCap Community / Editorial+---++# Every Memecoin Is Now a 3D World You Can Walk Into++## The community is the asset — so why does it live in a chat box?++Strip a memecoin down to what actually moves it and you don't find a product. You find a crowd. The chart is downstream of the community: the holders, the believers, the people refreshing the chart at 3am, the ones aping the next candle and the ones diamond-handing through the dip. On a memecoin, the community *is* the asset.++And yet that community lives in the two saddest tabs on the internet: a Telegram group on one side, a price chart on the other. The thing everyone agrees is the whole point — the people — has no place. You can't walk into a coin. You can't see who else is there. You can't feel the market move.++[three.ws](https://three.ws) **/play** changes that. It turns every [pump.fun](https://pump.fun) coin into its own live 3D world — a shared, walk-around space where holders show up as real 3D avatars, talk to each other by voice, and watch the coin's on-chain activity ripple through the environment around them in real time. The coin's chart isn't on a screen somewhere else. The chart is the *weather*.++It's live now at **[three.ws/play](https://three.ws/play)**, in the browser, no install, no extension. Pick a coin and you're standing in it.++## One coin, one world++The mental model is simple: **every coin is a room, keyed to its mint address.**++You open the /play lobby and see the trending pump.fun coins, plus a search box that reaches every coin on pump.fun — not just what's hot, *any* token. Pick one. You drop in as a 3D avatar standing on a plaza, under a sky, with a giant slowly-turning gold coin in the middle stamped with that token's art. A stadium jumbotron towers over the plaza showing the coin's name, its live market cap, and a count of how many people are in this community *right now*.++Other people are there too — real avatars, moving, with names floating over their heads and chat bubbles when they talk. You move with WASD and the mouse on desktop, or a touch joystick on mobile; sprint, jump, orbit the camera, wave an emote. Everyone in that space entered the same coin. Walk into a different coin and you're with a different crowd, in a different world.++Under the hood this is enforced by the multiplayer server: players are matched into the same room instance **only when their coin matches**. Each token is an isolated world. There's no bleed between communities — the people in $DOGE's world and the people in some fresh launch's world never see each other, because they're literally in different rooms anchored to different mints. A community becomes a shareable URL (`three.ws/play?coin=<mint>`); send it and someone lands directly in your coin's world.++## The world reacts to the chain++This is the part that makes people stop and stare.++Every /play world is streaming that coin's **real on-chain trades** — the actual pump.fun swap tape — and piping them straight into the environment. The market doesn't sit politely on a panel. It physically moves the world around you:++- **Every buy ripples green** across the plaza and kicks the glowing boundary ring.+- **Every sell ripples red.**+- **Sustained volume spins the coin totem faster** — the room visibly speeds up when the tape heats up.+- **The rolling percentage change becomes the weather.** Green and the fog opens out, the sun flares — euphoria. Red and the fog closes in and the light dims — a storm rolls over the world. The mood drifts like a tide, not a strobe, so it reads as atmosphere rather than noise.+- **A whale trade detonates.** When a single trade crosses the whale threshold, a column of light fires up over the totem, a shockwave rolls out across the plaza, and on a big buy a fountain of golden coins rains off the top — with a toast naming what just happened ("🐋 Whale bought $X of $TICKER").++The coin's price becomes the room's pulse. You don't read the market — you stand inside it and feel it flinch. A quiet coin is a calm, still world. A coin getting aped into orbit is a thunderstorm of green light and falling coins. Nobody has to narrate the action in chat; the world *is* the action.++## A trading terminal you can walk up to++Atmosphere is one half. The other half is a real, legible terminal — because people in a coin's world want the numbers, not just the vibe.++Past the totem stands a second giant screen: a live in-world **trading terminal** for the coin. It's not a decoration and it's not a screenshot. It polls the same on-chain swap feed the rest of the platform uses and paints, in real time:++- the **price** (with the leading-zero sub-decimal notation memecoins need — $0.0₇123 and the like),+- the session **price chart** with a live, glowing line,+- **market cap**, **live volume**, **trade count**, and **buy/sell flow** as a pressure bar,+- and a **scrolling ticker of the latest real trades** — side, size in SOL and USD, the trader's short address, and how long ago.++Tap the terminal and it opens the coin straight on pump.fun. And you don't even have to leave: /play ships a native in-world **buy flow**. Click Buy and the three.ws server builds the unsigned pump.fun transaction — handling both the bonding curve and the post-graduation AMM — your Solana wallet signs it, and it broadcasts. You can ape the coin while standing inside its world, surrounded by the people who already did.++That's the loop a memecoin has never had in one place: *see the crowd → feel the market → read the tape → buy the coin*, without ever switching tabs.++## Walk up to someone and talk++A crowd you can't talk to is just wallpaper. /play has **spatial voice chat**, and it's the thing that makes a coin's world feel like a real gathering instead of a chat box with 3D models.++It works the way your ears do. Walk up to someone and you hear them. Drift away and they fade out. Their voice comes from *their direction* — someone on your left sounds like they're on your left. Get far enough and they're gone. The audio is genuine peer-to-peer WebRTC with HRTF spatial panning and distance falloff; the server only passes the connection handshake between two people and never touches the audio itself. Connections open only to the people near enough to hear, so the voice layer stays light no matter how busy the plaza gets — which is also exactly what spatial audio *should* do.++Voice is opt-in (the mic stays off until you tap it), and when someone's talking, their nameplate pulses so you can pick the speaker out of a crowd. Alongside it there's text chat with floating bubbles and a set of emotes. The result is that a coin's world feels less like a Discord and more like actually being *somewhere* with other holders — clusters of people talking near the totem, someone shouting across the plaza when a whale lands.++## A thousand coins, a thousand worlds++If every coin shared one generic world, the whole thing would feel like a template. It doesn't.++Each coin's world is generated **deterministically from its mint address**. The mint is hashed into a seed, the seed picks one of several biome archetypes — Verdant Meadow, Dune Sea, Frostfields, Ashen Caldera, Neon Expanse, Lagoon Shore — and then nudges that biome's palette and scatters its flora from the same seed. So a given coin **always** renders the same world (your coin's place is *its* place, every time you return), and a thousand different coins render a thousand recognizably different ones. Two tokens that happen to land in the same biome still get their own color and layout.++Walking into a new coin and seeing what world it "is" becomes its own small ritual — a frozen tundra, a neon alien expanse, an ashen volcanic caldera. The world is a fingerprint of the mint.++## Build it together — and it stays++A community's world isn't read-only. /play includes **collaborative voxel building**: a block palette and a build mode where anyone in the world can place and break blocks together, in real time, on a shared grid in the middle of the plaza.++It's server-authoritative — every block is validated and synced through the same room everyone's in, so what you build is what everyone sees. And critically, **builds persist**. The world's creation is saved per coin and rehydrated when the room spins back up, so a community's monument to their token survives even after the last person logs off and the room is torn down. Come back tomorrow and the thing your community built is still standing.++That's the difference between a chat log and a place. A chat scrolls away. A place accumulates.++## The flagship: the $THREE town++There's one world that's always pinned to the top of the lobby, badged official, dressed in a fixed signature biome instead of the seeded lottery: the **$THREE town**, three.ws's own coin community. It's the front door — the world a first-time visitor lands in — and its identity (name, art, market cap) refreshes live from pump.fun so the pinned card is never stale. It's also the proof that this isn't a tech demo bolted onto a homepage: the platform runs its own community in its own product.++## It's all real++For a CoinMarketCap reader, the load-bearing question is always: *is any of this actually real, or is it a render?* Here's what's under the hood, plainly:++- **Real multiplayer.** The worlds run on an authoritative [Colyseus](https://colyseus.io) server deployed on Google Cloud Run. Clients send movement ~15 times a second; the server validates every update (anti-teleport step clamp, world bounds, name and message rate limits), keeps the authoritative state, and broadcasts only what changed via a binary delta protocol. It's the same proven engine behind the platform's `/walk` scene.+- **Real on-chain data.** The chart, the ticker, the market cap, the reactor's green-and-red — all of it is driven by live pump.fun trending, search, coin, and swap-tape feeds. Nothing is mocked or canned. An empty coin honestly says "no recent trades yet — be the first to ape in."+- **Real avatars.** Players load actual GLB/VRM 3D models — pick a preset, browse your own avatars and the public gallery, paste a URL, drop in your own `.glb`, or bring the 3D agent you built on three.ws. Draco-compressed models (most pump.fun and Sketchfab exports) just work.+- **Real voice.** Peer-to-peer WebRTC with spatial HRTF audio, proximity-gated so it scales and so it sounds right.+- **Real buys.** A native pump.fun transaction built server-side and signed by your own wallet — not a redirect dressed up as a feature.++And it's **open source** under Apache 2.0, like the rest of the platform.++## Why this matters++Memecoins have spent two years proving that attention and community are the actual product, and that the chart is just the scoreboard. But the tools the space gives a community have barely moved past a group chat and a candlestick. The "community" tab on most coins is a link to a Telegram.++/play makes the community tab a *place*. It gives a token:++- **A spatial home** — a room of its own, anchored to its mint, that holders can walk into and that you can link anyone directly into.+- **An embodied crowd** — real avatars and spatial voice, so being "in" a coin means being somewhere with other people, not staring at a member count.+- **A living chart** — the on-chain tape rendered as environment, so the market is something you experience, not just read.+- **A persistent artifact** — a world the community can build in, that survives and accumulates instead of scrolling away.+- **A path to action** — read the tape and buy the coin from inside its own world.++For projects, that's a reason to send your holders somewhere that isn't a chat app. For traders, it's a way to *feel* a coin's momentum and meet the people behind it before you ape. For the space as a whole, it's a glimpse of what a memecoin community looks like when it finally gets a body.++## Try it++1. Go to **[three.ws/play](https://three.ws/play)**.+2. Pick a trending coin, or search any pump.fun token by name or ticker.+3. Choose an avatar — a preset, your own upload, or your three.ws agent.+4. Drop in. Walk around. Tap the mic to talk to whoever's there. Watch the world react as the trades land. Build something. Buy the coin.++Or just open the front door: the pinned **$THREE town** at the top of the lobby.++The chart has always told you *what* a coin is doing. /play lets you go stand where it's happening.++---++*three.ws is an open-source, browser-native platform for 3D AI agents and on-chain communities, live at [three.ws](https://three.ws) and open source under Apache 2.0. Coin Communities (/play) is live at [three.ws/play](https://three.ws/play).*diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex f1499d285..e017a8a97 100644Binary files a/multiplayer/src/rooms/WalkRoom.js and b/multiplayer/src/rooms/WalkRoom.js differdiff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.jsindex c670803eb..7e1f72ce3 100644--- a/multiplayer/src/schemas.js+++ b/multiplayer/src/schemas.js@@ -25,6 +25,9 @@ export class Player extends Schema {this.avatar = '';// Optional three.ws agent id this player is embodying (for cross-links).this.agent = '';+ // True while this player is in spatial voice chat, so peers know to open a+ // WebRTC connection to them and the UI can mark their nameplate.+ this.voice = false;this.tsServer = 0; // server-side last-update epoch ms (for interpolation)}}@@ -41,6 +44,7 @@ defineTypes(Player, {emoteTs: 'float64',avatar: 'string',agent: 'string',+ voice: 'boolean',tsServer: 'float64',});diff --git a/scripts/smoke-voxel-build.mjs b/scripts/smoke-voxel-build.mjsnew file mode 100644index 000000000..57fd7da40--- /dev/null+++ b/scripts/smoke-voxel-build.mjs@@ -0,0 +1,86 @@+// End-to-end smoke test for the Coin Communities voxel build server.+//+// Boots nothing itself — point it at a running multiplayer server (default+// ws://localhost:2567). It joins a coin world, then exercises the place/remove+// contract the client relies on:+// 1. a legal place lands in authoritative state.blocks+// 2. a repaint changes the block type in place (no new cell)+// 3. an out-of-bounds place is rejected+// 4. a bad block type is rejected+// 5. a remove deletes the cell+// 6. a second client joining sees the persisted build (rehydration path)+//+// Exit code 0 = all assertions passed.++import { Client } from 'colyseus.js';++const URL = process.env.GAME_SERVER_URL || 'ws://localhost:2567';+const COIN = process.env.SMOKE_COIN || 'So11111111111111111111111111111111111111112';++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+let failures = 0;+function check(name, cond) {+ console.log(`${cond ? ' ok ' : 'FAIL '} ${name}`);+ if (!cond) failures++;+}++async function join() {+ const client = new Client(URL);+ const room = await client.joinOrCreate('walk_world', {+ coin: COIN, coinName: 'Wrapped SOL', coinSymbol: 'SOL', name: 'smoke-bot',+ });+ return room;+}++async function main() {+ console.log(`→ ${URL} coin=${COIN.slice(0, 8)}…`);+ const room = await join();+ await sleep(300); // let initial state sync++ // 1. Legal place at origin, gold (type 8).+ room.send('place', { x: 0, y: 0, z: 0, t: 8 });+ await sleep(250);+ check('legal place lands in state.blocks', room.state.blocks.get('0,0,0')?.t === 8);++ // 2. Repaint the same cell to neon (type 9) — same cell, new type, size unchanged.+ const sizeBeforeRepaint = room.state.blocks.size;+ room.send('place', { x: 0, y: 0, z: 0, t: 9 });+ await sleep(250);+ check('repaint changes type in place', room.state.blocks.get('0,0,0')?.t === 9);+ check('repaint does not grow the world', room.state.blocks.size === sizeBeforeRepaint);++ // 3. Out-of-bounds place (far outside MAX_GRID_XZ=30) is rejected.+ room.send('place', { x: 999, y: 0, z: 0, t: 1 });+ await sleep(200);+ check('out-of-bounds place rejected', !room.state.blocks.has('999,0,0'));++ // 4. Bad block type (>= BLOCK_TYPE_COUNT) is rejected.+ room.send('place', { x: 2, y: 0, z: 2, t: 99 });+ await sleep(200);+ check('bad block type rejected', !room.state.blocks.has('2,0,2'));++ // 5. Non-integer cell rejected.+ room.send('place', { x: 1.5, y: 0, z: 0, t: 1 });+ await sleep(200);+ check('non-integer cell rejected', !room.state.blocks.has('1.5,0,0'));++ // 6. A second client sees the persisted build immediately on join.+ const room2 = await join();+ await sleep(400);+ check('second client sees the persisted block', room2.state.blocks.get('0,0,0')?.t === 9);++ // 7. Remove deletes the cell in authoritative state and propagates to peers.+ room.send('remove', { x: 0, y: 0, z: 0 });+ await sleep(300);+ check('remove deletes cell for sender', !room.state.blocks.has('0,0,0'));+ check('remove propagates to other clients', !room2.state.blocks.has('0,0,0'));++ room.leave();+ room2.leave();+ await sleep(150);++ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILED`);+ process.exit(failures === 0 ? 0 : 1);+}++main().catch((e) => { console.error('smoke error:', e?.message ?? e); process.exit(2); });diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 5f5eeb33b..3454a8991 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -12,6 +12,7 @@import { renderAvatarThumb } from './avatar-thumb.js';import { resolveAvatarUrl } from './avatar-rig.js';import { validateGlb, uploadGlb } from './avatar-upload.js';+import { GUEST_SENTINEL, playAs } from './play-handoff.js';function el(tag, props = {}, kids = []) {const n = document.createElement(tag);@@ -99,6 +100,20 @@ export class CommunityUI {el('span', { class: 'cc-gallery-ico', text: '🖼' }),el('span', { class: 'cc-gallery-text', text: 'Browse gallery' }),]);+ // Create a brand-new avatar without leaving the lobby — the headline action.+ // Opens the in-app creator (design from scratch or from a photo); the exported+ // GLB is staged locally and adopted instantly, then the world uploads it so+ // peers see it too. Lazy-loaded so the avatar SDK never bloats the lobby boot.+ this.createBtn = el('button', {+ type: 'button', class: 'cc-create-btn',+ title: 'Create a brand-new 3D avatar — design it or build it from a photo',+ onclick: () => this._openCreate(),+ }, [+ el('span', { class: 'cc-create-ico', 'aria-hidden': 'true', text: '✦' }),+ el('span', { class: 'cc-create-copy', html: 'Create your avatar<small>Design from scratch or from a photo — drop straight in</small>' }),+ el('span', { class: 'cc-create-arrow', 'aria-hidden': 'true', text: '→' }),+ ]);+this.uploadStatus = el('div', { class: 'cc-upload-status', role: 'status', 'aria-live': 'polite', hidden: true });this.lobby = el('div', { id: 'cc-lobby' }, [@@ -122,7 +137,8 @@ export class CommunityUI {el('label', { class: 'cc-name-label', for: 'cc-name-input', text: 'Your name' }),this.nameInput,]),- el('div', { class: 'cc-avatar-label', html: 'Your avatar<small>Pick one, browse the gallery, paste a URL, or drop your own .glb</small>' }),+ el('div', { class: 'cc-avatar-label', html: 'Your avatar<small>Create your own, pick a preset, browse the gallery, paste a URL, or drop your own .glb</small>' }),+ this.createBtn,this.presetRow,el('div', { class: 'cc-avatar-custom' }, [this.customInput, this.galleryBtn, this.uploadBtn]),this.uploadStatus,@@ -203,6 +219,143 @@ export class CommunityUI {this._setAvatar(url, false);}+ // ---------------------------------------------------------- create avatar+ // The complete in-lobby creation workflow. A method chooser opens over the+ // lobby; each method ends with a real GLB the player can drop in with:+ // • Create → the in-app avatar creator (design from scratch / from a+ // photo). Anonymous, exports a GLB Blob we adopt instantly.+ // • Upload → reuse the bar's validated .glb upload.+ // • Studio → the full sculpt/outfit builder at /create/studio (richer,+ // saves to your three.ws account). Opens in a new tab.+ _openCreate() {+ if (this._createModal) return;++ const card = (icon, title, desc, badge, onActivate) => {+ const c = el('button', {+ type: 'button', class: 'cc-create-card',+ onclick: () => onActivate(),+ }, [+ el('span', { class: 'cc-create-card-ico', 'aria-hidden': 'true', text: icon }),+ el('span', { class: 'cc-create-card-body' }, [+ el('span', { class: 'cc-create-card-title' }, [+ document.createTextNode(title),+ badge ? el('span', { class: 'cc-create-card-badge', text: badge }) : null,+ ]),+ el('span', { class: 'cc-create-card-desc', text: desc }),+ ]),+ el('span', { class: 'cc-create-card-arrow', 'aria-hidden': 'true', text: '→' }),+ ]);+ return c;+ };++ const cards = el('div', { class: 'cc-create-methods' }, [+ card('✦', 'Design your avatar', 'Build a 3D character from scratch or from a selfie, then drop straight into the world. No sign-in needed.', 'Recommended', () => this._launchEditor()),+ card('⬆', 'Upload a .glb', 'Already have a model from Blender, Mixamo, VRoid, or Ready Player Me? Bring it in.', '', () => { this._closeCreate(); this.uploadFile.click(); }),+ card('✨', 'Advanced studio', 'Sculpt face & body, layer outfits and accessories, and save it to your three.ws account.', 'Opens in a new tab', () => { window.open('/create/studio', '_blank', 'noopener'); this._closeCreate(); }),+ ]);++ const closeBtn = el('button', { type: 'button', class: 'cc-create-close', 'aria-label': 'Close', text: '×', onclick: () => this._closeCreate() });+ const modal = el('div', {+ class: 'cc-create-modal', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'cc-create-title',+ }, [+ el('div', { class: 'cc-create-head' }, [+ el('div', {}, [+ el('h2', { id: 'cc-create-title', class: 'cc-create-title', text: 'Create your avatar' }),+ el('p', { class: 'cc-create-sub', text: 'However you make it, your avatar is ready to play the moment it’s done.' }),+ ]),+ closeBtn,+ ]),+ cards,+ ]);+ const overlay = el('div', { class: 'cc-create-overlay', onclick: (e) => { if (e.target === overlay) this._closeCreate(); } }, [modal]);++ this._createModal = overlay;+ this._createKeyHandler = (e) => {+ if (e.key === 'Escape') { e.stopPropagation(); this._closeCreate(); }+ };+ document.addEventListener('keydown', this._createKeyHandler, true);+ document.body.appendChild(overlay);+ // Animate in on the next frame and move focus into the dialog.+ requestAnimationFrame(() => {+ overlay.classList.add('cc-on');+ cards.querySelector('.cc-create-card')?.focus();+ });+ }++ _closeCreate() {+ const overlay = this._createModal;+ if (!overlay) return;+ this._createModal = null;+ if (this._createKeyHandler) {+ document.removeEventListener('keydown', this._createKeyHandler, true);+ this._createKeyHandler = null;+ }+ overlay.classList.remove('cc-on');+ const done = () => overlay.remove();+ overlay.addEventListener('transitionend', done, { once: true });+ setTimeout(done, 260); // fallback if transitionend never fires+ this.createBtn.focus();+ }++ // Open the in-app avatar creator (Studio builder + photo editor) in a modal.+ // On export it hands us a GLB Blob, which we adopt as the active avatar.+ async _launchEditor() {+ this._closeCreate();+ this.createBtn.classList.add('cc-busy');+ try {+ const { AvatarCreator } = await import('../avatar-creator.js');+ this._creator?.dispose?.();+ this._creator = new AvatarCreator(document.body, (blob, meta = {}) => {+ this._adoptCreatedAvatar(blob, meta);+ });+ await this._creator.openDefaultEditor();+ } catch (err) {+ console.warn('[coincommunities] avatar creator failed to open:', err?.message);+ this.toast('Couldn’t open the avatar creator. Try uploading a .glb instead.', 'warn');+ } finally {+ this.createBtn.classList.remove('cc-busy');+ }+ }++ // Stage a freshly-created GLB locally (instant self-preview), surface it as the+ // selected chip, and make the guest sentinel the active avatar. The world reads+ // the sentinel, shows it to the creator immediately from the local blob, and+ // uploads it in the background so peers can load it too (see play-handoff.js).+ async _adoptCreatedAvatar(blob, meta = {}) {+ this._setUploadState('working', 'Saving your new avatar…');+ try {+ // Pass the player's chosen name only if they set one — playAs persists it as+ // the display name, and we don't want a placeholder shadowing the guest-id+ // fallback the world assigns to unnamed players.+ const name = this.getName();+ await playAs({ blob, name, source: meta.provider || 'three-ws-create', dest: null });+ this._addCreatedChip(name || 'My avatar');+ this._setUploadState('done', 'Your avatar is ready — pick a community to drop in.');+ this.toast('Your avatar is ready — pick a community below to drop in.', 'info');+ } catch (err) {+ console.warn('[coincommunities] could not adopt created avatar:', err?.message);+ this._setUploadState('error', 'Couldn’t save your new avatar. Please try again.');+ }+ }++ // Surface the just-created avatar as its own selected chip (replacing any prior+ // one) and make the guest sentinel the active avatar. The chip starts with a+ // loading shimmer, then renders a real portrait of the new model — the sentinel+ // resolves to the locally-staged blob, so no upload round-trip is needed.+ _addCreatedChip(name) {+ if (this._createdChip?.isConnected) this._createdChip.remove();+ const chip = el('button', {+ class: 'cc-avatar-chip cc-avatar-loading cc-avatar-created',+ title: name || 'Your new avatar', 'aria-label': name || 'Your new avatar',+ onclick: () => this._setAvatar(GUEST_SENTINEL, false),+ }, [el('span', { class: 'cc-avatar-glyph', text: '✦' })]);+ chip._url = GUEST_SENTINEL;+ this._createdChip = chip;+ this.presetRow.insertBefore(chip, this.presetRow.firstChild);+ this._renderChipPreview(chip, { url: GUEST_SENTINEL, label: name || 'Your avatar' });+ this._setAvatar(GUEST_SENTINEL, false);+ }+// Open the platform avatar gallery (your own avatars + the public gallery)// with live 3D previews, and adopt the chosen one. Lazy-loaded so the picker// and its model-viewer dependency aren't in the lobby's critical bundle.@@ -504,15 +657,57 @@ export class CommunityUI {this.emoteTray = el('div', { id: 'cc-emotes' });+ // Spatial voice toggle. Off by default (no mic until the player opts in);+ // the icon + label reflect every state (connecting / live / muted / blocked).+ // The SVG carries its own mute slash, shown via the button's data-state.+ this.voiceLabel = el('span', { class: 'cc-voice-label', text: 'Voice' });+ this.voiceBtn = el('button', {+ class: 'cc-voice', type: 'button', 'data-state': 'off',+ 'aria-label': 'Voice chat', title: 'Join voice — talk to people near you',+ onclick: () => this.h.onVoiceToggle?.(),+ }, [+ el('span', { class: 'cc-voice-ico', html:+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">'+ + '<rect class="cc-voice-cap" x="9" y="2.5" width="6" height="11" rx="3"/>'+ + '<path class="cc-voice-stand" d="M6 11a6 6 0 0 0 12 0M12 17v4M9 21h6"/>'+ + '<line class="cc-voice-slash" x1="4" y1="3.4" x2="20" y2="20.6"/>'+ + '</svg>' }),+ this.voiceLabel,+ ]);+const hint = el('div', { id: 'cc-hint', html:'<kbd>W A S D</kbd> / drag-joystick to move · <kbd>drag</kbd> to look · scroll zoom · <kbd>Enter</kbd> chat' });this.joystick = el('div', { id: 'cc-joystick' });- this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, chat, this.emoteTray, hint, this.joystick]);+ this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, this.voiceBtn, chat, this.emoteTray, hint, this.joystick]);document.body.appendChild(this.hud);}+ // Reflect the voice engine's state on the mic button: label, tooltip, and the+ // data-state hook the CSS uses to colour the icon / show the mute slash.+ setVoiceState(state) {+ if (!this.voiceBtn) return;+ const map = {+ off: ['Voice', 'Join voice — talk to people near you'],+ connecting: ['Connecting…', 'Requesting microphone access…'],+ on: ['Mic on', 'You’re live — click to mute'],+ muted: ['Muted', 'Muted — click to unmute (you can still hear everyone)'],+ denied: ['Mic blocked', 'Microphone blocked — allow it in your browser settings'],+ error: ['Voice error', 'Couldn’t start voice — check your mic and try again'],+ unsupported:['No voice', 'Voice chat isn’t supported in this browser'],+ };+ const [label, title] = map[state] || map.off;+ this.voiceBtn.setAttribute('data-state', state);+ this.voiceLabel.textContent = label;+ this.voiceBtn.title = title;+ this.voiceBtn.disabled = state === 'unsupported';+ if (state !== 'on') this.voiceBtn.classList.remove('cc-voice-speaking');+ }++ // Pulse the mic button while the local player is actually speaking.+ setMicSpeaking(on) { this.voiceBtn?.classList.toggle('cc-voice-speaking', !!on); }+setEmotes(list) {this.emoteTray.textContent = '';for (const e of list) {diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 658d88ac8..aadb733e2 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -265,6 +265,139 @@ html, body {.cc-gallery-ico { font-size: 13px; line-height: 1; }.cc-gallery-btn.cc-busy { pointer-events: none; opacity: 0.65; }+/* create-avatar — the headline action in the bar. Filled white so it reads as+ the primary path; spans the bar so it never competes with the equal-weight+ secondary actions (gallery / upload / paste) below it. */+.cc-create-btn {+ display: flex; align-items: center; gap: 14px; width: 100%; text-align: left; cursor: pointer;+ background: #fff; color: var(--cc-ink); border: 1px solid #fff; border-radius: var(--cc-radius);+ padding: 13px 16px; margin: 2px 0 4px; font: inherit;+ box-shadow: var(--cc-glow);+ transition: transform 0.1s ease, box-shadow 0.16s ease, filter 0.16s ease;+}+.cc-create-btn:hover { transform: translateY(-1px); box-shadow: 0 0 0 1px #fff, 0 0 22px rgba(255, 255, 255, 0.5); }+.cc-create-btn:active { transform: translateY(0); }+.cc-create-btn:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px #fff; }+.cc-create-ico {+ flex: none; width: 30px; height: 30px; border-radius: 50%; display: grid; place-items: center;+ background: var(--cc-ink); color: #fff; font-size: 15px; line-height: 1;+}+.cc-create-copy { flex: 1; min-width: 0; font-weight: 700; font-size: 14px; letter-spacing: 0.01em; }+.cc-create-copy small { display: block; color: rgba(6, 6, 7, 0.62); font-weight: 500; font-size: 12px; margin-top: 2px; letter-spacing: 0; }+.cc-create-arrow { flex: none; font-size: 16px; opacity: 0.55; transition: transform 0.16s ease, opacity 0.16s ease; }+.cc-create-btn:hover .cc-create-arrow { transform: translateX(3px); opacity: 1; }+.cc-create-btn.cc-busy { pointer-events: none; opacity: 0.7; }+.cc-create-btn.cc-busy .cc-create-ico { animation: cc-upload-pulse 0.9s ease-in-out infinite; }+@media (prefers-reduced-motion: reduce) {+ .cc-create-btn:hover { transform: none; }+ .cc-create-btn.cc-busy .cc-create-ico { animation: none; }+}++/* freshly-created avatar chip — selected ring matches the other adopted chips */+.cc-avatar-chip.cc-avatar-created.cc-on { border-color: #fff; }++/* create-avatar method chooser — a focused modal over the lobby */+.cc-create-overlay {+ position: fixed; inset: 0; z-index: 90; display: grid; place-items: center; padding: 20px;+ background: rgba(4, 4, 5, 0.78); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);+ opacity: 0; transition: opacity 0.2s ease;+}+.cc-create-overlay.cc-on { opacity: 1; }+.cc-create-modal {+ width: min(560px, 100%); max-height: calc(100dvh - 40px); overflow-y: auto;+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow); padding: 22px;+ transform: translateY(10px) scale(0.99); transition: transform 0.22s cubic-bezier(0.2, 0.7, 0.2, 1);+}+.cc-create-overlay.cc-on .cc-create-modal { transform: none; }+.cc-create-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 18px; }+.cc-create-title { margin: 0; font-size: 19px; font-weight: 700; letter-spacing: 0.01em; }+.cc-create-sub { margin: 5px 0 0; color: var(--cc-dim); font-size: 13px; line-height: 1.45; max-width: 42ch; }+.cc-create-close {+ flex: none; width: 32px; height: 32px; border-radius: var(--cc-radius-sm); cursor: pointer;+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); color: var(--cc-dim);+ font-size: 20px; line-height: 1; transition: border-color 0.15s ease, color 0.15s ease, background 0.15s ease;+}+.cc-create-close:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); background: var(--cc-bg3); }+.cc-create-close:focus-visible { outline: none; border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi); }+.cc-create-methods { display: flex; flex-direction: column; gap: 10px; }+.cc-create-card {+ display: flex; align-items: center; gap: 14px; width: 100%; text-align: left; cursor: pointer; font: inherit;+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ padding: 14px 16px; color: var(--cc-text);+ transition: border-color 0.14s ease, background 0.14s ease, transform 0.1s ease;+}+.cc-create-card:hover { border-color: var(--cc-edge-hi); background: var(--cc-bg3); transform: translateY(-1px); }+.cc-create-card:active { transform: translateY(0); }+.cc-create-card:focus-visible { outline: none; border-color: #fff; box-shadow: 0 0 0 1px #fff; }+.cc-create-card-ico {+ flex: none; width: 40px; height: 40px; border-radius: var(--cc-radius-sm); display: grid; place-items: center;+ background: var(--cc-bg3); border: 1px solid var(--cc-edge); font-size: 19px; line-height: 1;+}+.cc-create-card:hover .cc-create-card-ico { border-color: var(--cc-edge-hi); }+.cc-create-card-body { flex: 1; min-width: 0; }+.cc-create-card-title { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 14px; }+.cc-create-card-badge {+ font-size: 10px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase;+ color: var(--cc-ink); background: #fff; border-radius: 999px; padding: 2px 8px;+}+.cc-create-card-desc { display: block; margin-top: 3px; color: var(--cc-dim); font-size: 12.5px; line-height: 1.45; font-weight: 400; }+.cc-create-card-arrow { flex: none; font-size: 16px; color: var(--cc-faint); transition: transform 0.16s ease, color 0.16s ease; }+.cc-create-card:hover .cc-create-card-arrow { transform: translateX(3px); color: var(--cc-text); }+@media (prefers-reduced-motion: reduce) {+ .cc-create-overlay, .cc-create-modal { transition: none; }+ .cc-create-card:hover, .cc-create-btn:hover { transform: none; }+}+@media (max-width: 560px) {+ .cc-create-modal { padding: 18px; }+ .cc-create-card { padding: 12px 13px; gap: 11px; }+ .cc-create-card-ico { width: 36px; height: 36px; font-size: 17px; }+}++/* In-app avatar creator iframe modal (AvatarCreator). Self-contained here so the+ builder/photo editor renders correctly on /play without the main-site stylesheet. */+.avatar-creator-overlay {+ position: fixed; inset: 0; z-index: 95; display: flex; align-items: center; justify-content: center;+ background: rgba(4, 4, 5, 0.92); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);+ animation: cc-create-fadein 0.22s ease;+}+@keyframes cc-create-fadein { from { opacity: 0; } to { opacity: 1; } }+.avatar-creator-modal {+ width: 95vw; height: 90vh; max-width: 1200px; display: flex; flex-direction: column;+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ overflow: hidden; box-shadow: var(--cc-shadow);+}+.avatar-creator-header {+ display: flex; align-items: center; justify-content: space-between; flex: none;+ padding: 12px 18px; border-bottom: 1px solid var(--cc-edge-soft);+}+.avatar-creator-title { font-size: 15px; font-weight: 600; letter-spacing: 0.02em; color: var(--cc-text); }+.avatar-creator-close {+ background: none; border: none; color: var(--cc-dim); font-size: 26px; line-height: 1; cursor: pointer;+ padding: 0 4px; transition: color 0.18s ease;+}+.avatar-creator-close:hover { color: var(--cc-text); }+.avatar-creator-body { flex: 1; position: relative; min-height: 0; }+.avatar-creator-container { position: absolute; inset: 0; width: 100%; height: 100%; }+.avatar-creator-iframe { width: 100%; height: 100%; border: none; }+.avatar-creator-loading {+ position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;+ gap: 14px; color: var(--cc-dim); font-size: 13px; pointer-events: none;+}+.avatar-creator-loading .spinner {+ width: 30px; height: 30px; border-radius: 50%;+ border: 2px solid var(--cc-edge); border-top-color: #fff; animation: cc-spin 0.8s linear infinite;+}+@keyframes cc-spin { to { transform: rotate(360deg); } }+.avatar-creator-error { color: #ff6b6b; font-size: 13px; }+@media (max-width: 700px) {+ .avatar-creator-modal { width: 100vw; height: 100dvh; max-width: none; border-radius: 0; border: none; }+}+@media (prefers-reduced-motion: reduce) {+ .avatar-creator-overlay { animation: none; }+ .avatar-creator-loading .spinner { animation: none; }+}+/* coin grid */.cc-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.18em; color: var(--cc-faint); margin: 10px 2px 14px; }.cc-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(224px, 1fr)); gap: 14px; }@@ -408,6 +541,45 @@ html, body {#cc-status[data-state="offline"], #cc-status[data-state="failed"] { cursor: pointer; }@keyframes cc-pulse { 50% { opacity: 0.3; } }+/* spatial voice toggle — top-right, tucked under the status pill */+.cc-voice {+ position: fixed; top: 96px; right: 14px; z-index: 22;+ display: inline-flex; align-items: center; gap: 8px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ padding: 8px 13px 8px 11px; color: var(--cc-dim); cursor: pointer;+ font-weight: 600; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase;+ box-shadow: var(--cc-shadow); backdrop-filter: blur(10px);+ transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease, box-shadow 0.12s ease;+}+.cc-voice:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); background: rgba(255, 255, 255, 0.05); }+.cc-voice:focus-visible { outline: none; border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi); }+.cc-voice:disabled { opacity: 0.45; cursor: not-allowed; }+.cc-voice-ico { display: inline-flex; }+.cc-voice-ico svg { width: 16px; height: 16px; display: block; }+.cc-voice-cap { fill: transparent; transition: fill 0.12s ease; }+.cc-voice-slash { display: none; opacity: 0.85; }+.cc-voice-label { line-height: 1; }+/* live (unmuted): white icon + brighter frame */+.cc-voice[data-state="on"] { color: #fff; border-color: var(--cc-edge-hi); }+.cc-voice[data-state="on"] .cc-voice-cap { fill: rgba(255, 255, 255, 0.16); }+/* connecting: pulse the icon while we ask for the mic */+.cc-voice[data-state="connecting"] .cc-voice-ico { animation: cc-pulse 1s infinite; }+/* muted: dim with the mute slash */+.cc-voice[data-state="muted"] { color: var(--cc-dim); }+.cc-voice[data-state="muted"] .cc-voice-slash { display: block; }+/* blocked / error: faint, slashed */+.cc-voice[data-state="denied"], .cc-voice[data-state="error"] { color: var(--cc-faint); }+.cc-voice[data-state="denied"] .cc-voice-slash { display: block; }+/* speaking: animated halo while the local player talks */+.cc-voice.cc-voice-speaking { border-color: #fff; box-shadow: 0 0 0 1px #fff, 0 0 18px rgba(255, 255, 255, 0.4); }+.cc-voice.cc-voice-speaking .cc-voice-ico { animation: cc-voice-pulse 0.7s ease-in-out infinite; }+@keyframes cc-voice-pulse { 50% { transform: scale(1.16); } }+@media (prefers-reduced-motion: reduce) {+ .cc-voice.cc-voice-speaking .cc-voice-ico,+ .cc-voice[data-state="connecting"] .cc-voice-ico,+ .cc-label.cc-speaking::before { animation: none; }+}+/* chat sidebar — dockable, minimizable, persistent log */#cc-chat {position: fixed; right: 14px; bottom: 14px; width: min(340px, 82vw);@@ -500,6 +672,15 @@ html, body {font-size: 11px; font-weight: 700; letter-spacing: 0.04em; color: #fff;text-shadow: 0 1px 4px rgba(0, 0, 0, 0.9); padding: 1px 6px; text-transform: uppercase;}+/* in-voice peers wear a small mic dot on their nameplate; it lights up and+ pulses while they're actually speaking, so you can spot the talker in a crowd. */+.cc-label.cc-invoice { display: inline-flex; align-items: center; gap: 5px; }+.cc-label.cc-invoice::before {+ content: ""; flex: none; width: 6px; height: 6px; border-radius: 50%;+ background: rgba(255, 255, 255, 0.6); box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5);+}+.cc-label.cc-speaking { color: #fff; text-shadow: 0 1px 4px rgba(0, 0, 0, 0.9), 0 0 10px rgba(255, 255, 255, 0.5); }+.cc-label.cc-speaking::before { background: #fff; box-shadow: 0 0 10px rgba(255, 255, 255, 0.9); animation: cc-voice-pulse 0.7s ease-in-out infinite; }.cc-bubble {background: #fff; color: var(--cc-ink); font-size: 13px; font-weight: 600; text-align: center;padding: 7px 12px; border-radius: var(--cc-radius); max-width: 220px; white-space: normal;diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 4fc6b0f80..69f87a953 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -33,6 +33,7 @@ import {} from './avatar-rig.js';import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';import { HOME_TOWN, isHomeTown } from './home-town.js';+import { VoiceChat, voiceSupported } from './voice-chat.js';const WORLD_RADIUS = 58; // a touch inside the server's 60m clampconst MOVE_SPEED = 4.2;@@ -88,6 +89,8 @@ class RemotePlayer {this._bubbleTimer = null;this.height = 1.7; // avatar head height; updated once the GLB measures+ this.voice = !!player.voice;+ this.label.classList.toggle('cc-invoice', this.voice);this.setAvatar(player.avatar);}setAvatar(url) {@@ -104,6 +107,11 @@ class RemotePlayer {apply(player) {this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z; this.targetYaw = player.yaw;if (player.name) this.label.textContent = player.name;+ if (player.voice !== undefined && !!player.voice !== this.voice) {+ this.voice = !!player.voice;+ this.label.classList.toggle('cc-invoice', this.voice);+ if (!this.voice) this.setSpeaking(false);+ }if (player.avatar !== this._avatarUrl) this.setAvatar(player.avatar);if (player.motion !== this.motion) {this.motion = player.motion;@@ -123,6 +131,13 @@ class RemotePlayer {clearTimeout(this._bubbleTimer);this._bubbleTimer = setTimeout(() => { this.bubble?.remove(); this.bubble = null; }, 5000);}+ // Pulse this peer's nameplate while they're talking, so you can see who's+ // speaking in a crowd, not just hear them.+ setSpeaking(on) {+ if (on === this._speaking) return;+ this._speaking = on;+ this.label.classList.toggle('cc-speaking', on);+ }tick(dt) {this.rig.position.x += (this.targetX - this.rig.position.x) * REMOTE_LERP;this.rig.position.y += (this.targetY - this.rig.position.y) * REMOTE_LERP;@@ -182,6 +197,7 @@ export class CoinCommunities {},onRename: (name) => this._rename(name),onBuy: () => this._openBuy(),+ onVoiceToggle: () => this._toggleVoice(),});// Collaborative building HUD (hotbar + place/break toggle). Hidden until the@@ -609,6 +625,13 @@ export class CoinCommunities {this._updateOnline();// Only offer building while there's a live link to build into.this.buildHud.setEnabled(status === 'online', 'Building needs a live connection');+ // A reconnect reissues every sessionId, stranding the voice mesh — refresh+ // our id, drop the stale peers, and re-announce so it re-forms.+ if (status === 'online' && this.voice?.joined && this.net.sessionId !== this.voice.selfId) {+ this.voice.setSelfId(this.net.sessionId);+ this.voice.resetPeers();+ this.net.setVoiceActive(true);+ }});this.net.on('add', (p, id) => this._onAdd(p, id));this.net.on('change', (p, id) => this._onChange(p, id));@@ -620,11 +643,51 @@ export class CoinCommunities {this.net.on('blockRemove', (key) => { const [x, y, z] = parseKey(key); this.voxels?.removeBlock(x, y, z); });this.buildHud.root.hidden = false;await this.net.connect();+ this._initVoice();this.phase = 'world';this._initJoystick();}+ // Stand up spatial voice for this community. Voice starts OFF (no mic access+ // until the player opts in); the mic button drives join/mute through here.+ _initVoice() {+ if (this.voice) { this.voice.dispose(); this.voice = null; }+ if (!voiceSupported()) { this.ui.setVoiceState('unsupported'); return; }+ this.voice = new VoiceChat({+ selfId: this.net.sessionId,+ sendSignal: (to, data) => this.net?.sendVoiceSignal(to, data),+ onStateChange: (s) => {+ this.ui.setVoiceState(s);+ this.net?.setVoiceActive(s === 'on' || s === 'muted');+ },+ onPeerSpeaking: (id, sp) => this.remotes.get(id)?.setSpeaking(sp),+ onLocalSpeaking: (sp) => this.ui.setMicSpeaking(sp),+ });+ // Relay signals from peers into the voice engine.+ this.net.on('voiceSignal', (msg) => this.voice?.onSignal(msg));+ this.ui.setVoiceState('off');+ }++ // Mic button: first tap joins voice (asks for the mic); later taps mute/unmute.+ async _toggleVoice() {+ if (!this.voice) return;+ if (this.voice.state === 'off') {+ this.ui.setVoiceState('connecting');+ try {+ await this.voice.join();+ } catch (err) {+ console.warn('[coincommunities] voice join failed:', err?.name, err?.message);+ this.ui.setVoiceState(err?.name === 'NotAllowedError' ? 'denied' : 'error');+ }+ } else {+ this.voice.toggleMute();+ }+ }+leave() {+ // Tear voice down before the socket so our final "left voice" flag still+ // sends, and peers' connections close cleanly.+ if (this.voice) { this.voice.dispose(); this.voice = null; }if (this.net) { this.net.destroy(); this.net = null; }for (const [, r] of this.remotes) r.dispose();this.remotes.clear();@@ -668,6 +731,7 @@ export class CoinCommunities {_onRemove(id) {const r = this.remotes.get(id);if (r) { r.dispose(); this.remotes.delete(id); this._updateOnline(); }+ this.voice?.removePeer(id);}_onChat(m) {const mine = m.id === this.net.sessionId;@@ -931,6 +995,7 @@ export class CoinCommunities {this.localAnim?.update(dt);for (const [, r] of this.remotes) r.tick(dt);this._updateLabels();+ this._updateVoice();if (this.net) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });}this._tickEnv(dt);@@ -992,6 +1057,21 @@ export class CoinCommunities {if (this.localRig) { this.localRig.position.copy(this.localPos); this.localRig.rotation.y = this.localYaw; }}+ // Feed the voice engine each frame: where the listener is (local avatar),+ // which way they're facing (camera forward, so left/right panning matches the+ // view), and every peer's live position + voice state.+ _updateVoice() {+ if (!this.voice) return;+ const peers = [];+ for (const [id, r] of this.remotes) {+ peers.push({ id, x: r.rig.position.x, y: r.rig.position.y, z: r.rig.position.z, voice: r.voice });+ }+ // Camera forward on the ground plane is (sin camYaw, cos camYaw) — see+ // _updateCamera, where the camera sits opposite this vector from the target.+ const forward = { x: Math.sin(this.camYaw), z: Math.cos(this.camYaw) };+ this.voice.update({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z }, peers, forward);+ }+_updateCamera() {// Track the avatar on the ground plane only — ignore jump height so the// camera stays planted while the character hops.diff --git a/src/game/community-net.js b/src/game/community-net.jsindex bf938fc25..c694e8e3c 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -71,6 +71,7 @@ export class CommunityNet {remove: new Set(), // (id)chat: new Set(), // ({id, name, text, ts})interact: new Set(), // ({from, fromName, action, ts}) — a peer interacted with us+ voiceSignal: new Set(), // ({from, data}) — relayed WebRTC SDP/ICE from a peerping: new Set(), // (ms) — smoothed round-trip latency to the serverblockAdd: new Set(), // (key, type) — a voxel appeared (placed or restored)blockChange: new Set(), // (key, type) — a voxel was repainted@@ -123,6 +124,7 @@ export class CommunityNet {this.room.onMessage('chat', (msg) => this._emit('chat', msg));this.room.onMessage('interact', (msg) => this._emit('interact', msg));+ this.room.onMessage('voice-signal', (msg) => this._emit('voiceSignal', msg));const $ = getStateCallbacks(this.room);$(this.room.state).players.onAdd((player, id) => {@@ -220,6 +222,10 @@ export class CommunityNet {sendPlace(x, y, z, t) { this.room?.send('place', { x, y, z, t }); }sendRemove(x, y, z) { this.room?.send('remove', { x, y, z }); }sendInteract(to, action) { this.room?.send('interact', { to, action }); }+ // Spatial voice: relay a WebRTC offer/answer/ICE candidate to one peer, and+ // flag ourselves in/out of voice so peers know whether to connect to us.+ sendVoiceSignal(to, data) { this.room?.send('voice-signal', { to, data }); }+ setVoiceActive(on) { this.room?.send('voice-state', { on: !!on }); }rename(name) { this.name = name; this.room?.send('rename', { name }); }setAvatar(avatar, agent) { this.avatar = avatar; this.room?.send('avatar', { avatar, agent }); }diff --git a/src/game/voice-chat.js b/src/game/voice-chat.jsnew file mode 100644index 000000000..3b9a5666f--- /dev/null+++ b/src/game/voice-chat.js@@ -0,0 +1,337 @@+// Spatial voice chat for Coin Communities — talk to the people standing near you.+//+// This is what makes a coin community feel like a real gathering instead of a+// chat box with avatars: walk up to someone and you hear them, drift away and+// they fade out, and their voice comes from their direction in the world.+//+// Design — a PROXIMITY-GATED WebRTC MESH:+// • Audio is peer-to-peer (WebRTC). The Colyseus room is only a signaling+// relay for SDP/ICE; it never carries audio.+// • We open a connection only to peers within earshot, and tear it down when+// they walk away. That bounds the mesh no matter how big the room gets AND+// is exactly what spatial audio needs — you only need audio from people you+// can hear.+// • Each remote's audio runs through a Web Audio PannerNode positioned at+// their world coordinates, with the listener pinned to the local avatar and+// oriented by the camera. Distance attenuation (linear, silent past+// MAX_DISTANCE) makes proximity legible by ear.+// • Only the lower sessionId in a pair sends the offer, so two peers coming+// into range at once never glare. The `voice` player flag (synced via the+// room) tells us who's actually in voice, so we never dial someone who+// can't answer.+//+// The scene owns the per-frame update (positions) and lifecycle; this module+// owns the microphone, the peer connections, and the audio graph.++// Proximity thresholds, in metres. CONNECT a little outside the audible edge so+// the handshake completes before someone is fully in earshot; DISCONNECT with+// hysteresis so a peer pacing the boundary doesn't thrash connections.+const CONNECT_RANGE = 27;+const DISCONNECT_RANGE = 33;++// Panner distance model: full volume within REF_DISTANCE, linearly down to+// silence at MAX_DISTANCE. Linear (not inverse) so walking past the edge is a+// clean fade to nothing rather than a never-quite-zero tail.+const REF_DISTANCE = 3;+const MAX_DISTANCE = 26;++// Voice-activity threshold (RMS of the time-domain signal) for the "speaking"+// indicator. Tuned to ignore room tone / breathing but catch normal speech.+const SPEAK_THRESHOLD = 0.018;+const METER_INTERVAL_MS = 120;++// Public STUN. A coin community can supply its own TURN servers (needed for+// peers behind symmetric NAT) by setting window.__VOICE_ICE__ to an array of+// RTCIceServer entries — real config, no placeholder credentials baked in.+function iceServers() {+ const base = [+ { urls: 'stun:stun.l.google.com:19302' },+ { urls: 'stun:stun1.l.google.com:19302' },+ ];+ const extra = (typeof window !== 'undefined' && Array.isArray(window.__VOICE_ICE__)) ? window.__VOICE_ICE__ : null;+ return extra && extra.length ? base.concat(extra) : base;+}++// True when the browser can actually run spatial voice. The mic button stays+// disabled (with an explanation) when this is false.+export function voiceSupported() {+ return typeof RTCPeerConnection !== 'undefined'+ && typeof navigator !== 'undefined'+ && !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)+ && (typeof AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined');+}++export class VoiceChat {+ /**+ * @param {object} o+ * @param {string} o.selfId our Colyseus sessionId (decides who dials)+ * @param {Function} o.sendSignal (to, data) → relay SDP/ICE to one peer+ * @param {Function} [o.onStateChange] (state) → 'off'|'on'|'muted'+ * @param {Function} [o.onPeerSpeaking] (peerId, speaking)+ * @param {Function} [o.onLocalSpeaking](speaking)+ */+ constructor(o) {+ this.selfId = o.selfId;+ this.sendSignal = o.sendSignal;+ this.onStateChange = o.onStateChange;+ this.onPeerSpeaking = o.onPeerSpeaking;+ this.onLocalSpeaking = o.onLocalSpeaking;++ this.peers = new Map(); // peerId → { pc, panner, analyser, audioEl, source, data, speaking }+ this.ctx = null;+ this.listener = null;+ this.localStream = null;+ this.localTrack = null;+ this.localAnalyser = null;+ this.localData = null;+ this.joined = false;+ this._state = 'off';+ this._localSpeaking = false;+ this._meterAt = 0;+ }++ get state() { return this._state; }++ _setState(s) {+ if (s === this._state) return;+ this._state = s;+ this.onStateChange?.(s);+ }++ // Capture the mic and open the audio graph. Must be called from a user+ // gesture (the mic button) so getUserMedia + AudioContext are allowed to+ // start. Throws on permission denial / no device — the caller surfaces it.+ async join() {+ if (this.joined) return this._state;+ const Ctx = window.AudioContext || window.webkitAudioContext;+ this.ctx = new Ctx();+ if (this.ctx.state === 'suspended') await this.ctx.resume();+ this.localStream = await navigator.mediaDevices.getUserMedia({+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },+ video: false,+ });+ this.localTrack = this.localStream.getAudioTracks()[0] || null;++ // Meter our own mic so we can show the local "speaking" pulse. This tap is+ // analysis-only — it's never connected to the output.+ const lsrc = this.ctx.createMediaStreamSource(this.localStream);+ this.localAnalyser = this.ctx.createAnalyser();+ this.localAnalyser.fftSize = 512;+ lsrc.connect(this.localAnalyser);+ this.localData = new Float32Array(this.localAnalyser.fftSize);++ this.listener = this.ctx.listener;+ this.joined = true;+ this._setState('on');+ return this._state;+ }++ // Toggle whether our mic is transmitted. Muting keeps every connection open+ // (we still hear everyone) and simply stops sending our audio.+ toggleMute() {+ if (!this.joined || !this.localTrack) return this._state;+ const muting = this._state === 'on';+ this.localTrack.enabled = !muting;+ this._setState(muting ? 'muted' : 'on');+ if (muting && this._localSpeaking) { this._localSpeaking = false; this.onLocalSpeaking?.(false); }+ return this._state;+ }++ // Per-frame from the scene: reposition the listener (local avatar + camera+ // facing) and every peer's panner, open connections to in-range voice peers,+ // and drop ones that walked away.+ // @param {{x,y,z}} selfPos listener position (local avatar)+ // @param {Array} peers [{ id, x, y, z, voice }] of remote players+ // @param {{x,z}} forward camera horizontal forward (for L/R panning)+ update(selfPos, peers, forward) {+ if (!this.joined || !this.ctx) return;+ this._setListener(selfPos, forward);++ for (const p of peers) {+ const peer = this.peers.get(p.id);+ const d = Math.hypot(p.x - selfPos.x, (p.y || 0) - (selfPos.y || 0), p.z - selfPos.z);+ if (peer) {+ this._setPanner(peer, p);+ if (!p.voice || d > DISCONNECT_RANGE) this._closePeer(p.id);+ } else if (p.voice && d < CONNECT_RANGE && this.selfId < p.id) {+ // Deterministic initiator: the lower sessionId dials, so two peers+ // entering range simultaneously never both offer.+ this._call(p.id);+ }+ }+ this._meter();+ }++ // Handle a relayed signal from a peer (offer / answer / ICE candidate).+ async onSignal({ from, data }) {+ if (!this.joined || !from || !data) return;+ let peer = this.peers.get(from);+ try {+ if (data.sdp) {+ if (data.sdp.type === 'offer') {+ if (!peer) { peer = this._createPeer(from, false); this._addLocalTracks(peer); }+ await peer.pc.setRemoteDescription(data.sdp);+ const answer = await peer.pc.createAnswer();+ await peer.pc.setLocalDescription(answer);+ this.sendSignal(from, { sdp: peer.pc.localDescription });+ } else if (data.sdp.type === 'answer' && peer) {+ await peer.pc.setRemoteDescription(data.sdp);+ }+ } else if (data.ice && peer) {+ // A candidate can arrive before the remote description is set; ignore+ // the resulting error rather than tear down a healthy connection.+ try { await peer.pc.addIceCandidate(data.ice); } catch { /* premature candidate */ }+ }+ } catch (err) {+ console.warn('[voice] signal handling failed:', err?.message);+ }+ }++ // A peer left the room — drop their connection immediately.+ removePeer(id) { this._closePeer(id); }++ // On a server reconnect every sessionId is reissued, so the old peer+ // connections (and our own id) are stale. Refresh the id and drop every+ // connection; the mesh re-forms from the new ids on the next update().+ setSelfId(id) { this.selfId = id; }+ resetPeers() { for (const id of [...this.peers.keys()]) this._closePeer(id); }++ // Leave voice entirely: close every connection, stop the mic, free the graph.+ dispose() {+ for (const id of [...this.peers.keys()]) this._closePeer(id);+ this.localStream?.getTracks().forEach((t) => t.stop());+ this.localStream = null;+ this.localTrack = null;+ try { this.ctx?.close(); } catch { /* already closed */ }+ this.ctx = null;+ this.joined = false;+ this._setState('off');+ }++ // ---------------------------------------------------------------- internals+ _call(id) {+ const peer = this._createPeer(id, true);+ this._addLocalTracks(peer); // adding tracks fires negotiationneeded → offer+ }++ _addLocalTracks(peer) {+ if (!this.localStream) return;+ for (const t of this.localStream.getTracks()) peer.pc.addTrack(t, this.localStream);+ }++ _createPeer(id, isCaller) {+ const pc = new RTCPeerConnection({ iceServers: iceServers() });++ const panner = this.ctx.createPanner();+ panner.panningModel = 'HRTF';+ panner.distanceModel = 'linear';+ panner.refDistance = REF_DISTANCE;+ panner.maxDistance = MAX_DISTANCE;+ panner.rolloffFactor = 1;+ panner.connect(this.ctx.destination);++ const analyser = this.ctx.createAnalyser();+ analyser.fftSize = 512;++ // A muted <audio> sink keeps the inbound stream "live" so the Web Audio+ // source actually pulls samples (a long-standing Chromium requirement);+ // the audible path is the panner, not this element.+ const audioEl = new Audio();+ audioEl.muted = true;+ audioEl.autoplay = true;++ const peer = { id, pc, panner, analyser, audioEl, source: null, data: new Float32Array(analyser.fftSize), speaking: false };+ this.peers.set(id, peer);++ pc.onicecandidate = (e) => { if (e.candidate) this.sendSignal(id, { ice: e.candidate }); };+ pc.ontrack = (e) => {+ const stream = e.streams[0] || new MediaStream([e.track]);+ audioEl.srcObject = stream;+ audioEl.play?.().catch(() => { /* sink is muted; autoplay is best-effort */ });+ const src = this.ctx.createMediaStreamSource(stream);+ peer.source = src;+ src.connect(panner);+ src.connect(analyser);+ };+ pc.onconnectionstatechange = () => {+ if (pc.connectionState === 'failed' || pc.connectionState === 'closed') this._closePeer(id);+ };+ // Only the caller renegotiates; the callee answers in onSignal, so adding+ // its tracks must not also try to fire an offer (which would glare).+ if (isCaller) {+ pc.onnegotiationneeded = async () => {+ try {+ const offer = await pc.createOffer();+ await pc.setLocalDescription(offer);+ this.sendSignal(id, { sdp: pc.localDescription });+ } catch (err) {+ console.warn('[voice] offer failed:', err?.message);+ }+ };+ }+ return peer;+ }++ _closePeer(id) {+ const peer = this.peers.get(id);+ if (!peer) return;+ this.peers.delete(id);+ try { peer.source?.disconnect(); } catch { /* not connected */ }+ try { peer.panner.disconnect(); } catch { /* not connected */ }+ try { peer.analyser.disconnect(); } catch { /* not connected */ }+ try { peer.pc.close(); } catch { /* already closed */ }+ if (peer.audioEl) peer.audioEl.srcObject = null;+ if (peer.speaking) this.onPeerSpeaking?.(id, false);+ }++ _setPanner(peer, p) {+ const panner = peer.panner;+ const y = p.y || 0;+ if (panner.positionX) {+ panner.positionX.value = p.x;+ panner.positionY.value = y;+ panner.positionZ.value = p.z;+ } else {+ panner.setPosition(p.x, y, p.z); // older Safari+ }+ }++ _setListener(pos, forward) {+ const l = this.listener;+ const fx = forward?.x ?? 0;+ const fz = forward?.z ?? -1;+ const y = pos.y || 0;+ if (l.positionX) {+ l.positionX.value = pos.x; l.positionY.value = y; l.positionZ.value = pos.z;+ l.forwardX.value = fx; l.forwardY.value = 0; l.forwardZ.value = fz;+ l.upX.value = 0; l.upY.value = 1; l.upZ.value = 0;+ } else {+ l.setPosition(pos.x, y, pos.z); // older Safari+ l.setOrientation(fx, 0, fz, 0, 1, 0);+ }+ }++ // Throttled voice-activity detection for the speaking indicators.+ _meter() {+ const now = (typeof performance !== 'undefined' ? performance.now() : 0);+ if (now - this._meterAt < METER_INTERVAL_MS) return;+ this._meterAt = now;++ if (this.localAnalyser) {+ const sp = this._state === 'on' && this._rms(this.localAnalyser, this.localData) > SPEAK_THRESHOLD;+ if (sp !== this._localSpeaking) { this._localSpeaking = sp; this.onLocalSpeaking?.(sp); }+ }+ for (const peer of this.peers.values()) {+ if (!peer.source) continue;+ const sp = this._rms(peer.analyser, peer.data) > SPEAK_THRESHOLD;+ if (sp !== peer.speaking) { peer.speaking = sp; this.onPeerSpeaking?.(peer.id, sp); }+ }+ }++ _rms(analyser, buf) {+ analyser.getFloatTimeDomainData(buf);+ let sum = 0;+ for (let i = 0; i < buf.length; i++) sum += buf[i] * buf[i];+ return Math.sqrt(sum / buf.length);+ }+}